code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
""" Purpose ------- A Portfolio represents a collection of Aggregate objects. Applications include * Model a book of insurance * Model a large account with several sub lines * Model a reinsurance portfolio or large treaty """ import collections import json import logging from copy import deepcopy import matplotlib.cm as cm import matplotlib.pyplot as plt import matplotlib import matplotlib.ticker as ticker import numpy as np import pandas as pd from pandas.io.formats.format import EngFormatter import pypandoc import scipy.stats as ss from scipy.interpolate import interp1d from IPython.core.display import HTML, display from matplotlib.ticker import MultipleLocator, StrMethodFormatter, MaxNLocator, FixedLocator, \ FixedFormatter, AutoMinorLocator from scipy import interpolate import re from pathlib import Path from .distr import Aggregate, Severity from .spectral import Distortion from .utils import ft, \ ift, sln_fit, sgamma_fit, \ axiter_factory, AxisManager, html_title, \ suptitle_and_tight, \ MomentAggregator, Answer, subsets, round_bucket, report_time # fontsize : int or float or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'} matplotlib.rcParams['legend.fontsize'] = 'xx-small' logger = logging.getLogger('aggregate') # debug # info # warning # error # critical class Portfolio(object): """ Portfolio creates and manages a portfolio of Aggregate objects. :param name: the name of the portfolio, no spaces or underscores :param spec_list: a list of 1) dictionary: Aggregate object dictionary specifications or 2) Aggregate: An actual aggregate objects or 3) tuple (type, dict) as returned by uw['name'] or 4) string: Names referencing objects in the optionally passed underwriter """ def __init__(self, name, spec_list, uw=None): self.name = name self.agg_list = [] self.line_names = [] logger.debug(f'Portfolio.__init__| creating new Portfolio {self.name}') # logger.debug(f'Portfolio.__init__| creating new Portfolio {self.name} at {super(Portfolio, self).__repr__()}') ma = MomentAggregator() max_limit = 0 for spec in spec_list: if isinstance(spec, Aggregate): # directly passed in an agg object a = spec agg_name = spec.name elif isinstance(spec, str): # look up object in uw return actual instance # note here you could do uw.aggregate[spec] and get the dictionary def # or uw(spec) to return the already-created (and maybe updated) object # we go the latter route...if user wants they can pull off the dict item themselves if uw is None: raise ValueError(f'Must pass valid Underwriter instance to create aggs by name') try: a = uw(spec) except e: logger.error(f'Item {spec} not found in your underwriter') raise e agg_name = a.name elif isinstance(spec, tuple): # uw returns type, spec assert spec[0] == 'agg' a = Aggregate(**spec[1]) agg_name = spec[1]['name'] elif isinstance(spec, dict): a = Aggregate(**spec) agg_name = spec['name'][0] if isinstance(spec['name'], list) else spec['name'] else: raise ValueError(f'Invalid type {type(spec)} passed to Portfolio, expect Aggregate, str or dict.') self.agg_list.append(a) self.line_names.append(agg_name) self.__setattr__(agg_name, a) ma.add_fs(a.report_ser[('freq', 'ex1')], a.report_ser[('freq', 'ex2')], a.report_ser[('freq', 'ex3')], a.report_ser[('sev', 'ex1')], a.report_ser[('sev', 'ex2')], a.report_ser[('sev', 'ex3')]) max_limit = max(max_limit, np.max(np.array(a.limit))) self.line_names_ex = self.line_names + ['total'] for n in self.line_names: # line names cannot equal total if n == 'total': raise ValueError('Line names cannot equal total, it is reserved for...total') # make a pandas data frame of all the statistics_df temp_report = pd.concat([a.report_ser for a in self.agg_list], axis=1) # max_limit = np.inf # np.max([np.max(a.get('limit', np.inf)) for a in spec_list]) temp = pd.DataFrame(ma.stats_series('total', max_limit, 0.999, remix=False)) self.statistics_df = pd.concat([temp_report, temp], axis=1) # future storage self.density_df = None self.augmented_df = None self.epd_2_assets = {} self.assets_2_epd = {} self.priority_capital_df = None self.priority_analysis_df = None self.audit_df = None self.padding = 0 self.tilt_amount = 0 self._linear_quantile_function = None self._cdf = None self._pdf = None self._tail_var = None self._tail_var2 = None self._inverse_tail_var = None self.bs = 0 self.log2 = 0 self.ex = 0 self.last_update = 0 self.hash_rep_at_last_update = '' self._distortion = None self.sev_calc = '' self._remove_fuzz = 0 self.approx_type = "" self.approx_freq_ge = 0 self.discretization_calc = '' # for storing the info about the quantile function self.q_temp = None self._renamer = None self._line_renamer = None self._tm_renamer = None # if created by uw it stores the program here self.program = '' self.audit_percentiles = [.9, .95, .99, .996, .999, .9999, 1 - 1e-6] self.dists = None self.dist_ans = None def __str__(self): """ Goal: readability :return: """ # cannot use ex, etc. because object may not have been updated if self.audit_df is None: ex = self.statistics_df.loc[('agg', 'mean'), 'total'] empex = np.nan isupdated = False else: ex = self.get_stat(stat="Mean") empex = self.get_stat() isupdated = True # df = pd.DataFrame(columns=['Statistic', 'Value']) # df = df.set_index('Statistic') # df.loc['Portfolio Name', 'Value'] = self.name # df.loc['Expected loss', 'Value'] = ex # df.loc['Model loss', 'Value'] = empex # df.loc['Error', 'Value'] = ex / empex - 1 # print(df) s = f'Portfolio name {self.name:<15s}\n' \ f'Theoretic expected loss {ex:15,.1f}\n' \ f'Actual expected loss {empex:15,.1f}\n' \ f'Error {empex / ex - 1:15.6f}\n' \ f'Discretization size {self.log2:15d}\n' \ f'Bucket size {self.bs:15.2f}\n' \ f'{object.__repr__(self)}' if not isupdated: s += '\nNOT UPDATED!' return s @property def distortion(self): return self._distortion def remove_fuzz(self, df=None, eps=0, force=False, log=''): """ remove fuzz at threshold eps. if not passed use np.finfo(np.float).eps. Apply to self.density_df unless df is not None Only apply if self.remove_fuzz or force :param eps: :param df: apply to dataframe df, default = self.density_df :param force: do regardless of self.remove_fuzz :return: """ if df is None: df = self.density_df if eps == 0: eps = np.finfo(np.float).eps if self._remove_fuzz or force: logger.debug(f'Portfolio.remove_fuzz | Removing fuzz from {self.name} dataframe, caller {log}') df[df.select_dtypes(include=['float64']).columns] = \ df.select_dtypes(include=['float64']).applymap(lambda x: 0 if abs(x) < eps else x) def __repr__(self): """ Goal unmbiguous :return: """ # return str(self.to_dict()) # this messes up when port = self has been enhanced... if isinstance(self, Portfolio): s = [super(Portfolio, self).__repr__(), f"{{ 'name': '{self.name}'"] else: s = [f'Non-Portfolio (enhanced) object {{ "name": "{self.name}"'] agg_list = [str({k: v for k, v in a.__dict__.items() if k in Aggregate.aggregate_keys}) for a in self.agg_list] s.append(f"'spec': [{', '.join(agg_list)}]") if self.bs > 0: s.append(f'"bs": {self.bs}') s.append(f'"log2": {self.log2}') s.append(f'"padding": {self.padding}') s.append(f'"tilt_amount": {self.tilt_amount}') s.append(f'"distortion": "{repr(self._distortion)}"') s.append(f'"sev_calc": "{self.sev_calc}"') s.append(f'"remove_fuzz": {self._remove_fuzz}') s.append(f'"approx_type": "{self.approx_type}"') s.append(f'"approx_freq_ge": {self.approx_freq_ge}') return ', '.join(s) + '}' def _repr_html_(self): s = [f'<h2>Portfolio object: {self.name}</h2>'] _n = len(self.agg_list) _s = "" if _n <= 1 else "s" s.append(f'Portfolio contains {_n} aggregate component{_s}') summary_sl = (slice(None), ['mean', 'cv', 'skew']) if self.audit_df is not None: _df = pd.concat((self.statistics_df.loc[summary_sl, :], self.audit_df[['Mean', 'EmpMean', 'MeanErr', 'CV', 'EmpCV', 'CVErr', 'P99.0']].T), sort=True) s.append(_df._repr_html_()) else: s.append(self.statistics_df.loc[summary_sl, :]._repr_html_()) return '\n'.join(s) def __hash__(self): """ hashing behavior :return: """ return hash(repr(self.__dict__)) def __iter__(self): """ make Portfolio iterable: for each x in Portfolio :return: """ return iter(self.agg_list) def __getitem__(self, item): """ allow Portfolio[slice] to return bits of agg_list :param item: :return: """ if type(item) == str: return self.agg_list[self.line_names.index(item)] return self.agg_list[item] @property def audit(self): """ Renamed version of the audit dataframe :return: """ if self.audit_df is not None: return self.audit_df.rename(columns=self.renamer, index=self.line_renamer).T @property def density(self): """ Renamed version of the density_df dataframe :return: """ if self.density_df is not None: return self.density_df.rename(columns=self.renamer) @property def augmented(self): """ Renamed version of the density_df dataframe :return: """ if self.augmented_df is not None: return self.augmented_df.rename(columns=self.renamer) @property def statistics(self): """ Renamed version of the statistics dataframe :return: """ return self.statistics_df.rename(columns=self.renamer) def json(self, stream=None): """ write object as json :param stream: :return: stream or text """ args = dict() args["bs"] = self.bs args["log2"] = self.log2 args["padding"] = self.padding args["tilt_amount"] = self.tilt_amount args["distortion"] = repr(self._distortion) args["sev_calc"] = self.sev_calc args["remove_fuzz"] = self._remove_fuzz args["approx_type"] = self.approx_type args["approx_freq_ge"] = self.approx_freq_ge args["last_update"] = str(self.last_update) args["hash_rep_at_last_update"] = str(self.hash_rep_at_last_update) d = dict() # original # d[self.name] = dict(args=args, spec=[a.spec for a in self.agg_list]) d['name'] = self.name d['args'] = args d['spec_list'] = [a._spec for a in self.agg_list] logger.debug(f'Portfolio.json| dummping {self.name} to {stream}') s = json.dumps(d) # , default_flow_style=False, indent=4) logger.debug(f'Portfolio.json | {s}') if stream is None: return s else: return stream.write(s) def save(self, filename='', mode='a'): """ persist to json in filename; if none save to user.json :param filename: :param mode: for file open :return: """ if filename == "": filename = Path.home() / 'agg/user.json' filename.parent.mkdir(parents=True, exist_ok=True) with filename.open(mode=mode, encoding='utf-8') as f: self.json(stream=f) logger.debug(f'Portfolio.save | {self.name} saved to {filename}') def __add__(self, other): """ Add two portfolio objects INDEPENDENT sum (down road can look for the same severity...) :param other: :return: """ assert isinstance(other, Portfolio) new_spec = [] for a in self.agg_list: c = deepcopy(a._spec) c['name'] = c['name'] new_spec.append(c) for a in other.agg_list: c = deepcopy(a._spec) c['name'] = c['name'] new_spec.append(c) return Portfolio(f'({self.name}) + ({other.name})', new_spec) def __rmul__(self, other): """ new = other * self; treat as scale change :param other: :return: """ assert other > 0 new_spec = [] for a in self.agg_list: new_spec.append(deepcopy(a._spec)) for d in new_spec: # d is a dictionary agg spec, need to adjust the severity s = d['severity'] if 'mean' in s: s['mean'] *= other elif 'scale' in s: s['scale'] *= other else: raise ValueError(f"Cannot adjust s['name'] for scale") return Portfolio(f'{other} x {self.name}', new_spec) def __mul__(self, other): """ new = self * other, other integer, sum of other independent copies :param other: :return: """ assert isinstance(other, int) new_spec = [] for a in self.agg_list: new_spec.append(deepcopy(a._spec)) for d in new_spec: # d is a dictionary agg spec, need to adjust the frequency # TODO better freq dists; deal with Bernoulli where n=log<1 d['frequency']['n'] *= other return Portfolio(f'Sum of {other} copies of {self.name}', new_spec) def snap(self, x): """ snap value x to the index of density_df :param x: :return: """ ix = self.density_df.index.get_loc(x, 'nearest') return self.density_df.iat[ix, 0] def audits(self, kind='all', **kwargs): """ produce audit plots to assess accuracy of outputs. Currently only exeqa available :param kind: :param kwargs: passed to pandas plot, e.g. set xlim :return: """ if kind == 'all': kind = ['exeqa'] for k in kind: if k == 'exeqa': temp = self.density_df.filter(regex='exeqa_.*(?<!total)$').copy() temp['sum'] = temp.sum(axis=1) temp['err'] = temp['sum'] - temp.index f, axs = plt.subplots(1, 2, figsize=(8, 3.75), constrained_layout=True) ax = axs.flatten() a = temp['err'].abs().plot(logy=True, title=f'Exeqa Sum Error', ax=ax[1], **kwargs) a.plot(self.density_df.loss, self.density_df.p_total, label='p_total') a.plot(self.density_df.loss, self.density_df.p_total * temp.err, label='prob wtd err') a.grid('b') a.legend(loc='lower left') if 'xlim' in kwargs: kwargs['ylim'] = kwargs['xlim'] temp.filter(regex='exeqa_.*(?<!total)$|sum').plot(title='exeqa and sum of parts', ax=ax[0], **kwargs).grid('b') f.suptitle(f'E[Xi | X=x] vs. Sum of Parts\nbs={self.bs}, log2={self.log2}, padding={self.padding}', fontsize='x-large') return f # for doc maker def get_stat(self, line='total', stat='EmpMean'): """ Other analysis suggests that iloc and iat are about same speed but slower than ix :param line: :param stat: :return: """ return self.audit_df.loc[line, stat] def q(self, p, kind='lower'): """ return lowest quantile, appropriate for discrete bucketing. quantile guaranteed to be in the index nearest does not work because you always want to pick rounding up Definition 2.1 (Quantiles) x(α) = qα(X) = inf{x ∈ R : P[X ≤ x] ≥ α} is the lower α-quantile of X x(α) = qα(X) = inf{x ∈ R : P[X ≤ x] > α} is the upper α-quantile of X. We use the x-notation if the dependence on X is evident, otherwise the q-notion. Acerbi and Tasche (2002) :param p: :param kind: allow upper or lower quantiles :return: """ if self._linear_quantile_function is None: # revised Dec 2019 self._linear_quantile_function = {} self.q_temp = self.density_df[['loss', 'F']].groupby('F').agg({'loss': np.min}) self.q_temp.loc[1, 'loss'] = self.q_temp.loss.iloc[-1] self.q_temp.loc[0, 'loss'] = 0 # revised Jan 2020 # F loss loss_s # 0.000000 0.0 0.0 # 0.667617 0.0 4500.0 # a value here is V and ^ which is the same: correct # 0.815977 4500.0 5500.0 # 0.937361 5500.0 9000.0 # upper and lower only differ at exact values of F where lower is loss and upper is loss_s # in between must take the next value for lower and the previous value for next to get the same answer self.q_temp = self.q_temp.sort_index() # that q_temp left cts, want right continuous: self.q_temp['loss_s'] = self.q_temp.loss.shift(-1) self.q_temp.iloc[-1, 1] = self.q_temp.iloc[-1, 0] # create interp functions # old # self._linear_quantile_function['upper'] = \ # interpolate.interp1d(self.q_temp.index, self.q_temp.loss_s, kind='previous', bounds_error=False, # fill_value='extrapolate') # self._linear_quantile_function['lower'] = \ # interpolate.interp1d(self.q_temp.index, self.q_temp.loss, kind='previous', bounds_error=False, # fill_value='extrapolate') # revised self._linear_quantile_function['upper'] = \ interpolate.interp1d(self.q_temp.index, self.q_temp.loss_s, kind='previous', bounds_error=False, fill_value='extrapolate') self._linear_quantile_function['lower'] = \ interpolate.interp1d(self.q_temp.index, self.q_temp.loss, kind='next', bounds_error=False, fill_value='extrapolate') # change to using loss_s self._linear_quantile_function['middle'] = \ interpolate.interp1d(self.q_temp.index, self.q_temp.loss_s, kind='linear', bounds_error=False, fill_value='extrapolate') l = float(self._linear_quantile_function[kind](p)) # because we are not interpolating the returned value must (should) be in the index... assert kind == 'middle' or l in self.density_df.index return l def cdf(self, x): """ distribution function :param x: :return: """ if self._cdf is None: # Dec 2019: kind='linear' --> kind='previous' self._cdf = interpolate.interp1d(self.density_df.loss, self.density_df.F, kind='previous', bounds_error=False, fill_value='extrapolate') return self._cdf(x) def sf(self, x): """ survival function :param x: :return: """ return 1 - self.cdf(x) def pdf(self, x): """ probability density function, assuming a continuous approximation of the bucketed density :param x: :return: """ if self._pdf is None: self._pdf = interpolate.interp1d(self.density_df.loss, self.density_df.p_total, kind='linear', bounds_error=False, fill_value='extrapolate') return self._pdf(x) / self.bs # # make some handy aliases; delete these go strictly with scipy.stats notation # def F(self, x): # """ # handy alias for distribution, CDF # :param x: # :return: # """ # return self.cdf(x) # # def S(self, x): # """ # handy alias for survival function, S # :param x: # :return: # """ # return self.sf(x) def var(self, p): """ value at risk = alias for quantile function :param p: :return: """ return self.q(p) def tvar(self, p, kind='interp'): """ Compute the tail value at risk at threshold p Really this function returns ES Definition 2.6 (Tail mean and Expected Shortfall) Assume E[X−] < ∞. Then x¯(α) = TM_α(X) = α^{−1}E[X 1{X≤x(α)}] + x(α) (α − P[X ≤ x(α)]) is α-tail mean at level α the of X. Acerbi and Tasche (2002) We are interested in the right hand exceedence [?? note > vs ≥] α^{−1}E[X 1{X > x(α)}] + x(α) (P[X ≤ x(α)] − α) McNeil etc. p66-70 - this follows from def of ES as an integral of the quantile function :param p: :param kind: 'interp' = interpolate exgta_total; 'tail' tail integral, 'body' NYI - (ex - body integral)/(1-p)+v 'inverse' from capital to p using interp method :return: """ assert self.density_df is not None if kind == 'tail': # original # _var = self.q(p) # ex = self.density_df.loc[_var + self.bs:, ['p_total', 'loss']].product(axis=1).sum() # pip = (self.density_df.loc[_var, 'F'] - p) * _var # t_var = 1 / (1 - p) * (ex + pip) # return t_var # revised if self._tail_var2 is None: self._tail_var2 = self.density_df[['p_total', 'loss']].product(axis=1).iloc[::-1].cumsum().iloc[::-1] _var = self.q(p) ex = self._tail_var2.loc[_var + self.bs] pip = (self.density_df.loc[_var, 'F'] - p) * _var t_var = 1 / (1 - p) * (ex + pip) return t_var elif kind == 'interp': # original implementation interpolated if self._tail_var is None: # make tvar function sup = (self.density_df.p_total[::-1] > 0).idxmax() if sup == self.density_df.index[-1]: sup = np.inf _x = self.density_df.F _y = self.density_df.exgta_total else: _x = self.density_df.F.values[:self.density_df.index.get_loc(sup)] _y = self.density_df.exgta_total.values[:self.density_df.index.get_loc(sup)] p0 = self.density_df.at[0., 'F'] if p0 > 0: ps = np.linspace(0, p0, 200, endpoint=False) tempx = np.hstack((ps, _x)) tempy = np.hstack((self.ex / (1-ps), _y)) self._tail_var = interpolate.interp1d(tempx, tempy, kind='linear', bounds_error=False, fill_value=(self.ex, sup)) else: self._tail_var = interpolate.interp1d(_x, _y, kind='linear', bounds_error=False, fill_value=(self.ex, sup)) if type(p) in [float, np.float]: return float(self._tail_var(p)) else: return self._tail_var(p) elif kind == 'inverse': if self._inverse_tail_var is None: # make tvar function self._inverse_tail_var = interpolate.interp1d(self.density_df.exgta_total, self.density_df.F, kind='linear', bounds_error=False, fill_value='extrapolate') if type(p) in [int, np.int, float, np.float]: return float(self._inverse_tail_var(p)) else: return self._inverse_tail_var(p) else: raise ValueError(f'Inadmissible kind passed to tvar; options are interp (default), inverse, or tail') def tvar_threshold(self, p, kind): """ Find the value pt such that TVaR(pt) = VaR(p) using numerical Newton Raphson """ a = self.q(p, kind) def f(p): return self.tvar(p) - a loop = 0 p1 = 1 - 2 * (1 - p) fp1 = f(p1) delta = 1e-5 while abs(fp1) > 1e-6 and loop < 10: df1 = (f(p1 + delta) - fp1) / delta p1 = p1 - fp1 / df1 fp1 = f(p1) loop += 1 if loop == 10: raise ValueError(f'Difficulty computing TVaR to match VaR at p={p}') return p1 def equal_risk_var_tvar(self, p_v, p_t): """ solve for equal risk var and tvar: find pv and pt such that sum of individual line VaR/TVaR at pv/pt equals the VaR(p) or TVaR(p_t) these won't return elements in the index because you have to interpolate hence using kind=middle """ # these two should obviously be the same target_v = self.q(p_v, 'middle') target_t = self.tvar(p_t) def fv(p): return sum([float(a.q(p, 'middle')) for a in self]) - target_v def ft(p): return sum([float(a.tvar(p)) for a in self]) - target_t ans = np.zeros(2) for i, f in enumerate([fv, ft]): p1 = 1 - 2 * (1 - (p_v if i == 0 else p_t)) fp1 = f(p1) loop = 0 delta = 1e-5 while abs(fp1) > 1e-6 and loop < 10: dfp1 = (f(p1 + delta) - fp1) / delta p1 = p1 - fp1 / dfp1 fp1 = f(p1) loop += 1 if loop == 100: raise ValueError(f'Trouble finding equal risk {"TVaR" if i else "VaR"} at p_v={p_v}, p_t={p_t}. ' 'No convergence after 100 iterations. ') ans[i] = p1 return ans def equal_risk_epd(self, a): """ determine the common epd threshold so sum sa equals a """ def f(p): return sum([self.epd_2_assets[(l, 0)](p) for l in self.line_names]) - a p1 = self.assets_2_epd[('total', 0)](a) fp1 = f(p1) loop = 0 delta = 1e-5 while abs(fp1) > 1e-6 and loop < 10: dfp1 = (f(p1 + delta) - fp1) / delta p1 = p1 - fp1 / dfp1 fp1 = f(p1) loop += 1 if loop == 100: raise ValueError(f'Trouble finding equal risk EPD at pe={pe}. No convergence after 100 iterations. ') return p1 def merton_perold(self, p, kind='lower'): """ compute <NAME>old capital allocation at VaR(p) capital using VaR as risk measure v = q(p) TODO TVaR version of <NAME> """ # figure total assets a = self.q(p, kind) # shorthand abbreviation df = self.density_df loss = df.loss ans = [] total = 0 for l in self.line_names: q = self.density_df.loss.iloc[np.searchsorted(self.density_df[f'ημ_{l}'].cumsum(), .995, side='right')] diff = a - q ans.append(diff) total += diff ans.append(total) return ans def cotvar(self, p): """ make the p co-tvar asset allocation using ISA Asset alloc = exgta = tail expected value, treating TVaR like a pricing variable """ av = self.q(p) return self.density_df.loc[av, [f'exgta_{l}' for l in self.line_names_ex]].values def as_severity(self, limit=np.inf, attachment=0, conditional=False): """ convert into a severity without recomputing throws error if self not updated :param limit: :param attachment: :param conditional: :return: """ if self.density_df is None: raise ValueError('Must update prior to converting to severity') return Severity(sev_name=self, sev_a=self.log2, sev_b=self.bs, exp_attachment=attachment, exp_limit=limit, sev_conditional=conditional) def fit(self, approx_type='slognorm', output='agg'): """ returns a dictionary specification of the portfolio aggregate_project if updated uses empirical moments, otherwise uses theoretic moments :param approx_type: slognorm | sgamma :param output: return a dict or agg language specification :return: """ if self.audit_df is None: # not updated m = self.statistics_df.loc[('agg', 'mean'), 'total'] cv = self.statistics_df.loc[('agg', 'cv'), 'total'] skew = self.statistics_df.loc[('agg', 'skew'), 'total'] else: # use statistics_df matched to computed aggregate_project m, cv, skew = self.audit_df.loc['total', ['EmpMean', 'EmpCV', 'EmpSkew']] name = f'{approx_type[0:4]}~{self.name[0:5]}' agg_str = f'agg {name} 1 claim sev ' if approx_type == 'slognorm': shift, mu, sigma = sln_fit(m, cv, skew) # self.fzapprox = ss.lognorm(sigma, scale=np.exp(mu), loc=shift) sev = {'sev_name': 'lognorm', 'sev_shape': sigma, 'sev_scale': np.exp(mu), 'sev_loc': shift} agg_str += f'{np.exp(mu)} * lognorm {sigma} + {shift} ' elif approx_type == 'sgamma': shift, alpha, theta = sgamma_fit(m, cv, skew) # self.fzapprox = ss.gamma(alpha, scale=theta, loc=shift) sev = {'sev_name': 'gamma', 'sev_a': alpha, 'sev_scale': theta, 'sev_loc': shift} agg_str += f'{theta} * lognorm {alpha} + {shift} ' else: raise ValueError(f'Inadmissible approx_type {approx_type} passed to fit') if output == 'agg': agg_str += ' fixed' return agg_str else: return {'name': name, 'note': f'frozen version of {self.name}', 'exp_en': 1, **sev, 'freq_name': 'fixed'} def collapse(self, approx_type='slognorm'): """ returns new Portfolio with the fit Deprecated...prefer uw(self.fit()) to go through the agg language approach :param approx_type: slognorm | sgamma :return: """ spec = self.fit(approx_type, output='dict') logger.debug(f'Portfolio.collapse | Collapse created new Portfolio with spec {spec}') logger.warning(f'Portfolio.collapse | Collapse is deprecated; use fit() instead.') return Portfolio(f'Collapsed {self.name}', [spec]) def percentiles(self, pvalues=None): """ report_ser on percentiles and large losses uses interpolation, audit_df uses nearest :pvalues: optional vector of log values to use. If None sensible defaults provided :return: DataFrame of percentiles indexed by line and log """ df = pd.DataFrame(columns=['line', 'log', 'Agg Quantile']) df = df.set_index(['line', 'log']) # df.columns.name = 'perspective' if pvalues is None: pvalues = [0.5, 0.75, 0.8, 0.85, 0.9, 0.95, 0.98, 0.99, 0.994, 0.995, 0.999, 0.9999] for line in self.line_names_ex: q_agg = interpolate.interp1d(self.density_df[f'p_{line}'].cumsum(), self.density_df.loss, kind='linear', bounds_error=False, fill_value='extrapolate') for p in pvalues: qq = q_agg(p) df.loc[(line, p), :] = [float(qq)] df = df.unstack(level=1) return df def recommend_bucket(self): """ data to help estimate a good bucket size :return: """ df = pd.DataFrame(columns=['line', 'bs10']) df = df.set_index('line') for a in self.agg_list: df.loc[a.name, :] = [a.recommend_bucket(10)] df['bs11'] = df['bs10'] / 2 df['bs12'] = df['bs10'] / 4 df['bs13'] = df['bs10'] / 8 df['bs14'] = df['bs10'] / 16 df['bs15'] = df['bs10'] / 32 df['bs16'] = df['bs10'] / 64 df['bs17'] = df['bs10'] / 128 df['bs18'] = df['bs10'] / 256 df['bs19'] = df['bs10'] / 515 df['bs20'] = df['bs10'] / 1024 df.loc['total', :] = df.sum() return df def best_bucket(self, log2=16): bs = sum([a.recommend_bucket(log2) for a in self]) return round_bucket(bs) def update(self, log2, bs, approx_freq_ge=100, approx_type='slognorm', remove_fuzz=False, sev_calc='discrete', discretization_calc='survival', normalize=True, padding=1, tilt_amount=0, epds=None, trim_df=False, verbose=False, add_exa=True, aggregate_cession_function=None): """ create density_df, performs convolution. optionally adds additional information if ``add_exa=True`` for allocation and priority analysis tilting: [@Grubel1999]: Computation of Compound Distributions I: Aliasing Errors and Exponential Tilting (ASTIN 1999) tilt x numbuck < 20 is recommended log. 210 num buckets and max loss from bucket size :param log2: :param bs: bucket size :param approx_freq_ge: use method of moments if frequency is larger than ``approx_freq_ge`` :param approx_type: type of method of moments approx to use (slognorm or sgamma) :param remove_fuzz: remove machine noise elements from FFT :param sev_calc: how to calculate the severity, discrete (point masses as xs) or continuous (uniform between xs points) :param discretization_calc: survival or distribution (accurate on right or left tails) :param normalize: if true, normalize the severity so sum probs = 1. This is generally what you want; but :param padding: for fft 1 = double, 2 = quadruple :param tilt_amount: for tiling methodology - see notes on density for suggested parameters :param epds: epd points for priority analysis; if None-> sensible defaults :param trim_df: remove unnecessary columns from density_df before returning :param verbose: level of output :param add_exa: run add_exa to append additional allocation information needed for pricing; if add_exa also add epd info :param aggregate_cession_function: function of Portfolio object that adjusts individual line densities; applied after line aggs created but before creating not-lines; actual statistics do not reflect impact. :return: """ self.log2 = log2 self.bs = bs self.padding = padding self.tilt_amount = tilt_amount self.approx_type = approx_type self.sev_calc = sev_calc self._remove_fuzz = remove_fuzz self.approx_type = approx_type self.approx_freq_ge = approx_freq_ge self.discretization_calc = discretization_calc if self.hash_rep_at_last_update == hash(self): logger.warning(f'Nothing has changed since last update at {self.last_update}') return self._linear_quantile_function = None ft_line_density = {} # line_density = {} # not_line_density = {} # add the densities # tilting: [@Grubel1999]: Computation of Compound Distributions I: Aliasing Errors and Exponential Tilting # (ASTIN 1999) # tilt x numbuck < 20 recommended log. 210 # num buckets and max loss from bucket size N = 1 << log2 MAXL = N * bs xs = np.linspace(0, MAXL, N, endpoint=False) # make all the single line aggs # note: looks like duplication but will all be references # easier for add_exa to have as part of the portfolio module # tilt if self.tilt_amount != 0: tilt_vector = np.exp(self.tilt_amount * np.arange(N)) else: tilt_vector = None # where the answer will live self.density_df = pd.DataFrame(index=xs) self.density_df['loss'] = xs ft_all = None for agg in self.agg_list: raw_nm = agg.name nm = f'p_{agg.name}' _a = agg.update(xs, self.padding, tilt_vector, 'exact' if agg.n < approx_freq_ge else approx_type, sev_calc, discretization_calc, normalize, verbose=verbose) if verbose: display(_a) if aggregate_cession_function is not None: aggregate_cession_function(agg, self.padding, tilt_vector) ft_line_density[raw_nm] = agg.ftagg_density self.density_df[nm] = agg.agg_density if ft_all is None: ft_all = np.copy(ft_line_density[raw_nm]) else: ft_all *= ft_line_density[raw_nm] self.density_df['p_total'] = np.real(ift(ft_all, self.padding, tilt_vector)) # ft_line_density['total'] = ft_all # make the not self.line_density = sum of all but the given line # have the issue here that if you divide and the dist # is symmetric then you get a div zero... for line in self.line_names: ft_not = np.ones_like(ft_all) if np.any(ft_line_density[line] == 0): # have to build up for not_line in self.line_names: if not_line != line: ft_not *= ft_line_density[not_line] else: if len(self.line_names) > 1: ft_not = ft_all / ft_line_density[line] self.density_df[f'ημ_{line}'] = np.real(ift(ft_not, self.padding, tilt_vector)) self.remove_fuzz(log='update') # make audit statistics_df df theoretical_stats = self.statistics_df.T.filter(regex='agg') theoretical_stats.columns = ['EX1', 'EX2', 'EX3', 'Mean', 'CV', 'Skew', 'Limit', 'P99.9Est'] theoretical_stats = theoretical_stats[['Mean', 'CV', 'Skew', 'Limit', 'P99.9Est']] # self.audit_percentiles = [0.9, 0.95, 0.99, 0.995, 0.996, 0.999, 0.9999, 1 - 1e-6] self.audit_df = pd.DataFrame( columns=['Sum probs', 'EmpMean', 'EmpCV', 'EmpSkew', "EmpKurt", 'EmpEX1', 'EmpEX2', 'EmpEX3'] + ['P' + str(100 * i) for i in self.audit_percentiles]) for col in self.line_names_ex: sump = np.sum(self.density_df[f'p_{col}']) t = self.density_df[f'p_{col}'] * self.density_df['loss'] ex1 = np.sum(t) t *= self.density_df['loss'] ex2 = np.sum(t) t *= self.density_df['loss'] ex3 = np.sum(t) t *= self.density_df['loss'] ex4 = np.sum(t) m, cv, s = MomentAggregator.static_moments_to_mcvsk(ex1, ex2, ex3) # empirical kurtosis kurt = (ex4 - 4 * ex3 * ex1 + 6 * ex1 ** 2 * ex2 - 3 * ex1 ** 4) / ((m * cv) ** 4) - 3 ps = np.zeros((len(self.audit_percentiles))) temp = self.density_df[f'p_{col}'].cumsum() for i, p in enumerate(self.audit_percentiles): ps[i] = (temp > p).idxmax() newrow = [sump, m, cv, s, kurt, ex1, ex2, ex3] + list(ps) self.audit_df.loc[col, :] = newrow self.audit_df = pd.concat((theoretical_stats, self.audit_df), axis=1, sort=True) self.audit_df['MeanErr'] = self.audit_df['EmpMean'] / self.audit_df['Mean'] - 1 self.audit_df['CVErr'] = self.audit_df['EmpCV'] / self.audit_df['CV'] - 1 self.audit_df['SkewErr'] = self.audit_df['EmpSkew'] / self.audit_df['Skew'] - 1 # add exa details if add_exa: self.add_exa(self.density_df, details=True) # default priority analysis logger.debug('Adding EPDs in Portfolio.update') if epds is None: epds = np.hstack( [np.linspace(0.5, 0.1, 4, endpoint=False)] + [np.linspace(10 ** -n, 10 ** -(n + 1), 9, endpoint=False) for n in range(1, 7)]) epds = np.round(epds, 7) self.priority_capital_df = pd.DataFrame(index=pd.Index(epds)) for col in self.line_names: for i in range(3): self.priority_capital_df['{:}_{:}'.format(col, i)] = self.epd_2_assets[(col, i)](epds) self.priority_capital_df['{:}_{:}'.format('total', 0)] = self.epd_2_assets[('total', 0)]( epds) col = 'not ' + col for i in range(2): self.priority_capital_df['{:}_{:}'.format(col, i)] = self.epd_2_assets[(col, i)](epds) self.priority_capital_df['{:}_{:}'.format('total', 0)] = self.epd_2_assets[('total', 0)](epds) self.priority_capital_df.columns = self.priority_capital_df.columns.str.split("_", expand=True) self.priority_capital_df.sort_index(axis=1, level=1, inplace=True) self.priority_capital_df.sort_index(axis=0, inplace=True) else: # at least want F and S to get quantile functions self.density_df['F'] = np.cumsum(self.density_df.p_total) self.density_df['S'] = 1 - self.density_df.F self.ex = self.audit_df.loc['total', 'EmpMean'] self.last_update = np.datetime64('now') self.hash_rep_at_last_update = hash(self) if trim_df: self.trim_df() # invalidate stored functions self._linear_quantile_function = None self.q_temp = None self._cdf = None def update_efficiently(self, log2, bs, approx_freq_ge=100, approx_type='slognorm', sev_calc='discrete', discretization_calc='survival', normalize=True, padding=1): """ runs stripped down versions of update and add_exa - bare bones code copied from those routines and cleaned for comments etc. :param log2: :param bs: :param approx_freq_ge: :param approx_type: :param remove_fuzz: :param sev_calc: :param discretization_calc: :param padding: :return: """ self.log2 = log2 self.bs = bs self.padding = padding self.approx_type = approx_type self.sev_calc = sev_calc self._remove_fuzz = True self.approx_type = approx_type self.approx_freq_ge = approx_freq_ge self.discretization_calc = discretization_calc ft_line_density = {} N = 1 << log2 MAXL = N * bs xs = np.linspace(0, MAXL, N, endpoint=False) # no tilt for efficient mode tilt_vector = None # where the answer will live self.density_df = pd.DataFrame(index=xs) self.density_df['loss'] = xs ft_all = None for agg in self.agg_list: raw_nm = agg.name nm = f'p_{agg.name}' _a = agg.update_efficiently(xs, self.padding, 'exact' if agg.n < approx_freq_ge else approx_type, sev_calc, discretization_calc, normalize) ft_line_density[raw_nm] = agg.ftagg_density self.density_df[nm] = agg.agg_density if ft_all is None: ft_all = np.copy(ft_line_density[raw_nm]) else: ft_all *= ft_line_density[raw_nm] self.density_df['p_total'] = np.real(ift(ft_all, self.padding, tilt_vector)) # make the not self.line_density = sum of all but the given line ft_nots = {} for line in self.line_names: ft_not = np.ones_like(ft_all) if np.any(ft_line_density[line] == 0): # have to build up for not_line in self.line_names: if not_line != line: ft_not *= ft_line_density[not_line] else: if len(self.line_names) > 1: ft_not = ft_all / ft_line_density[line] self.density_df[f'ημ_{line}'] = np.real(ift(ft_not, self.padding, tilt_vector)) ft_nots[line] = ft_not self.remove_fuzz(log='update_efficiently') # no audit statistics_df # BEGIN add_exa ================================================================================================ # add exa details now in-line # def add_exa(self, df, details, ft_nots=None): # Call is self.add_exa(self.density_df, details=True) # name in add_exa, keeps code shorter df = self.density_df cut_eps = np.finfo(np.float).eps # sum of p_total is so important...we will rescale it... if not np.all(df.p_total >= 0): # have negative densities...get rid of them first_neg = np.argwhere((df.p_total < 0).to_numpy()).min() sum_p_total = df.p_total.sum() df['F'] = np.cumsum(df.p_total) df['S'] = \ df.p_total.shift(-1, fill_value=min(df.p_total.iloc[-1], max(0, 1. - (df.p_total.sum()))))[::-1].cumsum()[::-1] # E(min(X, a)) # df['exa_total'] = self.cumintegral(df['S']) df['exa_total'] = df.S.shift(1, fill_value=0).cumsum() * self.bs df['lev_total'] = df['exa_total'] df['exlea_total'] = \ (df.exa_total - df.loss * df.S) / df.F n_ = df.shape[0] if n_ < 1100: mult = 1 elif n_ < 15000: mult = 10 else: mult = 100 loss_max = df[['loss', 'exlea_total']].query(' exlea_total>loss ').loss.max() if np.isnan(loss_max): loss_max = 0 else: loss_max += mult * bs # try nan in place of 0 V df.loc[0:loss_max, 'exlea_total'] = np.nan df['e_total'] = np.sum(df.p_total * df.loss) df['exgta_total'] = df.loss + (df.e_total - df.exa_total) / df.S df['exeqa_total'] = df.loss # E(X | X=a) = a(!) included for symmetry was exa # FFT functions for use in exa calculations # computing sums so minimal padding required def loc_ft(x): return ft(x, 1, None) def loc_ift(x): return ift(x, 1, None) # where is S=0 Seq0 = (df.S == 0) for col in self.line_names: df['exeqa_' + col] = \ np.real(loc_ift(loc_ft(df.loss * df['p_' + col]) * ft_nots[col])) / df.p_total df.loc[df.p_total < cut_eps, 'exeqa_' + col] = 0 df['exeqa_ημ_' + col] = \ np.real(loc_ift(loc_ft(df.loss * df['ημ_' + col]) * loc_ft(df['p_' + col]))) / df.p_total df.loc[df.p_total < cut_eps, 'exeqa_ημ_' + col] = 0 stemp = 1 - df['p_' + col].cumsum() # df['lev_' + col] = self.cumintegral(stemp) df['lev_' + col] = stemp.shift(1, fill_value=0).cumsum() * self.bs stemp = 1 - df['ημ_' + col].cumsum() df['lev_ημ_' + col] = stemp.shift(1, fill_value=0).cumsum() * self.bs # EX_i | X<= a; temp is used in le and gt calcs temp = np.cumsum(df['exeqa_' + col] * df.p_total) df['exlea_' + col] = temp / df.F df.loc[0:loss_max, 'exlea_' + col] = 0 # df.loc[0:loss_max, 'loss'] temp_not = np.cumsum(df['exeqa_ημ_' + col] * df.p_total) df['exlea_ημ_' + col] = temp_not / df.F df.loc[0:loss_max, 'exlea_ημ_' + col] = 0 # df.loc[0:loss_max, 'loss'] # constant value, helpful in calculations # df['e_' + col] = np.sum(df['p_' + col] * df.loss) # df['e_ημ_' + col] = np.sum(df['ημ_' + col] * df.loss) # # df['exgta_' + col] = (df['e_' + col] - temp) / df.S # temp = df.loss.iloc[0] # loss # df.loss.iloc[0] = 1 # avoid divide by zero # # # df['exi_x_' + col] = np.sum( # # df['exeqa_' + col] * df.p_total / df.loss) # temp_xi_x = np.cumsum(df['exeqa_' + col] * df.p_total / df.loss) # df['exi_xlea_' + col] = temp_xi_x / df.F # df.loc[0, 'exi_xlea_' + col] = 0 # df.F=0 at zero # # more generally F=0 error: V # df.loc[df.exlea_total == 0, 'exi_xlea_' + col] = 0 # # not version # df['exi_x_ημ_' + col] = np.sum( # df['exeqa_ημ_' + col] * df.p_total / df.loss) # # as above # temp_xi_x_not = np.cumsum( # df['exeqa_ημ_' + col] * df.p_total / df.loss) # df['exi_xlea_ημ_' + col] = temp_xi_x_not / df.F # df.loc[0, 'exi_xlea_ημ_' + col] = 0 # df.F=0 at zero # # more generally F=0 error: # df.loc[df.exlea_total == 0, 'exi_xlea_ημ_' + col] = 0 # # put value back # df.loss.iloc[0] = temp # this is so important we will calculate it directly df['exi_xgta_' + col] = ((df[f'exeqa_{col}'] / df.loss * df.p_total).shift(-1)[ ::-1].cumsum()) / df.S # need this NOT to be nan otherwise exa won't come out correctly df.loc[Seq0, 'exi_xgta_' + col] = 0. df['exi_xgta_ημ_' + col] = ((df[f'exeqa_ημ_{col}'] / df.loss * df.p_total).shift(-1)[ ::-1].cumsum()) / df.S df.loc[Seq0, 'exi_xgta_ημ_' + col] = 0. df['exi_xeqa_' + col] = df['exeqa_' + col] / df['loss'] df.loc[0, 'exi_xeqa_' + col] = 0 df['exi_xeqa_ημ_' + col] = df['exeqa_ημ_' + col] / df['loss'] df.loc[0, 'exi_xeqa_ημ_' + col] = 0 df[f'exa_{col}'] = (df.S * df['exi_xgta_' + col]).shift(1, fill_value=0).cumsum() * self.bs df['exa_ημ_' + col] = (df.S * df['exi_xgta_ημ_' + col]).shift(1, fill_value=0).cumsum() * self.bs # END add_exa ================================================================================================== self.last_update = np.datetime64('now') # invalidate stored functions self._linear_quantile_function = None self.q_temp = None self._cdf = None def trim_df(self): """ trim out unwanted columns from density_df epd used in graphics :return: """ self.density_df = self.density_df.drop( self.density_df.filter(regex='^e_|^exi_xlea|^[a-z_]+ημ').columns, axis=1 ) def gradient(self, epsilon=1 / 128, kind='homog', method='forward', distortion=None, remove_fuzz=True, extra_columns=None, do_swap=True): """ Compute the gradient of various quantities relative to a change in the volume of each portfolio component. Focus is on the quantities used in rate calculations: S, gS, p_total, exa, exag, exi_xgta, exi_xeqq, exeqa, exgta etc. homog: inhomog: :param epsilon: the increment to use; scale is 1+epsilon :param kind: homog[ogeneous] or inhomog: homog computes impact of f((1+epsilon)X_i)-f(X_i). Inhomog scales the frequency and recomputes. Note inhomog will have a slight scale issues with E[Severity] :param method: forward, central (using epsilon/2) or backwards :param distortion: if included derivatives of statistics using the distortion, such as exag are also computed :param extra_columns: extra columns to compute dervs of. Note there is virtually no overhead of adding additional columns :param do_swap: force the step to replace line with line+epsilon in all not line2's line2!=line1; whether you need this or not depends on what variables you to be differentiated. E.g. if you ask for exa_total only you don't need to swap. But if you want exa_A, exa_B you do, otherwise the d/dA exa_B won't be correct. TODO: replace with code! :return: DataFrame of gradients and audit_df in an Answer class """ if kind == 'inhomog' or kind[:7] == 'inhomog': raise NotImplementedError(f'kind=={kind} not yet implemented') if method == 'central': raise NotImplementedError(f'method=={method} not yet implemented') if method not in ('forward', 'backwards', 'central'): raise ValueError('Inadmissible option passed to gradient.') if self.tilt_amount: raise ValueError('Gradients do not allow tilts') # central = run this code forwards and backwards with epsilon / 2 and average?! # Forwards or backwards if method == 'forward': delta = 1 + epsilon dx = epsilon pm = '+' else: delta = 1 - epsilon dx = -epsilon pm = '-' # FFT functions for use in exa calculations; padding needs to be consistent with agg def loc_ft(x): return ft(x, self.padding, None) def loc_ift(x): return ift(x, self.padding, None) # setup (compare self.update) xs = self.density_df['loss'].values tilt_vector = None # (1+e)X computed for each line agg_epsilon_df = pd.DataFrame(index=xs) # compute the individual line (1+epsilon)X_i and then the revised total new_aggs = {} for base_agg in self.agg_list: agg = base_agg.rescale(delta, kind) new_aggs[base_agg.name] = agg _a = agg.update(xs, self.padding, tilt_vector, 'exact' if agg.n < self.approx_freq_ge else self.approx_type, self.sev_calc, self.discretization_calc, verbose=False) agg_epsilon_df[f'p_{agg.name}'] = agg.agg_density # the total with the line incremented agg_epsilon_df[f'p_total_{agg.name}'] = \ np.real(loc_ift(agg.ftagg_density * loc_ft(self.density_df[f'ημ_{agg.name}']))) self.remove_fuzz(df=agg_epsilon_df, force=remove_fuzz, log='gradient') percentiles = [0.9, 0.95, 0.99, 0.996, 0.999, 0.9999, 1 - 1e-6] audit_df = pd.DataFrame( columns=['Sum probs', 'EmpMean', 'EmpCV', 'EmpSkew', 'EmpEX1', 'EmpEX2', 'EmpEX3'] + ['P' + str(100 * i) for i in percentiles]) # 949 = epsilon 916 Delta ep = chr(949) D = chr(916) for col in agg_epsilon_df.columns: sump = np.sum(agg_epsilon_df[col]) t = agg_epsilon_df[col] * xs ex1 = np.sum(t) t *= xs ex2 = np.sum(t) t *= xs ex3 = np.sum(t) m, cv, s = MomentAggregator.static_moments_to_mcvsk(ex1, ex2, ex3) ps = np.zeros((len(percentiles))) temp = agg_epsilon_df[col].cumsum() for i, p in enumerate(percentiles): ps[i] = (temp > p).idxmax() audit_df.loc[f'{col[2:]}{pm}{ep}', :] = [sump, m, cv, s, ex1, ex2, ex3] + list(ps) for l in self.line_names_ex: audit_df.loc[l, :] = self.audit_df.loc[l, :] # differences for l in self.line_names: audit_df.loc[f'{l}{D}', :] = audit_df.loc[f'{l}{pm}{ep}'] - audit_df.loc[l] audit_df.loc[f'total_{l}{D}', :] = audit_df.loc[f'total_{l}{pm}{ep}'] - audit_df.loc['total'] audit_df = audit_df.sort_index() # now need to iterate through each line to compute differences # variables we want to differentiate # note asking for derv of exa_A makes things a lot more complex...see swap function below # may want to default to not including that? columns_of_interest = ['S'] + [f'exa_{line}' for line in self.line_names_ex] if extra_columns: columns_of_interest += extra_columns # these are the columns add_exa expects columns_p_only = ['loss'] + [f'p_{line}' for line in self.line_names_ex] + \ [f'ημ_{line}' for line in self.line_names] # first, need a base and add exag to coi if distortion: _x = self.apply_distortion(distortion, create_augmented=False) base = _x.augmented_df columns_of_interest.extend(['gS'] + [f'exag_{line}' for line in self.line_names_ex]) else: base = self.density_df # and then a holder for the answer answer = pd.DataFrame(index=pd.Index(xs, name='loss'), columns=pd.MultiIndex.from_arrays(((), ()), names=('partial_wrt', 'line'))) answer.columns.name = 'derivatives' # the exact same as add exa; same padding no tilt def ae_ft(x): return ft(x, 1, None) def swap(adjust_line): """ in the not line swap A for Ae E.g. X = A + B + C and adjust_Line = A. Then not A is the same, but for not B and not C you need to swap A with A+epsilon. This function accomplishes the swap. :param ημ: :param A: :param Ae: :return: collection of all not lines with adjusted adjust_line adjusted_not_fft[line] is fft of not_line with adjust_line swapped out for line + epsilon """ # look if there are just two lines then this is easy......but want to see if this works too... adjusted_not_fft = {} adjust_line_ft = ae_ft(agg_epsilon_df[f'p_{adjust_line}']) base_line_ft = ae_ft(base[f'p_{adjust_line}']) adj_factor = adjust_line_ft / base_line_ft adj_factor[np.logical_and(base_line_ft == 0, adjust_line_ft == 0)] = 0 n_and = np.sum(np.logical_and(base_line_ft == 0, adjust_line_ft == 0)) n_or = np.sum(np.logical_or(base_line_ft == 0, adjust_line_ft == 0)) # TODO sort this out...often not actually the same... logger.info(f'SAME? And={n_and} Or={n_or}; Zeros in fft(line) and ' 'fft(line + epsilon for {adjust_line}.') for line in self.line_names: if line == adjust_line: # nothing changes, adjust_line not in not adjust_line it doesn't need to change adjusted_not_fft[line] = ae_ft(base[f'ημ_{line}']) else: adjusted_not_fft[line] = ae_ft(base[f'ημ_{line}']) * adj_factor return adjusted_not_fft # finally perform iteration and compute differences for line in self.line_names: gradient_df = base[columns_p_only].copy() gradient_df[f'p_{line}'] = agg_epsilon_df[f'p_{line}'] gradient_df['p_total'] = agg_epsilon_df[f'p_total_{line}'] if do_swap: # we also need to update ημ_lines whenever it includes line (i.e. always # call original add_exa function, operates on gradient_df in-place self.add_exa(gradient_df, details=False, ft_nots=swap(line)) else: self.add_exa(gradient_df, details=False) if distortion is not None: # apply to line + epsilon gradient_df = self.apply_distortion(distortion, df_in=gradient_df, create_augmented=False).augmented_df # compute differentials and store answer! # print(columns_of_interest) # print([(line, i) for i in columns_of_interest]) # print(type(gradient_df)) # temp0 = gradient_df[columns_of_interest] # temp1 = base[columns_of_interest] # temp2 = (temp0 - temp1) / dx answer[[(line, i) for i in columns_of_interest]] = (gradient_df[columns_of_interest] - base[columns_of_interest]) / dx return Answer(gradient=answer, audit=audit_df, new_aggs=new_aggs) def report(self, report_list='quick'): """ :param report_list: :return: """ full_report_list = ['statistics', 'quick', 'audit', 'priority_capital', 'priority_analysis'] if report_list == 'all': report_list = full_report_list for r in full_report_list: if r in report_list: html_title(f'{r} Report for {self.name}', 1) if r == 'priority_capital': if self.priority_capital_df is not None: display(self.priority_capital_df.loc[1e-3:1e-2, :].style) else: html_title(f'Report {r} not generated', 2) elif r == 'quick': if self.audit_df is not None: df = self.audit_df[['Mean', 'EmpMean', 'MeanErr', 'CV', 'EmpCV', 'CVErr', 'P99.0']] display(df.style) else: html_title(f'Report {r} not generated', 2) else: df = getattr(self, r + '_df', None) if df is not None: try: display(df.style) except ValueError: display(df) else: html_title(f'Report {r} not generated', 2) def plot(self, kind='density', line='all', p=0.99, c=0, a=0, axiter=None, figsize=None, height=2, aspect=1, **kwargs): """ kind = density simple plotting of line density or not line density; input single line or list of lines; log underscore appended as appropriate kind = audit Miscellaneous audit graphs kind = priority LEV EXA, E2Pri and combined plots by line kind = quick four bar charts of EL etc. kind = collateral plot to illustrate bivariate density of line vs not line with indicated asset a and capital c :param kind: density | audit | priority | quick | collateral :param line: lines to use, defaults to all :param p: for graphics audit, x-axis scale has maximum q(p) :param c: collateral amount :param a: asset amount :param axiter: optional, pass in to use existing ``axiter`` :param figsize: arguments passed to axis_factory if no axiter :param height: :param aspect: :param kwargs: passed to pandas plot routines :return: """ do_tight = (axiter is None) if kind == 'quick': if self.audit_df is not None: axiter = axiter_factory(axiter, 4, figsize, height, aspect) else: axiter = axiter_factory(axiter, 3, figsize, height, aspect) self.statistics_df.loc[('agg', 'mean')]. \ sort_index(ascending=True, axis=0). \ plot(kind='bar', rot=-45, title='Expected Loss', ax=next(axiter)) self.statistics_df.loc[('agg', 'cv')]. \ sort_index(ascending=True, axis=0). \ plot(kind='bar', rot=-45, title='Coeff of Variation', ax=next(axiter)) self.statistics_df.loc[('agg', 'skew')]. \ sort_index(ascending=True, axis=0). \ plot(kind='bar', rot=-45, title='Skewness', ax=next(axiter)) if self.audit_df is not None: self.audit_df['P99.9']. \ sort_index(ascending=True, axis=0). \ plot(kind='bar', rot=-45, title='99.9th Percentile', ax=next(axiter)) elif kind == 'density': if isinstance(line, str): if line == 'all': line = [f'p_{i}' for i in self.line_names_ex] else: line = ['p_' + line] elif isinstance(line, list): line = ['p_' + i if i[0:2] != 'ημ' else i for i in line] else: raise ValueError line = sorted(line) if 'subplots' in kwargs and len(line) > 1: axiter = axiter_factory(axiter, len(line), figsize, height, aspect) ax = axiter.grid(len(line)) else: axiter = axiter_factory(axiter, 1, figsize, height, aspect) # want to be able to pass an axis in rather than an axiter... if isinstance(axiter, AxisManager): ax = axiter.grid(1) else: ax = axiter self.density_df[line].sort_index(axis=1). \ plot(sort_columns=True, ax=ax, **kwargs) if 'logy' in kwargs: _t = 'log Density' else: _t = 'Density' if 'subplots' in kwargs and isinstance(ax, collections.Iterable): for a, l in zip(ax, line): a.set(title=f'{l} {_t}') a.legend().set_visible(False) elif isinstance(ax, collections.Iterable): for a in ax: a.set(title=f'{_t}') else: ax.set(title=_t) elif kind == 'audit': D = self.density_df # n_lines = len(self.line_names_ex) n_plots = 12 # * n_lines + 8 # assumes that not lines have been taken out! axiter = axiter_factory(axiter, n_plots, figsize, height, aspect) # make appropriate scales density_scale = D.filter(regex='^p_').iloc[1:, :].max().max() expected_loss_scale = np.sum(D.loss * D.p_total) * 1.05 large_loss_scale = (D.p_total.cumsum() > p).idxmax() # densities temp = D.filter(regex='^p_', axis=1) ax = axiter.grid(1) temp.plot(ax=ax, ylim=(0, density_scale), xlim=(0, large_loss_scale), title='Densities') ax = axiter.grid(1) temp.plot(ax=ax, logx=True, ylim=(0, density_scale), title='Densities log/linear') ax = axiter.grid(1) temp.plot(ax=ax, logy=True, xlim=(0, large_loss_scale), title='Densities linear/log') ax = axiter.grid(1) temp.plot(ax=ax, logx=True, logy=True, title='Densities log/log') # graph of cumulative loss cost and rate of change of cumulative loss cost temp = D.filter(regex='^exa_[^η]') # need to check exa actually computed if temp.shape[1] == 0: logger.error('Update exa before audit plot') return ax = axiter.grid(1) temp.plot(legend=True, ax=ax, xlim=(0, large_loss_scale), ylim=(0, expected_loss_scale), title='Loss Cost by Line: $E(X_i(a))$') ax = axiter.grid(1) temp.diff().plot(legend=True, ax=ax, xlim=(0, large_loss_scale), ylim=(0, D.index[1]), title='Change in Loss Cost by Line: $\\nabla E(X_i(a))$') # E(X_i / X | X > a); exi_x_lea_ dropped prefix_and_titles = dict(exi_xgta_=r'$E(X_i/X \mid X>a)$', exeqa_=r'$E(X_i \mid X=a)$', exlea_=r'$E(X_i \mid X \leq a)$', exgta_=r'$E(X_i \mid X>a)$') for prefix in prefix_and_titles.keys(): regex = f'^{prefix}[a-zA-Z]' ax = axiter.grid(1) D.filter(regex=regex).plot(ax=ax, xlim=(0, large_loss_scale)) if prefix == 'exgta_': ax.set_title(r'$E(X_i \mid X > a)$ by line and total') if prefix.find('xi_x') > 0: # these are fractions between zero and 1; plot sum on same axis and adjust limit D.filter(regex=regex).sum(axis=1).plot(ax=ax, label='calced total') ax.set_ylim(-.05, 1.05) # so you can see if anything weird is going on elif prefix == 'exgta_' or prefix == 'exeqa_': # scale same as x axis - so you can see E(X | X=a) is the diagonal ds ax.set_ylim(0, large_loss_scale) else: # scale like mean ax.set_ylim(0, expected_loss_scale) ax.set_title(prefix_and_titles[prefix]) ax.legend(frameon=False) # Lee diagrams by peril - will fit in the sixth small plot ax = next(axiter) # force total first ax.plot(D.loc[:, 'p_total'].cumsum(), D.loss, label='total') for c in D.filter(regex='^p_[^t]').columns: ax.plot(D.loc[:, c].cumsum(), D.loss, label=c[2:]) ax.legend(frameon=False) ax.set_title('Lee Diagram') ax.set_xlim(0, 1) ax.set_ylim(0, large_loss_scale) elif kind == 'priority': xmax = self.q(p) n_lines = len(self.line_names_ex) n_plots = 3 + 2 * n_lines if axiter is None: axiter = axiter_factory(axiter, n_plots, figsize, height, aspect) for prefix, fmt in dict(lev_='LEV', exa_=r'$E(X_i\mid X=a)$', e2pri_=r'$E_2(X_i \mid X=a)$').items(): ax = axiter.grid(1) self.density_df.filter(regex=f'{prefix}').plot(ax=ax, xlim=(0, xmax), title=fmt) ax.set_xlabel('Capital assets') for line in self.line_names: ax = axiter.grid(1) self.density_df.filter(regex=f'(lev|exa|e2pri)_{line}$').plot(ax=ax, xlim=(0, xmax), title=f'{line.title()} by Priority') ax.set_xlabel('Capital assets') for col in self.line_names_ex: ax = axiter.grid(1) self.density_df.filter(regex=f'epd_[012]_{col}').plot(ax=ax, xlim=(0, xmax), title=f'{col.title()} EPDs', logy=True) elif kind == 'collateral': assert line != '' and line != 'all' if axiter is None: axiter = axiter_factory(axiter, 2, figsize, height, aspect) cmap = cm.BuGn if a == 0: a = self.q(p) pline = self.density_df.loc[0:a, f'p_{line}'].values notline = self.density_df.loc[0:a, f'ημ_{line}'].values xs = self.density_df.loc[0:a, 'loss'].values N = pline.shape[0] biv = np.matmul(notline.reshape((N, 1)), pline.reshape((1, N))) biv = biv # / np.sum(np.sum(biv)) for rho in [1, 0.05]: ax = next(axiter) ax.imshow(biv ** rho, cmap=cmap, origin='lower', extent=[0, xs[-1], 0, xs[-1]], interpolation='nearest', **kwargs) cy = a - c ax.plot((c, c), (a - c, xs[-1]), 'k', linewidth=0.5) ax.plot((0, a), (a, 0), 'k', linewidth=0.5) if c > 0: ax.plot((c, xs[-1]), (cy, xs[-1] * (a / c - 1)), 'k', linewidth=0.5) ax.plot((0, c, c), (a - c, a - c, 0), c='k', ls='--', linewidth=0.25) ax.set_xlim(0, xs[-1]) ax.set_ylim(0, xs[-1]) ax.set_xlabel(f'Line {line}') ax.set_ylabel(f'Not {line}') else: logger.error(f'Portfolio.plot | Unknown plot type {kind}') raise ValueError(f'Portfolio.plot unknown plot type {kind}') if do_tight: axiter.tidy() suptitle_and_tight(f'{kind.title()} Plots for {self.name.title()}') def uat_interpolation_functions(self, a0, e0): """ Perform quick audit of interpolation functions :param a0: base assets :param e0: base epd :return: """ # audit interpolation functions temp = pd.DataFrame(columns=['line', 'priority', 'epd', 'a from e', 'assets', 'e from a']) e2a = self.epd_2_assets a2e = self.assets_2_epd for i in range(3): for c in self.line_names + ['total'] + ['not ' + i for i in self.line_names]: # if i == 0 and c == 'total' or c != 'total': if (c, i) in a2e: e = a2e[(c, i)](a0) a = e2a[(c, i)](e0) temp.loc[c + "_" + str(i), :] = (c, i, e, e2a[(c, i)](e), a, a2e[(c, i)](a)) display(temp.style) def add_exa(self, df, details, ft_nots=None): """ Use fft to add exa_XXX = E(X_i | X=a) to each dist also add exlea = E(X_i | X <= a) = sum_{x<=a} exa(x)*f(x) where f is for the total ie. self.density_df['exlea_attrit'] = np.cumsum( self.density_df.exa_attrit * self.density_df.p_total) / self.density_df.F and add exgta = E(X_i | X>a) since E(X) = E(X | X<= a)F(a) + E(X | X>a)S(a) we have exgta = (ex - exlea F) / S and add the actual expected losses (not theoretical) the empirical amount: self.density_df['e_attrit'] = np.sum( self.density_df.p_attrit * self.density_df.loss) Mid point adjustment is handled by the example creation routines self.density_df.loss = self.density_df.loss - bs/2 **YOU CANNOT HAVE A LINE with a name starting t!!!** See LCA_Examples for original code Alternative approach to exa: use UC=unconditional versions of exlea and exi_xgta: * exleaUC = np.cumsum(port.density_df['exeqa_' + col] * port.density_df.p_total) # unconditional * exixgtaUC =np.cumsum( self.density_df.loc[::-1, 'exeqa_' + col] / self.density_df.loc[::-1, 'loss'] * self.density_df.loc[::-1, 'p_total'] ) * exa = exleaUC + exixgtaUC * self.density_df.loss :param df: data frame to add to. Initially add_exa was only called by update and wrote to self.density_df. But now it is called by gradient too which writes to gradient_df, so we need to pass in this argument :param details: True = include everything; False = do not include junk around epd etc :param ft_nots: FFTs of the not lines (computed in gradients) so you don't round trip an FFT; gradients needs to recompute all the not lines each time around and it is stilly to do that twice """ # will need two decorators for epd functions: these handle swapping the arguments and # protecting against value errors def minus_arg_wrapper(a_func): def new_fun(x): try: x = a_func(-x) except ValueError: x = 999 return x return new_fun def minus_ans_wrapper(a_func): def new_fun(x): try: x = -a_func(x) except ValueError: x = 999 return x return new_fun # eps is used NOT to do silly things when x is so small F(x)< eps # below this percentile you do not try to condition on the event! # np.finfo(np.float).eps = 2.2204460492503131e-16 cut_eps = np.finfo(np.float).eps # get this done # defuzz(self.density_df, cut_eps) # bucket size bs = self.bs # self.density_df['loss'].iloc[1] - self.density_df['loss'].iloc[0] # index has already been reset # sum of p_total is so important...we will rescale it... if not np.all(df.p_total >= 0): # have negative densities...get rid of them first_neg = df.query('p_total < 0') logger.warning( f'Portfolio.add_exa | p_total has a negative value starting at {first_neg.head()}; NOT setting to zero...') sum_p_total = df.p_total.sum() logger.info(f'Portfolio.add_exa | {self.name}: sum of p_total is 1 - ' f'{1 - sum_p_total:12.8e} NOT RESCALING') # df.p_total /= sum_p_total df['F'] = np.cumsum(df.p_total) # this method is terrible because you lose precision for very small values of S # df['S'] = 1 - df.F # old method # df['S'] = np.hstack((df.p_total.to_numpy()[:0:-1].cumsum()[::-1], # min(df.p_total.iloc[-1], # max(0, 1. - (df.p_total.sum()))))) # which was ugly and not quite right because the it ended ... pn plast vs pn+plast, plast # Dec 2020 df['S'] = \ df.p_total.shift(-1, fill_value=min(df.p_total.iloc[-1], max(0, 1. - (df.p_total.sum()))))[::-1].cumsum()[::-1] # get rounding errors, S may not go below zero logger.info( f'Portfolio.add_exa | {self.name}: S <= 0 values has length {len(np.argwhere((df.S <= 0).to_numpy()))}') # E(min(X, a)) # needs to be shifted down by one for the partial integrals.... # temp = np.hstack((0, np.array(df.iloc[:-1, :].loc[:, 'S'].cumsum()))) # df['exa_total'] = temp * bs # df['exa_total'] = self.cumintegral(df['S']) df['exa_total'] = df.S.shift(1, fill_value=0).cumsum() * self.bs df['lev_total'] = df['exa_total'] # $E(X\wedge a)=\int_0^a tf(t)dt + aS(a)$ therefore exlea # (EXpected $X$ given Less than or Equal to **a**) # $$=E(X \mid X\le a)=\frac{E(X\wedge a)-aS(a)}{F(a)}$$ df['exlea_total'] = \ (df.exa_total - df.loss * df.S) / df.F # fix very small values # don't pretend you know values! # find the largest value where exlea_total > loss, which has to be an error # 100 bs is a hack, move a little beyond last problem observation # from observation looks about right with 1<<16 buckets # TODO What is this crap? n_ = df.shape[0] if n_ < 1100: mult = 1 elif n_ < 15000: mult = 10 else: mult = 100 loss_max = df[['loss', 'exlea_total']].query(' exlea_total>loss ').loss.max() if np.isnan(loss_max): loss_max = 0 else: loss_max += mult * bs # try nan in place of 0 V df.loc[0:loss_max, 'exlea_total'] = np.nan # df.loc[df.F < 2 * cut_eps, 'exlea_total'] = df.loc[ # df.F < 2*cut_eps, 'loss'] # if F(x)<very small then E(X | X<x) = x, you are certain to be above the threshold # this is more stable than dividing by the very small F(x) df['e_total'] = np.sum(df.p_total * df.loss) # epds for total on a stand alone basis (all that makes sense) df['epd_0_total'] = \ np.maximum(0, (df['e_total'] - df['lev_total'])) / \ df['e_total'] df['exgta_total'] = df.loss + (df.e_total - df.exa_total) / df.S df['exeqa_total'] = df.loss # E(X | X=a) = a(!) included for symmetry was exa # E[1/X 1_{X>a}] used for reimbursement effectiveness graph # Nov 2020 tweaks index_inv = 1.0 / df.loss df['e1xi_1gta_total'] = (df['p_total'] * index_inv).shift(-1)[::-1].cumsum() # FFT functions for use in exa calculations # computing sums so minimal padding required def loc_ft(x): return ft(x, 1, None) def loc_ift(x): return ift(x, 1, None) # where is S=0 Seq0 = (df.S == 0) for col in self.line_names: # ### Additional Variables # # * exeqa_line = $E(X_i \mid X=a)$ # * exlea_line = $E(X_i \mid X\le a)$ # * e_line = $E(X_i)$ # * exgta_line = $E(X_i \mid X \ge a)$ # * exi_x_line = $E(X_i / X \mid X = a)$ # * and similar for le and gt a # * exa_line = $E(X_i(a))$ # * Price based on same constant ROE formula (later we will do $g$s) # # # THE MONEY CALCULATION # EX_i | X=a, E(xi eq a) # # # # if ft_nots is None: df['exeqa_' + col] = \ np.real(loc_ift(loc_ft(df.loss * df['p_' + col]) * loc_ft(df['ημ_' + col]))) / df.p_total else: df['exeqa_' + col] = \ np.real(loc_ift(loc_ft(df.loss * df['p_' + col]) * ft_nots[col])) / df.p_total # these are unreliable estimates because p_total=0 JUNE 25: this makes a difference! df.loc[df.p_total < cut_eps, 'exeqa_' + col] = 0 df['exeqa_ημ_' + col] = \ np.real(loc_ift(loc_ft(df.loss * df['ημ_' + col]) * loc_ft(df['p_' + col]))) / df.p_total # these are unreliable estimates because p_total=0 JUNE 25: this makes a difference! df.loc[df.p_total < cut_eps, 'exeqa_ημ_' + col] = 0 # E(X_{i, 2nd priority}(a)) # need the stand alone LEV calc # E(min(Xi, a) # needs to be shifted down by one for the partial integrals.... stemp = 1 - df['p_' + col].cumsum() # temp = np.hstack((0, stemp.iloc[:-1].cumsum())) # df['lev_' + col] = temp * bs df['lev_' + col] = stemp.shift(1, fill_value=0).cumsum() * self.bs if details: df['e2pri_' + col] = \ np.real(loc_ift(loc_ft(df['lev_' + col]) * loc_ft(df['ημ_' + col]))) stemp = 1 - df['ημ_' + col].cumsum() # temp = np.hstack((0, stemp.iloc[:-1].cumsum())) # df['lev_ημ_' + col] = temp * bs df['lev_ημ_' + col] = stemp.shift(1, fill_value=0).cumsum() * self.bs # EX_i | X<= a; temp is used in le and gt calcs temp = np.cumsum(df['exeqa_' + col] * df.p_total) df['exlea_' + col] = temp / df.F # revised version for small losses: do not know this value df.loc[0:loss_max, 'exlea_' + col] = 0 # df.loc[0:loss_max, 'loss'] temp_not = np.cumsum(df['exeqa_ημ_' + col] * df.p_total) df['exlea_ημ_' + col] = temp_not / df.F # revised version for small losses: do not know this value df.loc[0:loss_max, 'exlea_ημ_' + col] = 0 # df.loc[0:loss_max, 'loss'] # constant value, helpful in calculations df['e_' + col] = np.sum(df['p_' + col] * df.loss) df['e_ημ_' + col] = np.sum(df['ημ_' + col] * df.loss) # EX_i | X>a df['exgta_' + col] = (df['e_' + col] - temp) / df.S # E{X_i / X | X > a} (note=a is trivial!) temp = df.loss.iloc[0] # loss df.loss.iloc[0] = 1 # avoid divide by zero # unconditional E(X_i/X) df['exi_x_' + col] = np.sum( df['exeqa_' + col] * df.p_total / df.loss) temp_xi_x = np.cumsum(df['exeqa_' + col] * df.p_total / df.loss) df['exi_xlea_' + col] = temp_xi_x / df.F df.loc[0, 'exi_xlea_' + col] = 0 # df.F=0 at zero # more generally F=0 error: V df.loc[df.exlea_total == 0, 'exi_xlea_' + col] = 0 # not version df['exi_x_ημ_' + col] = np.sum( df['exeqa_ημ_' + col] * df.p_total / df.loss) # as above temp_xi_x_not = np.cumsum( df['exeqa_ημ_' + col] * df.p_total / df.loss) df['exi_xlea_ημ_' + col] = temp_xi_x_not / df.F df.loc[0, 'exi_xlea_ημ_' + col] = 0 # df.F=0 at zero # more generally F=0 error: df.loc[df.exlea_total == 0, 'exi_xlea_ημ_' + col] = 0 # put value back df.loss.iloc[0] = temp # this is so important we will calculate it directly rather than the old: # df['exi_xgta_' + col] = (df['exi_x_' + col] - temp_xi_x) / df.S # the last value is undefined because we know nothing about what happens beyond our array # above that we need a shift: > second to last value will only involve the last row (the John Major problem) # hence # Nov 2020, consider added fill values using same approach as exi_xgtag_[CHANGE NOT MADE, investigate] # fill_value = df[f'exeqa_{col}'].iloc[-1] / df.loss.iloc[-1] * df.S.iloc[-1] fill_value = np.nan # logger.info(f'exi_xgta_ fill_value = {fill_value}') df['exi_xgta_' + col] = ((df[f'exeqa_{col}'] / df.loss * df.p_total).shift(-1, fill_value=fill_value)[ ::-1].cumsum()) / df.S # print(df['exi_xgta_' + col].tail()) # need this NOT to be nan otherwise exa won't come out correctly df.loc[Seq0, 'exi_xgta_' + col] = 0. # df['exi_xgta_ημ_' + col] = \ # (df['exi_x_ημ_' + col] - temp_xi_x_not) / df.S # as for line # fill_value = df[f'exeqa_ημ_{col}'].iloc[-1] / df.loss.iloc[-1] * df.S.iloc[-1] df['exi_xgta_ημ_' + col] = ((df[f'exeqa_ημ_{col}'] / df.loss * df.p_total).shift(-1, fill_value=fill_value)[ ::-1].cumsum()) / df.S df.loc[Seq0, 'exi_xgta_ημ_' + col] = 0. df['exi_xeqa_' + col] = df['exeqa_' + col] / df['loss'] df.loc[0, 'exi_xeqa_' + col] = 0 df['exi_xeqa_ημ_' + col] = df['exeqa_ημ_' + col] / df['loss'] df.loc[0, 'exi_xeqa_ημ_' + col] = 0 # need the loss cost with equal priority rule # exa_ = E(X_i(a)) = E(X_i | X<= a)F(a) + E(X_i / X| X>a) a S(a) # = exlea F(a) + exixgta * a * S(a) # and hence get loss cost for line i # df['exa_' + col] = \ # df['exlea_' + col] * df.F + df.loss * \ # df.S * df['exi_xgta_' + col] # df['exa_ημ_' + col] = \ # df['exlea_ημ_' + col] * df.F + df.loss * \ # df.S * df['exi_xgta_ημ_' + col] # alt calc using S: validated the same, going with this as a more direct calc df[f'exa_{col}'] = (df.S * df['exi_xgta_' + col]).shift(1, fill_value=0).cumsum() * self.bs df['exa_ημ_' + col] = (df.S * df['exi_xgta_ημ_' + col]).shift(1, fill_value=0).cumsum() * self.bs # E[1/X 1_{X>a}] used for reimbursement effectiveness graph # Nov 2020 # df['e1xi_1gta_total'] = (df['p_total'] * index_inv).shift(-1)[::-1].cumsum() df[f'e1xi_1gta_{col}'] = (df[f'p_{col}'] * index_inv).shift(-1)[::-1].cumsum() if details: # epds df['epd_0_' + col] = \ np.maximum(0, (df['e_' + col] - df['lev_' + col])) / \ df['e_' + col] df['epd_0_ημ_' + col] = \ np.maximum(0, (df['e_ημ_' + col] - df['lev_ημ_' + col])) / \ df['e_ημ_' + col] df['epd_1_' + col] = \ np.maximum(0, (df['e_' + col] - df['exa_' + col])) / \ df['e_' + col] df['epd_1_ημ_' + col] = \ np.maximum(0, (df['e_ημ_' + col] - df['exa_ημ_' + col])) / \ df['e_ημ_' + col] df['epd_2_' + col] = \ np.maximum(0, (df['e_' + col] - df['e2pri_' + col])) / \ df['e_' + col] # epd interpolation functions # capital and epd functions: for i = 0 and 1 we want line and not line loss_values = df.loss.values for i in [0, 1, 2]: epd_values = -df['epd_{:}_{:}'.format(i, col)].values # if np.any(epd_values[1:] <= epd_values[:-1]): # print(i, col) # print( 1e12*(epd_values[1:][epd_values[1:] <= epd_values[:-1]] - # epd_values[:-1][epd_values[1:] <= epd_values[:-1]])) # raise ValueError('Need to be sorted ascending') self.epd_2_assets[(col, i)] = minus_arg_wrapper( interpolate.interp1d(epd_values, loss_values, kind='linear', assume_sorted=True, fill_value='extrapolate')) self.assets_2_epd[(col, i)] = minus_ans_wrapper( interpolate.interp1d(loss_values, epd_values, kind='linear', assume_sorted=True, fill_value='extrapolate')) for i in [0, 1]: epd_values = -df['epd_{:}_ημ_{:}'.format(i, col)].values self.epd_2_assets[('not ' + col, i)] = minus_arg_wrapper( interpolate.interp1d(epd_values, loss_values, kind='linear', assume_sorted=True, fill_value='extrapolate')) self.assets_2_epd[('not ' + col, i)] = minus_ans_wrapper( interpolate.interp1d(loss_values, epd_values, kind='linear', assume_sorted=True, fill_value='extrapolate')) # put in totals for the ratios... this is very handy in later use for metric in ['exi_xlea_', 'exi_xgta_', 'exi_xeqa_']: df[metric + 'sum'] = df.filter(regex=metric + '[^η]').sum(axis=1) if details: epd_values = -df['epd_0_total'].values # if np.any(epd_values[1:] <= epd_values[:-1]): # print('total') # print(epd_values[1:][epd_values[1:] <= epd_values[:-1]]) # raise ValueError('Need to be sorted ascending') loss_values = df.loss.values self.epd_2_assets[('total', 0)] = minus_arg_wrapper( interpolate.interp1d(epd_values, loss_values, kind='linear', assume_sorted=True, fill_value='extrapolate')) self.assets_2_epd[('total', 0)] = minus_ans_wrapper( interpolate.interp1d(loss_values, epd_values, kind='linear', assume_sorted=True, fill_value='extrapolate')) def calibrate_distortion(self, name, r0=0.0, df=[0.0, .9], premium_target=0.0, roe=0.0, assets=0.0, p=0.0, kind='lower', S_column='S', S_calc='cumsum'): """ Find transform to hit a premium target given assets of ``assets``. Fills in the values in ``g_spec`` and returns params and diagnostics...so you can use it either way...more convenient :param name: name of distortion :param r0: fixed parameter if applicable :param df: t-distribution degrees of freedom :param premium_target: target premium :param roe: or ROE :param assets: asset level :param p: :param kind: :param S_column: column of density_df to use for calibration (allows routine to be used in other contexts; if so used must input a premium_target directly. If assets they are used; else max assets used :return: """ # figure assets assert S_calc in ('S', 'cumsum') if S_column == 'S': if assets == 0: assert (p > 0) assets = self.q(p, kind) # figure premium target el = self.density_df.loc[assets, 'exa_total'] if premium_target == 0: assert (roe > 0) # expected losses with assets premium_target = (el + roe * assets) / (1 + roe) else: # if assets not entered, calibrating to unlimited premium; set assets = max loss and let code trim it if assets == 0: assets = self.density_df.loss.iloc[-1] el = self.density_df.loc[assets, 'exa_total'] # extract S and trim it: we are doing int from zero to assets # integration including ENDpoint is if S_calc == 'S': Splus = self.density_df.loc[0:assets, S_column].values else: Splus = (1 - self.density_df.loc[0:assets, 'p_total'].cumsum()).values last_non_zero = np.argwhere(Splus) ess_sup = 0 if len(last_non_zero) == 0: # no nonzero element last_non_zero = len(Splus) + 1 else: last_non_zero = last_non_zero.max() # remember length = max index + 1 because zero based if last_non_zero + 1 < len(Splus): # now you have issues... # truncate at first zero; numpy indexing because values S = Splus[:last_non_zero + 1] ess_sup = self.density_df.index[last_non_zero + 1] logger.warning( 'Portfolio.calibrate_distortion | Mass issues in calibrate_distortion...' f'{name} at {last_non_zero}, loss = {ess_sup}') else: # this calc sidesteps the Splus created above.... if S_calc == 'original': S = self.density_df.loc[0:assets - self.bs, S_column].values else: S = (1 - self.density_df.loc[0:assets - self.bs, 'p_total'].cumsum()).values # now all S values should be greater than zero and it is decreasing assert np.all(S > 0) and np.all(S[:-1] >= S[1:]) if name == 'ph': lS = np.log(S) shape = 0.95 # starting param def f(rho): trho = S ** rho ex = np.sum(trho) * self.bs ex_prime = np.sum(trho * lS) * self.bs return ex - premium_target, ex_prime elif name == 'wang': n = ss.norm() shape = 0.95 # starting param def f(lam): temp = n.ppf(S) + lam tlam = n.cdf(temp) ex = np.sum(tlam) * self.bs ex_prime = np.sum(n.pdf(temp)) * self.bs return ex - premium_target, ex_prime elif name == 'ly': # linear yield model; min rol is ro/(1+ro) shape = 1.25 # starting param mass = ess_sup * r0 / (1 + r0) def f(rk): num = r0 + S * (1 + rk) den = 1 + r0 + rk * S tlam = num / den ex = np.sum(tlam) * self.bs + mass ex_prime = np.sum(S * (den ** -1 - num / (den ** 2))) * self.bs return ex - premium_target, ex_prime elif name == 'clin': # capped linear, input rf as min rol shape = 1 mass = ess_sup * r0 def f(r): r0_rS = r0 + r * S ex = np.sum(np.minimum(1, r0_rS)) * self.bs + mass ex_prime = np.sum(np.where(r0_rS < 1, S, 0)) * self.bs return ex - premium_target, ex_prime elif name == 'roe': # constant roe # TODO Note if you input the roe this is easy! shape = 0.25 def f(r): v = 1 / (1 + r) d = 1 - v mass = ess_sup * d r0_rS = d + v * S ex = np.sum(np.minimum(1, r0_rS)) * self.bs + mass ex_prime = np.sum(np.where(r0_rS < 1, S, 0)) * self.bs return ex - premium_target, ex_prime elif name == 'lep': # layer equivalent pricing # params are d=r0/(1+r0) and delta* = r/(1+r) d = r0 / (1 + r0) shape = 0.25 # starting param # these hard to compute variables do not change with the parameters rSF = np.sqrt(S * (1 - S)) mass = ess_sup * d def f(r): spread = r / (1 + r) - d temp = d + (1 - d) * S + spread * rSF ex = np.sum(np.minimum(1, temp)) * self.bs + mass ex_prime = (1 + r) ** -2 * np.sum(np.where(temp < 1, rSF, 0)) * self.bs return ex - premium_target, ex_prime elif name == 'tt': # wang-t-t ... issue with df, will set equal to 5.5 per Shaun's paper # finding that is a reasonable level; user can input alternative # TODO bivariate solver for t degrees of freedom? # param is shape like normal t = ss.t(df) shape = 0.95 # starting param def f(lam): temp = t.ppf(S) + lam tlam = t.cdf(temp) ex = np.sum(tlam) * self.bs ex_prime = np.sum(t.pdf(temp)) * self.bs return ex - premium_target, ex_prime elif name == 'cll': # capped loglinear shape = 0.95 # starting parameter lS = np.log(S) lS[0] = 0 ea = np.exp(r0) def f(b): uncapped = ea * S ** b ex = np.sum(np.minimum(1, uncapped)) * self.bs ex_prime = np.sum(np.where(uncapped < 1, uncapped * lS, 0)) * self.bs return ex - premium_target, ex_prime elif name == 'dual': # dual moment # be careful about partial at s=1 shape = 2.0 # starting parameter lS = -np.log(1 - S) # prob a bunch of zeros... lS[S == 1] = 0 def f(rho): temp = (1 - S) ** rho trho = 1 - temp ex = np.sum(trho) * self.bs ex_prime = np.sum(temp * lS) * self.bs return ex - premium_target, ex_prime elif name == 'tvar': # tvar shape = 0.9 # starting parameter def f(rho): temp = np.where(S <= 1-rho, S / (1 - rho), 1) temp2 = np.where(S <= 1-rho, S / (1 - rho)**2, 1) ex = np.sum(temp) * self.bs ex_prime = np.sum(temp2) * self.bs return ex - premium_target, ex_prime elif name == 'wtdtvar': # weighted tvar with fixed p parameters shape = 0.5 # starting parameter p0, p1 = df s = np.array([0., 1-p1, 1-p0, 1.]) def f(w): pt = (1 - p1) / (1 - p0) * (1 - w) + w gs = np.array([0., pt, 1., 1.]) g = interp1d(s, gs, kind='linear') trho = g(S) ex = np.sum(trho) * self.bs ex_prime = (np.sum(np.minimum(S / (1 - p1), 1) - np.minimum(S / (1 - p0), 1))) * self.bs return ex - premium_target, ex_prime else: raise ValueError(f'calibrate_distortion not implemented for {name}') # numerical solve except for tvar, and roe when premium is known if name == 'roe': assert el and premium_target r = (premium_target - el) / (assets - premium_target) shape = r r0 = 0 fx = 0 else: i = 0 fx, fxp = f(shape) # print(premium_target) # print('dist iter error shape deriv') max_iter = 200 if name == 'tvar' else 50 while abs(fx) > 1e-5 and i < max_iter: # print(f'{name}\t{i: 3d}\t{fx: 8.3f}\t{shape:8.3f}\t{fxp:8.3f}') shape = shape - fx / fxp fx, fxp = f(shape) i += 1 # print(f'{name}\t{i: 3d}\t{fx+premium_target: 8.3f}\t{shape:8.3f}\t{fxp:8.3f}\n\n') if abs(fx) > 1e-5: logger.warning( f'Portfolio.calibrate_distortion | Questionable convergenge! {name}, target ' f'{premium_target} error {fx}, {i} iterations') # build answer dist = Distortion(name=name, shape=shape, r0=r0, df=df) dist.error = fx dist.assets = assets dist.premium_target = premium_target return dist def calibrate_distortions(self, LRs=None, ROEs=None, As=None, Ps=None, kind='lower', r0=0.03, df=5.5, strict=True, S_calc='cumsum'): """ Calibrate assets a to loss ratios LRs and asset levels As (iterables) ro for LY, it :math:`ro/(1+ro)` corresponds to a minimum rate on line :param LRs: LR or ROEs given :param ROEs: ROEs override LRs :param As: Assets or probs given :param Ps: probability levels for quantiles :param r0: for distortions that have a min ROL :param df: for tt :param strict: if True only use distortions with no mass at zero, otherwise use anything reasonable for pricing :param return_distortions: return the created distortions :return: """ ans = pd.DataFrame( columns=['$a$', 'LR', '$S$', '$\\iota$', '$\\delta$', '$\\nu$', '$EL$', '$P$', 'Levg', '$K$', 'ROE', 'param', 'error', 'method'], dtype=np.float) ans = ans.set_index(['$a$', 'LR', 'method'], drop=True) dists = {} if As is None: if Ps is None: raise ValueError('Must specify assets or quantile probabilities') else: As = [self.q(p, kind) for p in Ps] for a in As: exa, S = self.density_df.loc[a, ['exa_total', 'S']] if ROEs is not None: # figure loss ratios LRs = [] for r in ROEs: delta = r / (1 + r) nu = 1 - delta prem = nu * exa + delta * a LRs.append(exa / prem) for lr in LRs: P = exa / lr profit = P - exa K = a - P iota = profit / K delta = iota / (1 + iota) nu = 1 - delta for dname in Distortion.available_distortions(pricing=True, strict=strict): dist = self.calibrate_distortion(name=dname, r0=r0, df=df, premium_target=P, assets=a, S_calc=S_calc) dists[dname] = dist ans.loc[(a, lr, dname), :] = [S, iota, delta, nu, exa, P, P / K, K, profit / K, dist.shape, dist.error] # very helpful to keep these... self.dist_ans = ans self.dists = dists return ans def apply_distortions(self, dist_dict, As=None, Ps=None, kind='lower', axiter=None, num_plots=1): """ Apply a list of distortions, summarize pricing and produce graphical output show loss values where :math:`s_ub > S(loss) > s_lb` by jump :param dist_dict: dictionary of Distortion objects :param As: input asset levels to consider OR :param Ps: input probs (near 1) converted to assets using ``self.q()`` :param num_plots: 0, 1 or 2 :return: """ ans = [] if As is None: As = np.array([float(self.q(p, kind)) for p in Ps]) if num_plots == 2 and axiter is None: axiter = axiter_factory(None, len(dist_dict)) elif num_plots == 3 and axiter is None: axiter = axiter_factory(None, 30) else: pass for g in dist_dict.values(): _x = self.apply_distortion(g, axiter, num_plots) df = _x.augmented_df # extract range of S values temp = df.loc[As, :].filter(regex='^loss|^S|exa[g]?_[^η][\.:~a-zA-Z0-9]*$|exag_sumparts|lr_').copy() # jump = sensible_jump(len(temp), num_assets) # temp = temp.loc[::jump, :].copy() temp['method'] = g.name ans.append(temp) ans_table = pd.concat(ans) ans_table['return'] = np.round(1 / ans_table.S, 0) df2 = ans_table.copy() df2 = df2.set_index(['loss', 'method', 'return', 'S']) df2.columns = df2.columns.str.split('_', expand=True) ans_stacked = pd.DataFrame(df2.stack().stack()).reset_index() ans_stacked.columns = ['assets', 'method', 'return', 'S', 'line', 'stat', 'value'] # figure reasonable max and mins for LR plots mn = ans_table.filter(regex='^lr').min().min() mn1 = mn mx = ans_table.filter(regex='^lr').max().max() mn = np.round(mn * 20, 0) / 20 mx = np.round(mx * 20, 0) / 20 if mx >= 0.9: mx = 1 if mn <= 0.2: mn = 0 if mn1 < mn: mn -= 0.1 # by line columns=method x capital if num_plots >= 1: raise ValueError('dropped seaborn') # sns.catplot(x='line', y='value', row='return', col='method', height=2.5, kind='bar', # data=ans_stacked.query(' stat=="lr" ')).set(ylim=(mn, mx), ylabel='LR') # sns.catplot(x='method', y='value', row='return', col='line', height=2.5, kind='bar', # data=ans_stacked.query(' stat=="lr" ')).set(ylim=(mn, mx), ylabel='LR') # sns.factorplot(x='return', y='value', row='line', col='method', size=2.5, kind='bar', # data=ans_stacked.query(' stat=="lr" ')).set(ylim=(mn, mx)) return ans_table, ans_stacked def apply_distortion(self, dist, plots=None, df_in=None, create_augmented=True, mass_hints=None, S_calculation='forwards', efficient=False): """ Apply the distortion, make a copy of density_df and append various columns to create augmented_df. augmented_df depends on the distortion but only includes variables that work for all asset levels, e.g. 1. marginal loss, lr, roe etc. 2. bottom up totals Top down total depend on where the "top" is and do not work in general. They are handled in analyze_distortions where you explicitly provide a top. Does not touch density_df: that is independent of distortions Optionally produce graphics of results controlled by plots a list containing none or more of: 1. basic: exag_sumparts, exag_total df.exa_total 2. extended: the full original set The issue with distortions that have a mass at 0 ================================================ exag is computed as the cumulative integral of beta g(S), which is unaffected by the mass. But beta = exi_xgtag is computed as (cumint exeqa / loss * gp_total) / gS which includes the point at infinity or sup loss. Since gp_total is computed as a difference of gS it does not see the mass ( and it will sum to 1 - mass). Therefore we need to add a term "E[X_i/X | X=sup loss or infty] mass" to the cumint term for all loss (upper limits of integration) <= ess sup(X). To do so requires an estimate of E[X_i/X | X=sup loss or infty], which is hard because the estimates tend to become unstable in the right tail and we only have estimates upto the largest modeled value, not actually infinity. In order to circumvent this difficulty introduce the mass_hint variable where you specifically input estimates of the values. mass_hint is optional. Note that if the largest loss really is infinite then exag will be infinite when there is a mass. It also requires identifying the sup loss, i.e. the largest loss with S>0. np.searchsorted can be used for the latter. It needs care but is not really difficult. The binding constraint is accurate estimation of E[X_i | X]. We will truncate augmented_df at the point that the sum exeqa is < loss - epsilon. In order to compute exeqa you must have S>0, so it will always be the case that the tail is "missing" and you need to add the mass, if there is one. :type create_augmented: object :param dist: agg.Distortion :param plots: iterable of plot types :param df_in: when called from gradient you want to pass in gradient_df and use that; otherwise use self.density_df :param create_augmented: store the output in self.augmented_df :param mass_hints: hints for values of E[X_i/X | X=x] as x --> infty (optional; if not entered estimated using last reliable value. Mass hints needs to have a get-item method so that mass_hints[line] is the hint for line. e.g. it can be a dictionary or pandas Series indexed by line names. mass_hints must sum to 1 over all lines. Total line obviously excluded. :param S_calculation: if forwards, recompute S summing p_total forwards...this gets the tail right; the old method was backwards, which does not change S :param efficient: just compute the bar minimum and return :return: density_df with extra columns appended """ # initially work will "full precision" if df_in is None: df = self.density_df.copy() else: df = df_in # PREVIOUSLY: did not make this adjustment because loss of resolution on small S values # however, it doesn't work well for very thick tailed distributions, hence intro of S_calculation # July 2020 (during COVID-Trump madness) try this instead if S_calculation == 'forwards': logger.debug('Using updated S_forwards calculation in apply_distortion! ') df['S'] = 1 - df.p_total.cumsum() # make g and ginv and other interpolation functions g, g_inv = dist.g, dist.g_inv # maybe important that p_total sums to 1 # this appeared not to make a difference, and introduces an undesirable difference from # the original density_df # df.loc[df.p_total < 0, :] = 0 # df['p_total'] = df['p_total'] / df['p_total'].sum() # df['F'] = df.p_total.cumsum() # df['S'] = 1 - df.F # floating point issues: THIS HAPPENS, so needs to be corrected... if len(df.loc[df.S < 0, 'S'] > 0): logger.warning(f"{len(df.loc[df.S < 0, 'S'] > 0)} negative S values being set to zero...") df.loc[df.S < 0, 'S'] = 0 # add the exag and distorted probs df['gS'] = g(df.S) df['gF'] = 1 - df.gS # updated for ability to prepend 0 in newer numpy # df['gp_total'] = np.diff(np.hstack((0, df.gF))) # also checked these two method give the same result: # bit2['gp1'] = -np.diff(bit2.gS, prepend=1) # bit2['gp2'] = np.diff(1 - bit2.gS, prepend=0) # validated using grt.test_df(): this is correct # t = grt.test_df(20,2) # t.A = t.A / t.A.sum() # # t['B'] = t.A.shift(-1, fill_value=0)[::-1].cumsum() # t['C'] = -np.diff(t.B, prepend=1) # t df['gp_total'] = -np.diff(df.gS, prepend=1) # weirdness occurs here were 0 appears as -0: get rid of that df.loc[df.gp_total==0, 'gp_total'] = 0.0 # Impact of mass at zero # if total has an ess sup < top of computed range then any integral a > ess sup needs to have # the mass added. It only needs to be added to quantities computed as integrals, not g(S(x)) # which includes it automatically. # total_mass is the mass for the total line, it will be apportioned below to the individual lines # total_mass = (mass %) x (ess sup loss), applied when S>0 # figure out where to truncate df (which turns into augmented_df) lnp = '|'.join(self.line_names) # in discrete distributions there are "gaps" of impossible values; do not want to worry about these idx_pne0 = df.query(' p_total > 0 ').index exeqa_err = np.abs( (df.loc[idx_pne0].filter(regex=f'exeqa_({lnp})').sum(axis=1) - df.loc[idx_pne0].loss) / df.loc[idx_pne0].loss) exeqa_err.iloc[0] = 0 # print(exeqa_err) # +1 because when you iloc you lose the last element (two code lines down) idx = int(exeqa_err[exeqa_err < 1e-4].index[-1] / self.bs + 1) # idx = np.argmax(exeqa_err > 1e-4) logger.debug(f'index of max reliable value = {idx}') if idx: # if exeqa_err > 1e-4 is empty, np.argmax returns zero...do not want to truncate at zero in that case df = df.iloc[:idx] # where gS==0, which should be empty set gSeq0 = (df.gS == 0) logger.debug(f'S==0 values: {df.gS.loc[gSeq0]}') if idx: logger.debug(f'Truncating augmented_df at idx={idx}, loss={idx*self.bs}, len(S==0) = {np.sum(gSeq0)} elements') # print(f'Truncating augmented_df at idx={idx}, loss={idx*self.bs}\nS==0 on len(S==0) = {np.sum(gSeq0)} elements') else: logger.debug(f'augmented_df not truncated (no exeqa error), len(S==0) = {np.sum(gSeq0)} elements') # print(f'augmented_df not truncated (no exeqa error\nS==0 on len(S==0) = {np.sum(gSeq0)} elements') # S better be decreasing if not np.alltrue(df.S.iloc[1:] <= df.S.iloc[:-1].values): logger.error('S = density_df.S is not non-increasing...carrying on but you should investigate...') # this should now apply in ALL mass situations... # total_mass = 0 # if dist.mass: # index where S>0 implies NEXT row must have p_total > 0 (since that will be the S value) # hence need to add one here # print(f'Index of ess_sup is {idx_ess_sup}') # total_mass = np.zeros_like(S) # locations and amount of mass to be added to computation of exi_xgtag below... # was + 1, removed... v # total_mass[:idx_ess_sup ] = dist.mass # logger.info(f'total_mass vector = {total_mass}') # print(f'total_mass vector = {total_mass}') if dist.mass and mass_hints is None: idx_ess_sup = df.S.to_numpy().nonzero()[0][-1] + 1 logger.info(f'Index of ess_sup is {idx_ess_sup}') # only add masses upto ess_sup # mass_S = pd.Series(0.0 index=df.index) # mass_S.iloc[:idx_ess_sup] = # logger.warning('No mass_hints given...estimating...') mass_hints = pd.Series(index=self.line_names) for line in self.line_names: # logger.warning(f'Individual line={line}') # print(f'Individual line={line}') mass_hints[line] = df[f'exi_xeqa_{line}'].iloc[-1] for ii in range(1, min(4, max(self.log2 - 8, 0))): avg_xix = df[f'exi_xeqa_{line}'].iloc[idx_ess_sup - (1 << ii):].mean() logger.debug(f'Avg weight last {1 << ii} observations is = {avg_xix:.5g} vs. last trusted ' f'is {mass_hints[line]:.5g}') # f'is {self.density_df[f"exi_xeqa_{line}"].iloc[idx_ess_sup]:.5g}') # print(f'Avg weight last {1 << ii} observations is = {avg_xix:.5g} vs. last ' # f'is {mass_hints[line]:.5g}') logger.debug('Generally, you want these values to be consistent, except for discrete distributions.') logger.warning(f'No mass_hints given, using estimated mass_hints = {mass_hints.to_numpy()} for {dist.name}' f' mass {dist.mass} {dist}') # print(f'Using estimated mass_hints = {mass_hints.to_numpy()}') report_time('apply_distortion - refob completed') for line in self.line_names: report_time(f'apply_distortion - starting {line} loop 1') # avoid double count: going up sum needs to be stepped one back, hence use cumintegral is perfect # for <=a cumintegral, for > a reverse and use cumsum (no step back) # UC = unconditional # old # # exleaUC = self.cumintegral(self.density_df[f'exeqa_{line}'] * df.gp_total, 1) # # correct that increasing integrals need the offset # exleaUC1 = np.cumsum(self.density_df[f'exeqa_{line}'] * df.gp_total) # # old # exixgtaUC = np.cumsum( # self.density_df.loc[::-1, f'exeqa_{line}'] / self.density_df.loc[::-1, 'loss'] * # df.loc[::-1, 'gp_total']) # # or shift...NO should be cumsum for gt # exixgtaUC1 = self.cumintegral( # self.density_df.loc[::-1, f'exeqa_{line}'] / self.density_df.loc[::-1, 'loss'] * # df.loc[::-1, 'gp_total'], 1)[::-1] # # Treatment of Masses # You are integrating down from infinity. You need to add the mass at the first # loss level with S>0, or, if S>0 for all x then you add the mass at all levels because # int_x^infty fun = int_F(x)^1 fun + (prob=1) * fun(1) (fun=TVaR) # The mass is (dist.mass x ess sup). # if S>0 but flat and there is a mass then need to include loss X g(S(loss)) term! # pick up right hand places where S is very small (rounding issues...) # OLD # # mass = 0 # if dist.mass: # logger.error("You cannot use a distortion with a mass at this time...") # # this is John's problem: the last scenario is getting all the weight... # # not clear how accurately this is computed numerically # # this amount is a # mass = total_mass * self.density_df[f'exi_xeqa_{line}'].iloc[idx_ess_sup] # logger.warning(f'Individual line={line} weight from portfolio mass = {mass}') # for ii in range(1, max(self.log2 - 4, 0)): # avg_xix = self.density_df[f'exi_xeqa_{line}'].iloc[idx_ess_sup - (1 << ii):].mean() # logger.warning(f'Avg weight last {1 << ii} observations is = {avg_xix:.5g} vs. last ' # f'is {self.density_df[f"exi_xeqa_{line}"].iloc[idx_ess_sup]}:.5g') # logger.warning('You want these values all to be consistent!') # old # mass = dist.mass * self.density_df.loss * self.density_df[f'exi_xeqa_{line}'] * \ # np.where(self.density_df.S > 0, 1, 0) # when computed using np.cumsum exixgtaUC is a pd.Series has an index so when it is mult by .loss # (which also has an index) it gets re-sorted into ascending order # when computed using cumintegral it is a numpy array with no index and so need reversing # the difference between UC and UC1 is a shift up by 1. # # Here is a little tester example to show what goes on # # test = pd.DataFrame(dict(x=range(20))) # test['a'] = 10 * test.x # test['y'] = test.x * 3 + 5 # bit = np.cumsum(test['y'][::-1]) # test['z'] = bit # test['w'] = bit / test.a # test # # df[f'exag_{line}'] = exleaUC + exixgtaUC * self.density_df.loss + mass # df[f'exag1_{line}'] = exleaUC1 + exixgtaUC * self.density_df.loss + mass # is this ever used? # df[f'exleag_{line}'] = exleaUC / df.gF # df[f'exleag1_{line}'] = exleaUC1 / df.gF # # again, exi_xgtag is super important, so we will compute it bare bones the same way as exi_xgta # df[f'exi_xgtag_{line}'] = exixgtaUC / df.gS # # # df['exi_xgtag_' + line] = ((df[f'exeqa_{line}'] / df.loss * # df.gp_total).shift(-1)[::-1].cumsum()) / df.gp_total.shift(-1)[::-1].cumsum() # exa uses S in the denominator...and actually checking values there is a difference between the sum and gS # # May 2020 new treatment of masses # mass = ημ_mass = total_mass = 0. if dist.mass: # this is John's problem: the last scenario is getting all the weight... # total_mass is is the "shortfall" in gp_total - it is added at the end; it is not necessary if the # distribution is actually bounded - then you already pick up the mass # only need to add masses up to this point - an issue for bounded variables # mass = total_mass * self.density_df[f'exi_xeqa_{line}'].iloc[idx_ess_sup] if np.allclose(1.0, df.gp_total.sum()): logger.info('gp_total sums to 1, mass accounted for in gp_total; no further adjustment needed') else: mass = dist.mass * mass_hints[line] ημ_mass = dist.mass * (np.sum(mass_hints) - mass_hints[line]) total_mass = dist.mass logger.info(f'sum(gp_total)={df.gp_total.sum():.5g} < 1, setting {line} mass = {mass}') # original # df['exi_xgtag_' + line] = ((df[f'exeqa_{line}'] / df.loss * # df.gp_total).shift(-1)[::-1].cumsum()) / df.gS # df['exi_xgtag_ημ_' + line] = ((df[f'exeqa_ημ_{line}'] / df.loss * # df.gp_total).shift(-1)[::-1].cumsum()) / df.gS # Nov 2020 # shift[-1] because result is for > a, so the first entry sums from bucket 1... # need the denominator to equal the numerator sum of p values # the shift up needs to be filled in with the last S value (for the tail) otherwise that probability # is lost...hence we need to set fill_values: last_gS = df.gS.iloc[-1] last_x = df[f'exeqa_{line}'].iloc[-1] / df.loss.iloc[-1] * last_gS logger.debug(f'Tail adjustment for {line}: {last_x:.6g}') df['exi_xgtag_' + line] = \ ((df[f'exeqa_{line}'] / df.loss * df.gp_total). shift(-1, fill_value=last_x)[::-1].cumsum() + mass) / (df.gS + total_mass) # need these to be zero so nan's do not propagate df.loc[gSeq0, 'exi_xgtag_' + line] = 0. if not efficient: last_x = df[f'exeqa_ημ_{line}'].iloc[-1] / df.loss.iloc[-1] * last_gS df['exi_xgtag_ημ_' + line] = \ ((df[f'exeqa_ημ_{line}'] / df.loss * df.gp_total). shift(-1, fill_value=last_x)[::-1].cumsum() + ημ_mass) / (df.gS + total_mass) df.loc[gSeq0, 'exi_xgtag_ημ_' + line] = 0. # # # following the Audit Vignette this is the way to go: # in fact, need to shift both down because cumint (prev just gS, but int beta g...integrands on same # basis # df[f'exag_{line}'] = (df[f'exi_xgtag_{line}'].shift(1) * df.gS.shift(1)).cumsum() * self.bs # df[f'exag_ημ_{line}'] = (df[f'exi_xgtag_ημ_{line}'].shift(1) * df.gS.shift(1)).cumsum() * self.bs # np.allclose( # (df[f'exi_xgtag_{line}'].shift(1, fill_value=0) * df.gS.shift(1, fill_value=0)).cumsum() * self.bs, # (df[f'exi_xgtag_{line}'] * df.gS).shift(1, fill_value=0).cumsum() * self.bs) # Doh df[f'exag_{line}'] = (df[f'exi_xgtag_{line}'] * df.gS).shift(1, fill_value=0).cumsum() * self.bs if not efficient: df[f'exag_ημ_{line}'] = (df[f'exi_xgtag_ημ_{line}'] * df.gS).shift(1, fill_value=0).cumsum() * self.bs # maybe sometime you want this unchecked item? # df[f'exleag_1{line}'] = np.cumsum( df[f'exeqa_{line}'] * df.p_total ) # it makes a difference NOT to divivde by df.gS but to compute the actual weights you are using (you mess # around with the last weight) # # # # these are all here for debugging...see # C:\S\TELOS\spectral_risk_measures_monograph\spreadsheets\[AS_IJW_example.xlsx] # df[f'exag1_{line}'] = exleaUC + exixgtaUC1 * self.density_df.loss + mass # df[f'exi_xgtag1_{line}'] = exixgtaUC1 / df.gS # df[f'exleaUC_{line}'] = exleaUC # df[f'exleaUCcs_{line}'] = exleaUCcs # df[f'U_{line}'] = exixgtaUC # df[f'U1_{line}'] = exixgtaUC1 # df[f'RAW_{line}'] = self.density_df.loc[::-1, f'exeqa_{line}'] / self.density_df.loc[::-1, 'loss'] * \ # df.loc[::-1, 'gp_total'] if efficient: # need to get to T.M and T.Q for pricing... laser in on those... # duplicated and edited code from below df['exag_total'] = df.gS.shift(1, fill_value=0).cumsum() * self.bs df['M.M_total'] = (df.gS - df.S) df['M.Q_total'] = (1 - df.gS) # hummmm.aliases, but...? # df['M.L_total'] = df['S'] # df['M.P_total'] = df['gS'] # df['T.L_total'] = df['exa_total'] # df['T.P_total'] = df['exag_total'] # critical insight is the layer ROEs are the same for all lines by law invariance # lhopital's rule estimate of g'(1) = ROE(1) # this could blow up... ϵ = 1e-10 gprime1 = (g(1 - ϵ) - (1 - ϵ)) / (1 - g(1 - ϵ)) df['M.ROE_total'] = np.where(df['M.Q_total']!=0, df['M.M_total'] / df['M.Q_total'], gprime1) # where is the ROE zero? need to handle separately else Q will blow up roe_zero = (df['M.ROE_total'] == 0.0) # print(f"g'(0)={gprime1:.5f}\nroe zero vector {roe_zero}") for line in self.line_names_ex: report_time(f'apply_distortion - starting {line} efficient loop') df[f'T.M_{line}'] = df[f'exag_{line}'] - df[f'exa_{line}'] mm_l = df[f'T.M_{line}'].diff().shift(-1) / self.bs # careful about where ROE==0 mq_l = mm_l / df['M.ROE_total'] mq_l.iloc[-1] = 0 mq_l.loc[roe_zero] = np.nan df[f'T.Q_{line}'] = mq_l.shift(1).cumsum() * self.bs df.loc[0, f'T.Q_{line}'] = 0 if create_augmented: self.augmented_df = df return Answer(augmented_df=df) # sum of parts: careful not to include the total twice! # not used # df['exag_sumparts'] = df.filter(regex='^exag_[^η]').sum(axis=1) # LEV under distortion g # originally # df['exag_total'] = self.cumintegral(df['gS']) # revised cumintegral does: v.shift(1, fill_value=0).cumsum() * bs df['exag_total'] = df.gS.shift(1, fill_value=0).cumsum() * self.bs # df.loc[0, 'exag_total'] = 0 # comparison of total and sum of parts # Dec 2019 added info to compute the total margin and capital allocation by layer # [MT].[L LR Q P M]_line: marginal or total (ground-up) loss, loss ratio etc. # do NOT divide MARGINAL versions by bs because they are per 1 wide layer # df['lookslikemmtotalxx'] = (df.gS - df.S) df['M.M_total'] = (df.gS - df.S) df['M.Q_total'] = (1 - df.gS) # hummmm.aliases, but...? df['M.L_total'] = df['S'] df['M.P_total'] = df['gS'] # df['T.L_total'] = df['exa_total'] # df['T.P_total'] = df['exag_total'] # critical insight is the layer ROEs are the same for all lines by law invariance # lhopital's rule estimate of g'(1) = ROE(1) # this could blow up... TODO extend Distortion class to return gprime1 ϵ = 1e-10 gprime1 = (g(1 - ϵ) - (1 - ϵ)) / (1 - g(1 - ϵ)) df['M.ROE_total'] = np.where(df['M.Q_total']!=0, df['M.M_total'] / df['M.Q_total'], gprime1) # where is the ROE zero? need to handle separately else Q will blow up roe_zero = (df['M.ROE_total'] == 0.0) report_time('apply_distortion - first line loop complete') # print(f"g'(0)={gprime1:.5f}\nroe zero vector {roe_zero}") for line in self.line_names_ex: report_time(f'apply_distortion - starting {line} loop 2') # these are not used # df[f'exa_{line}_pcttotal'] = df['exa_' + line] / df.exa_total # df[f'exag_{line}_pcttotal'] = df['exag_' + line] / df.exag_total # hummm more aliases df[f'T.L_{line}'] = df[f'exa_{line}'] df[f'T.P_{line}'] = df[f'exag_{line}'] df.loc[0, f'T.P_{line}'] = 0 # TOTALs = ground up cumulative sums # exag is the layer (marginal) premium and exa is the layer (marginal) loss df[f'T.LR_{line}'] = df[f'exa_{line}'] / df[f'exag_{line}'] df[f'T.M_{line}'] = df[f'exag_{line}'] - df[f'exa_{line}'] df.loc[0, f'T.M_{line}'] = 0 # MARGINALs # MM should be per unit width layer so need to divide by bs # prepend=0 satisfies: if # d['B'] = d.A.cumsum() # d['C'] = np.diff(d.B, prepend=0) # then d.C == d.A, which is what you want. # note this overwrites M.M_total set above # T.M starts at zero, by previous line and sense: no assets ==> no prem or loss # old # df[f'M.M_{line}'] = np.diff(df[f'T.M_{line}'], prepend=0) / self.bs # new: df[f'M.M_{line}'] = df[f'T.M_{line}'].diff().shift(-1) / self.bs # careful about where ROE==0 df[f'M.Q_{line}'] = df[f'M.M_{line}'] / df['M.ROE_total'] df[f'M.Q_{line}'].iloc[-1] = 0 df.loc[roe_zero, f'M.Q_{line}'] = np.nan # WHAT IS THE LAYER AT ZERO? Should it have a price? What is that price? # TL and TP at zero are both 1 if line != 'total': df[f'M.L_{line}'] = df[f'exi_xgta_{line}'] * df['S'] df[f'M.P_{line}'] = df[f'exi_xgtag_{line}'] * df['gS'] df[f'M.LR_{line}'] = df[f'M.L_{line}'] / df[f'M.P_{line}'] # for total need to reflect layer width... # Jan 2020 added shift down df[f'T.Q_{line}'] = df[f'M.Q_{line}'].shift(1).cumsum() * self.bs df.loc[0, f'T.Q_{line}'] = 0 df[f'T.ROE_{line}'] = df[f'T.M_{line}'] / df[f'T.Q_{line}'] # leverage df[f'T.PQ_{line}'] = df[f'T.P_{line}'] / df[f'T.Q_{line}'] df[f'M.PQ_{line}'] = df[f'M.P_{line}'] / df[f'M.Q_{line}'] # in order to undo some numerical issues, things will slightly not add up # but that appears to be a numerical issue around the calc of exag df['T.L_total'] = df['exa_total'] df['T.P_total'] = df['exag_total'] df['T.Q_total'] = df.loss - df['exag_total'] df['T.M_total'] = df['exag_total'] - df['exa_total'] df['T.PQ_total'] = df['T.P_total'] / df['T.Q_total'] df['T.LR_total'] = df['T.L_total'] / df['T.P_total'] df['T.ROE_total'] = df['T.M_total'] / df['T.Q_total'] f_distortion = f_byline = f_bylineg = f_exas = None if plots == 'all': plots = ['basic', 'extended'] if plots: if 'basic' in plots: f_distortion, ax = plt.subplots(1, 1, figsize=(4, 4)) ax.plot(df.exag_sumparts, label='Sum of Parts') ax.plot(df.exag_total, label='Total') ax.plot(df.exa_total, label='Loss') ax.legend() ax.set_title(f'Mass audit for {dist.name}') ax.legend(loc="upper right") ax.grid() if 'extended' in plots: # yet more graphics, but the previous one is the main event # truncate for graphics max_x = 1.1 * self.q(1 - 1e-6) df_plot = df.loc[0:max_x, :] f_exas, axs, axiter = AxisManager.make_figure(12, sharex=True) ax = next(axiter) df_plot.filter(regex='^p_').sort_index(axis=1).plot(ax=ax) ax.set_ylim(0, df_plot.filter(regex='p_[^η]').iloc[1:, :].max().max()) ax.set_title("Densities") ax.legend(loc="upper right") ax.grid() ax = next(axiter) df_plot.loc[:, ['p_total', 'gp_total']].plot(ax=ax) ax.set_title("Total Density and Distortion") ax.legend(loc="upper right") ax.grid() ax = next(axiter) df_plot.loc[:, ['S', 'gS']].plot(ax=ax) ax.set_title("S, gS") ax.legend(loc="upper right") ax.grid() # exi_xlea removed for prefix in ['exa', 'exag', 'exeqa', 'exgta', 'exi_xeqa', 'exi_xgta']: # look ahead operator: does not match n just as the next char, vs [^n] matches everything except n ax = next(axiter) df_plot.filter(regex=f'^{prefix}_(?!ημ)[a-zA-Z0-9]+$').sort_index(axis=1).plot(ax=ax) ax.set_title(f'{prefix} by line') ax.legend(loc="upper left") ax.grid() if prefix.find('xi_x') > 0: # fix scale for proportions ax.set_ylim(-0.025, 1.025) ax = next(axiter) df_plot.filter(regex='^exa_.*_pcttotal$').sort_index(axis=1).plot(ax=ax) ax.set_title('Proportion of loss: T.L_line / T.L_total') ax.set_ylim(0, 1.05) ax.legend(loc='upper left') ax.grid() ax = next(axiter) df_plot.filter(regex='^exag_.*_pcttotal$').sort_index(axis=1).plot(ax=ax) ax.set_title('Proportion of premium: T.P_line / T.P_total') # ax.set_ylim(0, 1.05) ax.legend(loc='upper left') ax.grid() ax = next(axiter) df_plot.filter(regex='^M.LR_').sort_index(axis=1).plot(ax=ax) ax.set_title('LR with the Natural (constant layer ROE) Allocation') ax.legend(loc='lower right') ax.grid() # by line plots nl = len(self.line_names_ex) f_byline, axs, axiter = AxisManager.make_figure(nl) for line in self.line_names: ax = next(axiter) df_plot.filter(regex=f'ex(le|eq|gt)a_{line}').sort_index(axis=1).plot(ax=ax) ax.set_title(f'{line} EXs') # ? ax.set(ylim=[0, self.q(0.999, 'lower')]) ax.legend(loc='upper left') ax.grid() AxisManager.tidy_up(f_byline, axiter) # compare exa with exag for all lines f_bylineg, axs, axiter = AxisManager.make_figure(nl) for line in self.line_names_ex: ax = next(axiter) df_plot.filter(regex=f'exa[g]?_{line}$').sort_index(axis=1).plot(ax=ax) ax.set_title(f'{line} T.L and T.P') ax.legend(loc='lower right') ax.grid() AxisManager.tidy_up(f_bylineg, axiter) if create_augmented: self.augmented_df = df # store associated distortion self._distortion = dist return Answer(augmented_df=df, f_distortion=f_distortion, f_byline=f_byline, f_bylineg=f_bylineg, f_exas=f_exas) def var_dict(self, p, kind='lower', total='total', snap=False): """ make a dictionary of value at risks for each line and the whole portfolio. Returns: {line : var(p, kind)} and includes the total as self.name line if p near 1 and epd uses 1-p. Example: for p, arg in zip([.996, .996, .996, .985, .01], ['var', 'lower', 'upper', 'tvar', 'epd']): print(port.var_dict(p, arg, snap=True)) :param p: :param kind: var (defaults to lower), upper, lower, tvar, epd :param total: name for total: total=='name' gives total name self.name :param snap: snap tvars to index :return: """ if kind=='var': kind = 'lower' if kind=='tvar': d = {a.name: a.tvar(p) for a in self.agg_list} d['total'] = self.tvar(p) elif kind=='epd': if p >= 0.7: p = 1 - p logger.debug(f'Illogical value of p={1-p:.5g} passed for epd; using {p:.5g}') d = {ln: float(self.epd_2_assets[(ln, 0)](p)) for ln in self.line_names_ex } else: d = {a.name: a.q(p, kind) for a in self.agg_list} d['total'] = self.q(p, kind) if total != 'total': d[self.name] = d['total'] del d['total'] if snap and kind in ['tvar', 'epd']: d = {k: self.snap(v) for k, v in d.items()} return d def gamma(self, a=None, p=None, kind='lower', compute_stand_alone=False, axs=None, plot_mode='return'): """ Return the vector gamma_a(x), the conditional layer effectiveness given assets a. Assets specified by percentile level and type (you need a in the index) gamma can be created with no base and no calibration - it does not depend on a distortion. It only depends on total losses. Returns the total and by layer versions, see "Main Result for Conditional Layer Effectiveness; Piano Diagram" in OneNote In total gamma_a(x) = E[ (a ^ X) / X | X > x] is the average rate of reimbursement for losses above x given capital a. It satisfies int_0^\infty gamma_a(x) S(x) dx = E[a ^ X]. Notice the integral is to infinity, regardless of the amount of capital a. By line gamma_{a,i}(x) = E[ E[X_i | X] / X {(X ^ a) / X} 1_{X>x} ] / E[ {E[X_i | X] / X} 1_{X>x} ]. The denominator equals total weights. It is the line-i recovery weighted layer effectiveness. It equals alpha_i(x) S(x). Now we have E[X_i(a)] = int_0^infty gamma_{a,i}(x) alpha_i(x) S(x) dx Note that you need upper and lower q's in aggs now too. Nov 2020: added arguments for plots; revised axes, separate plots by line :param a: input a or p and kind as usual :param p: asset level percentile :param kind: lower or upper :param compute_stand_alone: add stand-alone evaluation of gamma :param axs: enough axes; only plot if not None :param plot_mode: return or linear scale for y axis :return: """ if a is None: assert p is not None a = self.q(p, kind) else: p = self.cdf(a) ql = self.q(p, 'lower') qu = self.q(p, 'upper') logger.warning( f'Input a={a} to gamma; computed p={p:.8g}, lower and upper quantiles are {ql:.8g} and {qu:.8g}') # alter in place or return a copy? For now return a copy... temp = self.density_df.filter(regex='^(p_|e1xi_1gta_|exi_xgta_|exi_xeqa_|' 'exeqa_)[a-zA-Z]|^S$|^loss$').copy() # var dictionaries var_dict = self.var_dict(p, kind, 'total') extreme_var_dict = self.var_dict(1 - (1 - p) / 100, kind, 'total') # rate of payment factor min_xa = np.minimum(temp.loss, a) / temp.loss temp['min_xa_x'] = min_xa # total is a special case ln = 'total' gam_name = f'gamma_{self.name}_{ln}' # unconditional version avoid divide and multiply by a small number # exeqa is closest to the raw output... temp[f'exi_x1gta_{ln}'] = (temp[f'loss'] * temp.p_total / temp.loss).shift(-1)[::-1].cumsum() * self.bs # equals this temp.S?! s_ = temp.p_total.shift(-1)[::-1].cumsum() * self.bs # print(s_[:-1:-1], temp[f'exi_x1gta_{ln}'].iloc[:-2], temp.S.iloc[:-1] * self.bs) t1, t2 = np.allclose(s_[:-1:-1], temp[f'exi_x1gta_{ln}'].iloc[-1]), \ np.allclose(temp[f'exi_x1gta_{ln}'].iloc[:-1], temp.S.iloc[:-1] * self.bs) logger.debug(f'TEMP: the following should be close: {t1}, {t2} (expect True/True)') # this V 1.0 is exi_x for total temp[gam_name] = (min_xa * 1.0 * temp.p_total).shift(-1)[::-1].cumsum() / \ (temp[f'exi_x1gta_{ln}']) * self.bs for ln in self.line_names: # sa = stand alone; need to figure the sa capital from the agg objects hence var_dict if axs is not None or compute_stand_alone: a_l = var_dict[ln] a_l_ = a_l - self.bs xinv = temp[f'e1xi_1gta_{ln}'] gam_name = f'gamma_{ln}_sa' s = 1 - temp[f'p_{ln}'].cumsum() temp[f'S_{ln}'] = s temp[gam_name] = 0 temp.loc[0:a_l_, gam_name] = (s[0:a_l_] - s[a_l] + a_l * xinv[a_l]) / s[0:a_l_] temp.loc[a_l:, gam_name] = a_l * xinv[a_l:] / s[a_l:] temp[gam_name] = temp[gam_name].shift(1) # method unreliable in extreme right tail, but now changed plotting, not an issue # temp.loc[extreme_var_dict[ln]:, gam_name] = np.nan # actual computation for l within portfolio allowing for correlations gam_name = f'gamma_{self.name}_{ln}' # unconditional version avoid divide and multiply by a small number # exeqa is closest to the raw output... temp[f'exi_x1gta_{ln}'] = (temp[f'exeqa_{ln}'] * temp.p_total / temp.loss).shift(-1)[::-1].cumsum() * self.bs temp[gam_name] = (min_xa * temp[f'exi_xeqa_{ln}'] * temp.p_total).shift(-1)[::-1].cumsum() / \ (temp[f'exi_x1gta_{ln}']) * self.bs # other stuff helpful for plotting # temp['BEST'] = 1 # temp.loc[a:, 'BEST'] = a / temp.loc[a:, 'loss'] # temp['WORST'] = np.maximum(0, 1 - temp.loc[a, 'S'] / temp.S) # single plot # if axs is not None: # axs = axs.flat # ax0 = axs[0] # renamer = self.renamer # temp.filter(regex='gamma|BEST|WORST').rename(columns=renamer).sort_index(1). \ # plot(ylim=[-.05, 1.05], linewidth=1, ax=ax0) # for ln in ax0.lines[:2]: # lbl = ln.get_label() # if lbl == lbl.upper(): # ln.set(linewidth=0.5, c='C7', linestyle='--' if lbl=='BEST' else ':', label=lbl.title()) # nl = len(self.line_names) # for i, ln in enumerate(ax0.lines[2:-1:2]): # ln.set(c=f'C{i}') # ax0.lines[2*i+3].set(c=f'C{i}', lw=.5) # if ln.get_label().find('part of'): # ln.set(ls='-', lw=1) # ax0.lines[-1].set(lw=1, c='C7') # ax0.grid('b') # # update to reflect changes to line styles # ax0.legend() # ax0.set(title=f'Layer Effectiveness, a={a:,.0f} at p={p:.3f}', xlim=[0, extreme_var_dict['total']]) # # # fancy comparison plots # temp_ex = None # if axs is not None: # # ax1 = return period scale, ax2 = linear scale, ax3 = survival functions # ax1, ax2 = axs[1:] # # temp_ex = temp.query(f'loss < {extreme_var_dict["total"]}').filter(regex='^gamma_|^p_') # temp_ex[[f'S_{l[2:]}' for l in temp_ex.filter(regex='p_').columns]] = \ # temp_ex.filter(regex='p_').shift(-1, fill_value=0).iloc[::-1].cumsum() # btemp = temp_ex.filter(regex='gamma_').rename(columns=renamer).sort_index(axis=1) # # first two plots are same except for scales # (1 / (1 - btemp.iloc[1:])).plot(logy=True, ylim=[0,1000], ax=ax1) # btemp.plot(ax=ax2, ylim=[0, 1.005]) # ax1.set(title='Gamma Functions (Return Period Scale)') # ax2.set(title='Gamma Functions') # # third plot: like first but log S scale on x and y # # # sort out colors # for ax in axs: # for i, line in enumerate(ax.lines[:-1:2]): # line.set(c=f'C{i}', lw=1) # ax.lines[2*i+1].set(c=f'C{i}', lw=.5) # ax.grid(which='major', axis='y') # ax.lines[2*nl].set(c='C7', lw=1) # # put in asset levels # for ax in axs: # for i, l in enumerate(self.line_names + [self.name]): # ln = ax.plot([var_dict[l], var_dict[l]], [1 if ax is ax1 else 0, ylim_zoom[1]], # label=f'{l} s/a assets {var_dict[l]/1e6:,.1f}M') # ln[0].set(linewidth=.5, linestyle='--', c=f'C{i}') # # update legend to reflect line style changes # ax.lines[-1].set(c='C7') # ax.legend(loc='upper right') if axs is not None: axi = iter(axs.flat) nr, nc = axs.shape v = self.var_dict(.996, 'lower', 'total') ef = EngFormatter(3, True) if plot_mode == 'return': def transformer(x): # transform on y scale return np.where(x==0, np.nan, 1.0 / (1 - x)) yscale = 'log' else: def transformer(x): # transform on y scale return x yscale = 'linear' # 1/s is re-used s1 = 1 / temp.S for i, ln in enumerate(self.line_names_ex): r, c = i // nc, i % nc ax = next(axi) if ln != 'total': # line 1/s ls1 = 1/temp[f'S_{ln}'] ax.plot(ls1, transformer(temp[f'gamma_{ln}_sa']), c='C1', label=f'SA {ln}') ax.plot(s1, transformer(temp[f'gamma_{self.name}_total']), lw=1, c='C7', label='total') c = 'C1' else: ls1 = s1 c = 'C0' ax.plot(s1, transformer(temp[f'gamma_{self.name}_{ln}']), c='C0', label=f'Pooled {ln}') temp['WORST'] = np.maximum(0, 1 - (1 - p) * ls1) temp['BEST'] = 1 temp.loc[v[ln]:, 'BEST'] = v[ln] / temp.loc[v[ln]:, 'loss'] ax.fill_between(ls1, transformer(temp.WORST), transformer(temp.BEST), lw=.5, ls='--', alpha=.1, color=c, label="Possible range") ax.plot(ls1, transformer(temp.BEST), lw=.5, ls='--', alpha=1, c=c) ax.plot(ls1, transformer(temp.WORST), lw=.5, ls=':', alpha=1, c=c) ax.set(xlim=[1, 1e9], xscale='log', yscale=yscale, xlabel='Loss return period' if r==nr-1 else None, ylabel='Coverage Effectiveness (RP)' if c==0 else None, title=f'{ln}, a={ef(v[ln]).strip()}') ax.axvline(1/(1-.996), ls='--', c='C7', lw=.5, label='Capital p') ll = ticker.LogLocator(10, numticks=10) ax.xaxis.set_major_locator(ll) lm = ticker.LogLocator(base=10.0, subs=np.arange(1.0, 10.0) * 0.1, numticks = 10) ax.xaxis.set_minor_locator(lm) ax.grid(lw=.25) ax.legend(loc='upper right') # tidy up axes try: while 1: ax.figure.delaxes(next(axi)) except StopIteration: pass temp.drop(columns=['BEST', 'WORST']) return Answer(gamma_df=temp.sort_index(axis=1), base=self.name, assets=a, p=p, kind=kind) def price(self, p, kind, g, mass_hints=None, efficient=True): """ Price using regulatory and pricing g functions Compute E_price (X wedge E_reg(X) ) where E_price uses the pricing distortion and E_reg uses the regulatory distortion regulatory capital distortion is applied on unlimited basis: ``reg_g`` can be: * if input < 1 it is a number interpreted as a p value and used to determine VaR capital * if input > 1 it is a directly input capital number * d dictionary: Distortion; spec { name = dist name | var | epd, shape=p value a distortion used directly ``pricing_g`` is { name = ph|wang and shape= or lr= or roe= }, if shape and lr or roe shape is overwritten if ly it must include ro in spec if lr and roe then lr is used :param p: a distortion function spec or just a number; if >1 assets if <1 a prob converted to quantile :param kind: var lower upper tvar epd :param g: pricing distortion function :param mass_hints: mass hints for distortions with a mass, pd.Series indexed by line names :param efficient: for apply_distortion :return: """ # figure regulatory assets; applied to unlimited losses vd = self.var_dict(p, kind, snap=True) a_reg = vd['total'] # relevant row for all statistics_df row = self.density_df.loc[a_reg] # figure pricing distortion if isinstance(g, Distortion): # just use it pass else: # spec as dict prem = 0 if 'lr' in g: # given LR, figure premium prem = row['exa_total'] / g['lr'] elif 'roe' in g: # given roe, figure premium roe = g['roe'] delta = roe / (1 + roe) prem = row['exa_total'] + delta * (a - row['exa_total']) if prem > 0: g = self.calibrate_distortion(name=g['name'], premium_target=prem, assets=a_reg) else: g = Distortion(**g) ans_ad = self.apply_distortion(g, create_augmented=False, mass_hints=mass_hints, efficient=efficient) aug_row = ans_ad.augmented_df.loc[a_reg] # holder for the answer df = pd.DataFrame(columns=['line', 'L', 'P', 'M', 'Q'], dtype=float) df.columns.name = 'statistic' df = df.set_index('line', drop=True) for line in self.line_names_ex: df.loc[line, :] = [aug_row[f'exa_{line}'], aug_row[f'exag_{line}'], aug_row[f'T.M_{line}'], aug_row[f'T.Q_{line}']] df['a'] = df.P + df.Q df['LR'] = df.L / df.P df['PQ'] = df.P / df.Q df['ROE'] = df.M / df.Q return Answer(pricing_df=df, dist=g) def analyze_distortions(self, a=0, p=0, kind='lower', mass_hints=None, efficient=True, augmented_dfs=None, regex=''): """ run analyze_distortion on self.dists :param a: :param p: the percentile of capital that the distortions are calibrated to :param efficient: :param mass_hints: :param kind: :param regex: regex to match name of distortion to apply :return: """ import re a, p = self.set_a_p(a, p) dfs = [] ans = Answer() if augmented_dfs is None: augmented_dfs = {} ans['augmented_dfs'] = augmented_dfs for k, d in self.dists.items(): if regex == '' or re.match(regex, k): if augmented_dfs is not None and k in augmented_dfs: use_self = True self.augmented_df = augmented_dfs[k] logger.info(f'Found {k} in provided augmented_dfs...') else: use_self = False logger.info(f'Running distortion {d} through analyze_distortion, p={p}...') # first distortion...add the comps...these are same for all dists ad_ans = self.analyze_distortion(d, p=p, kind=kind, add_comps=len(dfs) == 0, mass_hints=mass_hints, efficient=efficient, use_self=use_self) dfs.append(ad_ans.exhibit) ans[f'{k}_exhibit'] = ad_ans.exhibit ans[f'{k}_pricing'] = ad_ans.pricing if not efficient and k not in augmented_dfs: # remember, augmented_dfs is part of ans augmented_dfs[k] = ad_ans.augmented_df ans['comp_df'] = pd.concat(dfs).sort_index() return ans def analyze_distortion(self, dname, dshape=None, dr0=.025, ddf=5.5, LR=None, ROE=None, p=None, kind='lower', A=None, use_self=False, plot=False, a_max_p=1-1e-8, add_comps=True, mass_hints=None, efficient=True): """ Graphic and summary DataFrame for one distortion showing results that vary by asset levelm such as increasing or decreasing cumulative premium. Characterized by the need to know an asset level, vs. apply_distortion that produced values for all asset levels. Returns DataFrame with values upto the input asset level...differentiates from apply_distortion graphics that cover the full range. analyze_pricing will then zoom in and only look at one asset level for micro-dynamics... Logic of arguments: if data_in == 'self' use self.augmented_df; this implies a distortion self.distortion else need to build the distortion and apply it if dname is a distortion use it else built one calibrated to input data LR/ROE/a/p: if p then a=q(p, kind) else p = MESSY if LR then P and ROE; if ROE then Q to P to LR these are used to calibrate distortion A newly made distortion is run through apply_distortion with no plot Logic to determine assets similar to calibrate_distortions. Can pass in a pre-calibrated distortion in dname Must pass LR or ROE to determine profit Must pass p or A to determine assets Output is an `Answer` class object containing Answer(augmented_df=deets, trinity_df=df, distortion=dist, fig1=f1 if plot else None, fig2=f2 if plot else None, pricing=pricing, exhibit=exhibit, roe_compare=exhibit2, audit_df=audit_df) Originally `example_factory`. example_factory_exhibits included: do the work to extract the pricing, exhibit and exhibit 2 DataFrames from deets Can also accept an ans object with an augmented_df element (how to call from outside) POINT: re-run exhibits at different p/a thresholds without recalibrating add relevant items to audit_df a = q(p) if both given; if not both given derived as usual Figures show :param dname: name of distortion :param dshape: if input use dshape and dr0 to make the distortion :param dr0: :param ddf: r0 and df params for distortion :param LR: otherwise use loss ratio and p or a loss ratio :param ROE: :param p: p value to determine capital. :param kind: type of VaR, upper or lower :param A: :param use_self: if true use self.augmented and self.distortion...else recompute :param plot: :param a_max_p: percentile to use to set the right hand end of plots :param add_comps: add old-fashioned method comparables (included =True as default to make backwards comp. :param mass_hints: for apply_distortion :param efficient: :return: various dataframes in an Answer class object """ report_time('analyze_distortion | start') # setup: figure what distortion to use, apply if necessary if use_self: # augmented_df was called deets before, FYI augmented_df = self.augmented_df if type(dname) == str: dist = self.dists[dname] elif isinstance(dname, Distortion): pass else: raise ValueError(f'Unexpected dname={dname} passed to analyze_distortion') a_cal = self.q(p, kind) exa = self.density_df.loc[a_cal, 'exa_total'] exag = augmented_df.loc[a_cal, 'exag_total'] K = a_cal - exag LR = exa / exag ROE = (exag - exa) / K else: # figure assets a_cal (for calibration) from p or A if p: # have p a_cal = self.q(p, kind) exa = self.density_df.loc[a_cal, 'exa_total'] else: # must have A...must be in index assert A is not None p = self.cdf(A) a_cal = self.q(p) exa = self.density_df.loc[a_cal, 'exa_total'] if a_cal != A: logger.info(f'a_cal:=q(p)={a_cal} is not equal to A={A} at p={p}') if dshape or isinstance(dname, Distortion): # specified distortion, fill in if isinstance(dname, Distortion): dist = dname else: dist = Distortion(dname, dshape, dr0, ddf) _x = self.apply_distortion(dist, create_augmented=False, mass_hints=mass_hints, efficient=efficient) augmented_df = _x.augmented_df exa = self.density_df.loc[a_cal, 'exa_total'] exag = augmented_df.loc[a_cal, 'exag_total'] profit = exag - exa K = a_cal - exag ROE = profit / K LR = exa / exag else: # figure distortion from LR or ROE and apply if LR is None: assert ROE is not None delta = ROE / (1 + ROE) nu = 1 - delta exag = nu * exa + delta * a_cal LR = exa / exag else: exag = exa / LR profit = exag - exa K = a_cal - exag ROE = profit / K # was wasteful # cd = self.calibrate_distortions(LRs=[LR], As=[a_cal], r0=dr0, df=ddf) dist = self.calibrate_distortion(dname, r0=dr0, df=ddf, roe=ROE, assets=a_cal) _x = self.apply_distortion(dist, create_augmented=False, mass_hints=mass_hints, efficient=efficient) augmented_df = _x.augmented_df report_time('analyze_distortion | distortion applied etc.') # other helpful audit values # keeps track of details of calc for Answer audit_df = pd.DataFrame(dict(stat=[p, LR, ROE, a_cal, K, dist.name, dist.shape]), index=['p', 'LR', "ROE", 'a_cal', 'K', 'dname', 'dshape']) audit_df.loc['a'] = a_cal audit_df.loc['kind'] = kind # make the pricing summary DataFrame and exhibit: this just contains info about dist # in non-efficient the renamer and existing columns collide and you get duplicates # transpose turns into rows... pricing = augmented_df.rename(columns=self.tm_renamer).loc[[a_cal]].T. \ filter(regex='^(T)\.(L|P|M|Q)_', axis=0).copy() pricing = pricing.loc[~pricing.index.duplicated()] # put in exact Q rather than add up the parts...more accurate pricing.at['T.Q_total', a_cal] = a_cal - exag # TODO EVIL! this reorders the lines and so messes up when port has lines not in alpha order pricing.index = pricing.index.str.split('_|\.', expand=True) pricing = pricing.sort_index() pricing = pd.concat((pricing, pricing.xs(('T','P'), drop_level=False).rename(index={'P': 'PQ'}) / pricing.xs(('T', 'Q')).to_numpy(), pricing.xs(('T', 'L'), drop_level=False).rename(index={'L': 'LR'}) / pricing.xs(('T', 'P')).to_numpy(), pricing.xs(('T', 'M'), drop_level=False).rename(index={'M': 'ROE'}) / pricing.xs(('T', 'Q')).to_numpy() )) pricing.index.set_names(['Method', 'stat', 'line'], inplace=True) pricing = pricing.sort_index() # make nicer exhibit exhibit = pricing.unstack(2).copy() exhibit.columns = exhibit.columns.droplevel(level=0) exhibit.loc[('T', 'a'), :] = exhibit.loc[('T', 'P'), :] + exhibit.loc[('T', 'Q'), :] exhibit.loc[('T', 'a'), :] = exhibit.loc[('T', 'a'), :] * a_cal / exhibit.at[('T', 'a'), 'total'] ans = Answer(augmented_df=augmented_df, distortion=dist, audit_df=audit_df, pricing=pricing, exhibit=exhibit) if add_comps: logger.debug('Adding comps...') ans = self.analyze_distortion_add_comps(ans, a_cal, p, kind, ROE) if plot: ans = self.analyze_distortion_plots(ans, dist, a_cal, p, self.q(a_max_p), ROE, LR) # ans['exhibit'] = ans.exhibit.swaplevel(0,1).sort_index() ans['exhibit'] = ans.exhibit.rename(index={'T': f'Dist {dist.name}'}).sort_index() return ans def analyze_distortion_add_comps(self, ans, a_cal, p, kind, ROE): """ make exhibit with comparison to old-fashioned methods: equal risk var/tvar, scaled var/tvar, stand-alone var/tvar, merton perold, co-TVaR. Not all of these methods is additive. covar method = proportion of variance (additive) Other methods could be added, e.g. a volatility method? Note on calculation =================== Each method computes allocated assets a_i (which it calls Q_i) = Li + Mi + Qi All methods are constant ROEs for capital We have Li in exhibit. Hence: L = Li P = (Li + ROE ai) / (1 + ROE) = v Li + d ai Q = a - P M = P - L ratios In most cases, ai is computed directly, e.g. as a scaled proportion of total assets etc. The covariance method is slightly different. Mi = vi M, vi = Cov(Xi, X) / Var(X) Pi = Li + Mi Qi = Mi / ROE ai = Pi + Qi and sum ai = sum Li + sum Mi + sum Qi = L + M + M/ROE = L + M + Q = a as required. To fit it in the same scheme as all other methods we compute qi = Li + Mi + Qi = Li + vi M + vi M / ROE = li + viM(1+1/ROE) = Li + vi M/d, d=ROE/(1+ROE) :param ans: answer containing dist and augmented_df elements :param a_cal: :param p: :param kind: :param LR: :param ROE: :return: ans Answer object with updated elements """ exhibit = ans.exhibit.copy() # display(exhibit) total_margin = exhibit.at[('T', 'M'), 'total'] logger.debug(f'Total margin = {total_margin}') # shut the style police up: done = [] # some reasonable traditional metrics # tvar threshold giving the same assets as p on VaR logger.debug(f'In analyze_distortion_comps p={p} and a_cal={a_cal}') try: p_t = self.tvar_threshold(p, kind) except ValueError as e: logger.warning(f'Error computing p_t threshold for VaR at p={p}') logger.warning(str(e)) p_t = np.nan try: pv, pt = self.equal_risk_var_tvar(p, p_t) except (ZeroDivisionError, ValueError) as e: logger.warning(f'Error computing pv, pt equal_risk_var_tvar for VaR, p={p}, kind={kind}, p_t={p_t}') logger.warning(str(e)) pv = np.nan pt = np.nan try: pe = self.assets_2_epd[('total', 0)](a_cal) p_e = self.equal_risk_epd(a_cal) except Exception as e: logger.warning(f'Error {e} calibrating EPDs') pe = p_e = 1 - p try: temp = exhibit.loc[('T', 'L'), :] exhibit.loc[('EL', 'Q'), :] = temp / temp['total'] * a_cal done.append('EL') exhibit.loc[('VaR', 'Q'), self.line_names_ex] = [float(a.q(p, kind)) for a in self] + [self.q(p, kind)] done.append('var') exhibit.loc[('TVaR', 'Q'), self.line_names_ex] = [float(a.tvar(p_t)) for a in self] + [self.tvar(p_t)] done.append('tvar') # print(done) exhibit.loc[('ScaledVaR', 'Q'), :] = exhibit.loc[('VaR', 'Q'), :] exhibit.loc[('ScaledTVaR', 'Q'), :] = exhibit.loc[('TVaR', 'Q'), :] exhibit.loc[('ScaledVaR', 'Q'), 'total'] = 0 exhibit.loc[('ScaledTVaR', 'Q'), 'total'] = 0 sumvar = exhibit.loc[('ScaledVaR', 'Q'), :].sum() sumtvar = exhibit.loc[('ScaledTVaR', 'Q'), :].sum() exhibit.loc[('ScaledVaR', 'Q'), :] = \ exhibit.loc[('ScaledVaR', 'Q'), :] * exhibit.at[('VaR', 'Q'), 'total'] / sumvar exhibit.loc[('ScaledTVaR', 'Q'), :] = \ exhibit.loc[('ScaledTVaR', 'Q'), :] * exhibit.at[('TVaR', 'Q'), 'total'] / sumtvar exhibit.at[('ScaledVaR', 'Q'), 'total'] = exhibit.at[('VaR', 'Q'), 'total'] exhibit.at[('ScaledTVaR', 'Q'), 'total'] = exhibit.at[('TVaR', 'Q'), 'total'] # these are NOT additive exhibit.at[('VaR', 'Q'), 'total'] = sumvar exhibit.at[('TVaR', 'Q'), 'total'] = sumtvar exhibit.loc[('EqRiskVaR', 'Q'), self.line_names_ex] = [float(a.q(pv, kind)) for a in self] + [self.q(p)] done.append('eqvar') # print(done) exhibit.loc[('EqRiskTVaR', 'Q'), self.line_names_ex] = [float(a.tvar(pt)) for a in self] + [self.tvar(p_t)] done.append('eqtvar') # print(done) exhibit.loc[('MerPer', 'Q'), self.line_names_ex] = self.merton_perold(p) done.append('merper') # print(done) # co-tvar at threshold to match capital exhibit.loc[('coTVaR', 'Q'), self.line_names_ex] = self.cotvar(p_t) done.append('cotvar') # print(done) # epd and scaled epd methods at 1-p threshold vd = self.var_dict(pe, kind='epd', total='total') logger.debug(f'Computing EPD at {pe:.3%} threshold, total = {vd["total"]}') exhibit.loc[('EPD', 'Q'), vd.keys()] = vd.values() exhibit.loc[('EPD', 'Q'), 'total'] = 0. exhibit.loc[('ScaledEPD', 'Q'), :] = exhibit.loc[('EPD', 'Q'), :] * vd['total'] / \ exhibit.loc[('EPD', 'Q')].sum() exhibit.loc[('ScaledEPD', 'Q'), 'total'] = vd['total'] exhibit.loc[('EPD', 'Q'), 'total'] = exhibit.loc[('EPD', 'Q')].iloc[:-1].sum() exhibit.loc[('EqRiskEPD', 'Q'), self.line_names_ex] = [float( self.epd_2_assets[(l, 0)](p_e) ) for l in self.line_names] + \ [float(self.epd_2_assets[('total',0)](pe))] done.append('epd') # print(done) # covariance = percent of variance allocation # qi = Li + Mi + Qi = Li + vi M + vi M / ROE = li + viM(1+1/ROE) = Li + vi M/d, d=ROE/(1+ROE) d = ROE / (1 + ROE) vars_ = self.audit_df['EmpEX2'] - self.audit_df['EmpEX1']**2 vars_ = vars_ / vars_.iloc[-1] exhibit.loc[('covar', 'Q'), :] = exhibit.loc[('T', 'L'), :] + vars_ * total_margin / d done.append('covar') except Exception as e: logger.warning('Some general out of bounds error on VaRs and TVaRs, setting all equal to zero. ' f'Last completed steps {done[-1] if len(done) else "none"}, ' 'out of var, tvar, eqvar, eqtvar merper. ') logger.warning(f'The built in warning is type {type(e)} saying {e}') for c in ['VaR', 'TVaR', 'ScaledVaR', 'ScaledTVaR', 'EqRiskVaR', 'EqRiskTVaR', 'MerPer', 'coTVaR']: if c.lower() in done: # these numbers have been computed pass else: # put in placeholder exhibit.loc[(c, 'Q'), :] = np.nan exhibit = exhibit.sort_index() # subtract the premium to get the actual capital try: for m in ['EL', 'VaR', 'TVaR', 'ScaledVaR', 'ScaledTVaR', 'EqRiskVaR', 'EqRiskTVaR', 'MerPer', 'coTVaR', 'EPD', 'ScaledEPD', 'EqRiskEPD', 'covar']: # Q as computed above gives assets not equity...so adjust # usual calculus: P = (L + ra)/(1+r); Q = a-P, remember Q above is a (sorry) exhibit.loc[(m, 'L'), :] = exhibit.loc[('T', 'L'), :] exhibit.loc[(m, 'P'), :] = (exhibit.loc[('T', 'L'), :] + ROE * exhibit.loc[(m, 'Q'), :]) / (1 + ROE) exhibit.loc[(m, 'Q'), :] -= exhibit.loc[(m, 'P'), :].values exhibit.loc[(m, 'M'), :] = exhibit.loc[(m, 'P'), :] - exhibit.loc[('T', 'L'), :].values exhibit.loc[(m, 'LR'), :] = exhibit.loc[('T', 'L'), :] / exhibit.loc[(m, 'P'), :] exhibit.loc[(m, 'ROE'), :] = exhibit.loc[(m, 'M'), :] / exhibit.loc[(m, 'Q'), :] exhibit.loc[(m, 'PQ'), :] = exhibit.loc[(m, 'P'), :] / exhibit.loc[(m, 'Q'), :] exhibit.loc[(m, 'a'), :] = exhibit.loc[(m, 'P'), :] + exhibit.loc[(m, 'Q'), :] except Exception as e: logger.error(f'Exception {e} creating LR, P, Q, ROE, or PQ') # print(ans.distortion.name) # display(exhibit) ans.audit_df.loc['TVaR@'] = p_t ans.audit_df.loc['erVaR'] = pv ans.audit_df.loc['erTVaR'] = pt ans.audit_df.loc['EPD@'] = pe ans.audit_df.loc['erEPD'] = p_e ans.update(exhibit=exhibit) return ans def analyze_distortion_plots(self, ans, dist, a_cal, p, a_max, ROE, LR): """ Create plots from an analyze_distortion ans class note: this only looks at distortion related items...it doesn't use anything from the comps :param ans: :param dist: :param a_cal: :param p: :param a_max: :param ROE: :param LR: :return: """ augmented_df = ans.augmented_df # top down stats: e.g. T.P[a_cal] - T.P and zero above a_cal # these are only going to apply to total...will not bother with by line # call this series V.P with v indicating a down arrow and a letter after and close to T # hack out space for nc in ['L', 'P', 'M', 'Q', 'LR', 'ROE', 'PQ']: augmented_df[f'V.{nc}_total'] = 0 augmented_df.loc[0:a_cal, 'V.L_total'] = \ augmented_df.at[a_cal, 'T.L_total'] - augmented_df.loc[0:a_cal, 'T.L_total'] augmented_df.loc[0:a_cal, 'V.P_total'] = \ augmented_df.at[a_cal, 'T.P_total'] - augmented_df.loc[0:a_cal, 'T.P_total'] augmented_df.loc[0:a_cal, 'V.M_total'] = \ augmented_df.at[a_cal, 'T.M_total'] - augmented_df.loc[0:a_cal, 'T.M_total'] augmented_df.loc[0:a_cal, 'V.Q_total'] = \ augmented_df.at[a_cal, 'T.Q_total'] - augmented_df.loc[0:a_cal, 'T.Q_total'] augmented_df.loc[0:a_cal, 'V.LR_total'] = \ augmented_df.loc[0:a_cal, 'V.L_total'] / augmented_df.loc[0:a_cal, 'V.P_total'] augmented_df.loc[0:a_cal, 'V.PQ_total'] = \ augmented_df.loc[0:a_cal, 'V.P_total'] / augmented_df.loc[0:a_cal, 'V.Q_total'] augmented_df.loc[0:a_cal, 'V.ROE_total'] = \ augmented_df.loc[0:a_cal, 'V.M_total'] / augmented_df.loc[0:a_cal, 'V.Q_total'] # bottom up calc is already done: it is the T. series in augmented_df # marginal calc also done: M. series # f_6_part = f_trinity = f_8_part = f_distortion = f_close = None # plot the distortion f_distortion, ax = plt.subplots(1, 1) dist.plot(ax=ax) # six part up and down plot def tidy(a, y=True): """ function to tidy up the graphics """ n = 6 a.set(xlabel='Assets') a.xaxis.set_major_locator(FixedLocator([a_cal])) ff = f'A={a_cal:,.0f}' a.xaxis.set_major_formatter(FixedFormatter([ff])) a.xaxis.set_minor_locator(MaxNLocator(n)) a.xaxis.set_minor_formatter(StrMethodFormatter('{x:,.0f}')) if y: a.yaxis.set_major_locator(MaxNLocator(n)) a.yaxis.set_minor_locator(AutoMinorLocator(4)) # gridlines with various options # https://matplotlib.org/3.1.0/gallery/color/named_colors.html a.grid(which='major', axis='x', c='cornflowerblue', alpha=1, linewidth=1) a.grid(which='major', axis='y', c='lightgrey', alpha=0.5, linewidth=1) a.grid(which='minor', axis='x', c='lightgrey', alpha=0.5, linewidth=1) a.grid(which='minor', axis='y', c='gainsboro', alpha=0.25, linewidth=0.5) # tick marks a.tick_params('x', which='major', labelsize=7, length=10, width=0.75, color='cornflowerblue', direction='out') a.tick_params('y', which='major', labelsize=7, length=5, width=0.75, color='black', direction='out') a.tick_params('both', which='minor', labelsize=7, length=2, width=0.5, color='black', direction='out') # plots f_6_part, axs = plt.subplots(3, 2, figsize=(8, 10), sharex=True, constrained_layout=True) axi = iter(axs.flatten()) # ONE ax = next(axi) # df[['Layer Loss', 'Layer Prem', 'Layer Capital']] augmented_df.filter(regex='^F|^gS|^S').rename(columns=self.renamer). \ plot(xlim=[0, a_max], ylim=[-0.025, 1.025], logy=False, title='F, S, gS: marginal premium and loss', ax=ax) tidy(ax) ax.legend(frameon=True, loc='center right') # TWO ax = next(axi) # df[['Layer Capital', 'Layer Margin']].plot(xlim=xlim, ax=ax) augmented_df.filter(regex='^M\.[QM]_total').rename(columns=self.renamer). \ plot(xlim=[0, a_max], ylim=[-0.05, 1.05], logy=False, title='Marginal Capital and Margin', ax=ax) tidy(ax) ax.legend(frameon=True, loc='center right') # THREE ax = next(axi) # df[['Premium↓', 'Loss↓', 'Capital↓', 'Assets↓', 'Risk Margin↓']].plot(xlim=xlim, ax=ax) augmented_df.filter(regex='^V\.(L|P|Q|M)_total').rename(columns=self.renamer). \ plot(xlim=[0, a_max], ylim=[0, a_max], logy=False, title=f'Decreasing LPMQ from {a_cal:.0f}', ax=ax) (a_cal - augmented_df.loc[:a_cal, 'loss']).plot(ax=ax, label='Assets') tidy(ax) ax.legend(frameon=True, loc='upper right') # FOUR ax = next(axi) augmented_df.filter(regex='^(T|V|M)\.LR_total').rename(columns=self.renamer). \ plot(xlim=[0, a_cal * 1.1], ylim=[-0.05, 1.05], ax=ax, title='Increasing, Decreasing and Marginal LRs') tidy(ax) ax.legend(frameon=True, loc='lower left') # FIVE ax = next(axi) augmented_df.filter(regex='^T\.(L|P|Q|M)_total|loss').rename(columns=self.renamer). \ plot(xlim=[0, a_max], ylim=[0, a_max], logy=False, title=f'Increasing LPMQ to {a_cal:.0f}', ax=ax) tidy(ax) ax.legend(frameon=True, loc='upper left') # SIX # could include leverage? ax = next(axi) augmented_df.filter(regex='^(M|T|V)\.ROE_(total)?$').rename(columns=self.renamer). \ plot(xlim=[0, a_max], # ylim=[-0.05, 1.05], logy=False, title=f'Increasing, Decreasing and Marginal ROE to {a_cal:.0f}', ax=ax) # df[['ROE↓', '*ROE↓', 'ROE↑', 'Marginal ROE', ]].plot(xlim=xlim, logy=False, ax=ax, ylim=ylim) # df[['ROE↓', 'ROE↑', 'Marginal ROE', 'P:S↓', 'P:S↑']].plot(xlim=xlim, logy=False, ax=a, ylim=[0,_]) ax.plot([0, a_max], [ROE, ROE], ":", linewidth=2, alpha=0.75, label='Avg ROE') # print('plot 6 completed\n' * 6) try: tidy(ax) ax.legend(loc='upper right') title = f'{self.name} with {str(dist)} Distortion\nCalibrated to LR={LR:.3f} and p={p:.3f}, ' \ f'Assets={a_cal:,.1f}, ROE={ROE:.3f}' f_6_part.suptitle(title, fontsize='x-large') except Exception as e: logger.error(f'Formatting error in last plot...\n{e}\n...continuing') # trinity plots def tidy2(a, k, xloc=0.25): n = 4 a.xaxis.set_major_locator(MultipleLocator(xloc)) a.xaxis.set_minor_locator(AutoMinorLocator(4)) a.xaxis.set_major_formatter(StrMethodFormatter('{x:.2f}')) a.yaxis.set_major_locator(MaxNLocator(2 * n)) a.yaxis.set_minor_locator(AutoMinorLocator(4)) a.grid(which='major', axis='x', c='lightgrey', alpha=0.5, linewidth=1) a.grid(which='major', axis='y', c='lightgrey', alpha=0.5, linewidth=1) a.grid(which='minor', axis='x', c='gainsboro', alpha=0.25, linewidth=0.5) a.grid(which='minor', axis='y', c='gainsboro', alpha=0.25, linewidth=0.5) # tick marks a.tick_params('both', which='major', labelsize=7, length=4, width=0.75, color='black', direction='out') a.tick_params('both', which='minor', labelsize=7, length=2, width=0.5, color='black', direction='out') # line to show where capital lies a.plot([0, 1], [k, k], linewidth=1, c='black', label='Assets') plots_done = [] try: f_trinity, axs = plt.subplots(1, 5, figsize=(8, 3), constrained_layout=True, sharey=True) axi = iter(axs.flatten()) xr = [-0.05, 1.05] audit = augmented_df.loc[:a_max, :] # ONE ax = next(axi) ax.plot(audit.gS, audit.loss, label='M.P_total') ax.plot(audit.S, audit.loss, label='M.L_total') ax.set(xlim=xr, title='Marginal Prem & Loss') ax.set(xlabel='Loss = S = Pr(X>a)\nPrem = g(S)', ylabel="Assets, a") tidy2(ax, a_cal) ax.legend(loc="upper right", frameon=True, edgecolor=None) plots_done.append(1) # TWO ax = next(axi) m = audit.F - audit.gF ax.plot(m, audit.loss, linewidth=2, label='M') ax.set(xlim=-0.01, title='Marginal Margin', xlabel='M = g(S) - S') tidy2(ax, a_cal, m.max() * 1.05 / 4) plots_done.append(2) # THREE ax = next(axi) ax.plot(1 - audit.gS, audit.loss, label='Q') ax.set(xlim=xr, title='Marginal Equity') ax.set(xlabel='Q = 1 - g(S)') tidy2(ax, a_cal) plots_done.append(3) # FOUR ax = next(axi) temp = audit.loc[self.q(1e-5):, :] r = (temp.gS - temp.S) / (1 - temp.gS) ax.plot(r, temp.loss, linewidth=2, label='ROE') ax.set(xlim=-0.05, title='Layer ROE') ax.set(xlabel='ROE = M / Q') tidy2(ax, a_cal, r.max() * 1.05 / 4) plots_done.append(4) # FIVE ax = next(axi) ax.plot(audit.S / audit.gS, audit.loss) ax.set(xlim=xr, title='Layer LR') ax.set(xlabel='LR = S / g(S)') tidy2(ax, a_cal) plots_done.append(5) except Exception as e: logger.error(f'Plotting error in trinity plots\n{e}\nPlots done {plots_done}\n...continuing') # # # # from original example_factory_sublines try: temp = augmented_df.filter(regex='exi_xgtag?_(?!sum)|^S|^gS|^(M|T)\.').copy() renamer = self.renamer augmented_df.index.name = 'Assets a' temp.index.name = 'Assets a' f_8_part, axs = plt.subplots(4, 2, figsize=(8, 10), constrained_layout=True, squeeze=False) ax = iter(axs.flatten()) # ONE a = (1 - augmented_df.filter(regex='p_').cumsum()).rename(columns=renamer).sort_index(1). \ plot(ylim=[0, 1], xlim=[0, a_max], title='Survival functions', ax=next(ax)) a.grid('b') # TWO a = augmented_df.filter(regex='exi_xgtag?').rename(columns=renamer).sort_index(1). \ plot(ylim=[0, 1], xlim=[0, a_max], title=r'$\alpha=E[X_i/X | X>a],\beta=E_Q$ by Line', ax=next(ax)) a.grid('b') # THREE total margins a = augmented_df.filter(regex=r'^T\.M').rename(columns=renamer).sort_index(1). \ plot(xlim=[0, a_max], title='Total Margins by Line', ax=next(ax)) a.grid('b') # FOUR marginal margins was dividing by bs end of first line # for some reason the last entry in M.M_total can be problematic. a = (augmented_df.filter(regex=r'^M\.M').rename(columns=renamer).sort_index(1).iloc[:-1, :]. plot(xlim=[0, a_max], title='Marginal Margins by Line', ax=next(ax))) a.grid('b') # FIVE a = augmented_df.filter(regex=r'^M\.Q|gF').rename(columns=renamer).sort_index(1). \ plot(xlim=[0, a_max], title='Capital = 1-gS = gF', ax=next(ax)) a.grid('b') for _ in a.lines: if _.get_label() == 'gF': _.set(linewidth=5, alpha=0.3) # recreate legend because changed lines a.legend() # SIX see apply distortion, line 1890 ROE is in augmented_df a = augmented_df.filter(regex='^ROE$|exi_xeqa').rename(columns=renamer).sort_index(1). \ plot(xlim=[0, a_max], title='M.ROE Total and $E[X_i/X | X=a]$ by line', ax=next(ax)) a.grid('b') # SEVEN improve scale selection a = augmented_df.filter(regex='M\.LR').rename(columns=renamer).sort_index(1). \ plot(ylim=[-.05, 1.5], xlim=[0, a_max], title='Marginal LR', ax=next(ax)) a.grid('b') # EIGHT a = augmented_df.filter(regex='T.LR_').rename(columns=renamer).sort_index(1). \ plot(ylim=[-.05, 1.25], xlim=[0, a_max], title='Increasing Total LR by Line', ax=next(ax)) a.grid('b') a.legend(loc='center right') except Exception as e: logger.error('Error', e) # # close up of plot 2 # bit = augmented_df.query(f'loss < {a_max}').filter(regex='exi_xgtag?_.*(?<!sum)$') f_close, ax = plt.subplots(1, 1, figsize=(8, 5)) ax = bit.rename(columns=renamer).plot(ylim=[-0.025, 1.025], ax=ax) ax.grid() nl = len(self.line_names) for i, l in enumerate(ax.lines[nl:]): ax.lines[i].set(linewidth=1, linestyle='--') l.set(color=ax.lines[i].get_color(), linewidth=2) ax.legend(loc='upper left') # slightly evil ans.update(fig_distortion=f_distortion, fig_six_up_down=f_6_part, fig_trinity=f_trinity, fig_eight=f_8_part, fig_close=f_close) return ans def top_down(self, distortions, A_or_p): """ DataFrame summary and nice plots showing marginal and average ROE, lr etc. as you write a layer from x to A If A=0 A=q(log) is used Not integrated into graphics format (plot) :param distortions: list or dictionary of CDistortion objects, or a single CDist object :param A_or_p: if <1 interpreted as a quantile, otherwise assets :return: """ logger.warning('Portfolio.top_down is deprecated. It has been replaced by Portfolio.example_factory.') # assert A_or_p > 0 # # if A_or_p < 1: # # call with one arg and interpret as log # A = self.q(A_or_p) # else: # A = A_or_p # # if isinstance(distortions, dict): # list_specs = distortions.values() # elif isinstance(distortions, list): # list_specs = distortions # else: # list_specs = [distortions] # # dfs = [] # for dist in list_specs: # g, g_inv = dist.g, dist.g_inv # # S = self.density_df.S # loss = self.density_df.loss # # a = A - self.bs # A-bs for pandas series (includes endpoint), a for numpy indexing; int(A / self.bs) # lossa = loss[0:a] # # Sa = S[0:a] # Fa = 1 - Sa # gSa = g(Sa) # premium = np.cumsum(gSa[::-1])[::-1] * self.bs # el = np.cumsum(Sa[::-1])[::-1] * self.bs # capital = A - lossa - premium # risk_margin = premium - el # assets = capital + premium # marg_roe = (gSa - Sa) / (1 - gSa) # lr = el / premium # roe = (premium - el) / capital # leverage = premium / capital # # rp = -np.log(Sa) # return period # marg_lr = Sa / gSa # # # sns.set_palette(sns.color_palette("Paired", 4)) # df = pd.DataFrame({'$F(x)$': Fa, '$x$': lossa, 'Premium': premium, r'$EL=E(X\wedge x)$': el, # 'Capital': capital, 'Risk Margin': risk_margin, 'Assets': assets, '$S(x)$': Sa, # '$g(S(x))$': gSa, 'Loss Ratio': lr, 'Marginal LR': marg_lr, 'ROE': roe, # 'Marginal ROE': marg_roe, 'P:S levg': leverage}) # df = df.set_index('$F(x)$', drop=True) # df.plot(subplots=True, rot=0, figsize=(14, 4), layout=(-1, 7)) # suptitle_and_tight(f'{str(dist)}: Statistics for Layer $x$ to $a$ vs. $F(x)$') # df['distortion'] = dist.name # dfs.append(df) # return pd.concat(dfs) def analysis_priority(self, asset_spec, output='df'): """ Create priority analysis report_ser. Can be called multiple times with different ``asset_specs`` asset_spec either a float used as an epd percentage or a dictionary. Entering an epd percentage generates the dictionary base = {i: self.epd_2_assets[('not ' + i, 0)](asset_spec) for i in self.line_names} :param asset_spec: epd :param output: df = pandas data frame; html = nice report, markdown = raw markdown text :return: """ ea = self.epd_2_assets ae = self.assets_2_epd if isinstance(asset_spec, dict): base = asset_spec else: if type(asset_spec) != float: raise ValueError("Input dictionary or float = epd target") base = {i: ea[('not ' + i, 0)](asset_spec) for i in self.line_names} if output == 'df': priority_analysis_df = pd.DataFrame( columns=['a', 'chg a', 'not_line epd sa @a', 'line epd @a 2pri', 'not_line epd eq pri', 'line epd eq pri', 'total epd'], index=pd.MultiIndex.from_arrays([[], []], names=['Line', 'Scenario'])) for col in set(self.line_names).intersection(set(base.keys())): notcol = 'not ' + col a_base = base[col] a = a_base e0 = ae[(notcol, 0)](a_base) e = e0 priority_analysis_df.loc[(col, 'base'), :] = ( a, a - a_base, e, ae[(col, 2)](a), ae[(notcol, 1)](a), ae[(col, 1)](a), ae[('total', 0)](a)) a = ea[(col, 2)](e0) priority_analysis_df.loc[(col, '2pri line epd = not line sa'), :] = ( a, a - a_base, ae[(notcol, 0)](a), ae[(col, 2)](a), ae[(notcol, 1)](a), ae[(col, 1)](a), ae[('total', 0)](a)) a = ea[(col, 2)](priority_analysis_df.ix[(col, 'base'), 'line epd eq pri']) priority_analysis_df.loc[(col, 'thought buying (line 2pri epd = base not line eq pri epd'), :] = ( a, a - a_base, ae[(notcol, 0)](a), ae[(col, 2)](a), ae[(notcol, 1)](a), ae[(col, 1)](a), ae[('total', 0)](a)) a = ea[(notcol, 1)](e0) priority_analysis_df.loc[(col, 'fair to not line, not line eq pri epd = base sa epd'), :] = ( a, a - a_base, ae[(notcol, 0)](a), ae[(col, 2)](a), ae[(notcol, 1)](a), ae[(col, 1)](a), ae[('total', 0)](a)) a = ea[(col, 1)](e0) priority_analysis_df.loc[(col, 'line eq pri epd = base not line sa'), :] = ( a, a - a_base, ae[(notcol, 0)](a), ae[(col, 2)](a), ae[(notcol, 1)](a), ae[(col, 1)](a), ae[('total', 0)](a)) a = ea[('total', 0)](e0) priority_analysis_df.loc[(col, 'total epd = base sa not line epd'), :] = ( a, a - a_base, ae[(notcol, 0)](a), ae[(col, 2)](a), ae[(notcol, 1)](a), ae[(col, 1)](a), ae[('total', 0)](a)) priority_analysis_df['pct chg'] = priority_analysis_df['chg a'] / priority_analysis_df.a return priority_analysis_df # else HTML or markdown output ans = [] for line in set(self.line_names).intersection(set(base.keys())): a = base[line] e = ae[(f'not {line}', 0)](a) a0 = float(ea[('total', 0)](e)) eb0a0 = ae[(f'not {line}', 0)](a0) eba0 = ae[(f'not {line}', 1)](a0) e2a0 = ae[(line, 2)](a0) e1a0 = ae[(line, 1)](a0) e2 = ae[(line, 2)](a) e1 = float(ae[(line, 1)](a)) a2 = float(ea[(line, 2)](e1)) af = float(ea[(f'not {line}', 1)](e)) af2 = float(ea[(line, 1)](e)) a3 = float(ea[(line, 2)](e)) a4 = float(ea[(f'not {line}', 1)](e)) story = f""" Consider adding **{line}** to the existing portfolio. The existing portfolio has capital {a:,.1f} and and epd of {e:.4g}. * If {line} is added as second priority to the existing lines with no increase in capital it has an epd of {e2:.4g}. * If the regulator requires the overall epd be a constant then the firm must increase capital to {a0:,.1f} or by {(a0 / a - 1) * 100:.2f} percent. - At the higher capital {line} has an epd of {e2a0:.4g} as second priority and the existing lines have an epd of {eb0a0:.4g} as first priority. - The existing and {line} epds under equal priority are {eba0:.4g} and {e1a0:.4g}. * If {line} *thought* it was added at equal priority it would have expected an epd of {e1:.4g}. In order to achieve this epd as second priority would require capital of {a2:,.1f}, an increase of {(a2 / a - 1) * 100:.2f} percent. * In order for {line} to have an epd equal to the existing lines as second priority would require capital of {a3:,.1f}, and increase of {(a3 / a - 1) * 100:.2f} percent. * In order for {line} to be added at equal priority and for the existing lines to have an unchanged epd requires capital of {af:,.1f}, an increase of {(af / a - 1) * 100:.2f} percent. * In order for {line} to be added at equal priority and to have an epd equal to the existing line epd requires capital of {af2:,.1f}, an increase of {(af2 / a - 1) * 100:.2f} percent. * In order for the existing lines to have an unchanged epd at equal priority requires capital of {a4:,.1f}, an increase of {(a4 / a - 1) * 100:.2f} percent. """ ans.append(story) ans = '\n'.join(ans) if output == 'html': display(HTML(pypandoc.convert_text(ans, to='html', format='markdown'))) else: return ans def analysis_collateral(self, line, c, a, debug=False): """ E(C(a,c)) expected value of line against not line with collateral c and assets a, c <= a :param line: line of business with collateral, analyzed against not line :param c: collateral, c <= a required; c=0 reproduces exa, c=a reproduces lev :param a: assets, assumed less than the max loss (i.e. within the square) :param debug: :return: """ assert (c <= a) xs = self.density_df['loss'].values pline = self.density_df['p_' + line].values notline = self.density_df['ημ_' + line].values ans = [] gt, incr, int1, int2, int3 = 0, 0, 0, 0, 0 c1, c2, c3 = 0, 0, 0 n_c = int(c / self.bs) n_max = len(xs) # this works as a rhs array[0:n_max] is the whole array, array[n_max] is an error err_count = 0 for loss in np.arange(a + self.bs, 2 * xs.max(), self.bs): n_loss = int(loss / self.bs) # 0...loss INCLUSIVE c1 = c / a * loss n_c1 = min(n_max, int(c1 / self.bs)) # need to adjust for trimming when loss > max loss # loss indexes...see notes in blue book la = max(0, n_loss - (n_max - 1)) lc = min(n_loss, n_max - 1) lb = lc + 1 if la == 0: ld = None else: ld = la - 1 try: s1 = slice(la, max(la, min(lb, n_c))) s2 = slice(max(la, min(lb, n_c)), max(la, min(lb, n_c1))) s3 = slice(max(la, min(lb, n_c1)), lb) if ld is None: # means go all the way to zero, do not have to worry about n_loss - n_c > 0 being smaller s1r = slice(lc, min(lc, n_loss - n_c), -1) s2r = slice(min(lc, n_loss - n_c), min(lc, n_loss - n_c1), -1) s3r = slice(min(lc, n_loss - n_c1), ld, -1) else: s1r = slice(lc, max(ld, min(lc, n_loss - n_c)), -1) s2r = slice(max(ld, min(lc, n_loss - n_c)), max(ld, min(lc, n_loss - n_c1)), -1) s3r = slice(max(ld, min(lc, n_loss - n_c1)), ld, -1) int1 = np.sum(xs[s1] * pline[s1] * notline[s1r]) int2 = c * np.sum(pline[s2] * notline[s2r]) int3 = a / loss * np.sum(xs[s3] * pline[s3] * notline[s3r]) ptot = np.sum(pline[s3] * notline[s3r]) except ValueError as e: logger.error(e) logger.error(f"Value error: loss={loss}, loss/b={loss / self.bs}, c1={c1}, c1/b={c1 / self.bs}") logger.error(f"n_loss {n_loss}, n_c {n_c}, n_c1 {n_c1}") logger.error(f'la={la}, lb={lb}, lc={lc}, ld={ld}') logger.error('ONE:', *map(len, [xs[s1], pline[s1], notline[s1r]])) logger.error('TWO:', *map(len, [pline[s2], notline[s2r]])) logger.error('THR:', *map(len, [xs[s3], pline[s3], notline[s3r]])) err_count += 1 if err_count > 3: break if n_loss < n_max: p = self.density_df.loc[loss, 'p_total'] else: p = np.nan incr = (int1 + int2 + int3) gt += incr c1 += int1 c2 += int2 c3 += int3 if debug: ans.append([loss, int1, int2, int3, int3 * loss / a / ptot, ptot, incr, c1, c2, c3, gt, p]) if incr / gt < 1e-12: if debug: logger.info(f'incremental change {incr / gt:12.6f}, breaking') break exlea = self.density_df.loc[a, 'exlea_' + line] exgta = self.density_df.loc[a, 'exgta_' + line] exix = self.density_df.loc[a, 'exi_xgta_' + line] exeqa = self.density_df.loc[a, 'exeqa_' + line] p_total = self.density_df.loc[a, 'p_total'] F = self.density_df.loc[a, 'F'] exa = self.density_df.loc[a, 'exa_' + line] lev = self.density_df.loc[a, 'lev_' + line] df = pd.DataFrame( [(line, a, c, p_total, F, gt, a * exix * (1 - F), exeqa, exlea, exgta, exix, exa, gt + exlea * F, lev)], columns=['line', 'a', 'c', 'p_total', 'F', 'gt', 'exa_delta', 'exeqa', 'exlea', 'exgta', 'exix', 'exa', 'ecac', 'lev'], ) if debug: ans = pd.DataFrame(ans, columns=['loss', 'int1', 'int2', 'int3', 'exeqa', 'ptot', 'incr', 'c1', 'c2', 'c3', 'gt', 'log']) ans = ans.set_index('loss', drop=True) ans.index.name = 'loss' else: ans = None return df, ans def uat_differential(self, line): """ Check the numerical and theoretical derivatives of exa agree for given line :param line: :return: """ test = self.density_df[f'exa_{line}'] dtest = np.gradient(test, test.index) dtest2 = self.density_df[f'exi_xgta_{line}'] * self.density_df.S ddtest = np.gradient(dtest) ddtest2 = -self.density_df[f'exeqa_{line}'] / self.density_df.loss * self.density_df.p_total f, axs = plt.subplots(1, 3, figsize=(12, 4)) axs[0].plot(test.index, test, label=f'exa_{line}') axs[1].plot(test.index, dtest, label='numdiff') axs[1].plot(test.index, dtest2, label='xi_xgta S(x)') axs[1].legend() axs[2].plot(test.index, ddtest, label='numdiff') axs[2].plot(test.index, ddtest2, label='-EXi(a)/a') axs[2].legend() def uat(self, As=None, Ps=[0.98], LRs=[0.965], r0=0.03, num_plots=1, verbose=False): """ Reconcile apply_distortion(s) with price and calibrate :type Ps: object :param As: Asset levels :param Ps: probability levels used to determine asset levels using quantile function :param LRs: loss ratios used to determine profitability :param r0: r0 level for distortions :param verbose: controls level of output :return: """ # figure As if As is None: As = [] for p in Ps: As.append(self.q(p)) # 0. Calibrate params = self.calibrate_distortions(LRs=LRs, As=As, r0=r0) # 1. Apply and compare to calibration K = As[0] LR = LRs[0] idx = (K, LR) dd = Distortion.distortions_from_params(params, index=idx, r0=r0, plot=False) if num_plots == 2: axiter = axiter_factory(None, len(dd)) elif num_plots == 3: axiter = axiter_factory(None, 30) else: axiter = None table, stacked = self.apply_distortions(dd, As, axiter, num_plots) table['lr err'] = table['lr_total'] - LR # 2. Price and compare to calibration pdfs = [] # pricing data frmes for name in Distortion.available_distortions(): pdf, _ = self.price(reg_g=K, pricing_g=dd[name]) pdf['dist'] = name pdfs.append(pdf) p = pd.concat(pdfs) p['lr err'] = p['lr'] - LR # a from apply, p from price a = table.query(f' loss=={K} ') # easier tests # sum of parts = total logger.info( f'Portfolio.uat | {self.name} Sum of parts all close to total: ' f'{np.allclose(a.exag_total, a.exag_sumparts)}') logger.info( f'Portfolio.uat | {self.name} Sum of parts vs total: ' f'{np.sum(np.abs(a.exag_total - a.exag_sumparts)):15,.1f}') pp = p[['dist', 'exag']] pp = pp.pivot(columns='dist').T.loc['exag'] aa = a.filter(regex='exa|method').set_index('method') test = pd.concat((aa, pp), axis=1, sort=True) for c in self.line_names_ex: test[f'err_{c}'] = test[c] / test[f'exag_{c}'] - 1 test['err sum/total'] = test['exag_sumparts'] / test['exag_total'] - 1 test = test[ [f'{i}{j}' for j in self.line_names_ex for i in ['exag_', '', 'err_']] + ['exag_sumparts', 'err sum/total']] lr_err = pd.DataFrame({'applyLR': a.lr_total, 'method': a.method, 'target': LR, 'errs': a.lr_total - LR}) lr_err = lr_err.reset_index(drop=False).set_index('method') lr_err = lr_err.rename(columns={'index': 'a'}) test = pd.concat((test, lr_err), axis=1, sort=True) overall_test = (test.filter(regex='err').abs()).sum().sum() if verbose: html_title(f'Combined, overall error {overall_test:.3e}') # (exag=apply)') display(test) if lr_err.errs.abs().max() > 1e-4: logger.error('Portfolio.uat | {self.name} UAT Loss Ratio Error {lr_err.errs.abs().max()}') if overall_test < 1e-7: logger.info(f'Portfolio.uat | {self.name} UAT All good, total error {overall_test:6.4e}') else: s = f'{self.name} UAT total error {overall_test:6.4e}' logger.error(f'Portfolio.uat | {s}') logger.error(f'Portfolio.uat | {s}') logger.error(f'Portfolio.uat | {s}') return a, p, test, params, dd, table, stacked @property def renamer(self): """ write a sensible renamer for the columns to use thusly self.density_df.rename(columns=renamer) write a tex version separately Create once per item...assume lines etc. never change :return: dictionary that can be used to rename columns """ if self._renamer is None: # make it # key : (before, after) # ημ needs to come last because of epd_nu etc. # keep lEV and EX(a) separate because otherwise index has non-unique values self._renamer = {} meta_namer = dict(p_=('', ' density'), lev_=('LEV[', 'a]'), exag_=('EQ[', '(a)]'), exa_=('E[', '(a)]'), exlea_=('E[', ' | X<=a]'), exgta_=('E[', ' | X>a]'), exeqa_=('E[', ' | X=a]'), e1xi_1gta_=('E[1/', ' 1(X>a)]'), exi_x_=('E[', '/X]'), exi_xgta_sum=('Sum Xi/X gt', ''), # exi_xgta_sum=('Sum of E[Xi/X|X>a]', ''), exi_xeqa_sum=("Sum Xi/X eq", ''), # exi_xeqa_sum=("Sum of E[Xi/X|X=a]", ''), exi_xgta_=('α=E[', '/X | X>a]'), exi_xeqa_=('E[', '/X | X=a]'), exi_xlea_=('E[', '/X | X<=a]'), epd_0_=('EPD(', ') stand alone'), epd_1_=('EPD(', ') within X'), epd_2_=('EPD(', ') second pri'), e2pri_=('E[X', '(a) second pri]'), ημ_=('All but ', ' density') ) for l in self.density_df.columns: if re.search('^ημ_', l): # nu_line -> not line density self._renamer[l] = re.sub('^ημ_([0-9A-Za-z\-_.,]+)', r'not \1 density', l) else: l0 = l.replace('ημ_', 'not ') for k, v in meta_namer.items(): d1 = l0.find(k) if d1 >= 0: d1 += len(k) b, a = v self._renamer[l] = f'{b}{l0[d1:]}{a}'.replace('total', 'X') break # augmented df items for l in self.line_names_ex: self._renamer[f'exag_{l}'] = f'EQ[{l}(a)]' self._renamer[f'exi_xgtag_{l}'] = f'β=EQ[{l}/X | X>a]' self._renamer[f'exi_xleag_{l}'] = f'EQ[{l}/X | X<=a]' self._renamer[f'e1xi_1gta_{l}'] = f'E[{l}/X 1(X >a)]' self._renamer['exag_sumparts'] = 'Sum of EQ[Xi(a)]' # more post-processing items for pre, m1 in zip(['M', 'T'], ['Marginal', 'Total']): for post, m2 in zip(['L', 'P', 'LR', 'Q', 'ROE', "PQ", "M"], ['Loss', 'Premium', 'Loss Ratio', 'Equity', 'ROE', 'Leverage (P:S)', "Margin"]): self._renamer[f'{pre}.{post}'] = f'{m1} {m2}' for line in self.line_names_ex: for pre, m1 in zip(['M', 'T'], ['Marginal', 'Total']): for post, m2 in zip(['L', 'P', 'LR', 'Q', 'ROE', "PQ", "M"], ['Loss', 'Premium', 'Loss Ratio', 'Equity', 'ROE', 'Leverage (P:S)', "Margin"]): self._renamer[f'{pre}.{post}_{line}'] = f'{m1} {m2} {line}' self._renamer['A'] = 'Assets' # self._renamer['exi/xgta'] = 'α=E[Xi/X | X > a]' # self._renamer['exi/xgtag'] = 'β=E_Q[Xi/X | X > a]' # gamma files for l in self.line_names: self._renamer[f'gamma_{l}_sa'] = f"γ {l} stand-alone" self._renamer[f'gamma_{self.name}_{l}'] = f"γ {l} part of {self.name}" self._renamer[f'p_{l}'] = f'{l} stand-alone density' self._renamer[f'S_{l}'] = f'{l} stand-alone survival' self._renamer['p_total'] = f'{self.name} total density' self._renamer['S_total'] = f'{self.name} total survival' self._renamer[f'gamma_{self.name}_total'] = f"γ {self.name} total" # for enhanced exhibits --- these are a bit specialized! self._renamer['mv'] = "$\\mathit{MVL}(a)$??" for orig in self.line_names_ex: l = self.line_renamer.get(orig, orig).replace('$', '') if orig == 'total': self._renamer[f'S'] = f"$S_{{{l}}}(a)$" else: self._renamer[f'S_{orig}'] = f"$S_{{{l}}}(a)$" self._renamer[f'lev_{orig}'] = f"$E[{l}\\wedge a]$" self._renamer[f'levg_{orig}'] = f"$\\rho({l}\\wedge a)$" self._renamer[f'exa_{orig}'] = f"$E[{l}(a)]$" self._renamer[f'exag_{orig}'] = f"$\\rho({l}\\subseteq X^c\\wedge a)$" self._renamer[f'ro_da_{orig}'] = "$\\Delta a_{ro}$" self._renamer[f'ro_dmv_{orig}'] = "$\\Delta \\mathit{MVL}_{ro}(a)$" self._renamer[f'ro_eva_{orig}'] = "$\\mathit{EGL}_{ro}(a)$" self._renamer[f'gc_da_{orig}'] = "$\\Delta a_{gc}$" self._renamer[f'gc_dmv_{orig}'] = "$\\Delta \\mathit{MVL}_{gc}(a)$" self._renamer[f'gc_eva_{orig}'] = "$\\mathit{EGL}_{gc}(a)$" return self._renamer @property def line_renamer(self): """ plausible defaults for nicer looking names replaces . or : with space and capitalizes (generally don't use . because it messes with analyze distortion.... leaves : alone converts X1 to tex converts XM1 to tex with minus (for reserves) :return: """ def rename(ln): # guesser ... if ln == 'total': return 'Total' if ln.find('.') > 0: return ln.replace('.', ' ').title() if ln.find(':') > 0: return ln.replace(':', ' ').title() # numbered lines ln = re.sub('([A-Z])m([0-9]+)', r'$\1_{-\2}$', ln) ln = re.sub('([A-Z])([0-9]+)', r'$\1_{\2}$', ln) return ln if self._line_renamer is None: self._line_renamer = { ln: rename(ln) for ln in self.line_names_ex} return self._line_renamer @property def tm_renamer(self): """ rename exa -> TL, exag -> TP etc. :return: """ if self._tm_renamer is None: self._tm_renamer = { f'exa_{l}' : f'T.L_{l}' for l in self.line_names_ex} self._tm_renamer.update({ f'exag_{l}' : f'T.P_{l}' for l in self.line_names_ex}) return self._tm_renamer @property def stat_renamer(self): return dict('') def set_a_p(self, a, p): """ sort out arguments for assets and prob level and make them consistent neither => set defaults a only set p p only set a both do nothing """ if a==0 and p==0: p = 0.995 a = self.q(p) # click to exact p = self.cdf(a) elif a: p = self.cdf(a) # snap to index a = self.q(p) elif p: a = self.q(p) # click to exact p = self.cdf(a) return a, float(p) # def example_factory_sublines(self, data_in, xlim=0): # """ # plausible plots for the specified example and a summary table # # data_in is augmented_df or Answer object coming out of example_factory # # example_factor is total; these exhibits look at subplots... # # The line names must be of the form [A-Z]anything and identified by the capital letter # # was agg extensions.plot_example # # :param data_in: result of running self.apply_distortion() # :param xlim: for plots # :return: # """ # # if isinstance(data_in, Answer): # augmented_df = data_in.augmented_df # else: # augmented_df = data_in # # temp = augmented_df.filter(regex='exi_xgtag?_(?!sum)|^S|^gS|^(M|T)\.').copy() # # add extra stats # # you have: # # ['M.M_Atame', 'M.M_Dthick', 'M.M_total', # # 'M.Q_Atame', 'M.Q_Dthick', 'M.Q_total', # # 'M.ROE', 'S', # # 'T.LR_Atame', 'T.LR_Dthick', 'T.LR_total', # # 'T.M_Atame', 'T.M_Dthick', 'T.M_total', # # 'T.Q_Atame', 'T.Q_Dthick', 'T.Q_total', # # 'T.ROE_Atame', 'T.ROE_Dthick', 'T.ROE_total', # # 'exi_xgta_Atame', 'exi_xgta_Dthick', # # 'exi_xgtag_Atame', 'exi_xgtag_Dthick', # # 'gS'] # # # temp['M.LR'] = temp['M.L'] / temp['M.P'] # # temp['M.ROE'] = (temp['M.P'] - temp['M.L']) / (1 - temp['M.P']) # # temp['M.M'] = temp['M.P'] - temp['M.L'] # for l in self.line_names_ex: # if l != 'total': # temp[f'M.L_{l}'] = temp[f'exi_xgta_{l}'] * temp.S # temp[f'M.P_{l}'] = temp[f'exi_xgtag_{l}'] * temp.gS # # temp[f'M.M.{l}'] = temp[f'exi_xgtag_{l}'] * temp['M.P'] - temp[f'exi_xgta_{l}'] * temp['M.L'] # temp[f'beta/alpha.{l}'] = temp[f'exi_xgtag_{l}'] / temp[f'exi_xgta_{l}'] # else: # temp[f'M.L_{l}'] = temp.S # temp[f'M.P_{l}'] = temp.gS # # temp[f'M.M.{l}'] = temp['M.P'] - temp['M.L'] # temp[f'M.LR_{l}'] = temp[f'M.L_{l}'] / temp[f'M.P_{l}'] # # should be zero: # temp[f'Chk L+M=p_{l}'] = temp[f'M.P_{l}'] - temp[f'M.L_{l}'] - temp[f'M.M_{l}'] # # renamer = self.renamer.copy() # # want to recast these now too...(special) # renamer.update({'S': 'M.L total', 'gS': 'M.P total'}) # augmented_df.index.name = 'Assets a' # temp.index.name = 'Assets a' # if xlim == 0: # xlim = self.q(1 - 1e-5) # # f, axs = plt.subplots(4, 2, figsize=(8, 10), constrained_layout=True, squeeze=False) # ax = iter(axs.flatten()) # # # ONE # a = (1 - augmented_df.filter(regex='p_').cumsum()).rename(columns=renamer).sort_index(1). \ # plot(ylim=[0, 1], xlim=[0, xlim], title='Survival functions', ax=next(ax)) # a.grid('b') # # # TWO # a = augmented_df.filter(regex='exi_xgtag?').rename(columns=renamer).sort_index(1). \ # plot(ylim=[0, 1], xlim=[0, xlim], title=r'$\alpha=E[X_i/X | X>a],\beta=E_Q$ by Line', ax=next(ax)) # a.grid('b') # # # THREE total margins # a = augmented_df.filter(regex=r'^T\.M').rename(columns=renamer).sort_index(1). \ # plot(xlim=[0, xlim], title='Total Margins by Line', ax=next(ax)) # a.grid('b') # # # FOUR marginal margins was dividing by bs end of first line # # for some reason the last entry in M.M_total can be problematic. # a = (augmented_df.filter(regex=r'^M\.M').rename(columns=renamer).sort_index(1).iloc[:-1, :]. # plot(xlim=[0, xlim], title='Marginal Margins by Line', ax=next(ax))) # a.grid('b') # # # FIVE # a = augmented_df.filter(regex=r'^M\.Q|gF').rename(columns=renamer).sort_index(1). \ # plot(xlim=[0, xlim], title='Capital = 1-gS = F!', ax=next(ax)) # a.grid('b') # for _ in a.lines: # if _.get_label() == 'gF': # _.set(linewidth=5, alpha=0.3) # # recreate legend because changed lines # a.legend() # # # SIX see apply distortion, line 1890 ROE is in augmented_df # a = augmented_df.filter(regex='^ROE$|exi_xeqa').rename(columns=renamer).sort_index(1). \ # plot(xlim=[0, xlim], title='M.ROE Total and $E[X_i/X | X=a]$ by line', ax=next(ax)) # a.grid('b') # # # SEVEN improve scale selection # a = temp.filter(regex='beta/alpha\.|M\.LR').rename(columns=renamer).sort_index(1). \ # plot(ylim=[-.05, 1.5], xlim=[0, xlim], title='Alpha, Beta and Marginal LR', # ax=next(ax)) # a.grid('b') # # # EIGHT # a = augmented_df.filter(regex='LR').rename(columns=renamer).sort_index(1). \ # plot(ylim=[-.05, 1.25], xlim=[0, xlim], title='Total ↑LR by Line', # ax=next(ax)) # a.grid('b') # # # return # if isinstance(data_in, Answer): # data_in['subline_summary'] = temp # data_in['fig_eight_plots'] = f # else: # data_in = Answer(summary=temp, fig_eight_by_line=f) # return data_in # def cumintegral(self, v, bs_override=0): # """ # cumulative integral of v with buckets size bs # # :param bs_override: # :param v: # :return: # """ # # if bs_override != 0: # bs = bs_override # else: # bs = self.bs # # if type(v) == np.ndarray: # logger.warning('CALLING cumintegral on a numpy array!!\n' * 5) # return np.hstack((0, v[:-1])).cumsum() * bs # else: # # was consistently (and obviously) the same # # t1 = np.hstack((0, v.values[:-1])).cumsum() * bs # # t2 = v.shift(1, fill_value=0).cumsum() * bs # # logger.warning(f'Alternative cumintegral allclose={np.allclose(t1, t2)}') # return v.shift(1, fill_value=0).cumsum() * bs @staticmethod def from_DataFrame(name, df): """ create portfolio from pandas dataframe uses columns with appropriate names Can be fed the agg output of uw.write_test( agg_program ) :param name: :param df: :return: """ # ...and this is why we love pandas so much spec_list = [g.dropna(axis=1).to_dict(orient='records') for n, g in df.groupby('name')] spec_list = [i[0] for i in spec_list] return Portfolio(name, spec_list) @staticmethod def from_Excel(name, ffn, sheet_name, **kwargs): """ read in from Excel works via a Pandas dataframe; kwargs passed through to pd.read_excel drops all blank columns (mostly for auditing purposes) delegates to from_dataFrame :param name: :param ffn: full file name, including path :param sheet_name: :param kwargs: :return: """ df = pd.read_excel(ffn, sheet_name=sheet_name, **kwargs) df = df.dropna(axis=1, how='all') return Portfolio.from_DataFrame(name, df) @staticmethod def from_dict_of_aggs(prefix, agg_dict, sub_ports=None, uw=None, bs=0, log2=0, padding=2, **kwargs): """ Create a portfolio from any iterable with values aggregate code snippets e.g. agg_dict = {label: agg_snippet } will create all the portfolios specified in subsets, or all if subsets=='all' labels for subports are concat of keys in agg_dict, so recommend you use A:, B: etc. as the snippet names. Portfolio names are prefix_[concat element names] agg_snippet is line agg blah without the tab or newline :param prefix: :param agg_dict: :param sub_ports: :param bs, log2, padding, kwargs: passed through to update; update if bs * log2 > 0 :return: """ agg_names = list(agg_dict.keys()) # holder for created portfolios ports = Answer() if sub_ports == 'all': sub_ports = subsets(agg_names) for sub_port in sub_ports: name = ''.join(sub_port) if prefix != '': name = f'{prefix}_{name}' pgm = f'port {name}\n' for l in agg_names: if l in sub_port: pgm += f'\t{agg_dict[l]}\n' if uw: ports[name] = uw(pgm) else: ports[name] = pgm if uw and bs * log2 > 0: ports[name].update(bs=bs, log2=log2, padding=padding, **kwargs) return ports
[ "logging.getLogger", "numpy.alltrue", "matplotlib.ticker.LogLocator", "numpy.sqrt", "IPython.core.display.display", "numpy.hstack", "pathlib.Path.home", "numpy.log", "scipy.interpolate.interp1d", "pandas.Index", "numpy.array", "matplotlib.ticker.MaxNLocator", "copy.deepcopy", "pandas.read_...
[((1265, 1295), 'logging.getLogger', 'logging.getLogger', (['"""aggregate"""'], {}), "('aggregate')\n", (1282, 1295), False, 'import logging\n'), ((4456, 4512), 'pandas.concat', 'pd.concat', (['[a.report_ser for a in self.agg_list]'], {'axis': '(1)'}), '([a.report_ser for a in self.agg_list], axis=1)\n', (4465, 4512), True, 'import pandas as pd\n'), ((4719, 4757), 'pandas.concat', 'pd.concat', (['[temp_report, temp]'], {'axis': '(1)'}), '([temp_report, temp], axis=1)\n', (4728, 4757), True, 'import pandas as pd\n'), ((12522, 12535), 'json.dumps', 'json.dumps', (['d'], {}), '(d)\n', (12532, 12535), False, 'import json\n'), ((27001, 27012), 'numpy.zeros', 'np.zeros', (['(2)'], {}), '(2)\n', (27009, 27012), True, 'import numpy as np\n'), ((32606, 32659), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['line', 'log', 'Agg Quantile']"}), "(columns=['line', 'log', 'Agg Quantile'])\n", (32618, 32659), True, 'import pandas as pd\n'), ((33413, 33451), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['line', 'bs10']"}), "(columns=['line', 'bs10'])\n", (33425, 33451), True, 'import pandas as pd\n'), ((37242, 37281), 'numpy.linspace', 'np.linspace', (['(0)', 'MAXL', 'N'], {'endpoint': '(False)'}), '(0, MAXL, N, endpoint=False)\n', (37253, 37281), True, 'import numpy as np\n'), ((37681, 37703), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': 'xs'}), '(index=xs)\n', (37693, 37703), True, 'import pandas as pd\n'), ((40967, 41031), 'pandas.concat', 'pd.concat', (['(theoretical_stats, self.audit_df)'], {'axis': '(1)', 'sort': '(True)'}), '((theoretical_stats, self.audit_df), axis=1, sort=True)\n', (40976, 41031), True, 'import pandas as pd\n'), ((42987, 43007), 'numpy.datetime64', 'np.datetime64', (['"""now"""'], {}), "('now')\n", (43000, 43007), True, 'import numpy as np\n'), ((44240, 44279), 'numpy.linspace', 'np.linspace', (['(0)', 'MAXL', 'N'], {'endpoint': '(False)'}), '(0, MAXL, N, endpoint=False)\n', (44251, 44279), True, 'import numpy as np\n'), ((44408, 44430), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': 'xs'}), '(index=xs)\n', (44420, 44430), True, 'import pandas as pd\n'), ((46559, 46580), 'numpy.cumsum', 'np.cumsum', (['df.p_total'], {}), '(df.p_total)\n', (46568, 46580), True, 'import numpy as np\n'), ((47250, 47268), 'numpy.isnan', 'np.isnan', (['loss_max'], {}), '(loss_max)\n', (47258, 47268), True, 'import numpy as np\n'), ((47465, 47493), 'numpy.sum', 'np.sum', (['(df.p_total * df.loss)'], {}), '(df.p_total * df.loss)\n', (47471, 47493), True, 'import numpy as np\n'), ((51831, 51851), 'numpy.datetime64', 'np.datetime64', (['"""now"""'], {}), "('now')\n", (51844, 51851), True, 'import numpy as np\n'), ((55108, 55130), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': 'xs'}), '(index=xs)\n', (55120, 55130), True, 'import pandas as pd\n'), ((73845, 73932), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['line', 'priority', 'epd', 'a from e', 'assets', 'e from a']"}), "(columns=['line', 'priority', 'epd', 'a from e', 'assets',\n 'e from a'])\n", (73857, 73932), True, 'import pandas as pd\n'), ((74391, 74410), 'IPython.core.display.display', 'display', (['temp.style'], {}), '(temp.style)\n', (74398, 74410), False, 'from IPython.core.display import HTML, display\n'), ((77952, 77973), 'numpy.cumsum', 'np.cumsum', (['df.p_total'], {}), '(df.p_total)\n', (77961, 77973), True, 'import numpy as np\n'), ((80005, 80023), 'numpy.isnan', 'np.isnan', (['loss_max'], {}), '(loss_max)\n', (80013, 80023), True, 'import numpy as np\n'), ((80481, 80509), 'numpy.sum', 'np.sum', (['(df.p_total * df.loss)'], {}), '(df.p_total * df.loss)\n', (80487, 80509), True, 'import numpy as np\n'), ((94369, 94387), 'numpy.argwhere', 'np.argwhere', (['Splus'], {}), '(Splus)\n', (94380, 94387), True, 'import numpy as np\n'), ((102934, 103101), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['$a$', 'LR', '$S$', '$\\\\iota$', '$\\\\delta$', '$\\\\nu$', '$EL$', '$P$',\n 'Levg', '$K$', 'ROE', 'param', 'error', 'method']", 'dtype': 'np.float'}), "(columns=['$a$', 'LR', '$S$', '$\\\\iota$', '$\\\\delta$', '$\\\\nu$',\n '$EL$', '$P$', 'Levg', '$K$', 'ROE', 'param', 'error', 'method'], dtype\n =np.float)\n", (102946, 103101), True, 'import pandas as pd\n'), ((105889, 105903), 'pandas.concat', 'pd.concat', (['ans'], {}), '(ans)\n', (105898, 105903), True, 'import pandas as pd\n'), ((105934, 105962), 'numpy.round', 'np.round', (['(1 / ans_table.S)', '(0)'], {}), '(1 / ans_table.S, 0)\n', (105942, 105962), True, 'import numpy as np\n'), ((130008, 130082), 'numpy.where', 'np.where', (["(df['M.Q_total'] != 0)", "(df['M.M_total'] / df['M.Q_total'])", 'gprime1'], {}), "(df['M.Q_total'] != 0, df['M.M_total'] / df['M.Q_total'], gprime1)\n", (130016, 130082), True, 'import numpy as np\n'), ((152666, 152729), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['line', 'L', 'P', 'M', 'Q']", 'dtype': 'float'}), "(columns=['line', 'L', 'P', 'M', 'Q'], dtype=float)\n", (152678, 152729), True, 'import pandas as pd\n'), ((174635, 174653), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {}), '(1, 1)\n', (174647, 174653), True, 'import matplotlib.pyplot as plt\n'), ((176251, 176324), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(3)', '(2)'], {'figsize': '(8, 10)', 'sharex': '(True)', 'constrained_layout': '(True)'}), '(3, 2, figsize=(8, 10), sharex=True, constrained_layout=True)\n', (176263, 176324), True, 'import matplotlib.pyplot as plt\n'), ((185551, 185585), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(8, 5)'}), '(1, 1, figsize=(8, 5))\n', (185563, 185585), True, 'import matplotlib.pyplot as plt\n'), ((198826, 199075), 'pandas.DataFrame', 'pd.DataFrame', (['[(line, a, c, p_total, F, gt, a * exix * (1 - F), exeqa, exlea, exgta, exix,\n exa, gt + exlea * F, lev)]'], {'columns': "['line', 'a', 'c', 'p_total', 'F', 'gt', 'exa_delta', 'exeqa', 'exlea',\n 'exgta', 'exix', 'exa', 'ecac', 'lev']"}), "([(line, a, c, p_total, F, gt, a * exix * (1 - F), exeqa, exlea,\n exgta, exix, exa, gt + exlea * F, lev)], columns=['line', 'a', 'c',\n 'p_total', 'F', 'gt', 'exa_delta', 'exeqa', 'exlea', 'exgta', 'exix',\n 'exa', 'ecac', 'lev'])\n", (198838, 199075), True, 'import pandas as pd\n'), ((199739, 199768), 'numpy.gradient', 'np.gradient', (['test', 'test.index'], {}), '(test, test.index)\n', (199750, 199768), True, 'import numpy as np\n'), ((199860, 199878), 'numpy.gradient', 'np.gradient', (['dtest'], {}), '(dtest)\n', (199871, 199878), True, 'import numpy as np\n'), ((199998, 200033), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(3)'], {'figsize': '(12, 4)'}), '(1, 3, figsize=(12, 4))\n', (200010, 200033), True, 'import matplotlib.pyplot as plt\n'), ((201891, 201906), 'pandas.concat', 'pd.concat', (['pdfs'], {}), '(pdfs)\n', (201900, 201906), True, 'import pandas as pd\n'), ((202558, 202596), 'pandas.concat', 'pd.concat', (['(aa, pp)'], {'axis': '(1)', 'sort': '(True)'}), '((aa, pp), axis=1, sort=True)\n', (202567, 202596), True, 'import pandas as pd\n'), ((202935, 203035), 'pandas.DataFrame', 'pd.DataFrame', (["{'applyLR': a.lr_total, 'method': a.method, 'target': LR, 'errs': a.\n lr_total - LR}"], {}), "({'applyLR': a.lr_total, 'method': a.method, 'target': LR,\n 'errs': a.lr_total - LR})\n", (202947, 203035), True, 'import pandas as pd\n'), ((203170, 203214), 'pandas.concat', 'pd.concat', (['(test, lr_err)'], {'axis': '(1)', 'sort': '(True)'}), '((test, lr_err), axis=1, sort=True)\n', (203179, 203214), True, 'import pandas as pd\n'), ((218780, 218831), 'pandas.read_excel', 'pd.read_excel', (['ffn'], {'sheet_name': 'sheet_name'}), '(ffn, sheet_name=sheet_name, **kwargs)\n', (218793, 218831), True, 'import pandas as pd\n'), ((9663, 9810), 'pandas.concat', 'pd.concat', (["(self.statistics_df.loc[summary_sl, :], self.audit_df[['Mean', 'EmpMean',\n 'MeanErr', 'CV', 'EmpCV', 'CVErr', 'P99.0']].T)"], {'sort': '(True)'}), "((self.statistics_df.loc[summary_sl, :], self.audit_df[['Mean',\n 'EmpMean', 'MeanErr', 'CV', 'EmpCV', 'CVErr', 'P99.0']].T), sort=True)\n", (9672, 9810), True, 'import pandas as pd\n'), ((13551, 13568), 'copy.deepcopy', 'deepcopy', (['a._spec'], {}), '(a._spec)\n', (13559, 13568), False, 'from copy import deepcopy\n'), ((13683, 13700), 'copy.deepcopy', 'deepcopy', (['a._spec'], {}), '(a._spec)\n', (13691, 13700), False, 'from copy import deepcopy\n'), ((19527, 19653), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['self.q_temp.index', 'self.q_temp.loss_s'], {'kind': '"""previous"""', 'bounds_error': '(False)', 'fill_value': '"""extrapolate"""'}), "(self.q_temp.index, self.q_temp.loss_s, kind='previous',\n bounds_error=False, fill_value='extrapolate')\n", (19547, 19653), False, 'from scipy import interpolate\n'), ((19759, 19879), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['self.q_temp.index', 'self.q_temp.loss'], {'kind': '"""next"""', 'bounds_error': '(False)', 'fill_value': '"""extrapolate"""'}), "(self.q_temp.index, self.q_temp.loss, kind='next',\n bounds_error=False, fill_value='extrapolate')\n", (19779, 19879), False, 'from scipy import interpolate\n'), ((20023, 20147), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['self.q_temp.index', 'self.q_temp.loss_s'], {'kind': '"""linear"""', 'bounds_error': '(False)', 'fill_value': '"""extrapolate"""'}), "(self.q_temp.index, self.q_temp.loss_s, kind='linear',\n bounds_error=False, fill_value='extrapolate')\n", (20043, 20147), False, 'from scipy import interpolate\n'), ((20639, 20768), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['self.density_df.loss', 'self.density_df.F'], {'kind': '"""previous"""', 'bounds_error': '(False)', 'fill_value': '"""extrapolate"""'}), "(self.density_df.loss, self.density_df.F, kind=\n 'previous', bounds_error=False, fill_value='extrapolate')\n", (20659, 20768), False, 'from scipy import interpolate\n'), ((21210, 21343), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['self.density_df.loss', 'self.density_df.p_total'], {'kind': '"""linear"""', 'bounds_error': '(False)', 'fill_value': '"""extrapolate"""'}), "(self.density_df.loss, self.density_df.p_total, kind=\n 'linear', bounds_error=False, fill_value='extrapolate')\n", (21230, 21343), False, 'from scipy import interpolate\n'), ((38876, 38896), 'numpy.ones_like', 'np.ones_like', (['ft_all'], {}), '(ft_all)\n', (38888, 38896), True, 'import numpy as np\n'), ((38912, 38946), 'numpy.any', 'np.any', (['(ft_line_density[line] == 0)'], {}), '(ft_line_density[line] == 0)\n', (38918, 38946), True, 'import numpy as np\n'), ((40058, 40093), 'numpy.sum', 'np.sum', (["self.density_df[f'p_{col}']"], {}), "(self.density_df[f'p_{col}'])\n", (40064, 40093), True, 'import numpy as np\n'), ((40182, 40191), 'numpy.sum', 'np.sum', (['t'], {}), '(t)\n', (40188, 40191), True, 'import numpy as np\n'), ((40251, 40260), 'numpy.sum', 'np.sum', (['t'], {}), '(t)\n', (40257, 40260), True, 'import numpy as np\n'), ((40320, 40329), 'numpy.sum', 'np.sum', (['t'], {}), '(t)\n', (40326, 40329), True, 'import numpy as np\n'), ((40389, 40398), 'numpy.sum', 'np.sum', (['t'], {}), '(t)\n', (40395, 40398), True, 'import numpy as np\n'), ((42811, 42845), 'numpy.cumsum', 'np.cumsum', (['self.density_df.p_total'], {}), '(self.density_df.p_total)\n', (42820, 42845), True, 'import numpy as np\n'), ((45280, 45300), 'numpy.ones_like', 'np.ones_like', (['ft_all'], {}), '(ft_all)\n', (45292, 45300), True, 'import numpy as np\n'), ((45316, 45350), 'numpy.any', 'np.any', (['(ft_line_density[line] == 0)'], {}), '(ft_line_density[line] == 0)\n', (45322, 45350), True, 'import numpy as np\n'), ((46245, 46263), 'numpy.finfo', 'np.finfo', (['np.float'], {}), '(np.float)\n', (46253, 46263), True, 'import numpy as np\n'), ((46349, 46372), 'numpy.all', 'np.all', (['(df.p_total >= 0)'], {}), '(df.p_total >= 0)\n', (46355, 46372), True, 'import numpy as np\n'), ((48824, 48866), 'numpy.cumsum', 'np.cumsum', (["(df['exeqa_' + col] * df.p_total)"], {}), "(df['exeqa_' + col] * df.p_total)\n", (48833, 48866), True, 'import numpy as np\n'), ((49016, 49061), 'numpy.cumsum', 'np.cumsum', (["(df['exeqa_ημ_' + col] * df.p_total)"], {}), "(df['exeqa_ημ_' + col] * df.p_total)\n", (49025, 49061), True, 'import numpy as np\n'), ((56315, 56342), 'numpy.sum', 'np.sum', (['agg_epsilon_df[col]'], {}), '(agg_epsilon_df[col])\n', (56321, 56342), True, 'import numpy as np\n'), ((56402, 56411), 'numpy.sum', 'np.sum', (['t'], {}), '(t)\n', (56408, 56411), True, 'import numpy as np\n'), ((56450, 56459), 'numpy.sum', 'np.sum', (['t'], {}), '(t)\n', (56456, 56459), True, 'import numpy as np\n'), ((56498, 56507), 'numpy.sum', 'np.sum', (['t'], {}), '(t)\n', (56504, 56507), True, 'import numpy as np\n'), ((77113, 77131), 'numpy.finfo', 'np.finfo', (['np.float'], {}), '(np.float)\n', (77121, 77131), True, 'import numpy as np\n'), ((77437, 77460), 'numpy.all', 'np.all', (['(df.p_total >= 0)'], {}), '(df.p_total >= 0)\n', (77443, 77460), True, 'import numpy as np\n'), ((80623, 80669), 'numpy.maximum', 'np.maximum', (['(0)', "(df['e_total'] - df['lev_total'])"], {}), "(0, df['e_total'] - df['lev_total'])\n", (80633, 80669), True, 'import numpy as np\n'), ((83791, 83833), 'numpy.cumsum', 'np.cumsum', (["(df['exeqa_' + col] * df.p_total)"], {}), "(df['exeqa_' + col] * df.p_total)\n", (83800, 83833), True, 'import numpy as np\n'), ((84054, 84099), 'numpy.cumsum', 'np.cumsum', (["(df['exeqa_ημ_' + col] * df.p_total)"], {}), "(df['exeqa_ημ_' + col] * df.p_total)\n", (84063, 84099), True, 'import numpy as np\n'), ((84391, 84423), 'numpy.sum', 'np.sum', (["(df['p_' + col] * df.loss)"], {}), "(df['p_' + col] * df.loss)\n", (84397, 84423), True, 'import numpy as np\n'), ((84458, 84491), 'numpy.sum', 'np.sum', (["(df['ημ_' + col] * df.loss)"], {}), "(df['ημ_' + col] * df.loss)\n", (84464, 84491), True, 'import numpy as np\n'), ((84805, 84854), 'numpy.sum', 'np.sum', (["(df['exeqa_' + col] * df.p_total / df.loss)"], {}), "(df['exeqa_' + col] * df.p_total / df.loss)\n", (84811, 84854), True, 'import numpy as np\n'), ((84896, 84948), 'numpy.cumsum', 'np.cumsum', (["(df['exeqa_' + col] * df.p_total / df.loss)"], {}), "(df['exeqa_' + col] * df.p_total / df.loss)\n", (84905, 84948), True, 'import numpy as np\n'), ((85255, 85307), 'numpy.sum', 'np.sum', (["(df['exeqa_ημ_' + col] * df.p_total / df.loss)"], {}), "(df['exeqa_ημ_' + col] * df.p_total / df.loss)\n", (85261, 85307), True, 'import numpy as np\n'), ((85374, 85429), 'numpy.cumsum', 'np.cumsum', (["(df['exeqa_ημ_' + col] * df.p_total / df.loss)"], {}), "(df['exeqa_ημ_' + col] * df.p_total / df.loss)\n", (85383, 85429), True, 'import numpy as np\n'), ((95472, 95485), 'numpy.all', 'np.all', (['(S > 0)'], {}), '(S > 0)\n', (95478, 95485), True, 'import numpy as np\n'), ((95490, 95513), 'numpy.all', 'np.all', (['(S[:-1] >= S[1:])'], {}), '(S[:-1] >= S[1:])\n', (95496, 95513), True, 'import numpy as np\n'), ((95557, 95566), 'numpy.log', 'np.log', (['S'], {}), '(S)\n', (95563, 95566), True, 'import numpy as np\n'), ((106476, 106496), 'numpy.round', 'np.round', (['(mn * 20)', '(0)'], {}), '(mn * 20, 0)\n', (106484, 106496), True, 'import numpy as np\n'), ((106515, 106535), 'numpy.round', 'np.round', (['(mx * 20)', '(0)'], {}), '(mx * 20, 0)\n', (106523, 106535), True, 'import numpy as np\n'), ((112959, 112984), 'numpy.diff', 'np.diff', (['df.gS'], {'prepend': '(1)'}), '(df.gS, prepend=1)\n', (112966, 112984), True, 'import numpy as np\n'), ((115161, 115211), 'numpy.alltrue', 'np.alltrue', (['(df.S.iloc[1:] <= df.S.iloc[:-1].values)'], {}), '(df.S.iloc[1:] <= df.S.iloc[:-1].values)\n', (115171, 115211), True, 'import numpy as np\n'), ((116383, 116415), 'pandas.Series', 'pd.Series', ([], {'index': 'self.line_names'}), '(index=self.line_names)\n', (116392, 116415), True, 'import pandas as pd\n'), ((127551, 127625), 'numpy.where', 'np.where', (["(df['M.Q_total'] != 0)", "(df['M.M_total'] / df['M.Q_total'])", 'gprime1'], {}), "(df['M.Q_total'] != 0, df['M.M_total'] / df['M.Q_total'], gprime1)\n", (127559, 127625), True, 'import numpy as np\n'), ((141895, 141919), 'numpy.minimum', 'np.minimum', (['temp.loss', 'a'], {}), '(temp.loss, a)\n', (141905, 141919), True, 'import numpy as np\n'), ((142503, 142560), 'numpy.allclose', 'np.allclose', (['s_[:-1:-1]', "temp[f'exi_x1gta_{ln}'].iloc[-1]"], {}), "(s_[:-1:-1], temp[f'exi_x1gta_{ln}'].iloc[-1])\n", (142514, 142560), True, 'import numpy as np\n'), ((142581, 142655), 'numpy.allclose', 'np.allclose', (["temp[f'exi_x1gta_{ln}'].iloc[:-1]", '(temp.S.iloc[:-1] * self.bs)'], {}), "(temp[f'exi_x1gta_{ln}'].iloc[:-1], temp.S.iloc[:-1] * self.bs)\n", (142592, 142655), True, 'import numpy as np\n'), ((147713, 147734), 'pandas.io.formats.format.EngFormatter', 'EngFormatter', (['(3)', '(True)'], {}), '(3, True)\n', (147725, 147734), False, 'from pandas.io.formats.format import EngFormatter\n'), ((180519, 180591), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(5)'], {'figsize': '(8, 3)', 'constrained_layout': '(True)', 'sharey': '(True)'}), '(1, 5, figsize=(8, 3), constrained_layout=True, sharey=True)\n', (180531, 180591), True, 'import matplotlib.pyplot as plt\n'), ((182815, 182890), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(4)', '(2)'], {'figsize': '(8, 10)', 'constrained_layout': '(True)', 'squeeze': '(False)'}), '(4, 2, figsize=(8, 10), constrained_layout=True, squeeze=False)\n', (182827, 182890), True, 'import matplotlib.pyplot as plt\n'), ((199156, 199275), 'pandas.DataFrame', 'pd.DataFrame', (['ans'], {'columns': "['loss', 'int1', 'int2', 'int3', 'exeqa', 'ptot', 'incr', 'c1', 'c2', 'c3',\n 'gt', 'log']"}), "(ans, columns=['loss', 'int1', 'int2', 'int3', 'exeqa', 'ptot',\n 'incr', 'c1', 'c2', 'c3', 'gt', 'log'])\n", (199168, 199275), True, 'import pandas as pd\n'), ((203403, 203416), 'IPython.core.display.display', 'display', (['test'], {}), '(test)\n', (203410, 203416), False, 'from IPython.core.display import HTML, display\n'), ((210271, 210317), 're.sub', 're.sub', (['"""([A-Z])m([0-9]+)"""', '"""$\\\\1_{-\\\\2}$"""', 'ln'], {}), "('([A-Z])m([0-9]+)', '$\\\\1_{-\\\\2}$', ln)\n", (210277, 210317), False, 'import re\n'), ((210334, 210378), 're.sub', 're.sub', (['"""([A-Z])([0-9]+)"""', '"""$\\\\1_{\\\\2}$"""', 'ln'], {}), "('([A-Z])([0-9]+)', '$\\\\1_{\\\\2}$', ln)\n", (210340, 210378), False, 'import re\n'), ((7834, 7852), 'numpy.finfo', 'np.finfo', (['np.float'], {}), '(np.float)\n', (7842, 7852), True, 'import numpy as np\n'), ((12979, 12990), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (12988, 12990), False, 'from pathlib import Path\n'), ((14092, 14109), 'copy.deepcopy', 'deepcopy', (['a._spec'], {}), '(a._spec)\n', (14100, 14109), False, 'from copy import deepcopy\n'), ((14812, 14829), 'copy.deepcopy', 'deepcopy', (['a._spec'], {}), '(a._spec)\n', (14820, 14829), False, 'from copy import deepcopy\n'), ((15936, 15998), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'figsize': '(8, 3.75)', 'constrained_layout': '(True)'}), '(1, 2, figsize=(8, 3.75), constrained_layout=True)\n', (15948, 15998), True, 'import matplotlib.pyplot as plt\n'), ((30967, 30977), 'numpy.exp', 'np.exp', (['mu'], {}), '(mu)\n', (30973, 30977), True, 'import numpy as np\n'), ((38098, 38109), 'IPython.core.display.display', 'display', (['_a'], {}), '(_a)\n', (38105, 38109), False, 'from IPython.core.display import HTML, display\n'), ((38402, 38434), 'numpy.copy', 'np.copy', (['ft_line_density[raw_nm]'], {}), '(ft_line_density[raw_nm])\n', (38409, 38434), True, 'import numpy as np\n'), ((41745, 41762), 'numpy.round', 'np.round', (['epds', '(7)'], {}), '(epds, 7)\n', (41753, 41762), True, 'import numpy as np\n'), ((44941, 44973), 'numpy.copy', 'np.copy', (['ft_line_density[raw_nm]'], {}), '(ft_line_density[raw_nm])\n', (44948, 44973), True, 'import numpy as np\n'), ((58292, 58317), 'pandas.Index', 'pd.Index', (['xs'], {'name': '"""loss"""'}), "(xs, name='loss')\n", (58300, 58317), True, 'import pandas as pd\n'), ((58357, 58423), 'pandas.MultiIndex.from_arrays', 'pd.MultiIndex.from_arrays', (['((), ())'], {'names': "('partial_wrt', 'line')"}), "(((), ()), names=('partial_wrt', 'line'))\n", (58382, 58423), True, 'import pandas as pd\n'), ((59472, 59526), 'numpy.logical_and', 'np.logical_and', (['(base_line_ft == 0)', '(adjust_line_ft == 0)'], {}), '(base_line_ft == 0, adjust_line_ft == 0)\n', (59486, 59526), True, 'import numpy as np\n'), ((59559, 59613), 'numpy.logical_and', 'np.logical_and', (['(base_line_ft == 0)', '(adjust_line_ft == 0)'], {}), '(base_line_ft == 0, adjust_line_ft == 0)\n', (59573, 59613), True, 'import numpy as np\n'), ((59641, 59694), 'numpy.logical_or', 'np.logical_or', (['(base_line_ft == 0)', '(adjust_line_ft == 0)'], {}), '(base_line_ft == 0, adjust_line_ft == 0)\n', (59654, 59694), True, 'import numpy as np\n'), ((91931, 92042), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['epd_values', 'loss_values'], {'kind': '"""linear"""', 'assume_sorted': '(True)', 'fill_value': '"""extrapolate"""'}), "(epd_values, loss_values, kind='linear', assume_sorted=\n True, fill_value='extrapolate')\n", (91951, 92042), False, 'from scipy import interpolate\n'), ((92157, 92268), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['loss_values', 'epd_values'], {'kind': '"""linear"""', 'assume_sorted': '(True)', 'fill_value': '"""extrapolate"""'}), "(loss_values, epd_values, kind='linear', assume_sorted=\n True, fill_value='extrapolate')\n", (92177, 92268), False, 'from scipy import interpolate\n'), ((95864, 95873), 'scipy.stats.norm', 'ss.norm', ([], {}), '()\n', (95871, 95873), True, 'import scipy.stats as ss\n'), ((133627, 133661), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(4, 4)'}), '(1, 1, figsize=(4, 4))\n', (133639, 133661), True, 'import matplotlib.pyplot as plt\n'), ((148851, 148883), 'numpy.maximum', 'np.maximum', (['(0)', '(1 - (1 - p) * ls1)'], {}), '(0, 1 - (1 - p) * ls1)\n', (148861, 148883), True, 'import numpy as np\n'), ((149674, 149708), 'matplotlib.ticker.LogLocator', 'ticker.LogLocator', (['(10)'], {'numticks': '(10)'}), '(10, numticks=10)\n', (149691, 149708), True, 'import matplotlib.ticker as ticker\n'), ((153935, 153953), 're.match', 're.match', (['regex', 'k'], {}), '(regex, k)\n', (153943, 153953), False, 'import re\n'), ((154989, 155003), 'pandas.concat', 'pd.concat', (['dfs'], {}), '(dfs)\n', (154998, 155003), True, 'import pandas as pd\n'), ((174913, 174934), 'matplotlib.ticker.FixedLocator', 'FixedLocator', (['[a_cal]'], {}), '([a_cal])\n', (174925, 174934), False, 'from matplotlib.ticker import MultipleLocator, StrMethodFormatter, MaxNLocator, FixedLocator, FixedFormatter, AutoMinorLocator\n'), ((175011, 175031), 'matplotlib.ticker.FixedFormatter', 'FixedFormatter', (['[ff]'], {}), '([ff])\n', (175025, 175031), False, 'from matplotlib.ticker import MultipleLocator, StrMethodFormatter, MaxNLocator, FixedLocator, FixedFormatter, AutoMinorLocator\n'), ((175071, 175085), 'matplotlib.ticker.MaxNLocator', 'MaxNLocator', (['n'], {}), '(n)\n', (175082, 175085), False, 'from matplotlib.ticker import MultipleLocator, StrMethodFormatter, MaxNLocator, FixedLocator, FixedFormatter, AutoMinorLocator\n'), ((175127, 175157), 'matplotlib.ticker.StrMethodFormatter', 'StrMethodFormatter', (['"""{x:,.0f}"""'], {}), "('{x:,.0f}')\n", (175145, 175157), False, 'from matplotlib.ticker import MultipleLocator, StrMethodFormatter, MaxNLocator, FixedLocator, FixedFormatter, AutoMinorLocator\n'), ((179467, 179488), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['xloc'], {}), '(xloc)\n', (179482, 179488), False, 'from matplotlib.ticker import MultipleLocator, StrMethodFormatter, MaxNLocator, FixedLocator, FixedFormatter, AutoMinorLocator\n'), ((179528, 179547), 'matplotlib.ticker.AutoMinorLocator', 'AutoMinorLocator', (['(4)'], {}), '(4)\n', (179544, 179547), False, 'from matplotlib.ticker import MultipleLocator, StrMethodFormatter, MaxNLocator, FixedLocator, FixedFormatter, AutoMinorLocator\n'), ((179589, 179618), 'matplotlib.ticker.StrMethodFormatter', 'StrMethodFormatter', (['"""{x:.2f}"""'], {}), "('{x:.2f}')\n", (179607, 179618), False, 'from matplotlib.ticker import MultipleLocator, StrMethodFormatter, MaxNLocator, FixedLocator, FixedFormatter, AutoMinorLocator\n'), ((179658, 179676), 'matplotlib.ticker.MaxNLocator', 'MaxNLocator', (['(2 * n)'], {}), '(2 * n)\n', (179669, 179676), False, 'from matplotlib.ticker import MultipleLocator, StrMethodFormatter, MaxNLocator, FixedLocator, FixedFormatter, AutoMinorLocator\n'), ((179716, 179735), 'matplotlib.ticker.AutoMinorLocator', 'AutoMinorLocator', (['(4)'], {}), '(4)\n', (179732, 179735), False, 'from matplotlib.ticker import MultipleLocator, StrMethodFormatter, MaxNLocator, FixedLocator, FixedFormatter, AutoMinorLocator\n'), ((196942, 196983), 'numpy.sum', 'np.sum', (['(xs[s1] * pline[s1] * notline[s1r])'], {}), '(xs[s1] * pline[s1] * notline[s1r])\n', (196948, 196983), True, 'import numpy as np\n'), ((197143, 197175), 'numpy.sum', 'np.sum', (['(pline[s3] * notline[s3r])'], {}), '(pline[s3] * notline[s3r])\n', (197149, 197175), True, 'import numpy as np\n'), ((205952, 205972), 're.search', 're.search', (['"""^ημ_"""', 'l'], {}), "('^ημ_', l)\n", (205961, 205972), False, 'import re\n'), ((4096, 4113), 'numpy.array', 'np.array', (['a.limit'], {}), '(a.limit)\n', (4104, 4113), True, 'import numpy as np\n'), ((31023, 31033), 'numpy.exp', 'np.exp', (['mu'], {}), '(mu)\n', (31029, 31033), True, 'import numpy as np\n'), ((37558, 37570), 'numpy.arange', 'np.arange', (['N'], {}), '(N)\n', (37567, 37570), True, 'import numpy as np\n'), ((41821, 41835), 'pandas.Index', 'pd.Index', (['epds'], {}), '(epds)\n', (41829, 41835), True, 'import pandas as pd\n'), ((88793, 88841), 'numpy.maximum', 'np.maximum', (['(0)', "(df['e_' + col] - df['lev_' + col])"], {}), "(0, df['e_' + col] - df['lev_' + col])\n", (88803, 88841), True, 'import numpy as np\n'), ((88945, 88999), 'numpy.maximum', 'np.maximum', (['(0)', "(df['e_ημ_' + col] - df['lev_ημ_' + col])"], {}), "(0, df['e_ημ_' + col] - df['lev_ημ_' + col])\n", (88955, 88999), True, 'import numpy as np\n'), ((89103, 89151), 'numpy.maximum', 'np.maximum', (['(0)', "(df['e_' + col] - df['exa_' + col])"], {}), "(0, df['e_' + col] - df['exa_' + col])\n", (89113, 89151), True, 'import numpy as np\n'), ((89255, 89309), 'numpy.maximum', 'np.maximum', (['(0)', "(df['e_ημ_' + col] - df['exa_ημ_' + col])"], {}), "(0, df['e_ημ_' + col] - df['exa_ημ_' + col])\n", (89265, 89309), True, 'import numpy as np\n'), ((89448, 89498), 'numpy.maximum', 'np.maximum', (['(0)', "(df['e_' + col] - df['e2pri_' + col])"], {}), "(0, df['e_' + col] - df['e2pri_' + col])\n", (89458, 89498), True, 'import numpy as np\n'), ((95688, 95700), 'numpy.sum', 'np.sum', (['trho'], {}), '(trho)\n', (95694, 95700), True, 'import numpy as np\n'), ((95738, 95755), 'numpy.sum', 'np.sum', (['(trho * lS)'], {}), '(trho * lS)\n', (95744, 95755), True, 'import numpy as np\n'), ((147880, 147919), 'numpy.where', 'np.where', (['(x == 0)', 'np.nan', '(1.0 / (1 - x))'], {}), '(x == 0, np.nan, 1.0 / (1 - x))\n', (147888, 147919), True, 'import numpy as np\n'), ((175219, 175233), 'matplotlib.ticker.MaxNLocator', 'MaxNLocator', (['n'], {}), '(n)\n', (175230, 175233), False, 'from matplotlib.ticker import MultipleLocator, StrMethodFormatter, MaxNLocator, FixedLocator, FixedFormatter, AutoMinorLocator\n'), ((175277, 175296), 'matplotlib.ticker.AutoMinorLocator', 'AutoMinorLocator', (['(4)'], {}), '(4)\n', (175293, 175296), False, 'from matplotlib.ticker import MultipleLocator, StrMethodFormatter, MaxNLocator, FixedLocator, FixedFormatter, AutoMinorLocator\n'), ((190040, 190103), 'pandas.MultiIndex.from_arrays', 'pd.MultiIndex.from_arrays', (['[[], []]'], {'names': "['Line', 'Scenario']"}), "([[], []], names=['Line', 'Scenario'])\n", (190065, 190103), True, 'import pandas as pd\n'), ((194571, 194627), 'pypandoc.convert_text', 'pypandoc.convert_text', (['ans'], {'to': '"""html"""', 'format': '"""markdown"""'}), "(ans, to='html', format='markdown')\n", (194592, 194627), False, 'import pypandoc\n'), ((197011, 197043), 'numpy.sum', 'np.sum', (['(pline[s2] * notline[s2r])'], {}), '(pline[s2] * notline[s2r])\n', (197017, 197043), True, 'import numpy as np\n'), ((197078, 197119), 'numpy.sum', 'np.sum', (['(xs[s3] * pline[s3] * notline[s3r])'], {}), '(xs[s3] * pline[s3] * notline[s3r])\n', (197084, 197119), True, 'import numpy as np\n'), ((202188, 202230), 'numpy.allclose', 'np.allclose', (['a.exag_total', 'a.exag_sumparts'], {}), '(a.exag_total, a.exag_sumparts)\n', (202199, 202230), True, 'import numpy as np\n'), ((206063, 206119), 're.sub', 're.sub', (['"""^ημ_([0-9A-Za-z\\\\-_.,]+)"""', '"""not \\\\1 density"""', 'l'], {}), "('^ημ_([0-9A-Za-z\\\\-_.,]+)', 'not \\\\1 density', l)\n", (206069, 206119), False, 'import re\n'), ((24318, 24357), 'numpy.linspace', 'np.linspace', (['(0)', 'p0', '(200)'], {'endpoint': '(False)'}), '(0, p0, 200, endpoint=False)\n', (24329, 24357), True, 'import numpy as np\n'), ((24386, 24405), 'numpy.hstack', 'np.hstack', (['(ps, _x)'], {}), '((ps, _x))\n', (24395, 24405), True, 'import numpy as np\n'), ((24434, 24469), 'numpy.hstack', 'np.hstack', (['(self.ex / (1 - ps), _y)'], {}), '((self.ex / (1 - ps), _y))\n', (24443, 24469), True, 'import numpy as np\n'), ((24505, 24605), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['tempx', 'tempy'], {'kind': '"""linear"""', 'bounds_error': '(False)', 'fill_value': '(self.ex, sup)'}), "(tempx, tempy, kind='linear', bounds_error=False,\n fill_value=(self.ex, sup))\n", (24525, 24605), False, 'from scipy import interpolate\n'), ((24729, 24824), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['_x', '_y'], {'kind': '"""linear"""', 'bounds_error': '(False)', 'fill_value': '(self.ex, sup)'}), "(_x, _y, kind='linear', bounds_error=False, fill_value=\n (self.ex, sup))\n", (24749, 24824), False, 'from scipy import interpolate\n'), ((25187, 25321), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['self.density_df.exgta_total', 'self.density_df.F'], {'kind': '"""linear"""', 'bounds_error': '(False)', 'fill_value': '"""extrapolate"""'}), "(self.density_df.exgta_total, self.density_df.F, kind=\n 'linear', bounds_error=False, fill_value='extrapolate')\n", (25207, 25321), False, 'from scipy import interpolate\n'), ((62302, 62360), 'IPython.core.display.display', 'display', (['self.priority_capital_df.loc[0.001:0.01, :].style'], {}), '(self.priority_capital_df.loc[0.001:0.01, :].style)\n', (62309, 62360), False, 'from IPython.core.display import HTML, display\n'), ((67411, 67437), 'numpy.sum', 'np.sum', (['(D.loss * D.p_total)'], {}), '(D.loss * D.p_total)\n', (67417, 67437), True, 'import numpy as np\n'), ((90272, 90383), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['epd_values', 'loss_values'], {'kind': '"""linear"""', 'assume_sorted': '(True)', 'fill_value': '"""extrapolate"""'}), "(epd_values, loss_values, kind='linear', assume_sorted=\n True, fill_value='extrapolate')\n", (90292, 90383), False, 'from scipy import interpolate\n'), ((90518, 90629), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['loss_values', 'epd_values'], {'kind': '"""linear"""', 'assume_sorted': '(True)', 'fill_value': '"""extrapolate"""'}), "(loss_values, epd_values, kind='linear', assume_sorted=\n True, fill_value='extrapolate')\n", (90538, 90629), False, 'from scipy import interpolate\n'), ((90883, 90994), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['epd_values', 'loss_values'], {'kind': '"""linear"""', 'assume_sorted': '(True)', 'fill_value': '"""extrapolate"""'}), "(epd_values, loss_values, kind='linear', assume_sorted=\n True, fill_value='extrapolate')\n", (90903, 90994), False, 'from scipy import interpolate\n'), ((91138, 91249), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['loss_values', 'epd_values'], {'kind': '"""linear"""', 'assume_sorted': '(True)', 'fill_value': '"""extrapolate"""'}), "(loss_values, epd_values, kind='linear', assume_sorted=\n True, fill_value='extrapolate')\n", (91158, 91249), False, 'from scipy import interpolate\n'), ((96036, 96048), 'numpy.sum', 'np.sum', (['tlam'], {}), '(tlam)\n', (96042, 96048), True, 'import numpy as np\n'), ((114721, 114734), 'numpy.sum', 'np.sum', (['gSeq0'], {}), '(gSeq0)\n', (114727, 114734), True, 'import numpy as np\n'), ((114973, 114986), 'numpy.sum', 'np.sum', (['gSeq0'], {}), '(gSeq0)\n', (114979, 114986), True, 'import numpy as np\n'), ((202344, 202382), 'numpy.abs', 'np.abs', (['(a.exag_total - a.exag_sumparts)'], {}), '(a.exag_total - a.exag_sumparts)\n', (202350, 202382), True, 'import numpy as np\n'), ((41577, 41617), 'numpy.linspace', 'np.linspace', (['(0.5)', '(0.1)', '(4)'], {'endpoint': '(False)'}), '(0.5, 0.1, 4, endpoint=False)\n', (41588, 41617), True, 'import numpy as np\n'), ((41642, 41698), 'numpy.linspace', 'np.linspace', (['(10 ** -n)', '(10 ** -(n + 1))', '(9)'], {'endpoint': '(False)'}), '(10 ** -n, 10 ** -(n + 1), 9, endpoint=False)\n', (41653, 41698), True, 'import numpy as np\n'), ((62670, 62687), 'IPython.core.display.display', 'display', (['df.style'], {}), '(df.style)\n', (62677, 62687), False, 'from IPython.core.display import HTML, display\n'), ((96550, 96590), 'numpy.sum', 'np.sum', (['(S * (den ** -1 - num / den ** 2))'], {}), '(S * (den ** -1 - num / den ** 2))\n', (96556, 96590), True, 'import numpy as np\n'), ((122994, 123012), 'numpy.sum', 'np.sum', (['mass_hints'], {}), '(mass_hints)\n', (123000, 123012), True, 'import numpy as np\n'), ((149811, 149831), 'numpy.arange', 'np.arange', (['(1.0)', '(10.0)'], {}), '(1.0, 10.0)\n', (149820, 149831), True, 'import numpy as np\n'), ((62955, 62972), 'IPython.core.display.display', 'display', (['df.style'], {}), '(df.style)\n', (62962, 62972), False, 'from IPython.core.display import HTML, display\n'), ((96493, 96505), 'numpy.sum', 'np.sum', (['tlam'], {}), '(tlam)\n', (96499, 96505), True, 'import numpy as np\n'), ((97812, 97832), 'numpy.sqrt', 'np.sqrt', (['(S * (1 - S))'], {}), '(S * (1 - S))\n', (97819, 97832), True, 'import numpy as np\n'), ((63044, 63055), 'IPython.core.display.display', 'display', (['df'], {}), '(df)\n', (63051, 63055), False, 'from IPython.core.display import HTML, display\n'), ((96947, 96972), 'numpy.where', 'np.where', (['(r0_rS < 1)', 'S', '(0)'], {}), '(r0_rS < 1, S, 0)\n', (96955, 96972), True, 'import numpy as np\n'), ((98494, 98502), 'scipy.stats.t', 'ss.t', (['df'], {}), '(df)\n', (98498, 98502), True, 'import scipy.stats as ss\n'), ((96874, 96894), 'numpy.minimum', 'np.minimum', (['(1)', 'r0_rS'], {}), '(1, r0_rS)\n', (96884, 96894), True, 'import numpy as np\n'), ((97426, 97451), 'numpy.where', 'np.where', (['(r0_rS < 1)', 'S', '(0)'], {}), '(r0_rS < 1, S, 0)\n', (97434, 97451), True, 'import numpy as np\n'), ((98921, 98930), 'numpy.log', 'np.log', (['S'], {}), '(S)\n', (98927, 98930), True, 'import numpy as np\n'), ((98970, 98980), 'numpy.exp', 'np.exp', (['r0'], {}), '(r0)\n', (98976, 98980), True, 'import numpy as np\n'), ((97353, 97373), 'numpy.minimum', 'np.minimum', (['(1)', 'r0_rS'], {}), '(1, r0_rS)\n', (97363, 97373), True, 'import numpy as np\n'), ((98665, 98677), 'numpy.sum', 'np.sum', (['tlam'], {}), '(tlam)\n', (98671, 98677), True, 'import numpy as np\n'), ((98010, 98029), 'numpy.minimum', 'np.minimum', (['(1)', 'temp'], {}), '(1, temp)\n', (98020, 98029), True, 'import numpy as np\n'), ((98098, 98124), 'numpy.where', 'np.where', (['(temp < 1)', 'rSF', '(0)'], {}), '(temp < 1, rSF, 0)\n', (98106, 98124), True, 'import numpy as np\n'), ((99410, 99423), 'numpy.log', 'np.log', (['(1 - S)'], {}), '(1 - S)\n', (99416, 99423), True, 'import numpy as np\n'), ((99071, 99094), 'numpy.minimum', 'np.minimum', (['(1)', 'uncapped'], {}), '(1, uncapped)\n', (99081, 99094), True, 'import numpy as np\n'), ((99140, 99180), 'numpy.where', 'np.where', (['(uncapped < 1)', '(uncapped * lS)', '(0)'], {}), '(uncapped < 1, uncapped * lS, 0)\n', (99148, 99180), True, 'import numpy as np\n'), ((99595, 99607), 'numpy.sum', 'np.sum', (['trho'], {}), '(trho)\n', (99601, 99607), True, 'import numpy as np\n'), ((99645, 99662), 'numpy.sum', 'np.sum', (['(temp * lS)'], {}), '(temp * lS)\n', (99651, 99662), True, 'import numpy as np\n'), ((99868, 99908), 'numpy.where', 'np.where', (['(S <= 1 - rho)', '(S / (1 - rho))', '(1)'], {}), '(S <= 1 - rho, S / (1 - rho), 1)\n', (99876, 99908), True, 'import numpy as np\n'), ((99931, 99976), 'numpy.where', 'np.where', (['(S <= 1 - rho)', '(S / (1 - rho) ** 2)', '(1)'], {}), '(S <= 1 - rho, S / (1 - rho) ** 2, 1)\n', (99939, 99976), True, 'import numpy as np\n'), ((100292, 100328), 'numpy.array', 'np.array', (['[0.0, 1 - p1, 1 - p0, 1.0]'], {}), '([0.0, 1 - p1, 1 - p0, 1.0])\n', (100300, 100328), True, 'import numpy as np\n'), ((99994, 100006), 'numpy.sum', 'np.sum', (['temp'], {}), '(temp)\n', (100000, 100006), True, 'import numpy as np\n'), ((100044, 100057), 'numpy.sum', 'np.sum', (['temp2'], {}), '(temp2)\n', (100050, 100057), True, 'import numpy as np\n'), ((100422, 100451), 'numpy.array', 'np.array', (['[0.0, pt, 1.0, 1.0]'], {}), '([0.0, pt, 1.0, 1.0])\n', (100430, 100451), True, 'import numpy as np\n'), ((100472, 100502), 'scipy.interpolate.interp1d', 'interp1d', (['s', 'gs'], {'kind': '"""linear"""'}), "(s, gs, kind='linear')\n", (100480, 100502), False, 'from scipy.interpolate import interp1d\n'), ((100552, 100564), 'numpy.sum', 'np.sum', (['trho'], {}), '(trho)\n', (100558, 100564), True, 'import numpy as np\n'), ((100610, 100637), 'numpy.minimum', 'np.minimum', (['(S / (1 - p1))', '(1)'], {}), '(S / (1 - p1), 1)\n', (100620, 100637), True, 'import numpy as np\n'), ((100640, 100667), 'numpy.minimum', 'np.minimum', (['(S / (1 - p0))', '(1)'], {}), '(S / (1 - p0), 1)\n', (100650, 100667), True, 'import numpy as np\n')]
from simtk import openmm as mm from simtk.openmm import app from simtk import unit import torch import numpy as np # Gas constant in kJ / mol / K R = 8.314e-3 class OpenMMEnergyInterface(torch.autograd.Function): @staticmethod def forward(ctx, input, openmm_context, temperature): device = input.device n_batch = input.shape[0] input = input.view(n_batch, -1, 3) n_dim = input.shape[1] energies = torch.zeros((n_batch, 1), dtype=input.dtype) forces = torch.zeros_like(input) kBT = R * temperature input = input.cpu().detach().numpy() for i in range(n_batch): # reshape the coordinates and send to OpenMM x = input[i, :].reshape(-1, 3) # Handle nans and infinities if np.any(np.isnan(x)) or np.any(np.isinf(x)): energies[i, 0] = np.nan else: openmm_context.setPositions(x) state = openmm_context.getState(getForces=True, getEnergy=True) # get energy energies[i, 0] = ( state.getPotentialEnergy().value_in_unit( unit.kilojoule / unit.mole) / kBT ) # get forces f = ( state.getForces(asNumpy=True).value_in_unit( unit.kilojoule / unit.mole / unit.nanometer ) / kBT ) forces[i, :] = torch.from_numpy(-f) forces = forces.view(n_batch, n_dim * 3) # Save the forces for the backward step, uploading to the gpu if needed ctx.save_for_backward(forces.to(device=device)) return energies.to(device=device) @staticmethod def backward(ctx, grad_output): forces, = ctx.saved_tensors return forces * grad_output, None, None class OpenMMEnergyInterfaceParallel(torch.autograd.Function): """ Uses parallel processing to get the energies of the batch of states """ @staticmethod def var_init(sys, temp): """ Method to initialize temperature and openmm context for workers of multiprocessing pool """ global temperature, openmm_context temperature = temp sim = app.Simulation(sys.topology, sys.system, mm.LangevinIntegrator(temp * unit.kelvin, 1.0 / unit.picosecond, 1.0 * unit.femtosecond), platform=mm.Platform.getPlatformByName('Reference')) openmm_context = sim.context @staticmethod def batch_proc(input): # Process state # openmm context and temperature are passed a global variables input = input.reshape(-1, 3) n_dim = input.shape[0] kBT = R * temperature # Handle nans and infinities if np.any(np.isnan(input)) or np.any(np.isinf(input)): energy = np.nan force = np.zeros_like(input) else: openmm_context.setPositions(input) state = openmm_context.getState(getForces=True, getEnergy=True) # get energy energy = state.getPotentialEnergy().value_in_unit( unit.kilojoule / unit.mole) / kBT # get forces force = -state.getForces(asNumpy=True).value_in_unit( unit.kilojoule / unit.mole / unit.nanometer) / kBT force = force.reshape(n_dim * 3) return energy, force @staticmethod def forward(ctx, input, pool): device = input.device input_np = input.cpu().detach().numpy() energies_out, forces_out = zip(*pool.map( OpenMMEnergyInterfaceParallel.batch_proc, input_np)) energies_np = np.array(energies_out)[:, None] forces_np = np.array(forces_out) energies = torch.from_numpy(energies_np) forces = torch.from_numpy(forces_np) energies = energies.type(input.dtype) forces = forces.type(input.dtype) # Save the forces for the backward step, uploading to the gpu if needed ctx.save_for_backward(forces.to(device=device)) return energies.to(device=device) @staticmethod def backward(ctx, grad_output): forces, = ctx.saved_tensors return forces * grad_output, None, None def regularize_energy(energy, energy_cut, energy_max): # Cast inputs to same type energy_cut = energy_cut.type(energy.type()) energy_max = energy_max.type(energy.type()) # Check whether energy finite energy_finite = torch.isfinite(energy) # Cap the energy at energy_max energy = torch.where(energy < energy_max, energy, energy_max) # Make it logarithmic above energy cut and linear below energy = torch.where( energy < energy_cut, energy, torch.log(energy - energy_cut + 1) + energy_cut ) energy = torch.where(energy_finite, energy, torch.tensor(np.nan, dtype=energy.dtype, device=energy.device)) return energy
[ "torch.log", "simtk.openmm.Platform.getPlatformByName", "torch.isfinite", "torch.from_numpy", "numpy.array", "torch.tensor", "simtk.openmm.LangevinIntegrator", "numpy.isnan", "torch.zeros_like", "numpy.isinf", "numpy.zeros_like", "torch.zeros", "torch.where" ]
[((4686, 4708), 'torch.isfinite', 'torch.isfinite', (['energy'], {}), '(energy)\n', (4700, 4708), False, 'import torch\n'), ((4757, 4809), 'torch.where', 'torch.where', (['(energy < energy_max)', 'energy', 'energy_max'], {}), '(energy < energy_max, energy, energy_max)\n', (4768, 4809), False, 'import torch\n'), ((449, 493), 'torch.zeros', 'torch.zeros', (['(n_batch, 1)'], {'dtype': 'input.dtype'}), '((n_batch, 1), dtype=input.dtype)\n', (460, 493), False, 'import torch\n'), ((511, 534), 'torch.zeros_like', 'torch.zeros_like', (['input'], {}), '(input)\n', (527, 534), False, 'import torch\n'), ((3928, 3948), 'numpy.array', 'np.array', (['forces_out'], {}), '(forces_out)\n', (3936, 3948), True, 'import numpy as np\n'), ((3968, 3997), 'torch.from_numpy', 'torch.from_numpy', (['energies_np'], {}), '(energies_np)\n', (3984, 3997), False, 'import torch\n'), ((4015, 4042), 'torch.from_numpy', 'torch.from_numpy', (['forces_np'], {}), '(forces_np)\n', (4031, 4042), False, 'import torch\n'), ((5060, 5122), 'torch.tensor', 'torch.tensor', (['np.nan'], {'dtype': 'energy.dtype', 'device': 'energy.device'}), '(np.nan, dtype=energy.dtype, device=energy.device)\n', (5072, 5122), False, 'import torch\n'), ((2382, 2475), 'simtk.openmm.LangevinIntegrator', 'mm.LangevinIntegrator', (['(temp * unit.kelvin)', '(1.0 / unit.picosecond)', '(1.0 * unit.femtosecond)'], {}), '(temp * unit.kelvin, 1.0 / unit.picosecond, 1.0 * unit\n .femtosecond)\n', (2403, 2475), True, 'from simtk import openmm as mm\n'), ((3081, 3101), 'numpy.zeros_like', 'np.zeros_like', (['input'], {}), '(input)\n', (3094, 3101), True, 'import numpy as np\n'), ((3876, 3898), 'numpy.array', 'np.array', (['energies_out'], {}), '(energies_out)\n', (3884, 3898), True, 'import numpy as np\n'), ((4933, 4967), 'torch.log', 'torch.log', (['(energy - energy_cut + 1)'], {}), '(energy - energy_cut + 1)\n', (4942, 4967), False, 'import torch\n'), ((1514, 1534), 'torch.from_numpy', 'torch.from_numpy', (['(-f)'], {}), '(-f)\n', (1530, 1534), False, 'import torch\n'), ((2612, 2654), 'simtk.openmm.Platform.getPlatformByName', 'mm.Platform.getPlatformByName', (['"""Reference"""'], {}), "('Reference')\n", (2641, 2654), True, 'from simtk import openmm as mm\n'), ((2988, 3003), 'numpy.isnan', 'np.isnan', (['input'], {}), '(input)\n', (2996, 3003), True, 'import numpy as np\n'), ((3015, 3030), 'numpy.isinf', 'np.isinf', (['input'], {}), '(input)\n', (3023, 3030), True, 'import numpy as np\n'), ((807, 818), 'numpy.isnan', 'np.isnan', (['x'], {}), '(x)\n', (815, 818), True, 'import numpy as np\n'), ((830, 841), 'numpy.isinf', 'np.isinf', (['x'], {}), '(x)\n', (838, 841), True, 'import numpy as np\n')]
""" Test to test truncation error and """ import numpy as np import time import matplotlib.pyplot as plt from HAPILite import CalcCrossSection, CalcCrossSectionWithError from lib.ReadComputeFunc import ReadData from lib.PartitionFunction import BD_TIPS_2017_PYTHON from matplotlib.backends.backend_pdf import PdfPages from matplotlib.ticker import FormatStrFormatter Molecule = "CO" TempValue = 300.0 Tref=296.0 P_Value = 1.0 OmegaWingValue = 100.0 OmegaRangeValue = [1./30000.*1e7, 1./300.*1e7] WaveNumber = np.arange(OmegaRangeValue[0], OmegaRangeValue[1]+0.01, 0.001) Database = ReadData(Molecule, Location="data/") MoleculeNumberDB, IsoNumberDB, LineCenterDB, LineIntensityDB, \ LowerStateEnergyDB, GammaSelf, TempRatioPower, ErrorArray = Database SelectIndex = np.logical_and(LineCenterDB>OmegaRangeValue[0], LineCenterDB<OmegaRangeValue[1]) LineCenterDB = LineCenterDB[SelectIndex] LineIntensityDB = LineIntensityDB[SelectIndex] LowerStateEnergyDB = LowerStateEnergyDB[SelectIndex] const_R = 1.4388028496642257 #Radiation Constant TempRange = np.arange(100,901,100) expPRange = np.arange(-5.,3.1,0.5) ErrorMatrix = np.zeros((len(TempRange), len(expPRange))) for TCounter, TempValue in enumerate(TempRange): for PCounter, expP in enumerate(expPRange): PValue = 10**expP ch = np.exp(-const_R*LowerStateEnergyDB/TempValue)*(1-np.exp(-const_R*LineCenterDB/TempValue)) zn = np.exp(-const_R*LowerStateEnergyDB/Tref)*(1-np.exp(-const_R*LineCenterDB/Tref)) SigmaT = BD_TIPS_2017_PYTHON(MoleculeNumberDB,IsoNumberDB,TempValue) SigmaTref = BD_TIPS_2017_PYTHON(MoleculeNumberDB,IsoNumberDB,Tref) LineIntensityScaled = LineIntensityDB*SigmaTref/SigmaT*ch/zn TotalIntensity = np.sum(LineIntensityScaled) CrossSection = CalcCrossSection(Database,Temp=TempValue, P = PValue,\ WN_Grid=WaveNumber, Profile="Voigt", OmegaWing=OmegaWingValue,\ OmegaWingHW=100.0, NCORES=-1) #Generate the area Area = np.trapz(CrossSection, WaveNumber) #Relative error RelativeError = (TotalIntensity - Area)/TotalIntensity*100.0 print(TempValue, PValue, "::", RelativeError) ErrorMatrix[TCounter, PCounter] = RelativeError np.savetxt("ErrorValue_HW_HS.csv", ErrorMatrix, delimiter=",")
[ "numpy.trapz", "numpy.logical_and", "HAPILite.CalcCrossSection", "numpy.exp", "lib.ReadComputeFunc.ReadData", "numpy.sum", "numpy.savetxt", "lib.PartitionFunction.BD_TIPS_2017_PYTHON", "numpy.arange" ]
[((514, 577), 'numpy.arange', 'np.arange', (['OmegaRangeValue[0]', '(OmegaRangeValue[1] + 0.01)', '(0.001)'], {}), '(OmegaRangeValue[0], OmegaRangeValue[1] + 0.01, 0.001)\n', (523, 577), True, 'import numpy as np\n'), ((589, 625), 'lib.ReadComputeFunc.ReadData', 'ReadData', (['Molecule'], {'Location': '"""data/"""'}), "(Molecule, Location='data/')\n", (597, 625), False, 'from lib.ReadComputeFunc import ReadData\n'), ((774, 862), 'numpy.logical_and', 'np.logical_and', (['(LineCenterDB > OmegaRangeValue[0])', '(LineCenterDB < OmegaRangeValue[1])'], {}), '(LineCenterDB > OmegaRangeValue[0], LineCenterDB <\n OmegaRangeValue[1])\n', (788, 862), True, 'import numpy as np\n'), ((1061, 1085), 'numpy.arange', 'np.arange', (['(100)', '(901)', '(100)'], {}), '(100, 901, 100)\n', (1070, 1085), True, 'import numpy as np\n'), ((1096, 1121), 'numpy.arange', 'np.arange', (['(-5.0)', '(3.1)', '(0.5)'], {}), '(-5.0, 3.1, 0.5)\n', (1105, 1121), True, 'import numpy as np\n'), ((2287, 2349), 'numpy.savetxt', 'np.savetxt', (['"""ErrorValue_HW_HS.csv"""', 'ErrorMatrix'], {'delimiter': '""","""'}), "('ErrorValue_HW_HS.csv', ErrorMatrix, delimiter=',')\n", (2297, 2349), True, 'import numpy as np\n'), ((1515, 1576), 'lib.PartitionFunction.BD_TIPS_2017_PYTHON', 'BD_TIPS_2017_PYTHON', (['MoleculeNumberDB', 'IsoNumberDB', 'TempValue'], {}), '(MoleculeNumberDB, IsoNumberDB, TempValue)\n', (1534, 1576), False, 'from lib.PartitionFunction import BD_TIPS_2017_PYTHON\n'), ((1595, 1651), 'lib.PartitionFunction.BD_TIPS_2017_PYTHON', 'BD_TIPS_2017_PYTHON', (['MoleculeNumberDB', 'IsoNumberDB', 'Tref'], {}), '(MoleculeNumberDB, IsoNumberDB, Tref)\n', (1614, 1651), False, 'from lib.PartitionFunction import BD_TIPS_2017_PYTHON\n'), ((1746, 1773), 'numpy.sum', 'np.sum', (['LineIntensityScaled'], {}), '(LineIntensityScaled)\n', (1752, 1773), True, 'import numpy as np\n'), ((1801, 1950), 'HAPILite.CalcCrossSection', 'CalcCrossSection', (['Database'], {'Temp': 'TempValue', 'P': 'PValue', 'WN_Grid': 'WaveNumber', 'Profile': '"""Voigt"""', 'OmegaWing': 'OmegaWingValue', 'OmegaWingHW': '(100.0)', 'NCORES': '(-1)'}), "(Database, Temp=TempValue, P=PValue, WN_Grid=WaveNumber,\n Profile='Voigt', OmegaWing=OmegaWingValue, OmegaWingHW=100.0, NCORES=-1)\n", (1817, 1950), False, 'from HAPILite import CalcCrossSection, CalcCrossSectionWithError\n'), ((2044, 2078), 'numpy.trapz', 'np.trapz', (['CrossSection', 'WaveNumber'], {}), '(CrossSection, WaveNumber)\n', (2052, 2078), True, 'import numpy as np\n'), ((1315, 1364), 'numpy.exp', 'np.exp', (['(-const_R * LowerStateEnergyDB / TempValue)'], {}), '(-const_R * LowerStateEnergyDB / TempValue)\n', (1321, 1364), True, 'import numpy as np\n'), ((1418, 1462), 'numpy.exp', 'np.exp', (['(-const_R * LowerStateEnergyDB / Tref)'], {}), '(-const_R * LowerStateEnergyDB / Tref)\n', (1424, 1462), True, 'import numpy as np\n'), ((1364, 1407), 'numpy.exp', 'np.exp', (['(-const_R * LineCenterDB / TempValue)'], {}), '(-const_R * LineCenterDB / TempValue)\n', (1370, 1407), True, 'import numpy as np\n'), ((1462, 1500), 'numpy.exp', 'np.exp', (['(-const_R * LineCenterDB / Tref)'], {}), '(-const_R * LineCenterDB / Tref)\n', (1468, 1500), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np from numpy import ma from .qctests import QCCheckVar def constant_cluster_size(x, tol=0): """Estimate the cluster size with (nearly) constant value Returns how many consecutive neighbor values are within a given tolerance range. Note that invalid values, like NaN, are ignored. """ assert np.ndim(x) == 1, 'Not ready for more than 1 dimension' # Adding a tolerance to handle roundings due to different numeric types. tol = tol + 1e-5 * tol ivalid = np.nonzero(~ma.getmaskarray(ma.fix_invalid(x)))[0] dx = np.diff(np.atleast_1d(x)[ivalid]) cluster_size = np.zeros(np.shape(x), dtype='i') for i, iv in enumerate(ivalid): idx = np.absolute(dx[i:].cumsum()) > tol if True in idx: cluster_size[iv] += np.nonzero(idx)[0].min() else: cluster_size[iv] += idx.size idx = np.absolute(dx[0:i][::-1].cumsum()) > tol if True in idx: cluster_size[iv] += np.nonzero(idx)[0].min() else: cluster_size[iv] += idx.size return cluster_size class ConstantClusterSize(QCCheckVar): """ Need to implement a check on time. TSG specifies constant value during 6 hrs. """ def set_features(self): cluster_size = constant_cluster_size(self.data[self.varname]) N = ma.compressed(self.data[self.varname]).size cluster_fraction = cluster_size / N self.features = {'constant_cluster_size': cluster_size, 'constant_cluster_fraction': cluster_fraction, } def test(self): self.flags = {} threshold = self.cfg['threshold'] # assert (np.size(threshold) == 1) \ # and (threshold is not None) \ # and (np.isfinite(threshold)) if isinstance(threshold, str) and (threshold[-1] == '%'): threshold = float(threshold[:-1]) * 1e-2 feature_name = 'constant_cluster_fraction' else: feature_name = 'constant_cluster_size' flag = np.zeros(self.data[self.varname].shape, dtype='i1') feature = self.features[feature_name] flag[np.nonzero(feature > threshold)] = self.flag_bad flag[np.nonzero(feature <= threshold)] = self.flag_good flag[ma.getmaskarray(self.data[self.varname])] = 9 self.flags[feature_name] = flag
[ "numpy.ma.getmaskarray", "numpy.ma.fix_invalid", "numpy.ndim", "numpy.zeros", "numpy.ma.compressed", "numpy.nonzero", "numpy.shape", "numpy.atleast_1d" ]
[((429, 439), 'numpy.ndim', 'np.ndim', (['x'], {}), '(x)\n', (436, 439), True, 'import numpy as np\n'), ((726, 737), 'numpy.shape', 'np.shape', (['x'], {}), '(x)\n', (734, 737), True, 'import numpy as np\n'), ((2173, 2224), 'numpy.zeros', 'np.zeros', (['self.data[self.varname].shape'], {'dtype': '"""i1"""'}), "(self.data[self.varname].shape, dtype='i1')\n", (2181, 2224), True, 'import numpy as np\n'), ((671, 687), 'numpy.atleast_1d', 'np.atleast_1d', (['x'], {}), '(x)\n', (684, 687), True, 'import numpy as np\n'), ((1439, 1477), 'numpy.ma.compressed', 'ma.compressed', (['self.data[self.varname]'], {}), '(self.data[self.varname])\n', (1452, 1477), False, 'from numpy import ma\n'), ((2284, 2315), 'numpy.nonzero', 'np.nonzero', (['(feature > threshold)'], {}), '(feature > threshold)\n', (2294, 2315), True, 'import numpy as np\n'), ((2346, 2378), 'numpy.nonzero', 'np.nonzero', (['(feature <= threshold)'], {}), '(feature <= threshold)\n', (2356, 2378), True, 'import numpy as np\n'), ((2410, 2450), 'numpy.ma.getmaskarray', 'ma.getmaskarray', (['self.data[self.varname]'], {}), '(self.data[self.varname])\n', (2425, 2450), False, 'from numpy import ma\n'), ((631, 648), 'numpy.ma.fix_invalid', 'ma.fix_invalid', (['x'], {}), '(x)\n', (645, 648), False, 'from numpy import ma\n'), ((891, 906), 'numpy.nonzero', 'np.nonzero', (['idx'], {}), '(idx)\n', (901, 906), True, 'import numpy as np\n'), ((1083, 1098), 'numpy.nonzero', 'np.nonzero', (['idx'], {}), '(idx)\n', (1093, 1098), True, 'import numpy as np\n')]
from __future__ import print_function, division import os,unittest,numpy as np def run_tddft_iter(calculator, label, freq): from pyscf.nao import system_vars_c, prod_basis_c, tddft_iter_c if label == "siesta": sv = system_vars_c().init_siesta_xml() elif label == "gpaw": sv = system_vars_c().init_gpaw(calculator) else: raise ValueError("Only siesta or gpaw calculator for the moment!") pb = prod_basis_c().init_prod_basis_pp(sv) td = tddft_iter_c(pb.sv, pb, tddft_iter_broadening=1e-2) omegas = np.linspace(freq[0], freq[freq.shape[0]-1], freq.shape[0]) + 1j*td.eps pxx_nonin = np.zeros(omegas.shape[0], dtype=float) pxx_inter = np.zeros(omegas.shape[0], dtype=float) vext = np.transpose(td.moms1) for iomega,omega in enumerate(omegas): pxx_nonin[iomega] = -np.dot(td.apply_rf0(vext[0,:], omega), vext[0,:]).imag pxx_inter = -td.comp_polariz_xx(omegas).imag return pxx_nonin, pxx_inter try: # run Siesta first from ase.units import Ry, eV, Ha from ase.calculators.siesta import Siesta from ase import Atoms H2O = Atoms("H2O", np.array([[0.0, -0.757, 0.587], [0.0, +0.757, 0.587], [0.0, 0.0, 0.0]]), cell = np.eye(3, dtype=float)) #H2O.center(vacuum=3.5) # unit cell 1 0 0 # 0 1 0 => siesta default unit cell use # 0 0 1 siesta_calc = Siesta( mesh_cutoff=150 * Ry, basis_set='SZ', energy_shift=(10 * 10**-3) * eV, xc = "PBE", fdf_arguments={ 'SCFMustConverge': False, 'COOP.Write': True, 'WriteDenchar': True, 'PAO.BasisType': 'split', 'DM.Tolerance': 1e-4, 'DM.MixingWeight': 0.01, 'MaxSCFIterations': 150, 'DM.NumberPulay': 4}) H2O.set_calculator(siesta_calc) efree_siesta = H2O.get_potential_energy() # run gpaw from gpaw import GPAW, PoissonSolver H2O_gp = Atoms("H2O", np.array([[0.0, -0.757, 0.587], [0.0, +0.757, 0.587], [0.0, 0.0, 0.0]])) H2O_gp.center(vacuum=3.5) convergence = {'density': 1e-7} poissonsolver = PoissonSolver(eps=1e-14, remove_moment=1 + 3) gpaw_calc = GPAW(xc='PBE', h=0.3, nbands=6, convergence=convergence, poissonsolver=poissonsolver, mode='lcao', setups="sg15", txt=None) H2O_gp.set_calculator(gpaw_calc) efree_gpaw = H2O_gp.get_potential_energy() dft = True except: dft = False class KnowValues(unittest.TestCase): def test_gpaw_vs_siesta_tddft_iter(self): """ init ao_log_c with it radial orbitals from GPAW """ if not dft: return omegas = np.linspace(0.0,2.0,500) pxx = {"nonin": {"siesta": np.zeros(omegas.shape[0], dtype=float), "gpaw": np.zeros(omegas.shape[0], dtype=float)}, "inter": {"siesta": np.zeros(omegas.shape[0], dtype=float), "gpaw": np.zeros(omegas.shape[0], dtype=float)} } pxx["nonin"]["siesta"], pxx["inter"]["siesta"] = run_tddft_iter(siesta_calc, "siesta", omegas) pxx["nonin"]["gpaw"], pxx["inter"]["gpaw"] = run_tddft_iter(gpaw_calc, "gpaw", omegas) import ase.units as un for key, val in pxx.items(): freq_shift = abs(omegas[np.argmax(val["siesta"])] - omegas[np.argmax(val["gpaw"])]) self.assertLess(freq_shift*un.Ha, 5.0) if __name__ == "__main__": unittest.main()
[ "numpy.eye", "gpaw.PoissonSolver", "gpaw.GPAW", "numpy.argmax", "numpy.array", "numpy.zeros", "numpy.linspace", "pyscf.nao.prod_basis_c", "pyscf.nao.system_vars_c", "unittest.main", "pyscf.nao.tddft_iter_c", "numpy.transpose", "ase.calculators.siesta.Siesta" ]
[((486, 537), 'pyscf.nao.tddft_iter_c', 'tddft_iter_c', (['pb.sv', 'pb'], {'tddft_iter_broadening': '(0.01)'}), '(pb.sv, pb, tddft_iter_broadening=0.01)\n', (498, 537), False, 'from pyscf.nao import system_vars_c, prod_basis_c, tddft_iter_c\n'), ((639, 677), 'numpy.zeros', 'np.zeros', (['omegas.shape[0]'], {'dtype': 'float'}), '(omegas.shape[0], dtype=float)\n', (647, 677), True, 'import os, unittest, numpy as np\n'), ((694, 732), 'numpy.zeros', 'np.zeros', (['omegas.shape[0]'], {'dtype': 'float'}), '(omegas.shape[0], dtype=float)\n', (702, 732), True, 'import os, unittest, numpy as np\n'), ((745, 767), 'numpy.transpose', 'np.transpose', (['td.moms1'], {}), '(td.moms1)\n', (757, 767), True, 'import os, unittest, numpy as np\n'), ((1482, 1792), 'ase.calculators.siesta.Siesta', 'Siesta', ([], {'mesh_cutoff': '(150 * Ry)', 'basis_set': '"""SZ"""', 'energy_shift': '(10 * 10 ** -3 * eV)', 'xc': '"""PBE"""', 'fdf_arguments': "{'SCFMustConverge': False, 'COOP.Write': True, 'WriteDenchar': True,\n 'PAO.BasisType': 'split', 'DM.Tolerance': 0.0001, 'DM.MixingWeight': \n 0.01, 'MaxSCFIterations': 150, 'DM.NumberPulay': 4}"}), "(mesh_cutoff=150 * Ry, basis_set='SZ', energy_shift=10 * 10 ** -3 *\n eV, xc='PBE', fdf_arguments={'SCFMustConverge': False, 'COOP.Write': \n True, 'WriteDenchar': True, 'PAO.BasisType': 'split', 'DM.Tolerance': \n 0.0001, 'DM.MixingWeight': 0.01, 'MaxSCFIterations': 150,\n 'DM.NumberPulay': 4})\n", (1488, 1792), False, 'from ase.calculators.siesta import Siesta\n'), ((2348, 2393), 'gpaw.PoissonSolver', 'PoissonSolver', ([], {'eps': '(1e-14)', 'remove_moment': '(1 + 3)'}), '(eps=1e-14, remove_moment=1 + 3)\n', (2361, 2393), False, 'from gpaw import GPAW, PoissonSolver\n'), ((2410, 2538), 'gpaw.GPAW', 'GPAW', ([], {'xc': '"""PBE"""', 'h': '(0.3)', 'nbands': '(6)', 'convergence': 'convergence', 'poissonsolver': 'poissonsolver', 'mode': '"""lcao"""', 'setups': '"""sg15"""', 'txt': 'None'}), "(xc='PBE', h=0.3, nbands=6, convergence=convergence, poissonsolver=\n poissonsolver, mode='lcao', setups='sg15', txt=None)\n", (2414, 2538), False, 'from gpaw import GPAW, PoissonSolver\n'), ((3611, 3626), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3624, 3626), False, 'import os, unittest, numpy as np\n'), ((551, 611), 'numpy.linspace', 'np.linspace', (['freq[0]', 'freq[freq.shape[0] - 1]', 'freq.shape[0]'], {}), '(freq[0], freq[freq.shape[0] - 1], freq.shape[0])\n', (562, 611), True, 'import os, unittest, numpy as np\n'), ((1142, 1213), 'numpy.array', 'np.array', (['[[0.0, -0.757, 0.587], [0.0, +0.757, 0.587], [0.0, 0.0, 0.0]]'], {}), '([[0.0, -0.757, 0.587], [0.0, +0.757, 0.587], [0.0, 0.0, 0.0]])\n', (1150, 1213), True, 'import os, unittest, numpy as np\n'), ((2123, 2194), 'numpy.array', 'np.array', (['[[0.0, -0.757, 0.587], [0.0, +0.757, 0.587], [0.0, 0.0, 0.0]]'], {}), '([[0.0, -0.757, 0.587], [0.0, +0.757, 0.587], [0.0, 0.0, 0.0]])\n', (2131, 2194), True, 'import os, unittest, numpy as np\n'), ((2863, 2889), 'numpy.linspace', 'np.linspace', (['(0.0)', '(2.0)', '(500)'], {}), '(0.0, 2.0, 500)\n', (2874, 2889), True, 'import os, unittest, numpy as np\n'), ((439, 453), 'pyscf.nao.prod_basis_c', 'prod_basis_c', ([], {}), '()\n', (451, 453), False, 'from pyscf.nao import system_vars_c, prod_basis_c, tddft_iter_c\n'), ((1311, 1333), 'numpy.eye', 'np.eye', (['(3)'], {'dtype': 'float'}), '(3, dtype=float)\n', (1317, 1333), True, 'import os, unittest, numpy as np\n'), ((232, 247), 'pyscf.nao.system_vars_c', 'system_vars_c', ([], {}), '()\n', (245, 247), False, 'from pyscf.nao import system_vars_c, prod_basis_c, tddft_iter_c\n'), ((2931, 2969), 'numpy.zeros', 'np.zeros', (['omegas.shape[0]'], {'dtype': 'float'}), '(omegas.shape[0], dtype=float)\n', (2939, 2969), True, 'import os, unittest, numpy as np\n'), ((2992, 3030), 'numpy.zeros', 'np.zeros', (['omegas.shape[0]'], {'dtype': 'float'}), '(omegas.shape[0], dtype=float)\n', (3000, 3030), True, 'import os, unittest, numpy as np\n'), ((3076, 3114), 'numpy.zeros', 'np.zeros', (['omegas.shape[0]'], {'dtype': 'float'}), '(omegas.shape[0], dtype=float)\n', (3084, 3114), True, 'import os, unittest, numpy as np\n'), ((3137, 3175), 'numpy.zeros', 'np.zeros', (['omegas.shape[0]'], {'dtype': 'float'}), '(omegas.shape[0], dtype=float)\n', (3145, 3175), True, 'import os, unittest, numpy as np\n'), ((305, 320), 'pyscf.nao.system_vars_c', 'system_vars_c', ([], {}), '()\n', (318, 320), False, 'from pyscf.nao import system_vars_c, prod_basis_c, tddft_iter_c\n'), ((3475, 3499), 'numpy.argmax', 'np.argmax', (["val['siesta']"], {}), "(val['siesta'])\n", (3484, 3499), True, 'import os, unittest, numpy as np\n'), ((3510, 3532), 'numpy.argmax', 'np.argmax', (["val['gpaw']"], {}), "(val['gpaw'])\n", (3519, 3532), True, 'import os, unittest, numpy as np\n')]
"""spin-weight harmonic transform module This module has benefited from pre-existing work by <NAME> """ from __future__ import print_function import os import numpy as np import pyfftw from lenspyx.shts import fsht from lenspyx import utils def vtm2map(spin, vtm, Nphi, pfftwthreads=None, bicubic_prefilt=False, phiflip=()): r"""Longitudinal Fourier transform to an ECP grid. Sends vtm array to (bicubic prefiltered map) with Nphi points equidistant in [0,2pi). With bicubic prefiltering this uses 2lmax + 1 1d Ntheta-sized FFTs and one 2d (Ntheta x Nphi) iFFT. The pyFFTW.FFTW is twice as fast than the pyFFTW.interface, but the FFTW wisdom calculation overhead can compensate for the gain if only one map is lensed. vtm comes from shts.vlm2vtm which returns a farray, with contiguous vtm[:,ip]. for spin 0 we have vtm^* = vt_-m, real filtered maps and we may use rffts. (not done) vtm should of size 2 * lmax + 1 Flipping phi amounts to phi -> 2pi - phi -> The phi fft is sent to its transpose. """ if pfftwthreads is None: pfftwthreads = int(os.environ.get('OMP_NUM_THREADS', 1)) lmax = (vtm.shape[1] - 1) // 2 Nt = vtm.shape[0] assert (Nt, 2 * lmax + 1) == vtm.shape, ((Nt, 2 * lmax + 1), vtm.shape) assert Nphi % 2 == 0, Nphi if bicubic_prefilt: #TODO: Could use real ffts for spin 0. For high-res interpolation this task can take about half of the total time. a = pyfftw.empty_aligned(Nt, dtype=complex) b = pyfftw.empty_aligned(Nt, dtype=complex) ret = pyfftw.empty_aligned((Nt, Nphi), dtype=complex) fftmap = pyfftw.empty_aligned((Nt, Nphi), dtype=complex) ifft2 = pyfftw.FFTW(fftmap, ret, axes=(0, 1), direction='FFTW_BACKWARD', threads=pfftwthreads) fft1d = pyfftw.FFTW(a, b, direction='FFTW_FORWARD', threads=1) fftmap[:] = 0. #NB: sometimes the operations above can result in nan's if Nphi > 2 * lmax: # There is unique correspondance m <-> kphi where kphi is the 2d flat map frequency for ip, m in enumerate(range(-lmax, lmax + 1)): fftmap[:, (Nphi + m if m < 0 else m)] = fft1d(vtm[:, ip]) else: # The correspondance m <-> k is not unique anymore, but given by # (m - k) = N j for j in 0,+- 1, +- 2 ,etc. -> m = k + Nj for ik in range(Nphi): # candidates for m index ms = lmax + ik + Nphi * np.arange(-lmax / Nphi - 1, lmax / Nphi + 1, dtype=int) ms = ms[np.where((ms >= 0) & (ms <= 2 * lmax))] fftmap[:, ik] = fft1d(np.sum(vtm[:, ms], axis=1)) w0 = Nphi * 6. / (2. * np.cos(2. * np.pi * np.fft.fftfreq(Nt)) + 4.) w1 = 6. / (2. * np.cos(2. * np.pi * np.fft.fftfreq(Nphi)) + 4.) fftmap[:] *= np.outer(w0, w1) retmap = ifft2().real if spin == 0 else ifft2() else : # Probably no real gain to expect here from pyfftw for the ffts. if Nphi > 2 * lmax + 1: a = np.zeros((Nt,Nphi),dtype = complex) a[:,:2 * lmax + 1] = vtm ret = np.fft.ifft(a) * (np.exp(np.arange(Nphi) * (-1j / Nphi * (2. * np.pi) * lmax)) * Nphi) else: ret = np.fft.ifft(vtm[:,lmax - Nphi//2:lmax + Nphi//2]) ret *= (np.exp(np.arange(Nphi) * (-1j / Nphi * (2. * np.pi) * Nphi /2)) * Nphi) retmap = ret.real if spin == 0 else ret retmap[phiflip, :] = retmap[phiflip, ::-1] return retmap def glm2vtm_sym(s, tht, glm): r"""This produces :math:`\sum_l _s\Lambda_{lm} v_{lm}` for pure gradient input for a range of colatitudes""" if s == 0: lmax = utils.nlm2lmax(len(glm)) ret = np.empty((2 * len(tht), 2 * lmax + 1), dtype=complex) ret[:, lmax:] = fsht.glm2vtm_s0sym(lmax, tht, -glm) ret[:, 0:lmax] = (ret[:, slice(2 * lmax + 1, lmax, -1)]).conjugate() return ret return vlm2vtm_sym(s, tht, utils.alm2vlm(glm)) def vlm2vtm_sym(s, tht, vlm): r"""This produces :math:`\sum_l _s\Lambda_{lm} v_{lm}` for a range of colatitudes""" assert s >= 0 tht = np.array(tht) lmax = int(np.sqrt(len(vlm)) - 1) assert (len(vlm) == (lmax + 1) ** 2) if s == 0: print("Consider using glm2vtm_sym for spin 0 for factor of 2 speed-up") return fsht.vlm2vtm_sym(lmax, s, tht, vlm) else: #: resolving poles, since fsht implementation does not handle them. north = np.where(tht <= 0.)[0] south = np.where(tht >= np.pi)[0] if len(north) == 0 and len(south) == 0: return fsht.vlm2vtm_sym(lmax, s, tht, vlm) else: nt = len(tht) ret = np.zeros( (2 * nt, 2 * lmax + 1), dtype=complex) if len(north) > 0: ret[north] = _vlm2vtm_northpole(s, vlm) ret[nt + north] = _vlm2vtm_southpole(s, vlm) if len(south) > 0: ret[south] = _vlm2vtm_southpole(s, vlm) ret[nt + south] = _vlm2vtm_northpole(s, vlm) if len(north) + len(south) < len(tht): others = np.where( (tht < np.pi) & (tht > 0.))[0] vtm = fsht.vlm2vtm_sym(lmax, s, tht[others], vlm) ret[others] = vtm[:len(others)] ret[nt + others] = vtm[len(others):] return ret def _vlm2vtm_northpole(s, vlm): r"""Spin-weight harmonics on the north pole :math: `_s\Lambda_{l,-s} (-1)^s \sqrt{ (2l + 1) / 4\pi }` and zero for other m. """ assert s >= 0, s lmax = int(np.sqrt(len(vlm)) - 1) assert (len(vlm) == (lmax + 1) ** 2) ret = np.zeros(2 * lmax + 1, dtype=complex) l = np.arange(lmax + 1) ret[lmax - s] = np.sum(vlm[l * l + l - s] * np.sqrt((2 * l + 1.))) / np.sqrt(4. * np.pi) * (-1) ** s return ret def _vlm2vtm_southpole(s, vlm): r"""Spin-weight harmonics on the north pole. :math:`_s\Lambda_{l,s} (-1)^l \sqrt{ (2l + 1) / 4\pi }` and zero for other m. """ assert s >= 0, s lmax = int(np.sqrt(len(vlm)) - 1) assert (len(vlm) == (lmax + 1) ** 2) ret = np.zeros(2 * lmax + 1, dtype=complex) l = np.arange(lmax + 1) ret[lmax + s] = np.sum(vlm[l * l + l + s] * (-1) ** l * np.sqrt((2 * l + 1.))) / np.sqrt(4. * np.pi) return ret
[ "numpy.sqrt", "numpy.where", "lenspyx.shts.fsht.glm2vtm_s0sym", "numpy.fft.fftfreq", "os.environ.get", "numpy.array", "numpy.zeros", "pyfftw.empty_aligned", "numpy.outer", "numpy.fft.ifft", "lenspyx.shts.fsht.vlm2vtm_sym", "numpy.sum", "pyfftw.FFTW", "lenspyx.utils.alm2vlm", "numpy.arang...
[((4154, 4167), 'numpy.array', 'np.array', (['tht'], {}), '(tht)\n', (4162, 4167), True, 'import numpy as np\n'), ((5674, 5711), 'numpy.zeros', 'np.zeros', (['(2 * lmax + 1)'], {'dtype': 'complex'}), '(2 * lmax + 1, dtype=complex)\n', (5682, 5711), True, 'import numpy as np\n'), ((5720, 5739), 'numpy.arange', 'np.arange', (['(lmax + 1)'], {}), '(lmax + 1)\n', (5729, 5739), True, 'import numpy as np\n'), ((6161, 6198), 'numpy.zeros', 'np.zeros', (['(2 * lmax + 1)'], {'dtype': 'complex'}), '(2 * lmax + 1, dtype=complex)\n', (6169, 6198), True, 'import numpy as np\n'), ((6207, 6226), 'numpy.arange', 'np.arange', (['(lmax + 1)'], {}), '(lmax + 1)\n', (6216, 6226), True, 'import numpy as np\n'), ((1495, 1534), 'pyfftw.empty_aligned', 'pyfftw.empty_aligned', (['Nt'], {'dtype': 'complex'}), '(Nt, dtype=complex)\n', (1515, 1534), False, 'import pyfftw\n'), ((1547, 1586), 'pyfftw.empty_aligned', 'pyfftw.empty_aligned', (['Nt'], {'dtype': 'complex'}), '(Nt, dtype=complex)\n', (1567, 1586), False, 'import pyfftw\n'), ((1601, 1648), 'pyfftw.empty_aligned', 'pyfftw.empty_aligned', (['(Nt, Nphi)'], {'dtype': 'complex'}), '((Nt, Nphi), dtype=complex)\n', (1621, 1648), False, 'import pyfftw\n'), ((1666, 1713), 'pyfftw.empty_aligned', 'pyfftw.empty_aligned', (['(Nt, Nphi)'], {'dtype': 'complex'}), '((Nt, Nphi), dtype=complex)\n', (1686, 1713), False, 'import pyfftw\n'), ((1730, 1821), 'pyfftw.FFTW', 'pyfftw.FFTW', (['fftmap', 'ret'], {'axes': '(0, 1)', 'direction': '"""FFTW_BACKWARD"""', 'threads': 'pfftwthreads'}), "(fftmap, ret, axes=(0, 1), direction='FFTW_BACKWARD', threads=\n pfftwthreads)\n", (1741, 1821), False, 'import pyfftw\n'), ((1833, 1887), 'pyfftw.FFTW', 'pyfftw.FFTW', (['a', 'b'], {'direction': '"""FFTW_FORWARD"""', 'threads': '(1)'}), "(a, b, direction='FFTW_FORWARD', threads=1)\n", (1844, 1887), False, 'import pyfftw\n'), ((2858, 2874), 'numpy.outer', 'np.outer', (['w0', 'w1'], {}), '(w0, w1)\n', (2866, 2874), True, 'import numpy as np\n'), ((3822, 3857), 'lenspyx.shts.fsht.glm2vtm_s0sym', 'fsht.glm2vtm_s0sym', (['lmax', 'tht', '(-glm)'], {}), '(lmax, tht, -glm)\n', (3840, 3857), False, 'from lenspyx.shts import fsht\n'), ((3985, 4003), 'lenspyx.utils.alm2vlm', 'utils.alm2vlm', (['glm'], {}), '(glm)\n', (3998, 4003), False, 'from lenspyx import utils\n'), ((4357, 4392), 'lenspyx.shts.fsht.vlm2vtm_sym', 'fsht.vlm2vtm_sym', (['lmax', 's', 'tht', 'vlm'], {}), '(lmax, s, tht, vlm)\n', (4373, 4392), False, 'from lenspyx.shts import fsht\n'), ((6313, 6333), 'numpy.sqrt', 'np.sqrt', (['(4.0 * np.pi)'], {}), '(4.0 * np.pi)\n', (6320, 6333), True, 'import numpy as np\n'), ((1134, 1170), 'os.environ.get', 'os.environ.get', (['"""OMP_NUM_THREADS"""', '(1)'], {}), "('OMP_NUM_THREADS', 1)\n", (1148, 1170), False, 'import os\n'), ((3064, 3099), 'numpy.zeros', 'np.zeros', (['(Nt, Nphi)'], {'dtype': 'complex'}), '((Nt, Nphi), dtype=complex)\n', (3072, 3099), True, 'import numpy as np\n'), ((3274, 3328), 'numpy.fft.ifft', 'np.fft.ifft', (['vtm[:, lmax - Nphi // 2:lmax + Nphi // 2]'], {}), '(vtm[:, lmax - Nphi // 2:lmax + Nphi // 2])\n', (3285, 3328), True, 'import numpy as np\n'), ((4495, 4515), 'numpy.where', 'np.where', (['(tht <= 0.0)'], {}), '(tht <= 0.0)\n', (4503, 4515), True, 'import numpy as np\n'), ((4534, 4556), 'numpy.where', 'np.where', (['(tht >= np.pi)'], {}), '(tht >= np.pi)\n', (4542, 4556), True, 'import numpy as np\n'), ((4627, 4662), 'lenspyx.shts.fsht.vlm2vtm_sym', 'fsht.vlm2vtm_sym', (['lmax', 's', 'tht', 'vlm'], {}), '(lmax, s, tht, vlm)\n', (4643, 4662), False, 'from lenspyx.shts import fsht\n'), ((4721, 4768), 'numpy.zeros', 'np.zeros', (['(2 * nt, 2 * lmax + 1)'], {'dtype': 'complex'}), '((2 * nt, 2 * lmax + 1), dtype=complex)\n', (4729, 4768), True, 'import numpy as np\n'), ((5814, 5834), 'numpy.sqrt', 'np.sqrt', (['(4.0 * np.pi)'], {}), '(4.0 * np.pi)\n', (5821, 5834), True, 'import numpy as np\n'), ((3155, 3169), 'numpy.fft.ifft', 'np.fft.ifft', (['a'], {}), '(a)\n', (3166, 3169), True, 'import numpy as np\n'), ((5206, 5249), 'lenspyx.shts.fsht.vlm2vtm_sym', 'fsht.vlm2vtm_sym', (['lmax', 's', 'tht[others]', 'vlm'], {}), '(lmax, s, tht[others], vlm)\n', (5222, 5249), False, 'from lenspyx.shts import fsht\n'), ((6288, 6308), 'numpy.sqrt', 'np.sqrt', (['(2 * l + 1.0)'], {}), '(2 * l + 1.0)\n', (6295, 6308), True, 'import numpy as np\n'), ((2582, 2620), 'numpy.where', 'np.where', (['((ms >= 0) & (ms <= 2 * lmax))'], {}), '((ms >= 0) & (ms <= 2 * lmax))\n', (2590, 2620), True, 'import numpy as np\n'), ((2660, 2686), 'numpy.sum', 'np.sum', (['vtm[:, ms]'], {'axis': '(1)'}), '(vtm[:, ms], axis=1)\n', (2666, 2686), True, 'import numpy as np\n'), ((5142, 5179), 'numpy.where', 'np.where', (['((tht < np.pi) & (tht > 0.0))'], {}), '((tht < np.pi) & (tht > 0.0))\n', (5150, 5179), True, 'import numpy as np\n'), ((5789, 5809), 'numpy.sqrt', 'np.sqrt', (['(2 * l + 1.0)'], {}), '(2 * l + 1.0)\n', (5796, 5809), True, 'import numpy as np\n'), ((2502, 2557), 'numpy.arange', 'np.arange', (['(-lmax / Nphi - 1)', '(lmax / Nphi + 1)'], {'dtype': 'int'}), '(-lmax / Nphi - 1, lmax / Nphi + 1, dtype=int)\n', (2511, 2557), True, 'import numpy as np\n'), ((3351, 3366), 'numpy.arange', 'np.arange', (['Nphi'], {}), '(Nphi)\n', (3360, 3366), True, 'import numpy as np\n'), ((2739, 2757), 'numpy.fft.fftfreq', 'np.fft.fftfreq', (['Nt'], {}), '(Nt)\n', (2753, 2757), True, 'import numpy as np\n'), ((2809, 2829), 'numpy.fft.fftfreq', 'np.fft.fftfreq', (['Nphi'], {}), '(Nphi)\n', (2823, 2829), True, 'import numpy as np\n'), ((3180, 3195), 'numpy.arange', 'np.arange', (['Nphi'], {}), '(Nphi)\n', (3189, 3195), True, 'import numpy as np\n')]
# Third-party import astropy.units as u import numpy as np from scipy.signal import argrelmin # Project from . import PhaseSpacePosition, Orbit __all__ = ['fast_lyapunov_max', 'lyapunov_max', 'surface_of_section'] def fast_lyapunov_max(w0, hamiltonian, dt, n_steps, d0=1e-5, n_steps_per_pullback=10, noffset_orbits=2, t1=0., atol=1E-10, rtol=1E-10, nmax=0, return_orbit=True): """ Compute the maximum Lyapunov exponent using a C-implemented estimator that uses the DOPRI853 integrator. Parameters ---------- w0 : `~gala.dynamics.PhaseSpacePosition`, array_like Initial conditions. hamiltonian : `~gala.potential.Hamiltonian` dt : numeric Timestep. n_steps : int Number of steps to run for. d0 : numeric (optional) The initial separation. n_steps_per_pullback : int (optional) Number of steps to run before re-normalizing the offset vectors. noffset_orbits : int (optional) Number of offset orbits to run. t1 : numeric (optional) Time of initial conditions. Assumed to be t=0. return_orbit : bool (optional) Store the full orbit for the parent and all offset orbits. Returns ------- LEs : :class:`~astropy.units.Quantity` Lyapunov exponents calculated from each offset / deviation orbit. orbit : `~gala.dynamics.Orbit` (optional) """ from gala.potential import PotentialBase from .lyapunov import dop853_lyapunov_max, dop853_lyapunov_max_dont_save # TODO: remove in v1.0 if isinstance(hamiltonian, PotentialBase): from ..potential import Hamiltonian hamiltonian = Hamiltonian(hamiltonian) if not hamiltonian.c_enabled: raise TypeError("Input Hamiltonian must contain a C-implemented " "potential and frame.") if not isinstance(w0, PhaseSpacePosition): w0 = np.asarray(w0) ndim = w0.shape[0]//2 w0 = PhaseSpacePosition(pos=w0[:ndim], vel=w0[ndim:]) _w0 = np.squeeze(w0.w(hamiltonian.units)) if _w0.ndim > 1: raise ValueError("Can only compute fast Lyapunov exponent for a single orbit.") if return_orbit: t, w, l = dop853_lyapunov_max(hamiltonian, _w0, dt, n_steps+1, t1, d0, n_steps_per_pullback, noffset_orbits, atol, rtol, nmax) w = np.rollaxis(w, -1) try: tunit = hamiltonian.units['time'] except (TypeError, AttributeError): tunit = u.dimensionless_unscaled orbit = Orbit.from_w(w=w, units=hamiltonian.units, t=t*tunit, hamiltonian=hamiltonian) return l/tunit, orbit else: l = dop853_lyapunov_max_dont_save(hamiltonian, _w0, dt, n_steps+1, t1, d0, n_steps_per_pullback, noffset_orbits, atol, rtol, nmax) try: tunit = hamiltonian.units['time'] except (TypeError, AttributeError): tunit = u.dimensionless_unscaled return l/tunit def lyapunov_max(w0, integrator, dt, n_steps, d0=1e-5, n_steps_per_pullback=10, noffset_orbits=8, t1=0., units=None): """ Compute the maximum Lyapunov exponent of an orbit by integrating many nearby orbits (``noffset``) separated with isotropically distributed directions but the same initial deviation length, ``d0``. This algorithm re-normalizes the offset orbits every ``n_steps_per_pullback`` steps. Parameters ---------- w0 : `~gala.dynamics.PhaseSpacePosition`, array_like Initial conditions. integrator : `~gala.integrate.Integrator` An instantiated `~gala.integrate.Integrator` object. Must have a run() method. dt : numeric Timestep. n_steps : int Number of steps to run for. d0 : numeric (optional) The initial separation. n_steps_per_pullback : int (optional) Number of steps to run before re-normalizing the offset vectors. noffset_orbits : int (optional) Number of offset orbits to run. t1 : numeric (optional) Time of initial conditions. Assumed to be t=0. units : `~gala.units.UnitSystem` (optional) If passing in an array (not a `~gala.dynamics.PhaseSpacePosition`), you must specify a unit system. Returns ------- LEs : :class:`~astropy.units.Quantity` Lyapunov exponents calculated from each offset / deviation orbit. orbit : `~gala.dynamics.Orbit` """ if units is not None: pos_unit = units['length'] vel_unit = units['length']/units['time'] else: pos_unit = u.dimensionless_unscaled vel_unit = u.dimensionless_unscaled if not isinstance(w0, PhaseSpacePosition): w0 = np.asarray(w0) ndim = w0.shape[0]//2 w0 = PhaseSpacePosition(pos=w0[:ndim]*pos_unit, vel=w0[ndim:]*vel_unit) _w0 = w0.w(units) ndim = 2*w0.ndim # number of iterations niter = n_steps // n_steps_per_pullback # define offset vectors to start the offset orbits on d0_vec = np.random.uniform(size=(ndim, noffset_orbits)) d0_vec /= np.linalg.norm(d0_vec, axis=0)[np.newaxis] d0_vec *= d0 w_offset = _w0 + d0_vec all_w0 = np.hstack((_w0, w_offset)) # array to store the full, main orbit full_w = np.zeros((ndim, n_steps+1, noffset_orbits+1)) full_w[:, 0] = all_w0 full_ts = np.zeros((n_steps+1,)) full_ts[0] = t1 # arrays to store the Lyapunov exponents and times LEs = np.zeros((niter, noffset_orbits)) ts = np.zeros_like(LEs) time = t1 total_steps_taken = 0 for i in range(1, niter+1): ii = i * n_steps_per_pullback orbit = integrator.run(all_w0, dt=dt, n_steps=n_steps_per_pullback, t1=time) tt = orbit.t.value ww = orbit.w(units) time += dt*n_steps_per_pullback main_w = ww[:, -1, 0:1] d1 = ww[:, -1, 1:] - main_w d1_mag = np.linalg.norm(d1, axis=0) LEs[i-1] = np.log(d1_mag/d0) ts[i-1] = time w_offset = ww[:, -1, 0:1] + d0 * d1 / d1_mag[np.newaxis] all_w0 = np.hstack((ww[:, -1, 0:1], w_offset)) full_w[:, (i-1)*n_steps_per_pullback+1:ii+1] = ww[:, 1:] full_ts[(i-1)*n_steps_per_pullback+1:ii+1] = tt[1:] total_steps_taken += n_steps_per_pullback LEs = np.array([LEs[:ii].sum(axis=0)/ts[ii-1] for ii in range(1, niter)]) try: t_unit = units['time'] except (TypeError, AttributeError): t_unit = u.dimensionless_unscaled orbit = Orbit.from_w(w=full_w[:, :total_steps_taken], units=units, t=full_ts[:total_steps_taken]*t_unit) return LEs/t_unit, orbit def surface_of_section(orbit, constant_idx, constant_val=0.): """ Generate and return a surface of section from the given orbit. Parameters ---------- orbit : `~gala.dynamics.Orbit` The input orbit to generate a surface of section for. constant_idx : int Integer that represents the coordinate to record crossings in. For example, for a 2D Hamiltonian where you want to make a SoS in :math:`y-p_y`, you would specify ``constant_idx=0`` (crossing the :math:`x` axis), and this will only record crossings for which :math:`p_x>0`. Returns ------- sos : numpy ndarray TODO: - Implement interpolation to get the other phase-space coordinates truly at the plane, instead of just at the orbital position closest to the plane. """ if orbit.norbits > 1: raise NotImplementedError("Not yet implemented, sorry!") w = ([getattr(orbit, x) for x in orbit.pos_components] + [getattr(orbit, v) for v in orbit.vel_components]) ndim = orbit.ndim p_ix = constant_idx + ndim # record position on specified plane when orbit crosses cross_idx = argrelmin((w[constant_idx] - constant_val) ** 2)[0] cross_idx = cross_idx[w[p_ix][cross_idx] > 0.] sos_pos = [w[i][cross_idx] for i in range(ndim)] sos_pos = orbit.pos.__class__(*sos_pos) sos_vel = [w[i][cross_idx] for i in range(ndim, 2*ndim)] sos_vel = orbit.vel.__class__(*sos_vel) return Orbit(sos_pos, sos_vel)
[ "numpy.hstack", "numpy.log", "numpy.asarray", "numpy.rollaxis", "numpy.linalg.norm", "numpy.zeros", "scipy.signal.argrelmin", "numpy.random.uniform", "numpy.zeros_like" ]
[((5368, 5414), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(ndim, noffset_orbits)'}), '(size=(ndim, noffset_orbits))\n', (5385, 5414), True, 'import numpy as np\n'), ((5531, 5557), 'numpy.hstack', 'np.hstack', (['(_w0, w_offset)'], {}), '((_w0, w_offset))\n', (5540, 5557), True, 'import numpy as np\n'), ((5614, 5663), 'numpy.zeros', 'np.zeros', (['(ndim, n_steps + 1, noffset_orbits + 1)'], {}), '((ndim, n_steps + 1, noffset_orbits + 1))\n', (5622, 5663), True, 'import numpy as np\n'), ((5700, 5724), 'numpy.zeros', 'np.zeros', (['(n_steps + 1,)'], {}), '((n_steps + 1,))\n', (5708, 5724), True, 'import numpy as np\n'), ((5809, 5842), 'numpy.zeros', 'np.zeros', (['(niter, noffset_orbits)'], {}), '((niter, noffset_orbits))\n', (5817, 5842), True, 'import numpy as np\n'), ((5852, 5870), 'numpy.zeros_like', 'np.zeros_like', (['LEs'], {}), '(LEs)\n', (5865, 5870), True, 'import numpy as np\n'), ((1938, 1952), 'numpy.asarray', 'np.asarray', (['w0'], {}), '(w0)\n', (1948, 1952), True, 'import numpy as np\n'), ((2516, 2534), 'numpy.rollaxis', 'np.rollaxis', (['w', '(-1)'], {}), '(w, -1)\n', (2527, 2534), True, 'import numpy as np\n'), ((5023, 5037), 'numpy.asarray', 'np.asarray', (['w0'], {}), '(w0)\n', (5033, 5037), True, 'import numpy as np\n'), ((5429, 5459), 'numpy.linalg.norm', 'np.linalg.norm', (['d0_vec'], {'axis': '(0)'}), '(d0_vec, axis=0)\n', (5443, 5459), True, 'import numpy as np\n'), ((6248, 6274), 'numpy.linalg.norm', 'np.linalg.norm', (['d1'], {'axis': '(0)'}), '(d1, axis=0)\n', (6262, 6274), True, 'import numpy as np\n'), ((6295, 6314), 'numpy.log', 'np.log', (['(d1_mag / d0)'], {}), '(d1_mag / d0)\n', (6301, 6314), True, 'import numpy as np\n'), ((6419, 6456), 'numpy.hstack', 'np.hstack', (['(ww[:, -1, 0:1], w_offset)'], {}), '((ww[:, -1, 0:1], w_offset))\n', (6428, 6456), True, 'import numpy as np\n'), ((8183, 8231), 'scipy.signal.argrelmin', 'argrelmin', (['((w[constant_idx] - constant_val) ** 2)'], {}), '((w[constant_idx] - constant_val) ** 2)\n', (8192, 8231), False, 'from scipy.signal import argrelmin\n')]
from __future__ import division, print_function import os, types import numpy as np import vtk from vtk.util.numpy_support import numpy_to_vtk from vtk.util.numpy_support import vtk_to_numpy import vtkplotter.colors as colors ############################################################################## vtkMV = vtk.vtkVersion().GetVTKMajorVersion() > 5 def add_actor(f): #decorator def wrapper(*args, **kwargs): actor = f(*args, **kwargs) args[0].actors.append(actor) return actor return wrapper def setInput(vtkobj, p, port=0): if isinstance(p, vtk.vtkAlgorithmOutput): vtkobj.SetInputConnection(port, p) # passing port return if vtkMV: vtkobj.SetInputData(p) else: vtkobj.SetInput(p) def isSequence(arg): if hasattr(arg, "strip"): return False if hasattr(arg, "__getslice__"): return True if hasattr(arg, "__iter__"): return True return False def arange(start,stop, step=1): return np.arange(start, stop, step) def vector(x, y=None, z=0.): if y is None: #assume x is already [x,y,z] return np.array(x, dtype=np.float64) return np.array([x,y,z], dtype=np.float64) def mag(z): if isinstance(z[0], np.ndarray): return np.array(list(map(np.linalg.norm, z))) else: return np.linalg.norm(z) def mag2(z): return np.dot(z,z) def norm(v): if isinstance(v[0], np.ndarray): return np.divide(v, mag(v)[:,None]) else: return v/mag(v) def to_precision(x, p): """ Returns a string representation of x formatted with a precision of p Based on the webkit javascript implementation taken from here: https://code.google.com/p/webkit-mirror/source/browse/JavaScriptCore/kjs/number_object.cpp Implemented in https://github.com/randlet/to-precision """ import math x = float(x) if x == 0.: return "0." + "0"*(p-1) out = [] if x < 0: out.append("-") x = -x e = int(math.log10(x)) tens = math.pow(10, e - p + 1) n = math.floor(x/tens) if n < math.pow(10, p - 1): e = e -1 tens = math.pow(10, e - p+1) n = math.floor(x / tens) if abs((n + 1.) * tens - x) <= abs(n * tens -x): n = n + 1 if n >= math.pow(10,p): n = n / 10. e = e + 1 m = "%.*g" % (p, n) if e < -2 or e >= p: out.append(m[0]) if p > 1: out.append(".") out.extend(m[1:p]) out.append('e') if e > 0: out.append("+") out.append(str(e)) elif e == (p -1): out.append(m) elif e >= 0: out.append(m[:e+1]) if e+1 < len(m): out.append(".") out.extend(m[e+1:]) else: out.append("0.") out.extend(["0"]*-(e+1)) out.append(m) return "".join(out) ######################################################################### def makeActor(poly, c='gold', alpha=0.5, wire=False, bc=None, edges=False, legend=None, texture=None): ''' Return a vtkActor from an input vtkPolyData, optional args: c, color in RGB format, hex, symbol or name alpha, transparency (0=invisible) wire, show surface as wireframe bc, backface color of internal surface edges, show edges as line on top of surface legend optional string texture jpg file name of surface texture, eg. 'metalfloor1' ''' clp = vtk.vtkCleanPolyData() setInput(clp, poly) clp.Update() pdnorm = vtk.vtkPolyDataNormals() setInput(pdnorm, clp.GetOutput()) pdnorm.ComputePointNormalsOn() pdnorm.ComputeCellNormalsOn() pdnorm.FlipNormalsOff() pdnorm.ConsistencyOn() pdnorm.Update() mapper = vtk.vtkPolyDataMapper() # check if color string contains a float, in this case ignore alpha if alpha is None: alpha=0.5 al = colors.getAlpha(c) if al: alpha = al setInput(mapper, pdnorm.GetOutput()) actor = vtk.vtkActor() actor.SetMapper(mapper) prp = actor.GetProperty() ######################################################################### ### On some vtk versions/platforms points are redered as ugly squares ### in such a case uncomment this line: if vtk.vtkVersion().GetVTKMajorVersion()>6: prp.RenderPointsAsSpheresOn() ######################################################################### if c is None: mapper.ScalarVisibilityOn() else: mapper.ScalarVisibilityOff() c = colors.getColor(c) prp.SetColor(c) prp.SetOpacity(alpha) prp.SetSpecular(0.1) prp.SetSpecularColor(c) prp.SetSpecularPower(1) prp.SetAmbient(0.1) prp.SetAmbientColor(c) prp.SetDiffuse(1) prp.SetDiffuseColor(c) if edges: prp.EdgeVisibilityOn() if wire: prp.SetRepresentationToWireframe() if texture: mapper.ScalarVisibilityOff() assignTexture(actor, texture) if bc: # defines a specific color for the backface backProp = vtk.vtkProperty() backProp.SetDiffuseColor(colors.getColor(bc)) backProp.SetOpacity(alpha) actor.SetBackfaceProperty(backProp) assignPhysicsMethods(actor) assignConvenienceMethods(actor, legend) return actor def makeAssembly(actors, legend=None): '''Group many actors as a single new actor''' assembly = vtk.vtkAssembly() for a in actors: assembly.AddPart(a) setattr(assembly, 'legend', legend) assignPhysicsMethods(assembly) assignConvenienceMethods(assembly, legend) if hasattr(actors[0], 'base'): setattr(assembly, 'base', actors[0].base) setattr(assembly, 'top', actors[0].top) return assembly def assignTexture(actor, name, scale=1, falsecolors=False, mapTo=1): '''Assign a texture to actor from file or name in /textures directory''' if mapTo == 1: tmapper = vtk.vtkTextureMapToCylinder() elif mapTo == 2: tmapper = vtk.vtkTextureMapToSphere() elif mapTo == 3: tmapper = vtk.vtkTextureMapToPlane() setInput(tmapper, polydata(actor)) if mapTo == 1: tmapper.PreventSeamOn() xform = vtk.vtkTransformTextureCoords() xform.SetInputConnection(tmapper.GetOutputPort()) xform.SetScale(scale,scale,scale) if mapTo == 1: xform.FlipSOn() xform.Update() mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(xform.GetOutputPort()) mapper.ScalarVisibilityOff() cdir = os.path.dirname(__file__) if cdir == '': cdir = '.' fn = cdir + '/textures/' + name + ".jpg" if os.path.exists(name): fn = name elif not os.path.exists(fn): colors.printc(('Texture', name, 'not found in', cdir+'/textures'), 'r') colors.printc('Available textures:', c='m', end=' ') for ff in os.listdir(cdir + '/textures'): colors.printc(ff.split('.')[0], end=' ', c='m') print() return jpgReader = vtk.vtkJPEGReader() jpgReader.SetFileName(fn) atext = vtk.vtkTexture() atext.RepeatOn() atext.EdgeClampOff() atext.InterpolateOn() if falsecolors: atext.MapColorScalarsThroughLookupTableOn() atext.SetInputConnection(jpgReader.GetOutputPort()) actor.GetProperty().SetColor(1,1,1) actor.SetMapper(mapper) actor.SetTexture(atext) # ########################################################################### def assignConvenienceMethods(actor, legend): if not hasattr(actor, 'legend'): setattr(actor, 'legend', legend) def _fclone(self, c=None, alpha=None, wire=False, bc=None, edges=False, legend=None, texture=None, rebuild=True): return clone(self, c, alpha, wire, bc, edges, legend, texture, rebuild) actor.clone = types.MethodType( _fclone, actor ) def _fpoint(self, i, p=None): if p is None : poly = polydata(self, True, 0) p = [0,0,0] poly.GetPoints().GetPoint(i, p) return np.array(p) else: poly = polydata(self, False, 0) poly.GetPoints().SetPoint(i, p) TI = vtk.vtkTransform() actor.SetUserMatrix(TI.GetMatrix()) # reset return self actor.point = types.MethodType( _fpoint, actor ) def _fN(self, index=0): return polydata(self, False, index).GetNumberOfPoints() actor.N = types.MethodType( _fN, actor ) def _fnormalize(self): return normalize(self) actor.normalize = types.MethodType( _fnormalize, actor ) def _fshrink(self, fraction=0.85): return shrink(self, fraction) actor.shrink = types.MethodType( _fshrink, actor ) def _fcutPlane(self, origin=(0,0,0), normal=(1,0,0), showcut=False): return cutPlane(self, origin, normal, showcut) actor.cutPlane = types.MethodType( _fcutPlane, actor ) def _fcutterw(self): return cutterWidget(self) actor.cutterWidget = types.MethodType( _fcutterw, actor ) def _fpolydata(self, rebuild=True, index=0): return polydata(self, rebuild, index) actor.polydata = types.MethodType( _fpolydata, actor ) def _fcoordinates(self, rebuild=True): return coordinates(self, rebuild) actor.coordinates = types.MethodType( _fcoordinates, actor ) def _fxbounds(self): b = polydata(actor, True).GetBounds() return (b[0],b[1]) actor.xbounds = types.MethodType( _fxbounds, actor ) def _fybounds(self): b = polydata(actor, True).GetBounds() return (b[2],b[3]) actor.ybounds = types.MethodType( _fybounds, actor ) def _fzbounds(self): b = polydata(actor, True).GetBounds() return (b[4],b[5]) actor.zbounds = types.MethodType( _fzbounds, actor ) def _fnormalAt(self, index): normals = polydata(self, True).GetPointData().GetNormals() return np.array(normals.GetTuple(index)) actor.normalAt = types.MethodType( _fnormalAt, actor ) def _fnormals(self): vtknormals = polydata(self, True).GetPointData().GetNormals() as_numpy = vtk_to_numpy(vtknormals) return as_numpy actor.normals = types.MethodType( _fnormals, actor ) def _fstretch(self, startpt, endpt): return stretch(self, startpt, endpt) actor.stretch = types.MethodType( _fstretch, actor) def _fsubdivide(self, N=1, method=0, legend=None): return subdivide(self, N, method, legend) actor.subdivide = types.MethodType( _fsubdivide, actor) def _fdecimate(self, fraction=0.5, N=None, verbose=True, boundaries=True): return decimate(self, fraction, N, verbose, boundaries) actor.decimate = types.MethodType( _fdecimate, actor) def _fcolor(self, c=None): if c is not None: self.GetProperty().SetColor(colors.getColor(c)) return self else: return np.array(self.GetProperty().GetColor()) actor.color = types.MethodType( _fcolor, actor) def _falpha(self, a=None): if a: self.GetProperty().SetOpacity(a) return self else: return self.GetProperty().GetOpacity() actor.alpha = types.MethodType( _falpha, actor) def _fwire(self, a=True): if a: self.GetProperty().SetRepresentationToWireframe() else: self.GetProperty().SetRepresentationToSurface() return self actor.wire = types.MethodType( _fwire, actor) def _fclosestPoint(self, pt, N=1, radius=None): return closestPoint(self, pt, N, radius) actor.closestPoint = types.MethodType( _fclosestPoint, actor) def _fintersectWithLine(self, p0, p1): return intersectWithLine(self, p0,p1) actor.intersectWithLine = types.MethodType(_fintersectWithLine , actor) def _fisInside(self, point, tol=0.0001): return isInside(self, point, tol) actor.isInside = types.MethodType(_fisInside , actor) def _finsidePoints(self, points, invert=False, tol=1e-05): return insidePoints(self, points, invert, tol) actor.insidePoints = types.MethodType(_finsidePoints , actor) def _fflipNormals(self): return flipNormals(self) actor.flipNormals = types.MethodType(_fflipNormals , actor) def _fcellCenters(self): return cellCenters(self) actor.cellCenters = types.MethodType(_fcellCenters, actor) def _fpointScalars(self, scalars, name): return pointScalars(self, scalars, name) actor.pointScalars = types.MethodType(_fpointScalars , actor) def _fpointColors(self, scalars, cmap='jet'): return pointColors(self, scalars, cmap) actor.pointColors = types.MethodType(_fpointColors , actor) def _fcellScalars(self, scalars, name): return cellScalars(self, scalars, name) actor.cellScalars = types.MethodType(_fcellScalars , actor) def _fcellColors(self, scalars, cmap='jet'): return cellColors(self, scalars, cmap) actor.cellColors = types.MethodType(_fcellColors , actor) def _fscalars(self, name): return scalars(self, name) actor.scalars = types.MethodType(_fscalars , actor) # ########################################################################### def assignPhysicsMethods(actor): def _fpos(self, p=None): if p is None: return np.array(self.GetPosition()) self.SetPosition(p) return self # return itself to concatenate methods actor.pos = types.MethodType( _fpos, actor ) def _faddpos(self, dp): self.SetPosition(np.array(self.GetPosition()) +dp ) return self actor.addpos = types.MethodType( _faddpos, actor ) def _fpx(self, px=None): # X _pos = self.GetPosition() if px is None: return _pos[0] newp = [px, _pos[1], _pos[2]] self.SetPosition(newp) return self actor.x = types.MethodType( _fpx, actor ) def _fpy(self, py=None): # Y _pos = self.GetPosition() if py is None: return _pos[1] newp = [_pos[0], py, _pos[2]] self.SetPosition(newp) return self actor.y = types.MethodType( _fpy, actor ) def _fpz(self, pz=None): # Z _pos = self.GetPosition() if pz is None: return _pos[2] newp = [_pos[0], _pos[1], pz] self.SetPosition(newp) return self actor.z = types.MethodType( _fpz, actor ) def _fscale(self, p=None): if p is None: return np.array(self.GetScale()) self.SetScale(p) return self # return itself to concatenate methods actor.scale = types.MethodType( _fscale, actor ) def _frotate(self, angle, axis, axis_point=[0,0,0], rad=False): if rad: angle *= 57.3 return rotate(self, angle, axis, axis_point, rad) actor.rotate = types.MethodType( _frotate, actor ) def _frotateX(self, angle, axis_point=[0,0,0], rad=False): if rad: angle *= 57.3 return rotate(self, angle, [1,0,0], axis_point, rad) actor.rotateX = types.MethodType( _frotateX, actor ) def _frotateY(self, angle, axis_point=[0,0,0], rad=False): if rad: angle *= 57.3 return rotate(self, angle, [0,1,0], axis_point, rad) actor.rotateY = types.MethodType( _frotateY, actor ) def _frotateZ(self, angle, axis_point=[0,0,0], rad=False): if rad: angle *= 57.3 return rotate(self, angle, [0,0,1], axis_point, rad) actor.rotateZ = types.MethodType( _frotateZ, actor ) def _forientation(self, newaxis=None, rotation=0): return orientation(self, newaxis, rotation) actor.orientation = types.MethodType( _forientation, actor ) def _fcenterOfMass(self): return centerOfMass(self) actor.centerOfMass = types.MethodType(_fcenterOfMass, actor) def _fvolume(self): return volume(self) actor.volume = types.MethodType(_fvolume, actor) def _farea(self): return area(self) actor.area = types.MethodType(_farea, actor) def _fdiagonalSize(self): return diagonalSize(self) actor.diagonalSize = types.MethodType(_fdiagonalSize, actor) ######################################################### def clone(actor, c=None, alpha=None, wire=False, bc=None, edges=False, legend=None, texture=None, rebuild=True): ''' Clone a vtkActor. If rebuild is True build its polydata in its current position in space ''' poly = polydata(actor, rebuild) if not poly.GetNumberOfPoints(): colors.printc('Limitation: cannot clone textured obj. Returning input.',1) return actor polyCopy = vtk.vtkPolyData() polyCopy.DeepCopy(poly) if legend is True and hasattr(actor, 'legend'): legend = actor.legend if alpha is None: alpha = actor.GetProperty().GetOpacity() if c is None: c = actor.GetProperty().GetColor() if texture is None and hasattr(actor, 'texture'): texture = actor.texture cact = makeActor(polyCopy, c, alpha, wire, bc, edges, legend, texture) cact.GetProperty().SetPointSize(actor.GetProperty().GetPointSize()) return cact def flipNormals(actor): # N.B. input argument gets modified rs = vtk.vtkReverseSense() setInput(rs, polydata(actor, True)) rs.ReverseNormalsOn() rs.Update() poly = rs.GetOutput() mapper = actor.GetMapper() setInput(mapper, poly) mapper.Update() actor.Modified() if hasattr(actor, 'poly'): actor.poly=poly return actor # return same obj for concatenation def normalize(actor): # N.B. input argument gets modified ''' Shift actor's center of mass at origin and scale its average size to unit. ''' cm = centerOfMass(actor) coords = coordinates(actor) if not len(coords) : return pts = coords - cm xyz2 = np.sum(pts * pts, axis=0) scale = 1/np.sqrt(np.sum(xyz2)/len(pts)) t = vtk.vtkTransform() t.Scale(scale, scale, scale) t.Translate(-cm) tf = vtk.vtkTransformPolyDataFilter() setInput(tf, actor.GetMapper().GetInput()) tf.SetTransform(t) tf.Update() mapper = actor.GetMapper() setInput(mapper, tf.GetOutput()) mapper.Update() actor.Modified() if hasattr(actor, 'poly'): actor.poly=tf.GetOutput() return actor # return same obj for concatenation def rotate(actor, angle, axis, axis_point=[0,0,0], rad=False): '''Rotate an actor around an arbitrary axis passing through axis_point''' anglerad = angle if not rad: anglerad = angle/57.3 axis = norm(axis) a = np.cos(anglerad / 2) b, c, d = -axis * np.sin(anglerad / 2) aa, bb, cc, dd = a * a, b * b, c * c, d * d bc, ad, ac, ab, bd, cd = b * c, a * d, a * c, a * b, b * d, c * d R = np.array([[aa + bb - cc - dd, 2 * (bc + ad), 2 * (bd - ac)], [2 * (bc - ad), aa + cc - bb - dd, 2 * (cd + ab)], [2 * (bd + ac), 2 * (cd - ab), aa + dd - bb - cc]]) rv = np.dot(R, actor.GetPosition()-np.array(axis_point)) + axis_point if rad: angle *= 57.3 # this vtk method only rotates in the origin of the actor: actor.RotateWXYZ(angle, axis[0], axis[1], axis[2] ) actor.SetPosition(rv) return actor def orientation(actor, newaxis=None, rotation=0): ''' Set/Get actor orientation. If rotation != 0 rotate actor around newaxis (in degree units) ''' initaxis = norm(actor.top - actor.base) if newaxis is None: return initaxis newaxis = norm(newaxis) TI = vtk.vtkTransform() actor.SetUserMatrix(TI.GetMatrix()) # reset pos = np.array(actor.GetPosition()) crossvec = np.cross(initaxis, newaxis) angle = np.arccos(np.dot(initaxis, newaxis)) T = vtk.vtkTransform() T.PostMultiply() T.Translate(-pos) if rotation: T.RotateWXYZ(rotation, initaxis) T.RotateWXYZ(angle*57.3, crossvec) T.Translate(pos) actor.SetUserMatrix(T.GetMatrix()) return actor ############################################################################ def shrink(actor, fraction=0.85): # N.B. input argument gets modified '''Shrink the triangle polydata in the representation of actor''' poly = polydata(actor, True) shrink = vtk.vtkShrinkPolyData() setInput(shrink, poly) shrink.SetShrinkFactor(fraction) shrink.Update() mapper = actor.GetMapper() setInput(mapper, shrink.GetOutput()) mapper.Update() actor.Modified() return actor # return same obj for concatenation def stretch(actor, q1, q2): '''Stretch actor between points q1 and q2''' if not hasattr(actor, 'base'): colors.printc('Please define vectors actor.base and actor.top at creation. Exit.','r') exit(0) TI = vtk.vtkTransform() actor.SetUserMatrix(TI.GetMatrix()) # reset p1, p2 = actor.base, actor.top q1,q2,z = np.array(q1), np.array(q2), np.array([0,0,1]) plength = np.linalg.norm(p2-p1) qlength = np.linalg.norm(q2-q1) T = vtk.vtkTransform() T.PostMultiply() T.Translate(-p1) cosa = np.dot(p2-p1, z)/plength n = np.cross(p2-p1, z) T.RotateWXYZ(np.arccos(cosa)*57.3, n) T.Scale(1,1, qlength/plength) cosa = np.dot(q2-q1, z)/qlength n = np.cross(q2-q1, z) T.RotateWXYZ(-np.arccos(cosa)*57.3, n) T.Translate(q1) actor.SetUserMatrix(T.GetMatrix()) return actor def cutPlane(actor, origin=(0,0,0), normal=(1,0,0), showcut=False): ''' Takes actor and cuts it with the plane defined by a point and a normal. showcut = shows the cut away part as thin wireframe ''' plane = vtk.vtkPlane() plane.SetOrigin(origin) plane.SetNormal(normal) poly = polydata(actor) clipper = vtk.vtkClipPolyData() setInput(clipper, poly) clipper.SetClipFunction(plane) clipper.GenerateClippedOutputOn() clipper.SetValue(0.) clipper.Update() if hasattr(actor, 'GetProperty'): alpha = actor.GetProperty().GetOpacity() c = actor.GetProperty().GetColor() bf = actor.GetBackfaceProperty() else: alpha=1 c='gold' bf=None leg = None if hasattr(actor, 'legend'): leg = actor.legend clipActor = makeActor(clipper.GetOutput(),c=c,alpha=alpha, legend=leg) clipActor.SetBackfaceProperty(bf) acts = [clipActor] if showcut: cpoly = clipper.GetClippedOutput() restActor = makeActor(cpoly, c=c, alpha=0.05, wire=1) acts.append(restActor) if len(acts)>1: asse = makeAssembly(acts) return asse else: return clipActor def mergeActors(actors, c=None, alpha=1, wire=False, bc=None, edges=False, legend=None, texture=None): ''' Build a new actor formed by the fusion of the polydata of the input objects. Similar to makeAssembly, but in this case the input objects become a single mesh. ''' polylns = vtk.vtkAppendPolyData() for a in actors: polylns.AddInputData(polydata(a, True)) polylns.Update() actor = makeActor(polylns.GetOutput(), c, alpha, wire, bc, edges, legend, texture) return actor ######################################################### # Useful Functions ######################################################### def isInside(actor, point, tol=0.0001): """Return True if point is inside a polydata closed surface""" poly = polydata(actor, True) points = vtk.vtkPoints() points.InsertNextPoint(point) pointsPolydata = vtk.vtkPolyData() pointsPolydata.SetPoints(points) sep = vtk.vtkSelectEnclosedPoints() sep.SetTolerance(tol) sep.CheckSurfaceOff() setInput(sep, pointsPolydata) if vtkMV: sep.SetSurfaceData(poly) else: sep.SetSurface(poly) sep.Update() return sep.IsInside(0) def insidePoints(actor, points, invert=False, tol=1e-05): """Return list of points that are inside a polydata closed surface""" poly = polydata(actor, True) # check if the stl file is closed featureEdge = vtk.vtkFeatureEdges() featureEdge.FeatureEdgesOff() featureEdge.BoundaryEdgesOn() featureEdge.NonManifoldEdgesOn() setInput(featureEdge, poly) featureEdge.Update() openEdges = featureEdge.GetOutput().GetNumberOfCells() if openEdges != 0: colors.printc("Warning: polydata is not a closed surface",5) vpoints = vtk.vtkPoints() for p in points: vpoints.InsertNextPoint(p) pointsPolydata = vtk.vtkPolyData() pointsPolydata.SetPoints(vpoints) sep = vtk.vtkSelectEnclosedPoints() sep.SetTolerance(tol) setInput(sep, pointsPolydata) if vtkMV: sep.SetSurfaceData(poly) else: sep.SetSurface(poly) sep.Update() mask1, mask2 = [], [] for i,p in enumerate(points): if sep.IsInside(i) : mask1.append(p) else: mask2.append(p) if invert: return mask2 else: return mask1 def pointIsInTriangle(p, p1,p2,p3): ''' Return True if a point is inside (or above/below) a triangle defined by 3 points in space. ''' p = np.array(p) u = np.array(p2) - p1 v = np.array(p3) - p1 n = np.cross(u,v) w = p - p1 ln= np.dot(n,n) if not ln: return True #degenerate triangle gamma = ( np.dot(np.cross(u,w), n) )/ ln beta = ( np.dot(np.cross(w,v), n) )/ ln alpha = 1-gamma-beta if 0<alpha<1 and 0<beta<1 and 0<gamma<1: return True return False def fillHoles(actor, size=None, legend=None): # not tested properly fh = vtk.vtkFillHolesFilter() if not size: mb = maxBoundSize(actor) size = mb/20 fh.SetHoleSize(size) poly = polydata(actor) setInput(fh, poly) fh.Update() fpoly = fh.GetOutput() factor = makeActor(fpoly, legend=legend) factor.SetProperty(actor.GetProperty()) return factor def cellCenters(actor): '''Get the list of cell centers of the mesh surface''' vcen = vtk.vtkCellCenters() setInput(vcen, polydata(actor, True)) vcen.Update() return coordinates(vcen.GetOutput()) def isIdentity(M, tol=1e-06): '''Check if vtkMatrix4x4 is Identity''' for i in [0,1,2,3]: for j in [0,1,2,3]: e = M.GetElement(i,j) if i==j: if np.abs(e-1) > tol: return False elif np.abs(e) > tol: return False return True def cleanPolydata(actor, tol=None): ''' Clean actor's polydata. tol paramenter defines how far should be the points from each other in terms of fraction of bounding box length. ''' poly = polydata(actor, False) cleanPolyData = vtk.vtkCleanPolyData() setInput(cleanPolyData, poly) if tol: cleanPolyData.SetTolerance(tol) cleanPolyData.PointMergingOn() cleanPolyData.Update() mapper = actor.GetMapper() setInput(mapper, cleanPolyData.GetOutput()) mapper.Update() actor.Modified() if hasattr(actor, 'poly'): actor.poly = cleanPolyData.GetOutput() return actor # NB: polydata is being changed #################################################################### get stuff def polydata(obj, rebuild=True, index=0): ''' Returns the vtkPolyData of a vtkActor or vtkAssembly. If rebuild=True returns a copy of polydata that corresponds to the current actor's position in space. If a vtkAssembly is passed, return the polydata of component index. ''' if isinstance(obj, vtk.vtkActor): if not rebuild: if hasattr(obj, 'poly') : if obj.poly: return obj.poly else: setattr(obj, 'poly', None) obj.poly = obj.GetMapper().GetInput() #cache it for speed return obj.poly M = obj.GetMatrix() if isIdentity(M): if hasattr(obj, 'poly') : if obj.poly: return obj.poly else: setattr(obj, 'poly', None) obj.poly = obj.GetMapper().GetInput() #cache it for speed return obj.poly # if identity return the original polydata # otherwise make a copy that corresponds to # the actual position in space of the actor transform = vtk.vtkTransform() transform.SetMatrix(M) tp = vtk.vtkTransformPolyDataFilter() tp.SetTransform(transform) if vtkMV: tp.SetInputData(obj.GetMapper().GetInput()) else: tp.SetInput(obj.GetMapper().GetInput()) tp.Update() return tp.GetOutput() elif isinstance(obj, vtk.vtkAssembly): cl = vtk.vtkPropCollection() obj.GetActors(cl) cl.InitTraversal() for i in range(index+1): act = vtk.vtkActor.SafeDownCast(cl.GetNextProp()) pd = act.GetMapper().GetInput() #not optimized if not rebuild: return pd M = act.GetMatrix() if isIdentity(M): return pd # if identity return the original polydata # otherwise make a copy that corresponds to # the actual position in space of the actor transform = vtk.vtkTransform() transform.SetMatrix(M) tp = vtk.vtkTransformPolyDataFilter() tp.SetTransform(transform) if vtkMV: tp.SetInputData(pd) else: tp.SetInput(pd) tp.Update() return tp.GetOutput() elif isinstance(obj, vtk.vtkPolyData): return obj elif isinstance(obj, vtk.vtkActor2D): return obj.GetMapper().GetInput() elif isinstance(obj, vtk.vtkImageActor): return obj.GetMapper().GetInput() elif obj is None: return None colors.printc("Fatal Error in polydata(): ", 'r', end='') colors.printc(("input is neither a vtkActor nor vtkAssembly.", [obj]), 'r') exit(1) def coordinates(actor, rebuild=True): """Return a merged list of coordinates of actors or polys""" pts = [] poly = polydata(actor, rebuild) for j in range(poly.GetNumberOfPoints()): p = [0, 0, 0] poly.GetPoint(j, p) pts.append(p) return np.array(pts) def xbounds(actor): '''Get the the actor bounding [xmin,xmax] ''' b = polydata(actor, True).GetBounds() return (b[0],b[1]) def ybounds(actor): '''Get the the actor bounding [ymin,ymax] ''' b = polydata(actor, True).GetBounds() return (b[2],b[3]) def zbounds(actor): '''Get the the actor bounding [zmin,zmax] ''' b = polydata(actor, True).GetBounds() return (b[4],b[5]) def centerOfMass(actor): '''Get the Center of Mass of the actor''' if vtkMV: #faster cmf = vtk.vtkCenterOfMass() setInput(cmf, polydata(actor, True)) cmf.Update() c = cmf.GetCenter() return np.array(c) else: pts = coordinates(actor, True) if not len(pts): return np.array([0,0,0]) return np.mean(pts, axis=0) def volume(actor): '''Get the volume occupied by actor''' mass = vtk.vtkMassProperties() setInput(mass, polydata(actor)) mass.Update() return mass.GetVolume() def area(actor): '''Get the surface area of actor''' mass = vtk.vtkMassProperties() setInput(mass, polydata(actor)) mass.Update() return mass.GetSurfaceArea() def averageSize(actor): cm = centerOfMass(actor) coords = coordinates(actor, True) if not len(coords) : return pts = coords - cm xyz2 = np.sum(pts * pts, axis=0) return np.sqrt(np.sum(xyz2)/len(pts)) def diagonalSize(actor): '''Get the length of the diagonal of actor bounding box''' b = polydata(actor).GetBounds() return np.sqrt((b[1]-b[0])**2 + (b[3]-b[2])**2 + (b[5]-b[4])**2) def maxBoundSize(actor): '''Get the maximum dimension in x, y or z of the actor bounding box''' b = polydata(actor, True).GetBounds() return max(abs(b[1]-b[0]), abs(b[3]-b[2]), abs(b[5]-b[4])) ######################################################################## def closestPoint(actor, pt, N=1, radius=None, returnIds=False): """ Find the closest point on a polydata given an other point. The appropriate locator is built on the fly and cached for speed. If N>1, return a list of N ordered closest points. If radius is given, get all points within. """ poly = polydata(actor, True) if N>1 or radius: plocexists = hasattr(actor, 'point_locator') if not plocexists or (plocexists and actor.point_locator is None): point_locator = vtk.vtkPointLocator() point_locator.SetDataSet(poly) point_locator.BuildLocator() setattr(actor, 'point_locator', point_locator) vtklist = vtk.vtkIdList() if N>1: actor.point_locator.FindClosestNPoints(N, pt, vtklist) else: actor.point_locator.FindPointsWithinRadius(radius, pt, vtklist) if returnIds: return [int(vtklist.GetId(k)) for k in range(vtklist.GetNumberOfIds())] else: trgp = [] for i in range(vtklist.GetNumberOfIds()): trgp_ = [0,0,0] vi = vtklist.GetId(i) poly.GetPoints().GetPoint(vi, trgp_ ) trgp.append( trgp_ ) return np.array(trgp) clocexists = hasattr(actor, 'cell_locator') if not clocexists or (clocexists and actor.cell_locator is None): cell_locator = vtk.vtkCellLocator() cell_locator.SetDataSet(poly) cell_locator.BuildLocator() setattr(actor, 'cell_locator', cell_locator) trgp = [0,0,0] cid = vtk.mutable(0) dist2 = vtk.mutable(0) subid = vtk.mutable(0) actor.cell_locator.FindClosestPoint(pt, trgp, cid, subid, dist2) if returnIds: return int(cid) else: return np.array(trgp) def pointScalars(actor, scalars, name): """ Set point scalars to the polydata """ poly = polydata(actor, False) scalars = np.array(scalars) - np.min(scalars) scalars = scalars/np.max(scalars) if len(scalars) != poly.GetNumberOfPoints(): colors.printc('Number of scalars != nr. of points',1) exit() arr = numpy_to_vtk(np.ascontiguousarray(scalars), deep=True) arr.SetName(name) poly.GetPointData().AddArray(arr) poly.GetPointData().SetActiveScalars(name) actor.GetMapper().ScalarVisibilityOn() def pointColors(actor, scalars, cmap='jet'): """ Set individual point colors by setting a scalar """ poly = polydata(actor, False) if len(scalars) != poly.GetNumberOfPoints(): colors.printc('Number of scalars != nr. of points',1) exit() lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(len(scalars)) lut.Build() vmin, vmax = np.min(scalars), np.max(scalars) n = len(scalars) for i in range(n): c = colors.colorMap(i, cmap, 0, n) lut.SetTableValue(i, c[0], c[1], c[2], 1) arr = numpy_to_vtk(np.ascontiguousarray(scalars), deep=True) arr.SetName('pointcolors_'+cmap) poly.GetPointData().AddArray(arr) poly.GetPointData().SetActiveScalars('pointcolors_'+cmap) actor.GetMapper().SetScalarRange(vmin, vmax) actor.GetMapper().SetLookupTable(lut) actor.GetMapper().ScalarVisibilityOn() def cellScalars(actor, scalars, name): """ Set cell scalars to the polydata """ poly = polydata(actor, False) scalars = np.array(scalars) - np.min(scalars) scalars = scalars/np.max(scalars) if len(scalars) != poly.GetNumberOfCells(): colors.printc('Number of scalars != nr. of cells',1) exit() arr = numpy_to_vtk(np.ascontiguousarray(scalars), deep=True) arr.SetName(name) poly.GetCellData().AddArray(arr) poly.GetCellData().SetActiveScalars(name) actor.GetMapper().ScalarVisibilityOn() def cellColors(actor, scalars, cmap='jet'): """ Set individual cell colors by setting a scalar """ poly = polydata(actor, False) if len(scalars) != poly.GetNumberOfCells(): colors.printc('Number of scalars != nr. of cells',1) exit() lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(len(scalars)) lut.Build() vmin, vmax = np.min(scalars), np.max(scalars) n = len(scalars) for i in range(n): c = colors.colorMap(i, cmap, 0, n) lut.SetTableValue(i, c[0], c[1], c[2], 1) arr = numpy_to_vtk(np.ascontiguousarray(scalars), deep=True) arr.SetName('cellcolors_'+cmap) poly.GetCellData().AddArray(arr) poly.GetCellData().SetActiveScalars('cellcolors_'+cmap) actor.GetMapper().SetScalarRange(vmin, vmax) actor.GetMapper().SetLookupTable(lut) actor.GetMapper().ScalarVisibilityOn() def scalars(actor, name): """ Retrieve point or cell scalars using array name """ poly = polydata(actor, False) arr = poly.GetPointData().GetArray(name) if not arr: arr = poly.GetCellData().GetArray(name) if arr: return vtk_to_numpy(arr) return None def cutterWidget(obj, outputname='clipped.vtk', c=(0.2, 0.2, 1), alpha=1, bc=(0.7, 0.8, 1), legend=None): '''Pop up a box widget to cut parts of actor. Return largest part.''' apd = polydata(obj) planes = vtk.vtkPlanes() planes.SetBounds(apd.GetBounds()) clipper = vtk.vtkClipPolyData() setInput(clipper, apd) clipper.SetClipFunction(planes) clipper.InsideOutOn() clipper.GenerateClippedOutputOn() # check if color string contains a float, in this case ignore alpha al = colors.getAlpha(c) if al: alpha = al act0Mapper = vtk.vtkPolyDataMapper() # the part which stays act0Mapper.SetInputConnection(clipper.GetOutputPort()) act0 = vtk.vtkActor() act0.SetMapper(act0Mapper) act0.GetProperty().SetColor(colors.getColor(c)) act0.GetProperty().SetOpacity(alpha) backProp = vtk.vtkProperty() backProp.SetDiffuseColor(colors.getColor(bc)) backProp.SetOpacity(alpha) act0.SetBackfaceProperty(backProp) act0.GetProperty().SetInterpolationToFlat() assignPhysicsMethods(act0) assignConvenienceMethods(act0, legend) act1Mapper = vtk.vtkPolyDataMapper() # the part which is cut away act1Mapper.SetInputConnection(clipper.GetClippedOutputPort()) act1 = vtk.vtkActor() act1.SetMapper(act1Mapper) act1.GetProperty().SetColor(colors.getColor(c)) act1.GetProperty().SetOpacity(alpha/10.) act1.GetProperty().SetRepresentationToWireframe() act1.VisibilityOn() ren = vtk.vtkRenderer() ren.SetBackground(1,1,1) ren.AddActor(act0) ren.AddActor(act1) renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) renWin.SetSize(600, 700) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) istyl = vtk.vtkInteractorStyleSwitch() istyl.SetCurrentStyleToTrackballCamera() iren.SetInteractorStyle(istyl) def SelectPolygons(vobj, event): vobj.GetPlanes(planes) boxWidget = vtk.vtkBoxWidget() boxWidget.OutlineCursorWiresOn() boxWidget.GetSelectedOutlineProperty().SetColor(1,0,1) boxWidget.GetOutlineProperty().SetColor(0.1,0.1,0.1) boxWidget.GetOutlineProperty().SetOpacity(0.8) boxWidget.SetPlaceFactor(1.05) boxWidget.SetInteractor(iren) setInput(boxWidget, apd) boxWidget.PlaceWidget() boxWidget.AddObserver("InteractionEvent", SelectPolygons) boxWidget.On() colors.printc('\nCutterWidget:\n Move handles to cut parts of the actor','m') colors.printc(' Press q to continue, Escape to exit','m') colors.printc((" Press X to save file to", outputname), 'm') def cwkeypress(obj, event): key = obj.GetKeySym() if key == "q" or key == "space" or key == "Return": iren.ExitCallback() elif key == "X": confilter = vtk.vtkPolyDataConnectivityFilter() setInput(confilter, clipper.GetOutput()) confilter.SetExtractionModeToLargestRegion() confilter.Update() cpd = vtk.vtkCleanPolyData() setInput(cpd, confilter.GetOutput()) cpd.Update() w = vtk.vtkPolyDataWriter() setInput(w, cpd.GetOutput()) w.SetFileName(outputname) w.Write() colors.printc("Saved file: "+outputname, 'g') elif key == "Escape": exit(0) iren.Initialize() iren.AddObserver("KeyPressEvent", cwkeypress) iren.Start() boxWidget.Off() return act0 def intersectWithLine(act, p0, p1): '''Return a list of points between p0 and p1 intersecting the actor''' if not hasattr(act, 'line_locator'): line_locator = vtk.vtkOBBTree() line_locator.SetDataSet(polydata(act, True)) line_locator.BuildLocator() setattr(act, 'line_locator', line_locator) intersectPoints = vtk.vtkPoints() intersection = [0, 0, 0] act.line_locator.IntersectWithLine(p0, p1, intersectPoints, None) pts=[] for i in range(intersectPoints.GetNumberOfPoints()): intersectPoints.GetPoint(i, intersection) pts.append(list(intersection)) return pts def subdivide(actor, N=1, method=0, legend=None): ''' Increase the number of points in actor surface N = number of subdivisions method = 0, Loop method = 1, Linear method = 2, Adaptive method = 3, Butterfly ''' triangles = vtk.vtkTriangleFilter() setInput(triangles, polydata(actor)) triangles.Update() originalMesh = triangles.GetOutput() if method==0: sdf = vtk.vtkLoopSubdivisionFilter() elif method==1: sdf = vtk.vtkLinearSubdivisionFilter() elif method==2: sdf = vtk.vtkAdaptiveSubdivisionFilter() elif method==3: sdf = vtk.vtkButterflySubdivisionFilter() else: colors.printc('Error in subdivide: unknown method.', 'r') exit(1) if method != 2: sdf.SetNumberOfSubdivisions(N) setInput(sdf, originalMesh) sdf.Update() out = sdf.GetOutput() if legend is None and hasattr(actor, 'legend'): legend=actor.legend sactor = makeActor(out, legend=legend) sactor.GetProperty().SetOpacity(actor.GetProperty().GetOpacity()) sactor.GetProperty().SetColor(actor.GetProperty().GetColor()) sactor.GetProperty().SetRepresentation(actor.GetProperty().GetRepresentation()) return sactor def decimate(actor, fraction=0.5, N=None, verbose=True, boundaries=True): ''' Downsample the number of vertices in a mesh. fraction gives the desired target of reduction. E.g. fraction=0.1 leaves 10% of the original nr of vertices. ''' poly = polydata(actor, True) if N: # N = desired number of points Np = poly.GetNumberOfPoints() fraction = float(N)/Np if fraction >= 1: return actor decimate = vtk.vtkDecimatePro() setInput(decimate, poly) decimate.SetTargetReduction(1.-fraction) decimate.PreserveTopologyOff() if boundaries: decimate.BoundaryVertexDeletionOn() else: decimate.BoundaryVertexDeletionOff() decimate.Update() if verbose: print ('Input nr. of pts:',poly.GetNumberOfPoints(),end='') print (' output:',decimate.GetOutput().GetNumberOfPoints()) mapper = actor.GetMapper() setInput(mapper, decimate.GetOutput()) mapper.Update() actor.Modified() if hasattr(actor, 'poly'): actor.poly=decimate.GetOutput() return actor # return same obj for concatenation
[ "vtk.vtkSelectEnclosedPoints", "vtk.vtkBoxWidget", "numpy.ascontiguousarray", "numpy.sin", "vtk.vtkButterflySubdivisionFilter", "numpy.arange", "vtkplotter.colors.getColor", "vtk.vtkShrinkPolyData", "vtk.vtkCleanPolyData", "vtk.vtkTextureMapToPlane", "vtk.vtkCellCenters", "vtkplotter.colors.ge...
[((979, 1007), 'numpy.arange', 'np.arange', (['start', 'stop', 'step'], {}), '(start, stop, step)\n', (988, 1007), True, 'import numpy as np\n'), ((1141, 1178), 'numpy.array', 'np.array', (['[x, y, z]'], {'dtype': 'np.float64'}), '([x, y, z], dtype=np.float64)\n', (1149, 1178), True, 'import numpy as np\n'), ((1351, 1363), 'numpy.dot', 'np.dot', (['z', 'z'], {}), '(z, z)\n', (1357, 1363), True, 'import numpy as np\n'), ((2017, 2040), 'math.pow', 'math.pow', (['(10)', '(e - p + 1)'], {}), '(10, e - p + 1)\n', (2025, 2040), False, 'import math\n'), ((2049, 2069), 'math.floor', 'math.floor', (['(x / tens)'], {}), '(x / tens)\n', (2059, 2069), False, 'import math\n'), ((3493, 3515), 'vtk.vtkCleanPolyData', 'vtk.vtkCleanPolyData', ([], {}), '()\n', (3513, 3515), False, 'import vtk\n'), ((3570, 3594), 'vtk.vtkPolyDataNormals', 'vtk.vtkPolyDataNormals', ([], {}), '()\n', (3592, 3594), False, 'import vtk\n'), ((3791, 3814), 'vtk.vtkPolyDataMapper', 'vtk.vtkPolyDataMapper', ([], {}), '()\n', (3812, 3814), False, 'import vtk\n'), ((3929, 3947), 'vtkplotter.colors.getAlpha', 'colors.getAlpha', (['c'], {}), '(c)\n', (3944, 3947), True, 'import vtkplotter.colors as colors\n'), ((4024, 4038), 'vtk.vtkActor', 'vtk.vtkActor', ([], {}), '()\n', (4036, 4038), False, 'import vtk\n'), ((5483, 5500), 'vtk.vtkAssembly', 'vtk.vtkAssembly', ([], {}), '()\n', (5498, 5500), False, 'import vtk\n'), ((6249, 6280), 'vtk.vtkTransformTextureCoords', 'vtk.vtkTransformTextureCoords', ([], {}), '()\n', (6278, 6280), False, 'import vtk\n'), ((6445, 6467), 'vtk.vtkDataSetMapper', 'vtk.vtkDataSetMapper', ([], {}), '()\n', (6465, 6467), False, 'import vtk\n'), ((6570, 6595), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (6585, 6595), False, 'import os, types\n'), ((6680, 6700), 'os.path.exists', 'os.path.exists', (['name'], {}), '(name)\n', (6694, 6700), False, 'import os, types\n'), ((7062, 7081), 'vtk.vtkJPEGReader', 'vtk.vtkJPEGReader', ([], {}), '()\n', (7079, 7081), False, 'import vtk\n'), ((7124, 7140), 'vtk.vtkTexture', 'vtk.vtkTexture', ([], {}), '()\n', (7138, 7140), False, 'import vtk\n'), ((7866, 7898), 'types.MethodType', 'types.MethodType', (['_fclone', 'actor'], {}), '(_fclone, actor)\n', (7882, 7898), False, 'import os, types\n'), ((8335, 8367), 'types.MethodType', 'types.MethodType', (['_fpoint', 'actor'], {}), '(_fpoint, actor)\n', (8351, 8367), False, 'import os, types\n'), ((8478, 8506), 'types.MethodType', 'types.MethodType', (['_fN', 'actor'], {}), '(_fN, actor)\n', (8494, 8506), False, 'import os, types\n'), ((8582, 8618), 'types.MethodType', 'types.MethodType', (['_fnormalize', 'actor'], {}), '(_fnormalize, actor)\n', (8598, 8618), False, 'import os, types\n'), ((8710, 8743), 'types.MethodType', 'types.MethodType', (['_fshrink', 'actor'], {}), '(_fshrink, actor)\n', (8726, 8743), False, 'import os, types\n'), ((8897, 8932), 'types.MethodType', 'types.MethodType', (['_fcutPlane', 'actor'], {}), '(_fcutPlane, actor)\n', (8913, 8932), False, 'import os, types\n'), ((9012, 9046), 'types.MethodType', 'types.MethodType', (['_fcutterw', 'actor'], {}), '(_fcutterw, actor)\n', (9028, 9046), False, 'import os, types\n'), ((9172, 9207), 'types.MethodType', 'types.MethodType', (['_fpolydata', 'actor'], {}), '(_fpolydata, actor)\n', (9188, 9207), False, 'import os, types\n'), ((9321, 9359), 'types.MethodType', 'types.MethodType', (['_fcoordinates', 'actor'], {}), '(_fcoordinates, actor)\n', (9337, 9359), False, 'import os, types\n'), ((9482, 9516), 'types.MethodType', 'types.MethodType', (['_fxbounds', 'actor'], {}), '(_fxbounds, actor)\n', (9498, 9516), False, 'import os, types\n'), ((9638, 9672), 'types.MethodType', 'types.MethodType', (['_fybounds', 'actor'], {}), '(_fybounds, actor)\n', (9654, 9672), False, 'import os, types\n'), ((9794, 9828), 'types.MethodType', 'types.MethodType', (['_fzbounds', 'actor'], {}), '(_fzbounds, actor)\n', (9810, 9828), False, 'import os, types\n'), ((10004, 10039), 'types.MethodType', 'types.MethodType', (['_fnormalAt', 'actor'], {}), '(_fnormalAt, actor)\n', (10020, 10039), False, 'import os, types\n'), ((10227, 10261), 'types.MethodType', 'types.MethodType', (['_fnormals', 'actor'], {}), '(_fnormals, actor)\n', (10243, 10261), False, 'import os, types\n'), ((10372, 10406), 'types.MethodType', 'types.MethodType', (['_fstretch', 'actor'], {}), '(_fstretch, actor)\n', (10388, 10406), False, 'import os, types\n'), ((10537, 10573), 'types.MethodType', 'types.MethodType', (['_fsubdivide', 'actor'], {}), '(_fsubdivide, actor)\n', (10553, 10573), False, 'import os, types\n'), ((10741, 10776), 'types.MethodType', 'types.MethodType', (['_fdecimate', 'actor'], {}), '(_fdecimate, actor)\n', (10757, 10776), False, 'import os, types\n'), ((11013, 11045), 'types.MethodType', 'types.MethodType', (['_fcolor', 'actor'], {}), '(_fcolor, actor)\n', (11029, 11045), False, 'import os, types\n'), ((11247, 11279), 'types.MethodType', 'types.MethodType', (['_falpha', 'actor'], {}), '(_falpha, actor)\n', (11263, 11279), False, 'import os, types\n'), ((11500, 11531), 'types.MethodType', 'types.MethodType', (['_fwire', 'actor'], {}), '(_fwire, actor)\n', (11516, 11531), False, 'import os, types\n'), ((11660, 11699), 'types.MethodType', 'types.MethodType', (['_fclosestPoint', 'actor'], {}), '(_fclosestPoint, actor)\n', (11676, 11699), False, 'import os, types\n'), ((11821, 11865), 'types.MethodType', 'types.MethodType', (['_fintersectWithLine', 'actor'], {}), '(_fintersectWithLine, actor)\n', (11837, 11865), False, 'import os, types\n'), ((11976, 12011), 'types.MethodType', 'types.MethodType', (['_fisInside', 'actor'], {}), '(_fisInside, actor)\n', (11992, 12011), False, 'import os, types\n'), ((12160, 12199), 'types.MethodType', 'types.MethodType', (['_finsidePoints', 'actor'], {}), '(_finsidePoints, actor)\n', (12176, 12199), False, 'import os, types\n'), ((12288, 12326), 'types.MethodType', 'types.MethodType', (['_fflipNormals', 'actor'], {}), '(_fflipNormals, actor)\n', (12304, 12326), False, 'import os, types\n'), ((12419, 12457), 'types.MethodType', 'types.MethodType', (['_fcellCenters', 'actor'], {}), '(_fcellCenters, actor)\n', (12435, 12457), False, 'import os, types\n'), ((12582, 12621), 'types.MethodType', 'types.MethodType', (['_fpointScalars', 'actor'], {}), '(_fpointScalars, actor)\n', (12598, 12621), False, 'import os, types\n'), ((12750, 12788), 'types.MethodType', 'types.MethodType', (['_fpointColors', 'actor'], {}), '(_fpointColors, actor)\n', (12766, 12788), False, 'import os, types\n'), ((12911, 12949), 'types.MethodType', 'types.MethodType', (['_fcellScalars', 'actor'], {}), '(_fcellScalars, actor)\n', (12927, 12949), False, 'import os, types\n'), ((13071, 13108), 'types.MethodType', 'types.MethodType', (['_fcellColors', 'actor'], {}), '(_fcellColors, actor)\n', (13087, 13108), False, 'import os, types\n'), ((13197, 13231), 'types.MethodType', 'types.MethodType', (['_fscalars', 'actor'], {}), '(_fscalars, actor)\n', (13213, 13231), False, 'import os, types\n'), ((13555, 13585), 'types.MethodType', 'types.MethodType', (['_fpos', 'actor'], {}), '(_fpos, actor)\n', (13571, 13585), False, 'import os, types\n'), ((13717, 13750), 'types.MethodType', 'types.MethodType', (['_faddpos', 'actor'], {}), '(_faddpos, actor)\n', (13733, 13750), False, 'import os, types\n'), ((13991, 14020), 'types.MethodType', 'types.MethodType', (['_fpx', 'actor'], {}), '(_fpx, actor)\n', (14007, 14020), False, 'import os, types\n'), ((14261, 14290), 'types.MethodType', 'types.MethodType', (['_fpy', 'actor'], {}), '(_fpy, actor)\n', (14277, 14290), False, 'import os, types\n'), ((14531, 14560), 'types.MethodType', 'types.MethodType', (['_fpz', 'actor'], {}), '(_fpz, actor)\n', (14547, 14560), False, 'import os, types\n'), ((14766, 14798), 'types.MethodType', 'types.MethodType', (['_fscale', 'actor'], {}), '(_fscale, actor)\n', (14782, 14798), False, 'import os, types\n'), ((14978, 15011), 'types.MethodType', 'types.MethodType', (['_frotate', 'actor'], {}), '(_frotate, actor)\n', (14994, 15011), False, 'import os, types\n'), ((15190, 15224), 'types.MethodType', 'types.MethodType', (['_frotateX', 'actor'], {}), '(_frotateX, actor)\n', (15206, 15224), False, 'import os, types\n'), ((15403, 15437), 'types.MethodType', 'types.MethodType', (['_frotateY', 'actor'], {}), '(_frotateY, actor)\n', (15419, 15437), False, 'import os, types\n'), ((15616, 15650), 'types.MethodType', 'types.MethodType', (['_frotateZ', 'actor'], {}), '(_frotateZ, actor)\n', (15632, 15650), False, 'import os, types\n'), ((15786, 15824), 'types.MethodType', 'types.MethodType', (['_forientation', 'actor'], {}), '(_forientation, actor)\n', (15802, 15824), False, 'import os, types\n'), ((15909, 15948), 'types.MethodType', 'types.MethodType', (['_fcenterOfMass', 'actor'], {}), '(_fcenterOfMass, actor)\n', (15925, 15948), False, 'import os, types\n'), ((16013, 16046), 'types.MethodType', 'types.MethodType', (['_fvolume', 'actor'], {}), '(_fvolume, actor)\n', (16029, 16046), False, 'import os, types\n'), ((16105, 16136), 'types.MethodType', 'types.MethodType', (['_farea', 'actor'], {}), '(_farea, actor)\n', (16121, 16136), False, 'import os, types\n'), ((16219, 16258), 'types.MethodType', 'types.MethodType', (['_fdiagonalSize', 'actor'], {}), '(_fdiagonalSize, actor)\n', (16235, 16258), False, 'import os, types\n'), ((16751, 16768), 'vtk.vtkPolyData', 'vtk.vtkPolyData', ([], {}), '()\n', (16766, 16768), False, 'import vtk\n'), ((17309, 17330), 'vtk.vtkReverseSense', 'vtk.vtkReverseSense', ([], {}), '()\n', (17328, 17330), False, 'import vtk\n'), ((17920, 17945), 'numpy.sum', 'np.sum', (['(pts * pts)'], {'axis': '(0)'}), '(pts * pts, axis=0)\n', (17926, 17945), True, 'import numpy as np\n'), ((17999, 18017), 'vtk.vtkTransform', 'vtk.vtkTransform', ([], {}), '()\n', (18015, 18017), False, 'import vtk\n'), ((18081, 18113), 'vtk.vtkTransformPolyDataFilter', 'vtk.vtkTransformPolyDataFilter', ([], {}), '()\n', (18111, 18113), False, 'import vtk\n'), ((18658, 18678), 'numpy.cos', 'np.cos', (['(anglerad / 2)'], {}), '(anglerad / 2)\n', (18664, 18678), True, 'import numpy as np\n'), ((18848, 19019), 'numpy.array', 'np.array', (['[[aa + bb - cc - dd, 2 * (bc + ad), 2 * (bd - ac)], [2 * (bc - ad), aa + cc -\n bb - dd, 2 * (cd + ab)], [2 * (bd + ac), 2 * (cd - ab), aa + dd - bb - cc]]'], {}), '([[aa + bb - cc - dd, 2 * (bc + ad), 2 * (bd - ac)], [2 * (bc - ad),\n aa + cc - bb - dd, 2 * (cd + ab)], [2 * (bd + ac), 2 * (cd - ab), aa +\n dd - bb - cc]])\n', (18856, 19019), True, 'import numpy as np\n'), ((19607, 19625), 'vtk.vtkTransform', 'vtk.vtkTransform', ([], {}), '()\n', (19623, 19625), False, 'import vtk\n'), ((19729, 19756), 'numpy.cross', 'np.cross', (['initaxis', 'newaxis'], {}), '(initaxis, newaxis)\n', (19737, 19756), True, 'import numpy as np\n'), ((19814, 19832), 'vtk.vtkTransform', 'vtk.vtkTransform', ([], {}), '()\n', (19830, 19832), False, 'import vtk\n'), ((20310, 20333), 'vtk.vtkShrinkPolyData', 'vtk.vtkShrinkPolyData', ([], {}), '()\n', (20331, 20333), False, 'import vtk\n'), ((20823, 20841), 'vtk.vtkTransform', 'vtk.vtkTransform', ([], {}), '()\n', (20839, 20841), False, 'import vtk\n'), ((21000, 21023), 'numpy.linalg.norm', 'np.linalg.norm', (['(p2 - p1)'], {}), '(p2 - p1)\n', (21014, 21023), True, 'import numpy as np\n'), ((21036, 21059), 'numpy.linalg.norm', 'np.linalg.norm', (['(q2 - q1)'], {}), '(q2 - q1)\n', (21050, 21059), True, 'import numpy as np\n'), ((21066, 21084), 'vtk.vtkTransform', 'vtk.vtkTransform', ([], {}), '()\n', (21082, 21084), False, 'import vtk\n'), ((21172, 21192), 'numpy.cross', 'np.cross', (['(p2 - p1)', 'z'], {}), '(p2 - p1, z)\n', (21180, 21192), True, 'import numpy as np\n'), ((21318, 21338), 'numpy.cross', 'np.cross', (['(q2 - q1)', 'z'], {}), '(q2 - q1, z)\n', (21326, 21338), True, 'import numpy as np\n'), ((21701, 21715), 'vtk.vtkPlane', 'vtk.vtkPlane', ([], {}), '()\n', (21713, 21715), False, 'import vtk\n'), ((21813, 21834), 'vtk.vtkClipPolyData', 'vtk.vtkClipPolyData', ([], {}), '()\n', (21832, 21834), False, 'import vtk\n'), ((22997, 23020), 'vtk.vtkAppendPolyData', 'vtk.vtkAppendPolyData', ([], {}), '()\n', (23018, 23020), False, 'import vtk\n'), ((23533, 23548), 'vtk.vtkPoints', 'vtk.vtkPoints', ([], {}), '()\n', (23546, 23548), False, 'import vtk\n'), ((23604, 23621), 'vtk.vtkPolyData', 'vtk.vtkPolyData', ([], {}), '()\n', (23619, 23621), False, 'import vtk\n'), ((23669, 23698), 'vtk.vtkSelectEnclosedPoints', 'vtk.vtkSelectEnclosedPoints', ([], {}), '()\n', (23696, 23698), False, 'import vtk\n'), ((24122, 24143), 'vtk.vtkFeatureEdges', 'vtk.vtkFeatureEdges', ([], {}), '()\n', (24141, 24143), False, 'import vtk\n'), ((24476, 24491), 'vtk.vtkPoints', 'vtk.vtkPoints', ([], {}), '()\n', (24489, 24491), False, 'import vtk\n'), ((24561, 24578), 'vtk.vtkPolyData', 'vtk.vtkPolyData', ([], {}), '()\n', (24576, 24578), False, 'import vtk\n'), ((24627, 24656), 'vtk.vtkSelectEnclosedPoints', 'vtk.vtkSelectEnclosedPoints', ([], {}), '()\n', (24654, 24656), False, 'import vtk\n'), ((25201, 25212), 'numpy.array', 'np.array', (['p'], {}), '(p)\n', (25209, 25212), True, 'import numpy as np\n'), ((25274, 25288), 'numpy.cross', 'np.cross', (['u', 'v'], {}), '(u, v)\n', (25282, 25288), True, 'import numpy as np\n'), ((25311, 25323), 'numpy.dot', 'np.dot', (['n', 'n'], {}), '(n, n)\n', (25317, 25323), True, 'import numpy as np\n'), ((25639, 25663), 'vtk.vtkFillHolesFilter', 'vtk.vtkFillHolesFilter', ([], {}), '()\n', (25661, 25663), False, 'import vtk\n'), ((26060, 26080), 'vtk.vtkCellCenters', 'vtk.vtkCellCenters', ([], {}), '()\n', (26078, 26080), False, 'import vtk\n'), ((26747, 26769), 'vtk.vtkCleanPolyData', 'vtk.vtkCleanPolyData', ([], {}), '()\n', (26767, 26769), False, 'import vtk\n'), ((29699, 29756), 'vtkplotter.colors.printc', 'colors.printc', (['"""Fatal Error in polydata(): """', '"""r"""'], {'end': '""""""'}), "('Fatal Error in polydata(): ', 'r', end='')\n", (29712, 29756), True, 'import vtkplotter.colors as colors\n'), ((29761, 29836), 'vtkplotter.colors.printc', 'colors.printc', (["('input is neither a vtkActor nor vtkAssembly.', [obj])", '"""r"""'], {}), "(('input is neither a vtkActor nor vtkAssembly.', [obj]), 'r')\n", (29774, 29836), True, 'import vtkplotter.colors as colors\n'), ((30132, 30145), 'numpy.array', 'np.array', (['pts'], {}), '(pts)\n', (30140, 30145), True, 'import numpy as np\n'), ((31022, 31045), 'vtk.vtkMassProperties', 'vtk.vtkMassProperties', ([], {}), '()\n', (31043, 31045), False, 'import vtk\n'), ((31198, 31221), 'vtk.vtkMassProperties', 'vtk.vtkMassProperties', ([], {}), '()\n', (31219, 31221), False, 'import vtk\n'), ((31467, 31492), 'numpy.sum', 'np.sum', (['(pts * pts)'], {'axis': '(0)'}), '(pts * pts, axis=0)\n', (31473, 31492), True, 'import numpy as np\n'), ((31671, 31740), 'numpy.sqrt', 'np.sqrt', (['((b[1] - b[0]) ** 2 + (b[3] - b[2]) ** 2 + (b[5] - b[4]) ** 2)'], {}), '((b[1] - b[0]) ** 2 + (b[3] - b[2]) ** 2 + (b[5] - b[4]) ** 2)\n', (31678, 31740), True, 'import numpy as np\n'), ((33644, 33658), 'vtk.mutable', 'vtk.mutable', (['(0)'], {}), '(0)\n', (33655, 33658), False, 'import vtk\n'), ((33671, 33685), 'vtk.mutable', 'vtk.mutable', (['(0)'], {}), '(0)\n', (33682, 33685), False, 'import vtk\n'), ((33698, 33712), 'vtk.mutable', 'vtk.mutable', (['(0)'], {}), '(0)\n', (33709, 33712), False, 'import vtk\n'), ((34805, 34825), 'vtk.vtkLookupTable', 'vtk.vtkLookupTable', ([], {}), '()\n', (34823, 34825), False, 'import vtk\n'), ((36417, 36437), 'vtk.vtkLookupTable', 'vtk.vtkLookupTable', ([], {}), '()\n', (36435, 36437), False, 'import vtk\n'), ((37663, 37678), 'vtk.vtkPlanes', 'vtk.vtkPlanes', ([], {}), '()\n', (37676, 37678), False, 'import vtk\n'), ((37732, 37753), 'vtk.vtkClipPolyData', 'vtk.vtkClipPolyData', ([], {}), '()\n', (37751, 37753), False, 'import vtk\n'), ((37963, 37981), 'vtkplotter.colors.getAlpha', 'colors.getAlpha', (['c'], {}), '(c)\n', (37978, 37981), True, 'import vtkplotter.colors as colors\n'), ((38022, 38045), 'vtk.vtkPolyDataMapper', 'vtk.vtkPolyDataMapper', ([], {}), '()\n', (38043, 38045), False, 'import vtk\n'), ((38139, 38153), 'vtk.vtkActor', 'vtk.vtkActor', ([], {}), '()\n', (38151, 38153), False, 'import vtk\n'), ((38293, 38310), 'vtk.vtkProperty', 'vtk.vtkProperty', ([], {}), '()\n', (38308, 38310), False, 'import vtk\n'), ((38584, 38607), 'vtk.vtkPolyDataMapper', 'vtk.vtkPolyDataMapper', ([], {}), '()\n', (38605, 38607), False, 'import vtk\n'), ((38714, 38728), 'vtk.vtkActor', 'vtk.vtkActor', ([], {}), '()\n', (38726, 38728), False, 'import vtk\n'), ((38950, 38967), 'vtk.vtkRenderer', 'vtk.vtkRenderer', ([], {}), '()\n', (38965, 38967), False, 'import vtk\n'), ((39066, 39087), 'vtk.vtkRenderWindow', 'vtk.vtkRenderWindow', ([], {}), '()\n', (39085, 39087), False, 'import vtk\n'), ((39157, 39188), 'vtk.vtkRenderWindowInteractor', 'vtk.vtkRenderWindowInteractor', ([], {}), '()\n', (39186, 39188), False, 'import vtk\n'), ((39234, 39264), 'vtk.vtkInteractorStyleSwitch', 'vtk.vtkInteractorStyleSwitch', ([], {}), '()\n', (39262, 39264), False, 'import vtk\n'), ((39431, 39449), 'vtk.vtkBoxWidget', 'vtk.vtkBoxWidget', ([], {}), '()\n', (39447, 39449), False, 'import vtk\n'), ((39874, 39959), 'vtkplotter.colors.printc', 'colors.printc', (['"""\nCutterWidget:\n Move handles to cut parts of the actor"""', '"""m"""'], {}), '("""\nCutterWidget:\n Move handles to cut parts of the actor""", \'m\'\n )\n', (39887, 39959), True, 'import vtkplotter.colors as colors\n'), ((39956, 40014), 'vtkplotter.colors.printc', 'colors.printc', (['""" Press q to continue, Escape to exit"""', '"""m"""'], {}), "(' Press q to continue, Escape to exit', 'm')\n", (39969, 40014), True, 'import vtkplotter.colors as colors\n'), ((40018, 40078), 'vtkplotter.colors.printc', 'colors.printc', (["(' Press X to save file to', outputname)", '"""m"""'], {}), "((' Press X to save file to', outputname), 'm')\n", (40031, 40078), True, 'import vtkplotter.colors as colors\n'), ((41319, 41334), 'vtk.vtkPoints', 'vtk.vtkPoints', ([], {}), '()\n', (41332, 41334), False, 'import vtk\n'), ((41887, 41910), 'vtk.vtkTriangleFilter', 'vtk.vtkTriangleFilter', ([], {}), '()\n', (41908, 41910), False, 'import vtk\n'), ((43315, 43335), 'vtk.vtkDecimatePro', 'vtk.vtkDecimatePro', ([], {}), '()\n', (43333, 43335), False, 'import vtk\n'), ((1100, 1129), 'numpy.array', 'np.array', (['x'], {'dtype': 'np.float64'}), '(x, dtype=np.float64)\n', (1108, 1129), True, 'import numpy as np\n'), ((1308, 1325), 'numpy.linalg.norm', 'np.linalg.norm', (['z'], {}), '(z)\n', (1322, 1325), True, 'import numpy as np\n'), ((1991, 2004), 'math.log10', 'math.log10', (['x'], {}), '(x)\n', (2001, 2004), False, 'import math\n'), ((2080, 2099), 'math.pow', 'math.pow', (['(10)', '(p - 1)'], {}), '(10, p - 1)\n', (2088, 2099), False, 'import math\n'), ((2133, 2156), 'math.pow', 'math.pow', (['(10)', '(e - p + 1)'], {}), '(10, e - p + 1)\n', (2141, 2156), False, 'import math\n'), ((2167, 2187), 'math.floor', 'math.floor', (['(x / tens)'], {}), '(x / tens)\n', (2177, 2187), False, 'import math\n'), ((2265, 2280), 'math.pow', 'math.pow', (['(10)', 'p'], {}), '(10, p)\n', (2273, 2280), False, 'import math\n'), ((4575, 4593), 'vtkplotter.colors.getColor', 'colors.getColor', (['c'], {}), '(c)\n', (4590, 4593), True, 'import vtkplotter.colors as colors\n'), ((5124, 5141), 'vtk.vtkProperty', 'vtk.vtkProperty', ([], {}), '()\n', (5139, 5141), False, 'import vtk\n'), ((5998, 6027), 'vtk.vtkTextureMapToCylinder', 'vtk.vtkTextureMapToCylinder', ([], {}), '()\n', (6025, 6027), False, 'import vtk\n'), ((10158, 10182), 'vtk.util.numpy_support.vtk_to_numpy', 'vtk_to_numpy', (['vtknormals'], {}), '(vtknormals)\n', (10170, 10182), False, 'from vtk.util.numpy_support import vtk_to_numpy\n'), ((16640, 16715), 'vtkplotter.colors.printc', 'colors.printc', (['"""Limitation: cannot clone textured obj. Returning input."""', '(1)'], {}), "('Limitation: cannot clone textured obj. Returning input.', 1)\n", (16653, 16715), True, 'import vtkplotter.colors as colors\n'), ((18701, 18721), 'numpy.sin', 'np.sin', (['(anglerad / 2)'], {}), '(anglerad / 2)\n', (18707, 18721), True, 'import numpy as np\n'), ((19779, 19804), 'numpy.dot', 'np.dot', (['initaxis', 'newaxis'], {}), '(initaxis, newaxis)\n', (19785, 19804), True, 'import numpy as np\n'), ((20710, 20802), 'vtkplotter.colors.printc', 'colors.printc', (['"""Please define vectors actor.base and actor.top at creation. Exit."""', '"""r"""'], {}), "(\n 'Please define vectors actor.base and actor.top at creation. Exit.', 'r')\n", (20723, 20802), True, 'import vtkplotter.colors as colors\n'), ((20940, 20952), 'numpy.array', 'np.array', (['q1'], {}), '(q1)\n', (20948, 20952), True, 'import numpy as np\n'), ((20954, 20966), 'numpy.array', 'np.array', (['q2'], {}), '(q2)\n', (20962, 20966), True, 'import numpy as np\n'), ((20968, 20987), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (20976, 20987), True, 'import numpy as np\n'), ((21138, 21156), 'numpy.dot', 'np.dot', (['(p2 - p1)', 'z'], {}), '(p2 - p1, z)\n', (21144, 21156), True, 'import numpy as np\n'), ((21284, 21302), 'numpy.dot', 'np.dot', (['(q2 - q1)', 'z'], {}), '(q2 - q1, z)\n', (21290, 21302), True, 'import numpy as np\n'), ((24396, 24457), 'vtkplotter.colors.printc', 'colors.printc', (['"""Warning: polydata is not a closed surface"""', '(5)'], {}), "('Warning: polydata is not a closed surface', 5)\n", (24409, 24457), True, 'import vtkplotter.colors as colors\n'), ((25222, 25234), 'numpy.array', 'np.array', (['p2'], {}), '(p2)\n', (25230, 25234), True, 'import numpy as np\n'), ((25248, 25260), 'numpy.array', 'np.array', (['p3'], {}), '(p3)\n', (25256, 25260), True, 'import numpy as np\n'), ((28331, 28349), 'vtk.vtkTransform', 'vtk.vtkTransform', ([], {}), '()\n', (28347, 28349), False, 'import vtk\n'), ((28394, 28426), 'vtk.vtkTransformPolyDataFilter', 'vtk.vtkTransformPolyDataFilter', ([], {}), '()\n', (28424, 28426), False, 'import vtk\n'), ((30663, 30684), 'vtk.vtkCenterOfMass', 'vtk.vtkCenterOfMass', ([], {}), '()\n', (30682, 30684), False, 'import vtk\n'), ((30794, 30805), 'numpy.array', 'np.array', (['c'], {}), '(c)\n', (30802, 30805), True, 'import numpy as np\n'), ((30920, 30940), 'numpy.mean', 'np.mean', (['pts'], {'axis': '(0)'}), '(pts, axis=0)\n', (30927, 30940), True, 'import numpy as np\n'), ((32738, 32753), 'vtk.vtkIdList', 'vtk.vtkIdList', ([], {}), '()\n', (32751, 32753), False, 'import vtk\n'), ((33463, 33483), 'vtk.vtkCellLocator', 'vtk.vtkCellLocator', ([], {}), '()\n', (33481, 33483), False, 'import vtk\n'), ((33850, 33864), 'numpy.array', 'np.array', (['trgp'], {}), '(trgp)\n', (33858, 33864), True, 'import numpy as np\n'), ((34029, 34046), 'numpy.array', 'np.array', (['scalars'], {}), '(scalars)\n', (34037, 34046), True, 'import numpy as np\n'), ((34049, 34064), 'numpy.min', 'np.min', (['scalars'], {}), '(scalars)\n', (34055, 34064), True, 'import numpy as np\n'), ((34091, 34106), 'numpy.max', 'np.max', (['scalars'], {}), '(scalars)\n', (34097, 34106), True, 'import numpy as np\n'), ((34172, 34226), 'vtkplotter.colors.printc', 'colors.printc', (['"""Number of scalars != nr. of points"""', '(1)'], {}), "('Number of scalars != nr. of points', 1)\n", (34185, 34226), True, 'import vtkplotter.colors as colors\n'), ((34272, 34301), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['scalars'], {}), '(scalars)\n', (34292, 34301), True, 'import numpy as np\n'), ((34710, 34764), 'vtkplotter.colors.printc', 'colors.printc', (['"""Number of scalars != nr. of points"""', '(1)'], {}), "('Number of scalars != nr. of points', 1)\n", (34723, 34764), True, 'import vtkplotter.colors as colors\n'), ((34916, 34931), 'numpy.min', 'np.min', (['scalars'], {}), '(scalars)\n', (34922, 34931), True, 'import numpy as np\n'), ((34933, 34948), 'numpy.max', 'np.max', (['scalars'], {}), '(scalars)\n', (34939, 34948), True, 'import numpy as np\n'), ((35017, 35047), 'vtkplotter.colors.colorMap', 'colors.colorMap', (['i', 'cmap', '(0)', 'n'], {}), '(i, cmap, 0, n)\n', (35032, 35047), True, 'import vtkplotter.colors as colors\n'), ((35129, 35158), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['scalars'], {}), '(scalars)\n', (35149, 35158), True, 'import numpy as np\n'), ((35649, 35666), 'numpy.array', 'np.array', (['scalars'], {}), '(scalars)\n', (35657, 35666), True, 'import numpy as np\n'), ((35669, 35684), 'numpy.min', 'np.min', (['scalars'], {}), '(scalars)\n', (35675, 35684), True, 'import numpy as np\n'), ((35711, 35726), 'numpy.max', 'np.max', (['scalars'], {}), '(scalars)\n', (35717, 35726), True, 'import numpy as np\n'), ((35791, 35844), 'vtkplotter.colors.printc', 'colors.printc', (['"""Number of scalars != nr. of cells"""', '(1)'], {}), "('Number of scalars != nr. of cells', 1)\n", (35804, 35844), True, 'import vtkplotter.colors as colors\n'), ((35890, 35919), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['scalars'], {}), '(scalars)\n', (35910, 35919), True, 'import numpy as np\n'), ((36323, 36376), 'vtkplotter.colors.printc', 'colors.printc', (['"""Number of scalars != nr. of cells"""', '(1)'], {}), "('Number of scalars != nr. of cells', 1)\n", (36336, 36376), True, 'import vtkplotter.colors as colors\n'), ((36528, 36543), 'numpy.min', 'np.min', (['scalars'], {}), '(scalars)\n', (36534, 36543), True, 'import numpy as np\n'), ((36545, 36560), 'numpy.max', 'np.max', (['scalars'], {}), '(scalars)\n', (36551, 36560), True, 'import numpy as np\n'), ((36629, 36659), 'vtkplotter.colors.colorMap', 'colors.colorMap', (['i', 'cmap', '(0)', 'n'], {}), '(i, cmap, 0, n)\n', (36644, 36659), True, 'import vtkplotter.colors as colors\n'), ((36741, 36770), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['scalars'], {}), '(scalars)\n', (36761, 36770), True, 'import numpy as np\n'), ((37383, 37400), 'vtk.util.numpy_support.vtk_to_numpy', 'vtk_to_numpy', (['arr'], {}), '(arr)\n', (37395, 37400), False, 'from vtk.util.numpy_support import vtk_to_numpy\n'), ((38217, 38235), 'vtkplotter.colors.getColor', 'colors.getColor', (['c'], {}), '(c)\n', (38232, 38235), True, 'import vtkplotter.colors as colors\n'), ((38340, 38359), 'vtkplotter.colors.getColor', 'colors.getColor', (['bc'], {}), '(bc)\n', (38355, 38359), True, 'import vtkplotter.colors as colors\n'), ((38792, 38810), 'vtkplotter.colors.getColor', 'colors.getColor', (['c'], {}), '(c)\n', (38807, 38810), True, 'import vtkplotter.colors as colors\n'), ((41139, 41155), 'vtk.vtkOBBTree', 'vtk.vtkOBBTree', ([], {}), '()\n', (41153, 41155), False, 'import vtk\n'), ((42042, 42072), 'vtk.vtkLoopSubdivisionFilter', 'vtk.vtkLoopSubdivisionFilter', ([], {}), '()\n', (42070, 42072), False, 'import vtk\n'), ((315, 331), 'vtk.vtkVersion', 'vtk.vtkVersion', ([], {}), '()\n', (329, 331), False, 'import vtk\n'), ((5175, 5194), 'vtkplotter.colors.getColor', 'colors.getColor', (['bc'], {}), '(bc)\n', (5190, 5194), True, 'import vtkplotter.colors as colors\n'), ((6059, 6086), 'vtk.vtkTextureMapToSphere', 'vtk.vtkTextureMapToSphere', ([], {}), '()\n', (6084, 6086), False, 'import vtk\n'), ((6734, 6752), 'os.path.exists', 'os.path.exists', (['fn'], {}), '(fn)\n', (6748, 6752), False, 'import os, types\n'), ((6762, 6835), 'vtkplotter.colors.printc', 'colors.printc', (["('Texture', name, 'not found in', cdir + '/textures')", '"""r"""'], {}), "(('Texture', name, 'not found in', cdir + '/textures'), 'r')\n", (6775, 6835), True, 'import vtkplotter.colors as colors\n'), ((6842, 6894), 'vtkplotter.colors.printc', 'colors.printc', (['"""Available textures:"""'], {'c': '"""m"""', 'end': '""" """'}), "('Available textures:', c='m', end=' ')\n", (6855, 6894), True, 'import vtkplotter.colors as colors\n'), ((6913, 6943), 'os.listdir', 'os.listdir', (["(cdir + '/textures')"], {}), "(cdir + '/textures')\n", (6923, 6943), False, 'import os, types\n'), ((8091, 8102), 'numpy.array', 'np.array', (['p'], {}), '(p)\n', (8099, 8102), True, 'import numpy as np\n'), ((8222, 8240), 'vtk.vtkTransform', 'vtk.vtkTransform', ([], {}), '()\n', (8238, 8240), False, 'import vtk\n'), ((21208, 21223), 'numpy.arccos', 'np.arccos', (['cosa'], {}), '(cosa)\n', (21217, 21223), True, 'import numpy as np\n'), ((25392, 25406), 'numpy.cross', 'np.cross', (['u', 'w'], {}), '(u, w)\n', (25400, 25406), True, 'import numpy as np\n'), ((25437, 25451), 'numpy.cross', 'np.cross', (['w', 'v'], {}), '(w, v)\n', (25445, 25451), True, 'import numpy as np\n'), ((28685, 28708), 'vtk.vtkPropCollection', 'vtk.vtkPropCollection', ([], {}), '()\n', (28706, 28708), False, 'import vtk\n'), ((29188, 29206), 'vtk.vtkTransform', 'vtk.vtkTransform', ([], {}), '()\n', (29204, 29206), False, 'import vtk\n'), ((29251, 29283), 'vtk.vtkTransformPolyDataFilter', 'vtk.vtkTransformPolyDataFilter', ([], {}), '()\n', (29281, 29283), False, 'import vtk\n'), ((30887, 30906), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (30895, 30906), True, 'import numpy as np\n'), ((31512, 31524), 'numpy.sum', 'np.sum', (['xyz2'], {}), '(xyz2)\n', (31518, 31524), True, 'import numpy as np\n'), ((32546, 32567), 'vtk.vtkPointLocator', 'vtk.vtkPointLocator', ([], {}), '()\n', (32565, 32567), False, 'import vtk\n'), ((33306, 33320), 'numpy.array', 'np.array', (['trgp'], {}), '(trgp)\n', (33314, 33320), True, 'import numpy as np\n'), ((42099, 42131), 'vtk.vtkLinearSubdivisionFilter', 'vtk.vtkLinearSubdivisionFilter', ([], {}), '()\n', (42129, 42131), False, 'import vtk\n'), ((4306, 4322), 'vtk.vtkVersion', 'vtk.vtkVersion', ([], {}), '()\n', (4320, 4322), False, 'import vtk\n'), ((6118, 6144), 'vtk.vtkTextureMapToPlane', 'vtk.vtkTextureMapToPlane', ([], {}), '()\n', (6142, 6144), False, 'import vtk\n'), ((10877, 10895), 'vtkplotter.colors.getColor', 'colors.getColor', (['c'], {}), '(c)\n', (10892, 10895), True, 'import vtkplotter.colors as colors\n'), ((17968, 17980), 'numpy.sum', 'np.sum', (['xyz2'], {}), '(xyz2)\n', (17974, 17980), True, 'import numpy as np\n'), ((19087, 19107), 'numpy.array', 'np.array', (['axis_point'], {}), '(axis_point)\n', (19095, 19107), True, 'import numpy as np\n'), ((21355, 21370), 'numpy.arccos', 'np.arccos', (['cosa'], {}), '(cosa)\n', (21364, 21370), True, 'import numpy as np\n'), ((40285, 40320), 'vtk.vtkPolyDataConnectivityFilter', 'vtk.vtkPolyDataConnectivityFilter', ([], {}), '()\n', (40318, 40320), False, 'import vtk\n'), ((40480, 40502), 'vtk.vtkCleanPolyData', 'vtk.vtkCleanPolyData', ([], {}), '()\n', (40500, 40502), False, 'import vtk\n'), ((40593, 40616), 'vtk.vtkPolyDataWriter', 'vtk.vtkPolyDataWriter', ([], {}), '()\n', (40614, 40616), False, 'import vtk\n'), ((40730, 40777), 'vtkplotter.colors.printc', 'colors.printc', (["('Saved file: ' + outputname)", '"""g"""'], {}), "('Saved file: ' + outputname, 'g')\n", (40743, 40777), True, 'import vtkplotter.colors as colors\n'), ((42158, 42192), 'vtk.vtkAdaptiveSubdivisionFilter', 'vtk.vtkAdaptiveSubdivisionFilter', ([], {}), '()\n', (42190, 42192), False, 'import vtk\n'), ((26387, 26400), 'numpy.abs', 'np.abs', (['(e - 1)'], {}), '(e - 1)\n', (26393, 26400), True, 'import numpy as np\n'), ((26436, 26445), 'numpy.abs', 'np.abs', (['e'], {}), '(e)\n', (26442, 26445), True, 'import numpy as np\n'), ((42219, 42254), 'vtk.vtkButterflySubdivisionFilter', 'vtk.vtkButterflySubdivisionFilter', ([], {}), '()\n', (42252, 42254), False, 'import vtk\n'), ((42273, 42330), 'vtkplotter.colors.printc', 'colors.printc', (['"""Error in subdivide: unknown method."""', '"""r"""'], {}), "('Error in subdivide: unknown method.', 'r')\n", (42286, 42330), True, 'import vtkplotter.colors as colors\n')]
from bs4 import BeautifulSoup import requests import pandas as pd import numpy as np import csv import tmdbsimple as tmdb import time import numpy as np import datetime import copy from unidecode import unidecode import calendar from ast import literal_eval from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from sklearn.metrics.pairwise import linear_kernel, cosine_similarity from nltk.stem.snowball import SnowballStemmer from nltk.stem.wordnet import WordNetLemmatizer from nltk.corpus import wordnet from surprise import Reader, Dataset, SVD, evaluate # import sys # from importlib import reload # reload(sys) # sys.setdefaultencoding('utf8') tmdb.API_KEY = 'API_KEY' path_src = '../the-movies-dataset/' path_dest = '../cinema-dataset/' final_list_recent_movies = [] def get_tmdb_info(title, original_year): search = tmdb.Search() response = search.movie(query=str(title)) for res in search.results: year = res['release_date'].split('-')[0] if str(year) == str(original_year): print(title) m = tmdb.Movies(res['id']) credits = m.credits() keywords = m.keywords() overview = ''.join([i if ord(i) < 128 else '~' for i in res['overview']]) cast = ''.join([i if ord(i) < 128 else '~' for i in str(credits['cast'][:5])]) crew = ''.join([i if ord(i) < 128 else '~' for i in str(credits['crew'][:5])]) title = ''.join([i if ord(i) < 128 else '~' for i in res['title']]) year = str(res['release_date']).split('-')[0] res = m.info() film = {'auseless':0, 'budget':res['budget'], 'genres':res['genres'], 'id': res['id'], 'imdb_id': res['imdb_id'], 'overview':overview, 'popularity':res['popularity'], 'poster_path':res['poster_path'], 'revenue':res['revenue'], 'runtime':res['runtime'],'title':title, 'vote_average':res['vote_average'], 'vote_count':res['vote_count'], 'year':year} links_csv = pd.read_csv(path_dest + 'links.csv') id_already_done = links_csv['tmdbId'].values for i in id_already_done: if int(str(res['id'])) == int(i): print("already in links") return title last_row_links = links_csv.tail(1) free_movieId = int(last_row_links['movieId'].values)+1 with open(path_dest + 'metadata.csv', 'a') as csvfile: fieldnames = list(film.keys()) fieldnames.sort() writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writerow(film) with open(path_dest + 'credits.csv', 'a') as csvfile: fieldnames = ['useless', 'cast','crew','id'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writerow({'useless':0, 'cast':cast, 'crew':crew, 'id':res['id']}) with open(path_dest + 'keywords.csv', 'a') as csvfile: fieldnames = ['useless', 'id', 'keywords'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writerow({'useless':0, 'id':res['id'], 'keywords':keywords['keywords']}) with open(path_dest + 'links.csv', 'a') as csvfile: fieldnames = ['useless', 'movieId', 'imdbId', 'tmdbId'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writerow({'useless':0, 'movieId':free_movieId, 'imdbId':str(res['imdb_id'])[2:], 'tmdbId':str(res['id'])+'.0'}) print("done") time.sleep(1) return title global_md, global_links, global_credits, global_keywords, global_cosine_sim, global_inverse_indices, global_indices_map, global_indices_map_for_tmdb, global_smd = None, None, None, None, None, None, None, None, None def get_global_md(): return global_md def get_global_links(): return global_links def get_global_credits(): return global_credits def get_global_keywords(): return global_keywords def get_global_cosine_sim(): return global_cosine_sim def get_global_inverse_indices(): return global_inverse_indices def get_global_indices_map(): return global_indices_map def get_global_indices_map_for_tmdb(): return global_indices_map_for_tmdb def get_global_smd(): return global_smd def load_everything(): md = pd.read_csv(path_dest + 'metadata.csv') links = pd.read_csv(path_dest + 'links.csv') credits = pd.read_csv(path_dest + 'credits.csv') keywords = pd.read_csv(path_dest + 'keywords.csv') del md['useless'] del links['useless'] del credits['useless'] del keywords['useless'] md['genres'] = md['genres'].fillna('[]').apply(literal_eval).apply(lambda x: [i['name'] for i in x] if isinstance(x, list) else []) md['popularity'] = md['popularity'].fillna('[]').apply(lambda x: [str(int(x))] if isinstance(x, float) or isinstance(x, int) else []) links = links[links['tmdbId'].notnull()]['tmdbId'].astype('int') md['id'] = md['id'].astype('int') smd = md[md['id'].isin(links)] keywords['id'] = keywords['id'].astype('int') credits['id'] = credits['id'].astype('int') md['id'] = md['id'].astype('int') md = md.merge(credits, on='id') md = md.merge(keywords, on='id') smd = md[md['id'].isin(links)] smd['cast'] = smd['cast'].apply(literal_eval) smd['crew'] = smd['crew'].apply(literal_eval) smd['keywords'] = smd['keywords'].apply(literal_eval) def get_director(x): for i in x: if i['job'] == 'Director': return i['name'] return np.nan indices = pd.Series(smd.index, index=smd['title']) smd['keywords'] = smd['keywords'].apply(lambda x: [i['name'] for i in x] if isinstance(x, list) else []) smd['cast'] = smd['cast'].apply(lambda x: [i['name'] for i in x] if isinstance(x, list) else []) smd['cast'] = smd['cast'].apply(lambda x: x[:3] if len(x) >=3 else x) smd['cast'] = smd['cast'].apply(lambda x: [str.lower(i.replace(" ", "")) for i in x]) smd['director'] = smd['crew'].apply(get_director) smd['director'] = smd['director'].astype('str').apply(lambda x: str.lower(x.replace(" ", ""))) smd['director'] = smd['director'].apply(lambda x: [x,x,x]) s = smd.apply(lambda x: pd.Series(x['keywords']),axis=1).stack().reset_index(level=1, drop=True) s.name = 'keyword' s = s.value_counts() s = s[s > 1] stemmer = SnowballStemmer('english') stemmer.stem('dogs') def filter_keywords(x): words = [] for i in x: if i in s: words.append(i) return words smd['keywords'] = smd['keywords'].apply(filter_keywords) smd['keywords'] = smd['keywords'].apply(lambda x: [stemmer.stem(i) for i in x]) smd['keywords'] = smd['keywords'].apply(lambda x: [str.lower(i.replace(" ", "")) for i in x]) smd['soup'] = smd['keywords'] + smd['cast'] + smd['director'] + smd['genres'] + smd['popularity'] # + smd['year'] smd['soup'] = smd['soup'].apply(lambda x: ' '.join(x)) count = CountVectorizer(analyzer='word', ngram_range=(1, 2), min_df=0, stop_words='english') count_matrix = count.fit_transform(smd['soup']) cosine_sim = cosine_similarity(count_matrix, count_matrix) smd = smd.reset_index() titles = smd['title'] indices = pd.Series(smd.index, index=smd['title']) inverse_indices = pd.Series(smd['title'], index=smd.index) def convert_int(x): try: return int(x) except: return np.nan id_map = pd.read_csv(path_dest + 'links.csv')[['movieId', 'tmdbId']] id_map['tmdbId'] = id_map['tmdbId'].apply(convert_int) id_map.columns = ['movieId', 'id'] id_map = id_map.merge(smd[['title', 'id']], on='id').set_index('title') indices_map = id_map.set_index('id') indices_map_for_tmdb = id_map.set_index('movieId') global global_md, global_links, global_credits, global_keywords, global_cosine_sim, global_inverse_indices, global_indices_map, global_indices_map_for_tmdb, global_smd global_md = copy.deepcopy(md) links = pd.read_csv(path_dest + 'links.csv') global_links = copy.deepcopy(links) global_credits = copy.deepcopy(credits) global_keywords = copy.deepcopy(keywords) global_cosine_sim = copy.deepcopy(cosine_sim) global_inverse_indices = copy.deepcopy(inverse_indices) global_indices_map = copy.deepcopy(indices_map) global_indices_map_for_tmdb = copy.deepcopy(indices_map_for_tmdb) global_smd = copy.deepcopy(smd) def get_recent_movies(): while True: global final_list_recent_movies final_list_recent_movies = [] # if False: # from shutil import copyfile # copyfile(path_src + 'pop_new_metadata.csv', path_dest + 'metadata.csv') # copyfile(path_src + 'pop_new_links.csv', path_dest + 'links.csv') # copyfile(path_src + 'credits.csv', path_dest + 'credits.csv') # copyfile(path_src + 'keywords.csv', path_dest + 'keywords.csv') now = datetime.datetime.now() year = now.year month = now.month if month - 2 < 1: month = 12 - (month - 2) year -= 1 else: month -= 2 data_finish = str(now.year)+"-"+str(now.month).zfill(2)+"-30" # 2017-01-01 data_start = str(year)+"-"+str(month).zfill(2)+"-1" url = "https://www.imdb.com/search/title?release_date=" + str(data_start) + "," + str(data_finish) + "&languages=en&sort=num_votes,desc&page=" for number_page in range(1, 4): print("PAGE: " + str(number_page)) url_num = url + str(number_page) req = requests.get(url_num) data = req.text data = ''.join([i if ord(i) < 128 else '~' for i in data]) soup = BeautifulSoup(data,"html.parser") for movie in soup.findAll('div', {'class':'lister-item mode-advanced'}): imdb_rate = float(movie.find('div', {'class':'inline-block ratings-imdb-rating'}).get('data-value')) metascore = movie.find('div', {'class':'inline-block ratings-metascore'}) if not metascore: continue metascore = int(str(metascore.text[:3])) if float(metascore/10) + imdb_rate < 12.0: continue a = movie.find('div', {'class':"lister-item-content"}).find('h3',{'class':"lister-item-header"}).find('a') imdb_link = "https://www.imdb.com" + '/'.join(str(a.get('href')).split('/')[:-1]) italian_title = a.text year = movie.find('div', {'class':"lister-item-content"}).find('h3',{'class':"lister-item-header"}).find('span', {'class':'lister-item-year text-muted unbold'}).text year = str(year)[1:5] req_info = requests.get(imdb_link + "/releaseinfo") data_info = req_info.text data_info = ''.join([i if ord(i) < 128 else '~' for i in data_info]) soup_info = BeautifulSoup(data_info,"html.parser") names = soup_info.find('table', {'class':'subpage_data spEven2Col', 'id':'akas'}) if not names: continue original_name = str(italian_title) names = names.text.split('\n\n') name_found = False for n in names: if len(n.split('\n')) != 2: continue state, name = n.split('\n') if state == "UK" or state == "USA": name_found = True original_name = name break if not name_found: for n in names: if len(n.split('\n')) != 2: continue state, name = n.split('\n') if state == "(original title)": original_name = name break if '~' in str(original_name): continue release_date_italy = soup_info.find('table', {'class':'subpage_data spFirst', 'id':'release_dates'}) release_date_found = None for n in release_date_italy.text.split('\n\n'): if len(n.split('\n')) != 2: continue state, release_date = n.split('\n') if state == "Italy": release_date_found = release_date break available = True if release_date_found: now = datetime.datetime.now() release_date_found_days, release_date_found_month, release_date_found_year = release_date_found.split(' ') if int(release_date_found_year) > int(now.year): available = False for month_idx in range(1, 13): if str(calendar.month_name[month_idx]) == release_date_found_month: if int(month_idx) > int(now.month): available = False break if int(month_idx) == int(now.month) and int(release_date_found_days) > int(now.day): available = False break md = pd.read_csv(path_dest + 'metadata.csv') title_already_done = md['title'].values if str(original_name) in title_already_done and original_name != None: if available: final_list_recent_movies.append([str(original_name), ""]) else: ry, rm, ra = release_date_found.split(' ') final_list_recent_movies.append([str(original_name), ' '.join([ry, rm[:3], ra])]) print(original_name + " already done") continue title_found = get_tmdb_info(original_name, year) if title_found != None: if available: final_list_recent_movies.append([str(original_name), ""]) else: ry, rm, ra = release_date_found.split(' ') final_list_recent_movies.append([str(original_name), ' '.join([ry, rm[:3], ra])]) load_everything() print("ready") time.sleep(int(np.random.randint(172800)+300)) from threading import Thread Thread(target=get_recent_movies).start() def get_all_cinema_movies(): return final_list_recent_movies def final_cinema_movies(userId): global final_list_recent_movies global global_cosine_sim, global_inverse_indices, global_indices_map, global_indices_map_for_tmdb, global_smd ratings = pd.read_csv(path_src + 'pop_new_ratings.csv') del ratings['useless'] from hybrid import get_svd svd = get_svd() print("cinema for " + str(userId)) def hybrid_recommandation(userId, title, svd): idx = 0 for i, t in enumerate(global_inverse_indices.values): if t == title: idx = i break sim_scores = list(enumerate(global_cosine_sim[int(idx)])) sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True) sim_scores = sim_scores[1:10] movie_indices = [i[0] for i in sim_scores] movies = global_smd.iloc[movie_indices][['title','id']] def pred(x): try: return svd.predict(userId, global_indices_map.loc[x]['movieId']).est except: return 0 movies['recommanded'] = movies['id'].apply(pred) movies = movies.sort_values('recommanded', ascending=False) total_predict = 0 for i in movies['recommanded'].values: total_predict += float(i) return total_predict dict_rank_movies = {} for m, available in final_list_recent_movies: total_predict = hybrid_recommandation(userId, m, svd) if available == "": dict_rank_movies[str(m)] = total_predict else: dict_rank_movies[str(m) + " [" + str(available) + "]"] = total_predict best_movie_sorted = sorted(dict_rank_movies.items(), key=lambda x: x[1], reverse=True) element_to_take = [] count_not_exit_yet = 0 count_exit_yet = 0 for i, (title, predict) in enumerate(best_movie_sorted): if count_exit_yet >= 2: break if ("2018]" in str(title) or "2019]" in str(title)) and count_not_exit_yet < 3: count_not_exit_yet += 1 element_to_take.append((title, predict)) elif "2018]" not in str(title) and "2019]" not in str(title): count_exit_yet += 1 element_to_take.append((title, predict)) try: print(element_to_take) except: pass return element_to_take
[ "pandas.Series", "hybrid.get_svd", "csv.DictWriter", "sklearn.metrics.pairwise.cosine_similarity", "pandas.read_csv", "sklearn.feature_extraction.text.CountVectorizer", "time.sleep", "requests.get", "bs4.BeautifulSoup", "nltk.stem.snowball.SnowballStemmer", "tmdbsimple.Search", "datetime.datet...
[((860, 873), 'tmdbsimple.Search', 'tmdb.Search', ([], {}), '()\n', (871, 873), True, 'import tmdbsimple as tmdb\n'), ((4518, 4557), 'pandas.read_csv', 'pd.read_csv', (["(path_dest + 'metadata.csv')"], {}), "(path_dest + 'metadata.csv')\n", (4529, 4557), True, 'import pandas as pd\n'), ((4570, 4606), 'pandas.read_csv', 'pd.read_csv', (["(path_dest + 'links.csv')"], {}), "(path_dest + 'links.csv')\n", (4581, 4606), True, 'import pandas as pd\n'), ((4621, 4659), 'pandas.read_csv', 'pd.read_csv', (["(path_dest + 'credits.csv')"], {}), "(path_dest + 'credits.csv')\n", (4632, 4659), True, 'import pandas as pd\n'), ((4675, 4714), 'pandas.read_csv', 'pd.read_csv', (["(path_dest + 'keywords.csv')"], {}), "(path_dest + 'keywords.csv')\n", (4686, 4714), True, 'import pandas as pd\n'), ((5795, 5835), 'pandas.Series', 'pd.Series', (['smd.index'], {'index': "smd['title']"}), "(smd.index, index=smd['title'])\n", (5804, 5835), True, 'import pandas as pd\n'), ((6607, 6633), 'nltk.stem.snowball.SnowballStemmer', 'SnowballStemmer', (['"""english"""'], {}), "('english')\n", (6622, 6633), False, 'from nltk.stem.snowball import SnowballStemmer\n'), ((7239, 7328), 'sklearn.feature_extraction.text.CountVectorizer', 'CountVectorizer', ([], {'analyzer': '"""word"""', 'ngram_range': '(1, 2)', 'min_df': '(0)', 'stop_words': '"""english"""'}), "(analyzer='word', ngram_range=(1, 2), min_df=0, stop_words=\n 'english')\n", (7254, 7328), False, 'from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\n'), ((7394, 7439), 'sklearn.metrics.pairwise.cosine_similarity', 'cosine_similarity', (['count_matrix', 'count_matrix'], {}), '(count_matrix, count_matrix)\n', (7411, 7439), False, 'from sklearn.metrics.pairwise import linear_kernel, cosine_similarity\n'), ((7509, 7549), 'pandas.Series', 'pd.Series', (['smd.index'], {'index': "smd['title']"}), "(smd.index, index=smd['title'])\n", (7518, 7549), True, 'import pandas as pd\n'), ((7572, 7612), 'pandas.Series', 'pd.Series', (["smd['title']"], {'index': 'smd.index'}), "(smd['title'], index=smd.index)\n", (7581, 7612), True, 'import pandas as pd\n'), ((8252, 8269), 'copy.deepcopy', 'copy.deepcopy', (['md'], {}), '(md)\n', (8265, 8269), False, 'import copy\n'), ((8282, 8318), 'pandas.read_csv', 'pd.read_csv', (["(path_dest + 'links.csv')"], {}), "(path_dest + 'links.csv')\n", (8293, 8318), True, 'import pandas as pd\n'), ((8338, 8358), 'copy.deepcopy', 'copy.deepcopy', (['links'], {}), '(links)\n', (8351, 8358), False, 'import copy\n'), ((8380, 8402), 'copy.deepcopy', 'copy.deepcopy', (['credits'], {}), '(credits)\n', (8393, 8402), False, 'import copy\n'), ((8425, 8448), 'copy.deepcopy', 'copy.deepcopy', (['keywords'], {}), '(keywords)\n', (8438, 8448), False, 'import copy\n'), ((8473, 8498), 'copy.deepcopy', 'copy.deepcopy', (['cosine_sim'], {}), '(cosine_sim)\n', (8486, 8498), False, 'import copy\n'), ((8528, 8558), 'copy.deepcopy', 'copy.deepcopy', (['inverse_indices'], {}), '(inverse_indices)\n', (8541, 8558), False, 'import copy\n'), ((8584, 8610), 'copy.deepcopy', 'copy.deepcopy', (['indices_map'], {}), '(indices_map)\n', (8597, 8610), False, 'import copy\n'), ((8645, 8680), 'copy.deepcopy', 'copy.deepcopy', (['indices_map_for_tmdb'], {}), '(indices_map_for_tmdb)\n', (8658, 8680), False, 'import copy\n'), ((8698, 8716), 'copy.deepcopy', 'copy.deepcopy', (['smd'], {}), '(smd)\n', (8711, 8716), False, 'import copy\n'), ((15215, 15260), 'pandas.read_csv', 'pd.read_csv', (["(path_src + 'pop_new_ratings.csv')"], {}), "(path_src + 'pop_new_ratings.csv')\n", (15226, 15260), True, 'import pandas as pd\n'), ((15329, 15338), 'hybrid.get_svd', 'get_svd', ([], {}), '()\n', (15336, 15338), False, 'from hybrid import get_svd\n'), ((7732, 7768), 'pandas.read_csv', 'pd.read_csv', (["(path_dest + 'links.csv')"], {}), "(path_dest + 'links.csv')\n", (7743, 7768), True, 'import pandas as pd\n'), ((9215, 9238), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (9236, 9238), False, 'import datetime\n'), ((14860, 14892), 'threading.Thread', 'Thread', ([], {'target': 'get_recent_movies'}), '(target=get_recent_movies)\n', (14866, 14892), False, 'from threading import Thread\n'), ((1087, 1109), 'tmdbsimple.Movies', 'tmdb.Movies', (["res['id']"], {}), "(res['id'])\n", (1098, 1109), True, 'import tmdbsimple as tmdb\n'), ((2062, 2098), 'pandas.read_csv', 'pd.read_csv', (["(path_dest + 'links.csv')"], {}), "(path_dest + 'links.csv')\n", (2073, 2098), True, 'import pandas as pd\n'), ((3724, 3737), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (3734, 3737), False, 'import time\n'), ((9857, 9878), 'requests.get', 'requests.get', (['url_num'], {}), '(url_num)\n', (9869, 9878), False, 'import requests\n'), ((9997, 10031), 'bs4.BeautifulSoup', 'BeautifulSoup', (['data', '"""html.parser"""'], {}), "(data, 'html.parser')\n", (10010, 10031), False, 'from bs4 import BeautifulSoup\n'), ((2636, 2682), 'csv.DictWriter', 'csv.DictWriter', (['csvfile'], {'fieldnames': 'fieldnames'}), '(csvfile, fieldnames=fieldnames)\n', (2650, 2682), False, 'import csv\n'), ((2874, 2920), 'csv.DictWriter', 'csv.DictWriter', (['csvfile'], {'fieldnames': 'fieldnames'}), '(csvfile, fieldnames=fieldnames)\n', (2888, 2920), False, 'import csv\n'), ((3174, 3220), 'csv.DictWriter', 'csv.DictWriter', (['csvfile'], {'fieldnames': 'fieldnames'}), '(csvfile, fieldnames=fieldnames)\n', (3188, 3220), False, 'import csv\n'), ((3491, 3537), 'csv.DictWriter', 'csv.DictWriter', (['csvfile'], {'fieldnames': 'fieldnames'}), '(csvfile, fieldnames=fieldnames)\n', (3505, 3537), False, 'import csv\n'), ((11039, 11079), 'requests.get', 'requests.get', (["(imdb_link + '/releaseinfo')"], {}), "(imdb_link + '/releaseinfo')\n", (11051, 11079), False, 'import requests\n'), ((11235, 11274), 'bs4.BeautifulSoup', 'BeautifulSoup', (['data_info', '"""html.parser"""'], {}), "(data_info, 'html.parser')\n", (11248, 11274), False, 'from bs4 import BeautifulSoup\n'), ((13712, 13751), 'pandas.read_csv', 'pd.read_csv', (["(path_dest + 'metadata.csv')"], {}), "(path_dest + 'metadata.csv')\n", (13723, 13751), True, 'import pandas as pd\n'), ((12932, 12955), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (12953, 12955), False, 'import datetime\n'), ((14793, 14818), 'numpy.random.randint', 'np.random.randint', (['(172800)'], {}), '(172800)\n', (14810, 14818), True, 'import numpy as np\n'), ((6455, 6479), 'pandas.Series', 'pd.Series', (["x['keywords']"], {}), "(x['keywords'])\n", (6464, 6479), True, 'import pandas as pd\n')]
import scipy.stats as st import numpy as np def getchannel(emplacement = 'trunku',intersection = 1): """ get channel Parameters ---------- emplacement : 'trunku' | 'thighr' | 'forearm' | 'calfr' intersection : 1 = LOS 0 : NLOS Returns ------- alphak : np.array tauk : np.array Notes ----- See : "Delay Dispersion of the On-Body Channel" (<NAME>, <NAME>) """ pdp = {'trunku':{'los':{'gamma':25.9,'gamma0':3.37,'k':26,'lambda-1':2.13,'sigma':4.02}, 'trans':{'gamma':'none','gamma0':'none','k':'none','lambda-1':'none','sigma':'none'}, 'nlos':{'gamma':'none','gamma0':'none','k':'none','lambda-1':'none','sigma':'none'}}, 'thighr':{'los':{'gamma':24.9,'gamma0':2.1,'k':7,'lambda-1':3.13,'sigma':4.62}, 'trans':{'gamma':46.7,'gamma0':1.6,'k':19,'lambda-1':2.46,'sigma':4.58}, 'nlos':{'gamma':58.9,'gamma0':1.6,'k':30,'lambda-1':2.35,'sigma':4.32}}, 'forearmr':{'los':{'gamma':22.3,'gamma0':2.3,'k':5,'lambda-1':2.27,'sigma':4.55}, 'trans':{'gamma':45.5,'gamma0':2.7,'k':13,'lambda-1':2.69,'sigma':4.28}, 'nlos':{'gamma':63,'gamma0':2.5,'k':27,'lambda-1':2.39,'sigma':4.31}}, 'calfr':{'los':{'gamma':29,'gamma0':3.3,'k':10,'lambda-1':2.98,'sigma':4.57}, 'trans':{'gamma':40.5,'gamma0':2.2,'k':23,'lambda-1':2.37,'sigma':4.61}, 'nlos':{'gamma':55,'gamma0':1.4,'k':32,'lambda-1':2.21,'sigma':4.65}} } g0 = {'trunku':{'mu0':-52.62,'sigma0':4.35}, 'thighr':{'mu0':-63.30,'sigma0':2.31}, 'forearmr':{'mu0':-59.96,'sigma0':3.28}, 'calfr':{'mu0':-62.93,'sigma0':1.69}, } condition = 'nlos' if intersection == 1: condition = 'los' if emplacement == 'trunku': condition = 'los' #number of paths K = pdp[emplacement][condition]['k'] #delay Lambda = 1./pdp[emplacement][condition]['lambda-1'] Tk = st.expon(0,Lambda) sampleTk = Tk.rvs(K) tauk = np.cumsum(sampleTk) #exponential decay gamma = pdp[emplacement][condition]['gamma'] #rician factor gamma0 = pdp[emplacement][condition]['gamma0'] #path amplitude alpha_k_dB_m = gamma0 + 10*np.log10(np.exp(-tauk)/gamma) sigmas = pdp[emplacement][condition]['sigma'] alpha_k_dB = st.norm(alpha_k_dB_m,sigmas) alphak = 10**(alpha_k_dB.rvs(size = len(tauk))/10) alphak = alphak/np.sqrt(sum(abs(alphak)**2)) # mean channel gain mu0 = g0[emplacement]['mu0']-5 sigma0 = g0[emplacement]['sigma0'] GdB_dist = st.norm(mu0,sigma0) GdB = GdB_dist.rvs() G = 10**(GdB/10.0) alphak = np.sqrt(G)*alphak alphak = intersection*alphak return alphak,tauk
[ "numpy.sqrt", "scipy.stats.norm", "numpy.exp", "scipy.stats.expon", "numpy.cumsum" ]
[((1997, 2016), 'scipy.stats.expon', 'st.expon', (['(0)', 'Lambda'], {}), '(0, Lambda)\n', (2005, 2016), True, 'import scipy.stats as st\n'), ((2052, 2071), 'numpy.cumsum', 'np.cumsum', (['sampleTk'], {}), '(sampleTk)\n', (2061, 2071), True, 'import numpy as np\n'), ((2367, 2396), 'scipy.stats.norm', 'st.norm', (['alpha_k_dB_m', 'sigmas'], {}), '(alpha_k_dB_m, sigmas)\n', (2374, 2396), True, 'import scipy.stats as st\n'), ((2615, 2635), 'scipy.stats.norm', 'st.norm', (['mu0', 'sigma0'], {}), '(mu0, sigma0)\n', (2622, 2635), True, 'import scipy.stats as st\n'), ((2696, 2706), 'numpy.sqrt', 'np.sqrt', (['G'], {}), '(G)\n', (2703, 2706), True, 'import numpy as np\n'), ((2278, 2291), 'numpy.exp', 'np.exp', (['(-tauk)'], {}), '(-tauk)\n', (2284, 2291), True, 'import numpy as np\n')]
import math import cv2 import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg def grayscale(img): """Applies the Grayscale transform This will return an image with only one color channel but NOTE: to see the returned image as grayscale (assuming your grayscaled image is called 'gray') you should call plt.imshow(gray, cmap='gray')""" return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # Or use BGR2GRAY if you read an image with cv2.imread() # return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) def canny(img, low_threshold, high_threshold): """Applies the Canny transform""" return cv2.Canny(img, low_threshold, high_threshold) def gaussian_blur(img, kernel_size): """Applies a Gaussian Noise kernel""" return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0) def region_of_interest(img, vertices): """ Applies an image mask. Only keeps the region of the image defined by the polygon formed from `vertices`. The rest of the image is set to black. `vertices` should be a numpy array of integer points. """ #defining a blank mask to start with mask = np.zeros_like(img) #defining a 3 channel or 1 channel color to fill the mask with depending on the input image if len(img.shape) > 2: channel_count = img.shape[2] # i.e. 3 or 4 depending on your image ignore_mask_color = (255,) * channel_count else: ignore_mask_color = 255 #filling pixels inside the polygon defined by "vertices" with the fill color cv2.fillPoly(mask, vertices, ignore_mask_color) #returning the image only where mask pixels are nonzero masked_image = cv2.bitwise_and(img, mask) return masked_image #---------------------------------------------------- def draw_lines_orig(img, lines, color=[255, 0, 0], thickness=2): """ Separate line segments by their slope ((y2-y1)/(x2-x1)). Use the slope-intercept form to extrapolate the line. This function draws `lines` with `color` and `thickness`. Lines are drawn on the image inplace (mutates the image). """ for line in lines: for x1,y1,x2,y2 in line: cv2.line(img, (x1, y1), (x2, y2), color, thickness) def hough_lines_orig(img, rho, theta, threshold, min_line_len, max_line_gap): """ `img` should be the output of a Canny transform. Returns an image with hough lines drawn alongwith the lines array. """ lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap) line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8) draw_lines_orig(line_img, lines) return line_img #---------------------------------------------------- def draw_lines(img, lines, color=[255, 0, 0], thickness=2): """Separate line segments by their slope ((y2-y1)/(x2-x1)). Use the slope-intercept form to extrapolate the line. This function draws `lines` with `color` and `thickness`. Lines are drawn on the image inplace (mutates the image). It may happen that only left-lane or right-lane is drawn depending on detection. """ left_lane, right_lane = seggregate_and_average_lane_lines(lines) extrapolated_lines = [] if left_lane.size != 1: # Make sure left_lane is not 'nan' left_line = extrapolate_lines(img.shape, left_lane) extrapolated_lines.append([left_line]) if right_lane.size != 1: # Make sure left_lane is not 'nan' right_line = extrapolate_lines(img.shape, right_lane) extrapolated_lines.append([right_line]) for line in extrapolated_lines: for x1,y1,x2,y2 in line: cv2.line(img, (x1, y1), (x2, y2), color, thickness) def hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap): """ `img` should be the output of a Canny transform. Returns an image with hough lines drawn alongwith the lines array. """ lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap) line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8) draw_lines(line_img, lines, thickness=6) return line_img def weighted_img(img, initial_img, α=0.8, β=1., γ=0.): """ `img` is the output of the hough_lines(), An image with lines drawn on it. Should be a blank image (all black) with lines drawn on it. `initial_img` should be the image before any processing. The result image is computed as follows: initial_img * α + img * β + γ NOTE: initial_img and img must be the same shape! """ return cv2.addWeighted(initial_img, α, img, β, γ) def seggregate_and_average_lane_lines(lines): """ Separate line segments by their slope ((y2-y1)/(x2-x1)). Slope < 0 => left-lane Slope > 0 => left-lane Return the Average for left and right lane """ left_lane = [] right_lane = [] for line in lines: for x1,y1,x2,y2 in line: # Fit the coordinates into degree 1 polynomial for getting slope and intercept slope, intercept = np.polyfit((x1, x2), (y1, y2), 1) # Only lines within a certain slope qualify as lane-lines if slope < -0.5 and slope > -0.9: left_lane.append((slope, intercept)) if slope < 0.9 and slope > 0.5: right_lane.append((slope, intercept)) return np.average(left_lane, axis = 0), np.average(right_lane, axis = 0) def extrapolate_lines(image_shape, line): """Use slope-intercept form for extrapolating the line. We draw from bottom of the image to 3/5th of the image height (the same height we chose for region of interest). Output of this function is the set of two coordinate points indicating the end-points of the extrapolated-line to be drawn. """ slope, intercept = line y1 = image_shape[0] y2 = int(y1 * (3 / 5)) x1 = int((y1 - intercept) / slope) x2 = int((y2 - intercept) / slope) return np.array([x1, y1, x2, y2]) def display_imgs(img_list, labels=[], cols=2, fig_size=(15,15)): """ Helper function to display images in a grid form """ if len(labels) > 0: # If label is provided, it must be provided for all images assert(len(img_list) == len(labels)) # At lieast one image must be provided assert(len(img_list) > 0) cmap = None # All single dimenson images must be displayed in 'gray' rows = math.ceil(len(img_list) / cols) plt.figure(figsize=fig_size) for i in range(len(img_list)): plt.subplot(rows, cols, i+1) if len(img_list[i].shape) == 2: cmap = 'gray' if len(labels) > 0: plt.title(labels[i]) plt.imshow(img_list[i], cmap=cmap) plt.tight_layout() plt.show() def to_hls(img): return cv2.cvtColor(img, cv2.COLOR_RGB2HLS) def process_image(image): """Process a colored image to detect the lane markings Input: Color (RGB) Image Output: Input image overlaid with lane markings """ # Step 1: Image Pre-processing to highlight lane markings # Convert to grayscale gsimg = grayscale(image) # Convert to HLS, isolate Yellow and White Color hlsimg = to_hls(image) white_mask = cv2.inRange(hlsimg, np.array([0, 200, 0], dtype=np.uint8), np.array([200, 255, 255], dtype=np.uint8)) yellow_mask = cv2.inRange(hlsimg, np.array([10, 0, 100], dtype=np.uint8), np.array([40, 255, 255], dtype=np.uint8)) yw_mask = cv2.bitwise_or(white_mask, yellow_mask) # Use the yellow-white mask to highlight the lane markings yw_masked_image = cv2.bitwise_and(gsimg, gsimg, mask=yw_mask) # Remove the noise in the image with a 5x5 Gaussian filter blurred_img = gaussian_blur(yw_masked_image, 5) # Step 2: Apply Canny Edge Detection cimg = canny(blurred_img, 50, 150) # Mask everything except the region of interest # As the markings are always in front, we only need to look at specific area in image. rows = image.shape[0] cols = image.shape[1] left_bottom = [cols * 0.1, rows] right_bottom = [cols * 0.95, rows] left_top = [cols * 0.4, rows * 0.6] right_top = [cols * 0.6, rows * 0.6] vertices = np.array([[left_bottom, left_top, right_top, right_bottom]], dtype=np.int32) roi_image = region_of_interest(cimg, vertices) # Step 3: Apply Hough Transform to extract line coordinates, and # extrapolate them to draw lane markings rho = 2 # distance resolution in pixels of the Hough grid theta = np.pi/180 # angular resolution in radians of the Hough grid threshold = 15 # minimum number of votes (intersections in Hough grid cell) min_line_len = 20 # minimum number of pixels making up a line max_line_gap = 20 # maximum gap in pixels between connectable line segments line_img = hough_lines(roi_image, rho, theta, threshold, min_line_len, max_line_gap) # Merge the original image with the lane-marking image annotated_image = weighted_img(line_img, image, α=0.7, β=1., γ=0.) return annotated_image
[ "numpy.polyfit", "numpy.array", "cv2.bitwise_or", "matplotlib.pyplot.imshow", "cv2.line", "numpy.zeros_like", "cv2.addWeighted", "cv2.fillPoly", "numpy.average", "cv2.cvtColor", "matplotlib.pyplot.title", "cv2.Canny", "cv2.GaussianBlur", "matplotlib.pyplot.show", "cv2.bitwise_and", "nu...
[((396, 433), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_RGB2GRAY'], {}), '(img, cv2.COLOR_RGB2GRAY)\n', (408, 433), False, 'import cv2\n'), ((644, 689), 'cv2.Canny', 'cv2.Canny', (['img', 'low_threshold', 'high_threshold'], {}), '(img, low_threshold, high_threshold)\n', (653, 689), False, 'import cv2\n'), ((782, 834), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['img', '(kernel_size, kernel_size)', '(0)'], {}), '(img, (kernel_size, kernel_size), 0)\n', (798, 834), False, 'import cv2\n'), ((1159, 1177), 'numpy.zeros_like', 'np.zeros_like', (['img'], {}), '(img)\n', (1172, 1177), True, 'import numpy as np\n'), ((1557, 1604), 'cv2.fillPoly', 'cv2.fillPoly', (['mask', 'vertices', 'ignore_mask_color'], {}), '(mask, vertices, ignore_mask_color)\n', (1569, 1604), False, 'import cv2\n'), ((1685, 1711), 'cv2.bitwise_and', 'cv2.bitwise_and', (['img', 'mask'], {}), '(img, mask)\n', (1700, 1711), False, 'import cv2\n'), ((2597, 2654), 'numpy.zeros', 'np.zeros', (['(img.shape[0], img.shape[1], 3)'], {'dtype': 'np.uint8'}), '((img.shape[0], img.shape[1], 3), dtype=np.uint8)\n', (2605, 2654), True, 'import numpy as np\n'), ((4108, 4165), 'numpy.zeros', 'np.zeros', (['(img.shape[0], img.shape[1], 3)'], {'dtype': 'np.uint8'}), '((img.shape[0], img.shape[1], 3), dtype=np.uint8)\n', (4116, 4165), True, 'import numpy as np\n'), ((4656, 4698), 'cv2.addWeighted', 'cv2.addWeighted', (['initial_img', 'α', 'img', 'β', 'γ'], {}), '(initial_img, α, img, β, γ)\n', (4671, 4698), False, 'import cv2\n'), ((6060, 6086), 'numpy.array', 'np.array', (['[x1, y1, x2, y2]'], {}), '([x1, y1, x2, y2])\n', (6068, 6086), True, 'import numpy as np\n'), ((6556, 6584), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'fig_size'}), '(figsize=fig_size)\n', (6566, 6584), True, 'import matplotlib.pyplot as plt\n'), ((6836, 6854), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (6852, 6854), True, 'import matplotlib.pyplot as plt\n'), ((6859, 6869), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6867, 6869), True, 'import matplotlib.pyplot as plt\n'), ((6900, 6936), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_RGB2HLS'], {}), '(img, cv2.COLOR_RGB2HLS)\n', (6912, 6936), False, 'import cv2\n'), ((7686, 7725), 'cv2.bitwise_or', 'cv2.bitwise_or', (['white_mask', 'yellow_mask'], {}), '(white_mask, yellow_mask)\n', (7700, 7725), False, 'import cv2\n'), ((7812, 7855), 'cv2.bitwise_and', 'cv2.bitwise_and', (['gsimg', 'gsimg'], {'mask': 'yw_mask'}), '(gsimg, gsimg, mask=yw_mask)\n', (7827, 7855), False, 'import cv2\n'), ((8422, 8498), 'numpy.array', 'np.array', (['[[left_bottom, left_top, right_top, right_bottom]]'], {'dtype': 'np.int32'}), '([[left_bottom, left_top, right_top, right_bottom]], dtype=np.int32)\n', (8430, 8498), True, 'import numpy as np\n'), ((2515, 2527), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2523, 2527), True, 'import numpy as np\n'), ((4026, 4038), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (4034, 4038), True, 'import numpy as np\n'), ((5458, 5487), 'numpy.average', 'np.average', (['left_lane'], {'axis': '(0)'}), '(left_lane, axis=0)\n', (5468, 5487), True, 'import numpy as np\n'), ((5491, 5521), 'numpy.average', 'np.average', (['right_lane'], {'axis': '(0)'}), '(right_lane, axis=0)\n', (5501, 5521), True, 'import numpy as np\n'), ((6629, 6659), 'matplotlib.pyplot.subplot', 'plt.subplot', (['rows', 'cols', '(i + 1)'], {}), '(rows, cols, i + 1)\n', (6640, 6659), True, 'import matplotlib.pyplot as plt\n'), ((6796, 6830), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img_list[i]'], {'cmap': 'cmap'}), '(img_list[i], cmap=cmap)\n', (6806, 6830), True, 'import matplotlib.pyplot as plt\n'), ((7381, 7418), 'numpy.array', 'np.array', (['[0, 200, 0]'], {'dtype': 'np.uint8'}), '([0, 200, 0], dtype=np.uint8)\n', (7389, 7418), True, 'import numpy as np\n'), ((7449, 7490), 'numpy.array', 'np.array', (['[200, 255, 255]'], {'dtype': 'np.uint8'}), '([200, 255, 255], dtype=np.uint8)\n', (7457, 7490), True, 'import numpy as np\n'), ((7560, 7598), 'numpy.array', 'np.array', (['[10, 0, 100]'], {'dtype': 'np.uint8'}), '([10, 0, 100], dtype=np.uint8)\n', (7568, 7598), True, 'import numpy as np\n'), ((7630, 7670), 'numpy.array', 'np.array', (['[40, 255, 255]'], {'dtype': 'np.uint8'}), '([40, 255, 255], dtype=np.uint8)\n', (7638, 7670), True, 'import numpy as np\n'), ((2186, 2237), 'cv2.line', 'cv2.line', (['img', '(x1, y1)', '(x2, y2)', 'color', 'thickness'], {}), '(img, (x1, y1), (x2, y2), color, thickness)\n', (2194, 2237), False, 'import cv2\n'), ((3702, 3753), 'cv2.line', 'cv2.line', (['img', '(x1, y1)', '(x2, y2)', 'color', 'thickness'], {}), '(img, (x1, y1), (x2, y2), color, thickness)\n', (3710, 3753), False, 'import cv2\n'), ((5144, 5177), 'numpy.polyfit', 'np.polyfit', (['(x1, x2)', '(y1, y2)', '(1)'], {}), '((x1, x2), (y1, y2), 1)\n', (5154, 5177), True, 'import numpy as np\n'), ((6766, 6786), 'matplotlib.pyplot.title', 'plt.title', (['labels[i]'], {}), '(labels[i])\n', (6775, 6786), True, 'import matplotlib.pyplot as plt\n')]
import os import io import json import trimesh import random import matplotlib.pyplot as plt import numpy as np import cv2 import torch def load_bop_meshes(model_path, obj_ids="all"): """ Returns: meshes: list[Trimesh] objID2clsID: dict, objID (original) --> i (0-indexed) """ # load meshes meshFiles = [f for f in os.listdir(model_path) if f.endswith('.ply')] meshFiles.sort() meshes = [] objID_2_clsID = {} i = 0 for _i in range(len(meshFiles)): mFile = meshFiles[_i] objId = int(os.path.splitext(mFile)[0][4:]) # skip non-selected objects if isinstance(obj_ids, list) and str(objId) not in obj_ids: continue objID_2_clsID[str(objId)] = i meshes.append(trimesh.load(os.path.join(model_path, mFile))) i += 1 # print('mesh from "%s" is loaded' % (model_path + mFile)) # return meshes, objID_2_clsID def load_bbox_3d(jsonFile): with open(jsonFile, 'r') as f: bbox_3d = json.load(f) return bbox_3d def collect_mesh_bbox(meshpath, outjson, oriented=False): meshes, _ = load_bop_meshes(meshpath) allv = [] for ms in meshes: if oriented: bbox = ms.bounding_box_oriented.vertices else: bbox = ms.bounding_box.vertices allv.append(bbox.tolist()) with open(outjson, 'w') as outfile: json.dump(allv, outfile, indent=4) def generate_shiftscalerotate_matrix(shift_limit, scale_limit, rotate_limit, width, height): dw = int(width * shift_limit) dh = int(height * shift_limit) pleft = random.randint(-dw, dw) ptop = random.randint(-dh, dh) shiftM = np.array([[1.0, 0.0, -pleft], [0.0, 1.0, -ptop], [0.0, 0.0, 1.0]]) # translation # random rotation and scaling cx = width / 2 # fix the rotation center to the image center cy = height / 2 ang = random.uniform(-rotate_limit, rotate_limit) sfactor = random.uniform(-scale_limit, +scale_limit) + 1 tmp = cv2.getRotationMatrix2D((cx, cy), ang, sfactor) # rotation with scaling rsM = np.concatenate((tmp, [[0, 0, 1]]), axis=0) # combination M = np.matmul(rsM, shiftM) return M.astype(np.float32) def draw_bounding_box(cvImg, R, T, bbox, intrinsics, color, thickness): rep = np.matmul(intrinsics, np.matmul(R, bbox.T) + T) x = np.int32(rep[0]/rep[2] + 0.5) y = np.int32(rep[1]/rep[2] + 0.5) bbox_lines = [0, 1, 0, 2, 0, 4, 5, 1, 5, 4, 6, 2, 6, 4, 3, 2, 3, 1, 7, 3, 7, 5, 7, 6] for i in range(12): id1 = bbox_lines[2*i] id2 = bbox_lines[2*i+1] cvImg = cv2.line(cvImg, (x[id1],y[id1]), (x[id2],y[id2]), color, thickness=thickness, lineType=cv2.LINE_AA) return cvImg def draw_pose_axis(cvImg, R, T, bbox, intrinsics, thickness): radius = np.linalg.norm(bbox, axis=1).mean() aPts = np.array([[0,0,0],[0,0,radius],[0,radius,0],[radius,0,0]]) rep = np.matmul(intrinsics, np.matmul(R, aPts.T) + T) x = np.int32(rep[0]/rep[2] + 0.5) y = np.int32(rep[1]/rep[2] + 0.5) cvImg = cv2.line(cvImg, (x[0],y[0]), (x[1],y[1]), (0,0,255), thickness=thickness, lineType=cv2.LINE_AA) cvImg = cv2.line(cvImg, (x[0],y[0]), (x[2],y[2]), (0,255,0), thickness=thickness, lineType=cv2.LINE_AA) cvImg = cv2.line(cvImg, (x[0],y[0]), (x[3],y[3]), (255,0,0), thickness=thickness, lineType=cv2.LINE_AA) return cvImg def get_single_bop_annotation(img_path, objID_2_clsID, obj_ids=None): """ Returns: K: camera intrinsic (3, 3) merged_mask: multiple object segmentation, merged_mask == instance_id --> mask; instance_id is not relevant to cls_id or obj_id class_ids: list[int], cls_id rotations: list[np.ndarray (3, 3)] translations: list[np.ndarray (3, 1)] """ # add attributes to function, for fast loading if not hasattr(get_single_bop_annotation, "dir_annots"): get_single_bop_annotation.dir_annots = {} # img_path = img_path.strip() cvImg = cv2.imread(img_path) height, width, _ = cvImg.shape # gt_dir, tmp, imgName = img_path.rsplit('/', 2) assert(tmp == 'rgb') imgBaseName, _ = os.path.splitext(imgName) im_id = int(imgBaseName) # camera_file = gt_dir + '/scene_camera.json' gt_file = gt_dir + "/scene_gt.json" # gt_info_file = gt_dir + "/scene_gt_info.json" gt_mask_visib = gt_dir + "/mask_visib/" if gt_dir in get_single_bop_annotation.dir_annots: gt_json, cam_json = get_single_bop_annotation.dir_annots[gt_dir] else: gt_json = json.load(open(gt_file)) # gt_info_json = json.load(open(gt_info_file)) cam_json = json.load(open(camera_file)) # get_single_bop_annotation.dir_annots[gt_dir] = [gt_json, cam_json] if str(im_id) in cam_json: annot_camera = cam_json[str(im_id)] else: annot_camera = cam_json[("%06d" % im_id)] if str(im_id) in gt_json: annot_poses = gt_json[str(im_id)] else: annot_poses = gt_json[("%06d" % im_id)] # annot_infos = gt_info_json[str(im_id)] objCnt = len(annot_poses) K = np.array(annot_camera['cam_K']).reshape(3,3) class_ids = [] # bbox_objs = [] rotations = [] translations = [] merged_mask = np.zeros((height, width), np.uint8) # segmenation masks instance_idx = 1 for i in range(objCnt): mask_vis_file = gt_mask_visib + ("%06d_%06d.png" %(im_id, i)) mask_vis = cv2.imread(mask_vis_file, cv2.IMREAD_UNCHANGED) # # bbox = annot_infos[i]['bbox_visib'] # bbox = annot_infos[i]['bbox_obj'] # contourImg = cv2.rectangle(contourImg, (bbox[0], bbox[1]), (bbox[0]+bbox[2], bbox[1]+bbox[3]), (0,0,255)) # cv2.imshow(str(i), mask_vis) # R = np.array(annot_poses[i]['cam_R_m2c']).reshape(3,3) T = np.array(annot_poses[i]['cam_t_m2c']).reshape(3,1) obj_id = str(annot_poses[i]['obj_id']) if obj_ids is not None and obj_id not in obj_ids: continue if not obj_id in objID_2_clsID: continue cls_id = objID_2_clsID[obj_id] # # bbox_objs.append(bbox) class_ids.append(cls_id) rotations.append(R) translations.append(T) # compose segmentation labels merged_mask[mask_vis==255] = instance_idx instance_idx += 1 return K, merged_mask, class_ids, rotations, translations def visualize_pred(img, gt, pred, mean, std): cvImg = img.to('cpu').numpy().transpose(1,2,0) # de-normalize cvImg = cvImg * (np.array(std).reshape(1,1,3) * 255) cvImg = cvImg + (np.array(mean).reshape(1,1,3) * 255) # cvImg = cv2.cvtColor(cvImg.astype(np.uint8), cv2.COLOR_RGB2BGR) # cvImg[:] = 255 cvRawImg = cvImg.copy() # gtPoses = gt.to('cpu').to_numpy() gtVisual = gtPoses.visualize(cvImg) # show predicted poses for score, cls_id, R, T in pred: pt3d = np.array(gtPoses.keypoints_3d[cls_id]) try: cvImg = draw_pose_axis(cvImg, R, T, pt3d, gtPoses.K, 2) except: pass return cvRawImg, cvImg, gtVisual def remap_pose(srcK, srcR, srcT, pt3d, dstK, transM): ptCnt = len(pt3d) pts = np.matmul(transM, np.matmul(srcK, np.matmul(srcR, pt3d.transpose()) + srcT)) xs = pts[0] / (pts[2] + 1e-8) ys = pts[1] / (pts[2] + 1e-8) xy2d = np.concatenate((xs.reshape(-1,1),ys.reshape(-1,1)), axis=1) retval, rot, trans = cv2.solvePnP(pt3d.reshape(ptCnt,1,3), xy2d.reshape(ptCnt,1,2), dstK, None, flags=cv2.SOLVEPNP_EPNP) if retval: newR = cv2.Rodrigues(rot)[0] # convert to rotation matrix newT = trans.reshape(-1, 1) newPts = np.matmul(dstK, np.matmul(newR, pt3d.transpose()) + newT) newXs = newPts[0] / (newPts[2] + 1e-8) newYs = newPts[1] / (newPts[2] + 1e-8) newXy2d = np.concatenate((newXs.reshape(-1,1),newYs.reshape(-1,1)), axis=1) diff_in_pix = np.linalg.norm(xy2d - newXy2d, axis=1).mean() return newR, newT, diff_in_pix else: print('Error in pose remapping!') return srcR, srcT, -1 # define a function which returns an image as numpy array from figure def get_img_from_matplotlib_fig(fig, dpi=300): buf = io.BytesIO() fig.savefig(buf, format="png", dpi=dpi) buf.seek(0) img_arr = np.frombuffer(buf.getvalue(), dtype=np.uint8) buf.close() img = cv2.imdecode(img_arr, 1) return img def visualize_accuracy_per_depth( accuracy_adi_per_class, accuracy_rep_per_class, accuracy_adi_per_depth, accuracy_rep_per_depth, depth_range): fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(8, 4)) rep_keys = accuracy_rep_per_class[0].keys() adi_keys = accuracy_adi_per_class[0].keys() depth_bins = len(accuracy_rep_per_depth) assert(len(accuracy_adi_per_depth) == len(accuracy_rep_per_depth)) ax1.set_title('Statistics of 2D error') ax1.set_xlabel('Depth') ax1.set_ylabel('Success Rate (%)') ax2.set_title('Statistics of 3D error') ax2.set_xlabel('Depth') # ax2.set_ylabel('Success Rate (%)') # ax2.yaxis.tick_right() for k in rep_keys: xs = np.arange(depth_range[0], depth_range[1], (depth_range[1]-depth_range[0])/depth_bins) ys = [] for i in range(depth_bins): if k in accuracy_rep_per_depth[i]: ys.append(accuracy_rep_per_depth[i][k]) else: ys.append(0) ys = np.array(ys) # # xnew = np.linspace(depth_range[0], depth_range[1], 300) / 1000 # ynew = UnivariateSpline(xs, ys, k=2, s=100)(xnew) # ax1.plot(xnew, ynew, label=k) ax1.plot(xs, ys, marker='o', label=k) for k in adi_keys: xs = np.arange(depth_range[0], depth_range[1], (depth_range[1]-depth_range[0])/depth_bins) ys = [] for i in range(depth_bins): if k in accuracy_adi_per_depth[i]: ys.append(accuracy_adi_per_depth[i][k]) else: ys.append(0) ys = np.array(ys) # # xnew = np.linspace(depth_range[0], depth_range[1], 300) / 1000 # ynew = UnivariateSpline(xs, ys, k=2, s=100)(xnew) # ax2.plot(xnew, ynew, label=k) ax2.plot(xs, ys, marker='o', label=k) ax1.legend(loc='lower right') ax2.legend(loc='upper right') ax1.grid() ax2.grid() matFig = get_img_from_matplotlib_fig(fig) # cv2.imshow("xx", matFig) # cv2.waitKey(0) return matFig def print_accuracy_per_class(accuracy_adi_per_class, accuracy_rep_per_class): assert(len(accuracy_adi_per_class) == len(accuracy_rep_per_class)) classNum = len(accuracy_adi_per_class) firstMeet = True for clsIdx in range(classNum): if len(accuracy_adi_per_class[clsIdx]) == 0: continue if firstMeet: adi_keys = accuracy_adi_per_class[clsIdx].keys() rep_keys = accuracy_rep_per_class[clsIdx].keys() titleLine = "\t" for k in adi_keys: titleLine += (k + ' ') titleLine += '\t' for k in rep_keys: titleLine += (k + ' ') print(titleLine) firstMeet = False line_per_class = ("cls_%02d" % clsIdx) for k in adi_keys: line_per_class += ('\t%.2f' % accuracy_adi_per_class[clsIdx][k]) line_per_class += '\t' for k in rep_keys: line_per_class += ('\t%.2f' % accuracy_rep_per_class[clsIdx][k]) print(line_per_class) def compute_pose_diff(mesh3ds, K, gtR, gtT, predR, predT): ptCnt = len(mesh3ds) pred_3d1 = (np.matmul(gtR, mesh3ds.T) + gtT).T pred_3d2 = (np.matmul(predR, mesh3ds.T) + predT).T p = np.matmul(K, pred_3d1.T) p[0] = p[0] / (p[2] + 1e-8) p[1] = p[1] / (p[2] + 1e-8) pred_2d1 = p[:2].T p = np.matmul(K, pred_3d2.T) p[0] = p[0] / (p[2] + 1e-8) p[1] = p[1] / (p[2] + 1e-8) pred_2d2 = p[:2].T error_3d = np.linalg.norm(pred_3d1 - pred_3d2, axis=1).mean() error_2d = np.linalg.norm(pred_2d1 - pred_2d2, axis=1).mean() return error_3d, error_2d
[ "numpy.int32", "io.BytesIO", "numpy.array", "cv2.imdecode", "numpy.linalg.norm", "numpy.arange", "os.listdir", "cv2.line", "numpy.matmul", "numpy.concatenate", "random.randint", "random.uniform", "os.path.splitext", "cv2.getRotationMatrix2D", "cv2.imread", "os.path.join", "numpy.zero...
[((1627, 1650), 'random.randint', 'random.randint', (['(-dw)', 'dw'], {}), '(-dw, dw)\n', (1641, 1650), False, 'import random\n'), ((1662, 1685), 'random.randint', 'random.randint', (['(-dh)', 'dh'], {}), '(-dh, dh)\n', (1676, 1685), False, 'import random\n'), ((1699, 1765), 'numpy.array', 'np.array', (['[[1.0, 0.0, -pleft], [0.0, 1.0, -ptop], [0.0, 0.0, 1.0]]'], {}), '([[1.0, 0.0, -pleft], [0.0, 1.0, -ptop], [0.0, 0.0, 1.0]])\n', (1707, 1765), True, 'import numpy as np\n'), ((1911, 1954), 'random.uniform', 'random.uniform', (['(-rotate_limit)', 'rotate_limit'], {}), '(-rotate_limit, rotate_limit)\n', (1925, 1954), False, 'import random\n'), ((2026, 2073), 'cv2.getRotationMatrix2D', 'cv2.getRotationMatrix2D', (['(cx, cy)', 'ang', 'sfactor'], {}), '((cx, cy), ang, sfactor)\n', (2049, 2073), False, 'import cv2\n'), ((2109, 2151), 'numpy.concatenate', 'np.concatenate', (['(tmp, [[0, 0, 1]])'], {'axis': '(0)'}), '((tmp, [[0, 0, 1]]), axis=0)\n', (2123, 2151), True, 'import numpy as np\n'), ((2179, 2201), 'numpy.matmul', 'np.matmul', (['rsM', 'shiftM'], {}), '(rsM, shiftM)\n', (2188, 2201), True, 'import numpy as np\n'), ((2374, 2405), 'numpy.int32', 'np.int32', (['(rep[0] / rep[2] + 0.5)'], {}), '(rep[0] / rep[2] + 0.5)\n', (2382, 2405), True, 'import numpy as np\n'), ((2412, 2443), 'numpy.int32', 'np.int32', (['(rep[1] / rep[2] + 0.5)'], {}), '(rep[1] / rep[2] + 0.5)\n', (2420, 2443), True, 'import numpy as np\n'), ((2874, 2943), 'numpy.array', 'np.array', (['[[0, 0, 0], [0, 0, radius], [0, radius, 0], [radius, 0, 0]]'], {}), '([[0, 0, 0], [0, 0, radius], [0, radius, 0], [radius, 0, 0]])\n', (2882, 2943), True, 'import numpy as np\n'), ((2999, 3030), 'numpy.int32', 'np.int32', (['(rep[0] / rep[2] + 0.5)'], {}), '(rep[0] / rep[2] + 0.5)\n', (3007, 3030), True, 'import numpy as np\n'), ((3037, 3068), 'numpy.int32', 'np.int32', (['(rep[1] / rep[2] + 0.5)'], {}), '(rep[1] / rep[2] + 0.5)\n', (3045, 3068), True, 'import numpy as np\n'), ((3079, 3183), 'cv2.line', 'cv2.line', (['cvImg', '(x[0], y[0])', '(x[1], y[1])', '(0, 0, 255)'], {'thickness': 'thickness', 'lineType': 'cv2.LINE_AA'}), '(cvImg, (x[0], y[0]), (x[1], y[1]), (0, 0, 255), thickness=\n thickness, lineType=cv2.LINE_AA)\n', (3087, 3183), False, 'import cv2\n'), ((3187, 3291), 'cv2.line', 'cv2.line', (['cvImg', '(x[0], y[0])', '(x[2], y[2])', '(0, 255, 0)'], {'thickness': 'thickness', 'lineType': 'cv2.LINE_AA'}), '(cvImg, (x[0], y[0]), (x[2], y[2]), (0, 255, 0), thickness=\n thickness, lineType=cv2.LINE_AA)\n', (3195, 3291), False, 'import cv2\n'), ((3295, 3399), 'cv2.line', 'cv2.line', (['cvImg', '(x[0], y[0])', '(x[3], y[3])', '(255, 0, 0)'], {'thickness': 'thickness', 'lineType': 'cv2.LINE_AA'}), '(cvImg, (x[0], y[0]), (x[3], y[3]), (255, 0, 0), thickness=\n thickness, lineType=cv2.LINE_AA)\n', (3303, 3399), False, 'import cv2\n'), ((4020, 4040), 'cv2.imread', 'cv2.imread', (['img_path'], {}), '(img_path)\n', (4030, 4040), False, 'import cv2\n'), ((4180, 4205), 'os.path.splitext', 'os.path.splitext', (['imgName'], {}), '(imgName)\n', (4196, 4205), False, 'import os\n'), ((5292, 5327), 'numpy.zeros', 'np.zeros', (['(height, width)', 'np.uint8'], {}), '((height, width), np.uint8)\n', (5300, 5327), True, 'import numpy as np\n'), ((8306, 8318), 'io.BytesIO', 'io.BytesIO', ([], {}), '()\n', (8316, 8318), False, 'import io\n'), ((8465, 8489), 'cv2.imdecode', 'cv2.imdecode', (['img_arr', '(1)'], {}), '(img_arr, 1)\n', (8477, 8489), False, 'import cv2\n'), ((8716, 8762), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(1)', 'ncols': '(2)', 'figsize': '(8, 4)'}), '(nrows=1, ncols=2, figsize=(8, 4))\n', (8728, 8762), True, 'import matplotlib.pyplot as plt\n'), ((11855, 11879), 'numpy.matmul', 'np.matmul', (['K', 'pred_3d1.T'], {}), '(K, pred_3d1.T)\n', (11864, 11879), True, 'import numpy as np\n'), ((11976, 12000), 'numpy.matmul', 'np.matmul', (['K', 'pred_3d2.T'], {}), '(K, pred_3d2.T)\n', (11985, 12000), True, 'import numpy as np\n'), ((1025, 1037), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1034, 1037), False, 'import json\n'), ((1409, 1443), 'json.dump', 'json.dump', (['allv', 'outfile'], {'indent': '(4)'}), '(allv, outfile, indent=4)\n', (1418, 1443), False, 'import json\n'), ((1969, 2011), 'random.uniform', 'random.uniform', (['(-scale_limit)', '(+scale_limit)'], {}), '(-scale_limit, +scale_limit)\n', (1983, 2011), False, 'import random\n'), ((2634, 2740), 'cv2.line', 'cv2.line', (['cvImg', '(x[id1], y[id1])', '(x[id2], y[id2])', 'color'], {'thickness': 'thickness', 'lineType': 'cv2.LINE_AA'}), '(cvImg, (x[id1], y[id1]), (x[id2], y[id2]), color, thickness=\n thickness, lineType=cv2.LINE_AA)\n', (2642, 2740), False, 'import cv2\n'), ((5486, 5533), 'cv2.imread', 'cv2.imread', (['mask_vis_file', 'cv2.IMREAD_UNCHANGED'], {}), '(mask_vis_file, cv2.IMREAD_UNCHANGED)\n', (5496, 5533), False, 'import cv2\n'), ((6997, 7035), 'numpy.array', 'np.array', (['gtPoses.keypoints_3d[cls_id]'], {}), '(gtPoses.keypoints_3d[cls_id])\n', (7005, 7035), True, 'import numpy as np\n'), ((9264, 9357), 'numpy.arange', 'np.arange', (['depth_range[0]', 'depth_range[1]', '((depth_range[1] - depth_range[0]) / depth_bins)'], {}), '(depth_range[0], depth_range[1], (depth_range[1] - depth_range[0]) /\n depth_bins)\n', (9273, 9357), True, 'import numpy as np\n'), ((9565, 9577), 'numpy.array', 'np.array', (['ys'], {}), '(ys)\n', (9573, 9577), True, 'import numpy as np\n'), ((9844, 9937), 'numpy.arange', 'np.arange', (['depth_range[0]', 'depth_range[1]', '((depth_range[1] - depth_range[0]) / depth_bins)'], {}), '(depth_range[0], depth_range[1], (depth_range[1] - depth_range[0]) /\n depth_bins)\n', (9853, 9937), True, 'import numpy as np\n'), ((10145, 10157), 'numpy.array', 'np.array', (['ys'], {}), '(ys)\n', (10153, 10157), True, 'import numpy as np\n'), ((354, 376), 'os.listdir', 'os.listdir', (['model_path'], {}), '(model_path)\n', (364, 376), False, 'import os\n'), ((2340, 2360), 'numpy.matmul', 'np.matmul', (['R', 'bbox.T'], {}), '(R, bbox.T)\n', (2349, 2360), True, 'import numpy as np\n'), ((2827, 2855), 'numpy.linalg.norm', 'np.linalg.norm', (['bbox'], {'axis': '(1)'}), '(bbox, axis=1)\n', (2841, 2855), True, 'import numpy as np\n'), ((2965, 2985), 'numpy.matmul', 'np.matmul', (['R', 'aPts.T'], {}), '(R, aPts.T)\n', (2974, 2985), True, 'import numpy as np\n'), ((5147, 5178), 'numpy.array', 'np.array', (["annot_camera['cam_K']"], {}), "(annot_camera['cam_K'])\n", (5155, 5178), True, 'import numpy as np\n'), ((7646, 7664), 'cv2.Rodrigues', 'cv2.Rodrigues', (['rot'], {}), '(rot)\n', (7659, 7664), False, 'import cv2\n'), ((11756, 11781), 'numpy.matmul', 'np.matmul', (['gtR', 'mesh3ds.T'], {}), '(gtR, mesh3ds.T)\n', (11765, 11781), True, 'import numpy as np\n'), ((11807, 11834), 'numpy.matmul', 'np.matmul', (['predR', 'mesh3ds.T'], {}), '(predR, mesh3ds.T)\n', (11816, 11834), True, 'import numpy as np\n'), ((12104, 12147), 'numpy.linalg.norm', 'np.linalg.norm', (['(pred_3d1 - pred_3d2)'], {'axis': '(1)'}), '(pred_3d1 - pred_3d2, axis=1)\n', (12118, 12147), True, 'import numpy as np\n'), ((12170, 12213), 'numpy.linalg.norm', 'np.linalg.norm', (['(pred_2d1 - pred_2d2)'], {'axis': '(1)'}), '(pred_2d1 - pred_2d2, axis=1)\n', (12184, 12213), True, 'import numpy as np\n'), ((787, 818), 'os.path.join', 'os.path.join', (['model_path', 'mFile'], {}), '(model_path, mFile)\n', (799, 818), False, 'import os\n'), ((5813, 5850), 'numpy.array', 'np.array', (["annot_poses[i]['cam_R_m2c']"], {}), "(annot_poses[i]['cam_R_m2c'])\n", (5821, 5850), True, 'import numpy as np\n'), ((5876, 5913), 'numpy.array', 'np.array', (["annot_poses[i]['cam_t_m2c']"], {}), "(annot_poses[i]['cam_t_m2c'])\n", (5884, 5913), True, 'import numpy as np\n'), ((8010, 8048), 'numpy.linalg.norm', 'np.linalg.norm', (['(xy2d - newXy2d)'], {'axis': '(1)'}), '(xy2d - newXy2d, axis=1)\n', (8024, 8048), True, 'import numpy as np\n'), ((557, 580), 'os.path.splitext', 'os.path.splitext', (['mFile'], {}), '(mFile)\n', (573, 580), False, 'import os\n'), ((6612, 6625), 'numpy.array', 'np.array', (['std'], {}), '(std)\n', (6620, 6625), True, 'import numpy as np\n'), ((6669, 6683), 'numpy.array', 'np.array', (['mean'], {}), '(mean)\n', (6677, 6683), True, 'import numpy as np\n')]
from IMLearn.learners import UnivariateGaussian, MultivariateGaussian import numpy as np import plotly.graph_objects as go import plotly.io as pio from utils import * pio.templates.default = "simple_white" import plotly.io as pio pio.renderers.default = "browser" def test_univariate_gaussian(): mu = 10 sigma = 1 # Question 1 - Draw samples and print fitted model samples = np.random.normal(mu, sigma, 1000) u = UnivariateGaussian() u.fit(samples) print(u.mu_, u.var_) # Question 2 - Empirically showing sample mean is consistent ms = np.linspace(10, 1000, 100).astype(int) estimated_mus = [] for m in ms: X = samples[0:m] estimated_mus.append(np.abs(u.fit(X).mu_ - mu)) go.Figure([go.Scatter(x=ms, y=estimated_mus, mode='markers+lines', name=r'$\widehat\mu$'), ], layout=go.Layout(barmode='overlay', title=r"$\text{Estimator vs. true value}$", xaxis_title="Number of samples", yaxis_title="Absolute distance |estimates - true value|", height=450)).show() # # Question 3 - Plotting Empirical PDF of fitted model samples_normal_vals = u.pdf(samples) go.Figure([go.Scatter(x=samples, y=samples_normal_vals, mode='markers', name=r'$\widehat\mu$'), ], layout=go.Layout(barmode='overlay', title=r"$\text{PDF values for samples}$", xaxis_title="PDF sample values", yaxis_title="Sample value", height=450)).show() def test_multivariate_gaussian(): # Question 4 - Draw samples and print fitted model m = MultivariateGaussian() multi_mu = [0, 0, 4, 0] multi_cov = np.array([[1, 0.2, 0, 0.5], [0.2, 2, 0, 0], [0, 0, 1, 0], [0.5, 0, 0, 1]]) multi_x = np.random.multivariate_normal(multi_mu, multi_cov, 1000) m.fit(multi_x) print("Expectation: ", m.mu_, "\n") print("Cov: ", m.cov_, "\n") # Question 5 - Likelihood evaluation ms_f1_f2 = np.linspace(-10, 10, 200).astype(float) samples_to_vals = np.array(np.meshgrid(ms_f1_f2, 0, ms_f1_f2, 0)).T.reshape(-1, 4) log_likelihood_func = lambda x: MultivariateGaussian.log_likelihood(x, multi_cov, multi_x) log_likelihood = np.apply_along_axis(log_likelihood_func, 1, samples_to_vals) fig = go.Figure() fig.add_trace(go.Heatmap(x=ms_f1_f2, y=ms_f1_f2, z=log_likelihood.reshape(200, 200).T, colorbar=dict(title="Log likelihood"))) fig.update_layout( title="values of log likelihood for changed f1, f3 mean values (f1, 0, f3, 0)", xaxis_title="f3", yaxis_title="f1") fig.show() # Question 6 - Maximum likelihood print("f1, f3 for max likelihood: ") print("f1: %.3f" % samples_to_vals[np.argmax(log_likelihood)][0]) print("f3: %.3f" % samples_to_vals[np.argmax(log_likelihood)][2]) if __name__ == '__main__': np.random.seed(0) test_univariate_gaussian() test_multivariate_gaussian()
[ "numpy.random.normal", "plotly.graph_objects.Layout", "numpy.random.multivariate_normal", "numpy.argmax", "numpy.array", "plotly.graph_objects.Figure", "numpy.apply_along_axis", "IMLearn.learners.MultivariateGaussian.log_likelihood", "numpy.random.seed", "numpy.linspace", "plotly.graph_objects.S...
[((395, 428), 'numpy.random.normal', 'np.random.normal', (['mu', 'sigma', '(1000)'], {}), '(mu, sigma, 1000)\n', (411, 428), True, 'import numpy as np\n'), ((437, 457), 'IMLearn.learners.UnivariateGaussian', 'UnivariateGaussian', ([], {}), '()\n', (455, 457), False, 'from IMLearn.learners import UnivariateGaussian, MultivariateGaussian\n'), ((1816, 1838), 'IMLearn.learners.MultivariateGaussian', 'MultivariateGaussian', ([], {}), '()\n', (1836, 1838), False, 'from IMLearn.learners import UnivariateGaussian, MultivariateGaussian\n'), ((1883, 1957), 'numpy.array', 'np.array', (['[[1, 0.2, 0, 0.5], [0.2, 2, 0, 0], [0, 0, 1, 0], [0.5, 0, 0, 1]]'], {}), '([[1, 0.2, 0, 0.5], [0.2, 2, 0, 0], [0, 0, 1, 0], [0.5, 0, 0, 1]])\n', (1891, 1957), True, 'import numpy as np\n'), ((1972, 2028), 'numpy.random.multivariate_normal', 'np.random.multivariate_normal', (['multi_mu', 'multi_cov', '(1000)'], {}), '(multi_mu, multi_cov, 1000)\n', (2001, 2028), True, 'import numpy as np\n'), ((2422, 2482), 'numpy.apply_along_axis', 'np.apply_along_axis', (['log_likelihood_func', '(1)', 'samples_to_vals'], {}), '(log_likelihood_func, 1, samples_to_vals)\n', (2441, 2482), True, 'import numpy as np\n'), ((2493, 2504), 'plotly.graph_objects.Figure', 'go.Figure', ([], {}), '()\n', (2502, 2504), True, 'import plotly.graph_objects as go\n'), ((3096, 3113), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (3110, 3113), True, 'import numpy as np\n'), ((2342, 2400), 'IMLearn.learners.MultivariateGaussian.log_likelihood', 'MultivariateGaussian.log_likelihood', (['x', 'multi_cov', 'multi_x'], {}), '(x, multi_cov, multi_x)\n', (2377, 2400), False, 'from IMLearn.learners import UnivariateGaussian, MultivariateGaussian\n'), ((577, 603), 'numpy.linspace', 'np.linspace', (['(10)', '(1000)', '(100)'], {}), '(10, 1000, 100)\n', (588, 603), True, 'import numpy as np\n'), ((2178, 2203), 'numpy.linspace', 'np.linspace', (['(-10)', '(10)', '(200)'], {}), '(-10, 10, 200)\n', (2189, 2203), True, 'import numpy as np\n'), ((754, 833), 'plotly.graph_objects.Scatter', 'go.Scatter', ([], {'x': 'ms', 'y': 'estimated_mus', 'mode': '"""markers+lines"""', 'name': '"""$\\\\widehat\\\\mu$"""'}), "(x=ms, y=estimated_mus, mode='markers+lines', name='$\\\\widehat\\\\mu$')\n", (764, 833), True, 'import plotly.graph_objects as go\n'), ((885, 1069), 'plotly.graph_objects.Layout', 'go.Layout', ([], {'barmode': '"""overlay"""', 'title': '"""$\\\\text{Estimator vs. true value}$"""', 'xaxis_title': '"""Number of samples"""', 'yaxis_title': '"""Absolute distance |estimates - true value|"""', 'height': '(450)'}), "(barmode='overlay', title='$\\\\text{Estimator vs. true value}$',\n xaxis_title='Number of samples', yaxis_title=\n 'Absolute distance |estimates - true value|', height=450)\n", (894, 1069), True, 'import plotly.graph_objects as go\n'), ((1290, 1379), 'plotly.graph_objects.Scatter', 'go.Scatter', ([], {'x': 'samples', 'y': 'samples_normal_vals', 'mode': '"""markers"""', 'name': '"""$\\\\widehat\\\\mu$"""'}), "(x=samples, y=samples_normal_vals, mode='markers', name=\n '$\\\\widehat\\\\mu$')\n", (1300, 1379), True, 'import plotly.graph_objects as go\n'), ((1426, 1573), 'plotly.graph_objects.Layout', 'go.Layout', ([], {'barmode': '"""overlay"""', 'title': '"""$\\\\text{PDF values for samples}$"""', 'xaxis_title': '"""PDF sample values"""', 'yaxis_title': '"""Sample value"""', 'height': '(450)'}), "(barmode='overlay', title='$\\\\text{PDF values for samples}$',\n xaxis_title='PDF sample values', yaxis_title='Sample value', height=450)\n", (1435, 1573), True, 'import plotly.graph_objects as go\n'), ((2249, 2286), 'numpy.meshgrid', 'np.meshgrid', (['ms_f1_f2', '(0)', 'ms_f1_f2', '(0)'], {}), '(ms_f1_f2, 0, ms_f1_f2, 0)\n', (2260, 2286), True, 'import numpy as np\n'), ((2962, 2987), 'numpy.argmax', 'np.argmax', (['log_likelihood'], {}), '(log_likelihood)\n', (2971, 2987), True, 'import numpy as np\n'), ((3032, 3057), 'numpy.argmax', 'np.argmax', (['log_likelihood'], {}), '(log_likelihood)\n', (3041, 3057), True, 'import numpy as np\n')]
#****************************************************************************** # # tempoGAN: A Temporally Coherent, Volumetric GAN for Super-resolution Fluid Flow # Copyright 2018 <NAME>, <NAME>, <NAME>, <NAME> # # This program is free software, distributed under the terms of the # Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # #****************************************************************************** import time import os import shutil import sys import math import tensorflow as tf from tensorflow.python.client import timeline import numpy as np # load manta tools sys.path.append("../tools") import tilecreator_t as tc import uniio import paramhelpers as ph from GAN import GAN, lrelu import fluiddataloader as FDL # --------------------------------------------- # initialize parameters / command line params outputOnly = int(ph.getParam( "out", False ))>0 # output/generation mode, main mode switch basePath = ph.getParam( "basePath", '../2ddata_gan/' ) randSeed = int(ph.getParam( "randSeed", 1 )) # seed for np and tf initialization load_model_test = int(ph.getParam( "load_model_test", -1 )) # the number of the test to load a model from. can be used in training and output mode. -1 to not load a model load_model_no = int(ph.getParam( "load_model_no", -1 )) # nubmber of the model to load simSizeLow = int(ph.getParam( "simSize", 64 )) # tiles of low res sim tileSizeLow = int(ph.getParam( "tileSize", 16 )) # size of low res tiles dt = float(ph.getParam( "dt", 1.0 )) # step time of training data #Data and Output loadPath = ph.getParam( "loadPath", '../2ddata_sim/' ) # path to training data fromSim = int(ph.getParam( "fromSim", 1000 )) # range of sim data to use, start index toSim = int(ph.getParam( "toSim", -1 )) # end index dataDimension = int(ph.getParam( "dataDim", 2 )) # dimension of dataset, can be 2 or 3. in case of 3D any scaling will only be applied to H and W (DHW) numOut = int(ph.getParam( "numOut", 200 )) # number ouf images to output (from start of sim) saveOut = int(ph.getParam( "saveOut", False ))>0 # save output of output mode as .npz in addition to images loadOut = int(ph.getParam( "loadOut", -1 )) # load output from npz to use in output mode instead of tiles. number or output dir, -1 for not use output data outputImages =int(ph.getParam( "img", True ))>0 # output images outputGif = int(ph.getParam( "gif", False ))>0 # output gif outputRef = int(ph.getParam( "ref", False ))>0 # output "real" data for reference in output mode (may not work with 3D) #models genModel = ph.getParam( "genModel", 'gen_test' ) # choose generator model discModel = ph.getParam( "discModel", 'disc_test' ) # choose discriminator model #Training learning_rate = float(ph.getParam( "learningRate", 0.0002 )) decayLR = int(ph.getParam( "decayLR", False ))>0 # decay learning rate? dropout = float(ph.getParam( "dropout", 1.0 )) # keep prob for all dropout layers during training dropoutOutput = float(ph.getParam( "dropoutOutput", dropout )) # affects testing, full sim output and progressive output during training beta = float(ph.getParam( "adam_beta1", 0.5 )) #1. momentum of adam optimizer weight_dld = float(ph.getParam( "weight_dld", 1.0)) # ? discriminator loss factor ? k = float(ph.getParam( "lambda", 1.0)) # influence/weight of l1 term on generator loss k2 = float(ph.getParam( "lambda2", 0.0)) # influence/weight of d_loss term on generator loss k_f = float(ph.getParam( "lambda_f", 1.0)) # changing factor of k k2_f = float(ph.getParam( "lambda2_f", 1.0)) # changing factor of k2 k2_l1 = float(ph.getParam( "lambda2_l1", 1.0)) # influence/weight of L1 layer term on discriminator loss k2_l2 = float(ph.getParam( "lambda2_l2", 1.0)) # influence/weight of L2 layer term on discriminator loss k2_l3 = float(ph.getParam( "lambda2_l3", 1.0)) # influence/weight of L3 layer term on discriminator loss k2_l4 = float(ph.getParam( "lambda2_l4", 1.0)) # influence/weight of L4 layer term on discriminator loss kt = float(ph.getParam("lambda_t", 1.0)) # tempo discriminator loss; 1.0 is good, 0.0 will disable kt_l = float(ph.getParam("lambda_t_l2", 0.0)) # l2 tempo loss (as naive alternative to discriminator); 1.0 is good, 0.0 will disable batch_size = int(ph.getParam( "batchSize", 128 )) # batch size for pretrainig and output, default for batchSizeDisc and batchSizeGen batch_size_disc = int(ph.getParam( "batchSizeDisc", batch_size )) # batch size for disc runs when training gan batch_size_gen = int(ph.getParam( "batchSizeGen", batch_size )) # batch size for gen runs when training gan trainGAN = int(ph.getParam( "trainGAN", True ))>0 # GAN trainng can be switched off to use pretrainig only trainingIters = int(ph.getParam( "trainingIters", 100000 )) # for GAN training discRuns = int(ph.getParam( "discRuns", 1 )) # number of discrimiinator optimizer runs per iteration genRuns = int(ph.getParam( "genRuns", 1 )) # number or generator optimizer runs per iteration batch_norm = int(ph.getParam( "batchNorm", True ))>0 # apply batch normalization to conv and deconv layers bn_decay = float(ph.getParam( "bnDecay", 0.999 )) # decay of batch norm EMA use_spatialdisc = int(ph.getParam( "use_spatialdisc", True )) #use spatial discriminator or not useVelocities = int(ph.getParam( "useVelocities", 0 )) # use velocities or not useVorticities = int(ph.getParam( "useVorticities", 0 )) # use vorticities or not premadeTiles = int(ph.getParam( "premadeTiles", 0 )) # use pre-made tiles? useDataAugmentation = int(ph.getParam( "dataAugmentation", 0 )) # use dataAugmentation or not minScale = float(ph.getParam( "minScale", 0.85 )) # augmentation params... maxScale = float(ph.getParam( "maxScale", 1.15 )) rot = int(ph.getParam( "rot", 2 )) #rot: 1: 90 degree rotations; 2: full rotation; else: nop rotation flip = int(ph.getParam( "flip", 1 )) #Test and Save testPathStartNo = int(ph.getParam( "testPathStartNo", 0 )) valiInterval = int(ph.getParam( "valiInterval", 20 )) # interval in iterations to run validation, should be lower or equal outputInterval numValis = int(ph.getParam( "numValis", 10 )) # number of validation runs to perform from vali data each interval, run as batch outputInterval = int(ph.getParam( "outputInterval", 100 )) # interval in iterations to output statistics saveInterval = int(ph.getParam( "saveInterval", 200 )) # interval in iterations to save model alwaysSave = int(ph.getParam( "alwaysSave", True )) # maxToKeep = int(ph.getParam( "keepMax", 3 )) # maximum number of model saves to keep in each test-run genValiImg = int(ph.getParam( "genValiImg", -1 )) # if > -1 generate validation image every output interval note = ph.getParam( "note", "" ) # optional info about the current test run, printed in log and overview data_fraction = float(ph.getParam( "data_fraction", 0.3 )) frameMax = int(ph.getParam( "frameMax", 200 )) frameMin = int(ph.getParam( "frameMin", 0 )) ADV_flag = int(ph.getParam( "adv_flag", True )) # Tempo parameter, add( or not) advection to pre/back frame to align saveMD = int(ph.getParam( "saveMetaData", 0 )) # profiling, add metadata to summary object? warning - only main training for now overlap = int(ph.getParam( "overlap", 3 )) # parameter for 3d unifile output, overlap of voxels ph.checkUnusedParams() useTempoD = False useTempoL2 = False if(kt > 1e-6): useTempoD = True if(kt_l > 1e-6): useTempoD = True if(kt > 1e-6 and kt_l > 1e-6): print("ERROR: temporal loss can only be either discriminator or L2, not both") exit(1) # initialize upRes = 4 # fixed for now... simSizeHigh = simSizeLow * upRes tileSizeHigh = tileSizeLow * upRes if not (dataDimension == 2 or dataDimension == 3): print('Unsupported data dimension {}. Only 2 and 3 are supported'.format(dataDimension)) exit(1) if toSim==-1: toSim = fromSim channelLayout_low = 'd' lowfilename = "density_low_%04d.uni" highfilename = "density_high_%04d.uni" mfl = ["density"] mfh = ["density"] if outputOnly: highfilename = None mfh = None if useVelocities: channelLayout_low += ',vx,vy,vz' mfl= np.append(mfl, "velocity") dirIDs = np.linspace(fromSim, toSim, (toSim-fromSim+1),dtype='int16') if (outputOnly): data_fraction = 1.0 kt = 0.0 kt_l = 0.0 useTempoD = False useTempoL2 = False useDataAugmentation = 0 if ((not useTempoD) and (not useTempoL2)): # should use the full sequence, not use multi_files tiCr = tc.TileCreator(tileSizeLow=tileSizeLow, simSizeLow=simSizeLow , dim =dataDimension, dim_t = 1, channelLayout_low = channelLayout_low, upres=upRes, premadeTiles=premadeTiles) floader = FDL.FluidDataLoader( print_info=1, base_path=loadPath, filename=lowfilename, oldNamingScheme=False, filename_y=highfilename, filename_index_min=frameMin, filename_index_max=frameMax, indices=dirIDs, data_fraction=data_fraction, multi_file_list=mfl, multi_file_list_y=mfh) else: lowparalen = len(mfl) highparalen = len(mfh) mfl_tempo= np.append(mfl, mfl) mfl= np.append(mfl_tempo, mfl) mol = np.append(np.zeros(lowparalen), np.ones(lowparalen)) mol = np.append(mol, np.ones(lowparalen)*2) mfh_tempo = np.append(mfh, mfh) mfh= np.append(mfh_tempo, mfh) moh = np.append(np.zeros(highparalen), np.ones(highparalen)) moh = np.append(moh, np.ones(highparalen)*2) tiCr = tc.TileCreator(tileSizeLow=tileSizeLow, simSizeLow=simSizeLow , dim =dataDimension, dim_t = 3, channelLayout_low = channelLayout_low, upres=upRes, premadeTiles=premadeTiles) floader = FDL.FluidDataLoader( print_info=1, base_path=loadPath, filename=lowfilename, oldNamingScheme=False, filename_y=highfilename, filename_index_max=frameMax, indices=dirIDs, data_fraction=data_fraction, multi_file_list=mfl, multi_file_idxOff=mol, multi_file_list_y=mfh , multi_file_idxOff_y=moh) if useDataAugmentation: tiCr.initDataAugmentation(rot=rot, minScale=minScale, maxScale=maxScale ,flip=flip) inputx, y, xFilenames = floader.get() if (not outputOnly): tiCr.addData(inputx,y) elif dataDimension == 3: simLowLength = inputx.shape[1] simLowWidth = inputx.shape[2] simLowHeight = inputx.shape[3] print("Random seed: {}".format(randSeed)) np.random.seed(randSeed) tf.set_random_seed(randSeed) # --------------------------------------------- # 2D: tileSize x tileSize tiles; 3D: tileSize x tileSize x tileSize chunks n_input = tileSizeLow ** 2 n_output = tileSizeHigh ** 2 if dataDimension == 3: n_input *= tileSizeLow n_output *= (tileSizeLow*upRes) n_inputChannels = 1 if useVelocities: n_inputChannels += 3 if useVorticities: n_inputChannels += 3 n_input *= n_inputChannels # init paths if not load_model_test == -1: if not os.path.exists(basePath + 'test_%04d/' % load_model_test): print('ERROR: Test to load does not exist.') load_path = basePath + 'test_%04d/model_%04d.ckpt' % (load_model_test, load_model_no) if outputOnly: out_path_prefix = 'out_%04d-%04d' % (load_model_test,load_model_no) test_path,_ = ph.getNextGenericPath(out_path_prefix, 0, basePath + 'test_%04d/' % load_model_test) else: test_path,_ = ph.getNextTestPath(testPathStartNo, basePath) else: test_path, load_model_test_new = ph.getNextTestPath(testPathStartNo, basePath) # logging & info sys.stdout = ph.Logger(test_path) print('Note: {}'.format(note)) print("\nCalled on machine '"+ os.uname()[1] +"' with: " + str(" ".join(sys.argv) ) ) print("\nUsing parameters:\n"+ph.paramsToString()) ph.writeParams(test_path+"params.json") # export parameters in human readable format if outputOnly: print('*****OUTPUT ONLY*****') if not outputOnly: os.makedirs(test_path+"/zbu_src") uniio.backupFile(__file__, test_path+"/zbu_src/") uniio.backupFile("../tools/tilecreator_t.py", test_path+"/zbu_src/") uniio.backupFile("../tools/GAN.py", test_path+"/zbu_src/") uniio.backupFile("../tools/fluiddataloader.py", test_path+"/zbu_src/") #input for gen x = tf.placeholder(tf.float32, shape=[None, n_input]) #reference input for disc x_disc = tf.placeholder(tf.float32, shape=[None, n_input]) #real input for disc y = tf.placeholder(tf.float32, shape=[None, n_output]) kk = tf.placeholder(tf.float32) kk2 = tf.placeholder(tf.float32) kkt = tf.placeholder(tf.float32) kktl = tf.placeholder(tf.float32) # keep probablity for dropout keep_prob = tf.placeholder(tf.float32) print("x: {}".format(x.get_shape())) # --- main graph setup --- rbId = 0 def resBlock(gan, inp, s1,s2, reuse, use_batch_norm, filter_size=3): global rbId # convolutions of resnet block if dataDimension == 2: filter = [filter_size,filter_size] filter1 = [1,1] elif dataDimension == 3: filter = [filter_size,filter_size,filter_size] filter1 = [1,1,1] gc1,_ = gan.convolutional_layer( s1, filter, tf.nn.relu, stride=[1], name="g_cA%d"%rbId, in_layer=inp, reuse=reuse, batch_norm=use_batch_norm, train=train) #->16,64 gc2,_ = gan.convolutional_layer( s2, filter, None , stride=[1], name="g_cB%d"%rbId, reuse=reuse, batch_norm=use_batch_norm, train=train) #->8,128 # shortcut connection gs1,_ = gan.convolutional_layer(s2, filter1 , None , stride=[1], name="g_s%d"%rbId, in_layer=inp, reuse=reuse, batch_norm=use_batch_norm, train=train) #->16,64 resUnit1 = tf.nn.relu( tf.add( gc2, gs1 ) ) rbId += 1 return resUnit1 def gen_resnet(_in, reuse=False, use_batch_norm=False, train=None): global rbId print("\n\tGenerator (resize-resnett3-deep)") with tf.variable_scope("generator", reuse=reuse) as scope: if dataDimension == 2: _in = tf.reshape(_in, shape=[-1, tileSizeLow, tileSizeLow, n_inputChannels]) #NHWC patchShape = [2,2] elif dataDimension == 3: _in = tf.reshape(_in, shape=[-1, tileSizeLow, tileSizeLow, tileSizeLow, n_inputChannels]) #NDHWC patchShape = [2,2,2] rbId = 0 gan = GAN(_in) gan.max_depool() inp = gan.max_depool() ru1 = resBlock(gan, inp, n_inputChannels*2,n_inputChannels*8, reuse, use_batch_norm,5) ru2 = resBlock(gan, ru1, 128, 128, reuse, use_batch_norm,5) inRu3 = ru2 ru3 = resBlock(gan, inRu3, 32, 8, reuse, use_batch_norm,5) ru4 = resBlock(gan, ru3, 2, 1, reuse, False,5) resF = tf.reshape( ru4, shape=[-1, n_output] ) print("\tDOFs: %d , %f m " % ( gan.getDOFs() , gan.getDOFs()/1000000.) ) return resF ############################################discriminator network############################################################### def disc_binclass(in_low, in_high, reuse=False, use_batch_norm=False, train=None): #in_low: low res reference input, same as generator input (condition) #in_high: real or generated high res input to classify #reuse: variable reuse #use_batch_norm: bool, if true batch norm is used in all but the first con layers #train: if use_batch_norm, tf bool placeholder print("\n\tDiscriminator (conditional binary classifier)") with tf.variable_scope("discriminator", reuse=reuse): if dataDimension == 2: shape = tf.shape(in_low) in_low = tf.slice(in_low,[0,0],[shape[0],int(n_input/n_inputChannels)]) in_low = GAN(tf.reshape(in_low, shape=[-1, tileSizeLow, tileSizeLow, 1])).max_depool(height_factor = upRes,width_factor=upRes) #NHWC in_high = tf.reshape(in_high, shape=[-1, tileSizeHigh, tileSizeHigh, 1]) filter=[4,4] stride = [2] stride2 = [2] elif dataDimension == 3: shape = tf.shape(in_low) in_low = tf.slice(in_low,[0,0],[shape[0],int(n_input/n_inputChannels)]) in_low = GAN(tf.reshape(in_low, shape=[-1, tileSizeLow, tileSizeLow, tileSizeLow, 1])).max_depool(depth_factor = upRes,height_factor = upRes,width_factor = upRes) #NDHWC in_high = tf.reshape(in_high, shape=[-1, tileSizeHigh, tileSizeHigh, tileSizeHigh, 1]) # dim D is not upscaled filter=[4,4,4] stride = [2,2] stride2 = [2] #merge in_low and in_high to [-1, tileSizeHigh, tileSizeHigh, 2] gan = GAN(tf.concat([in_low, in_high], axis=-1), bn_decay=bn_decay) #64 d1,_ = gan.convolutional_layer(32, filter, lrelu, stride=stride2, name="d_c1", reuse=reuse) #32 d2,_ = gan.convolutional_layer(64, filter, lrelu, stride=stride2, name="d_c2", reuse=reuse, batch_norm=use_batch_norm, train=train) #64 d3,_ = gan.convolutional_layer(128, filter, lrelu, stride=stride, name="d_c3", reuse=reuse, batch_norm=use_batch_norm, train=train) #128 d4,_ = gan.convolutional_layer(256, filter, lrelu, stride=[1], name="d_c4", reuse=reuse, batch_norm=use_batch_norm, train=train) #256 shape=gan.flatten() gan.fully_connected_layer(1, None, name="d_l5") print("\tDOFs: %d " % gan.getDOFs()) return gan.y(), d1, d2, d3, d4 ############################################ Tempo discriminator network ############################################################ def disc_binclass_cond_tempo(in_high, n_t_channels=3, reuse=False, use_batch_norm=False, train=None): # NO in_low: low res reference input, same as generator input (no condition) # in_high: real or generated high res input to classify, shape should be batch, dim_z, dim_y, dim_x, channels # reuse: variable reuse # use_batch_norm: bool, if true batch norm is used in all but the first con layers # train: if use_batch_norm, tf bool placeholder print("\n\tDiscriminator for Tempo (conditional binary classifier)") print("\n\tTempo, nearby frames packed as channels, number %d" % n_t_channels) with tf.variable_scope("discriminatorTempo", reuse=reuse): if dataDimension == 2: in_high = tf.reshape(in_high, shape=[-1, tileSizeHigh, tileSizeHigh, n_t_channels]) filter=[4,4] stride = [2] stride2 = [2] elif dataDimension == 3: in_high = tf.reshape(in_high, shape=[-1, tileSizeHigh, tileSizeHigh, tileSizeHigh, n_t_channels]) # dim D is not upscaled filter=[4,4,4] stride = [2,2] stride2 = [2] # merge in_low and in_high to [-1, tileSizeHigh, tileSizeHigh, 2] gan = GAN(in_high, bn_decay=bn_decay) # 64 t1, _ = gan.convolutional_layer(32, filter, lrelu, stride=stride2, name="t_c1", reuse=reuse) # 32 t2, _ = gan.convolutional_layer(64, filter, lrelu, stride=stride2, name="t_c2", reuse=reuse, batch_norm=use_batch_norm, train=train) # 64 t3, _ = gan.convolutional_layer(128, filter, lrelu, stride=stride, name="t_c3", reuse=reuse, batch_norm=use_batch_norm, train=train) # 128 t4, _ = gan.convolutional_layer(256, filter, lrelu, stride=[1], name="t_c4", reuse=reuse, batch_norm=use_batch_norm, train=train) # 256 shape = gan.flatten() gan.fully_connected_layer(1, None, name="t_l5") print("\tDOFs: %d " % gan.getDOFs()) return gan.y() ############################################gen_test############################################################### def gen_test(_in, reuse=False, use_batch_norm=False, train=None): global rbId print("\n\tGenerator-test") with tf.variable_scope("generator-test", reuse=reuse) as scope: if dataDimension == 2: _in = tf.reshape(_in, shape=[-1, tileSizeLow, tileSizeLow, n_inputChannels]) #NHWC patchShape = [2,2] elif dataDimension == 3: _in = tf.reshape(_in, shape=[-1, tileSizeLow, tileSizeLow, tileSizeLow, n_inputChannels]) #NDHWC patchShape = [2,2,2] rbId = 0 gan = GAN(_in) gan.max_depool() i2np,_ = gan.deconvolutional_layer(32, patchShape, None, stride=[1,1], name="g_D1", reuse=reuse, batch_norm=False, train=train, init_mean=0.99) gan.max_depool() inp,_ = gan.deconvolutional_layer(1 , patchShape, None, stride=[1,1], name="g_D2", reuse=reuse, batch_norm=False, train=train, init_mean=0.99) return tf.reshape( inp, shape=[-1, n_output] ) ############################################disc_test############################################################### def disc_test(in_low, in_high, reuse=False, use_batch_norm=False, train=None): print("\n\tDiscriminator-test") with tf.variable_scope("discriminator_test", reuse=reuse): if dataDimension == 2: shape = tf.shape(in_low) in_low = tf.slice(in_low,[0,0],[shape[0],int(n_input/n_inputChannels)]) in_low = GAN(tf.reshape(in_low, shape=[-1, tileSizeLow, tileSizeLow, 1])).max_depool(height_factor = upRes,width_factor = upRes) #NHWC in_high = tf.reshape(in_high, shape=[-1, tileSizeHigh, tileSizeHigh, 1]) filter=[4,4] stride2 = [2] elif dataDimension == 3: shape = tf.shape(in_low) in_low = tf.slice(in_low,[0,0],[shape[0],int(n_input/n_inputChannels)]) in_low = GAN(tf.reshape(in_low, shape=[-1, tileSizeLow, tileSizeLow, tileSizeLow, 1])).max_depool(depth_factor = upRes,height_factor = upRes,width_factor = upRes) #NDHWC in_high = tf.reshape(in_high, shape=[-1, tileSizeHigh, tileSizeHigh, tileSizeHigh, 1]) # dim D is not upscaled filter=[4,4,4] stride2 = [2] #merge in_low and in_high to [-1, tileSizeHigh, tileSizeHigh, 2] gan = GAN(tf.concat([in_low, in_high], axis=-1), bn_decay=bn_decay) #64 d1,_ = gan.convolutional_layer(32, filter, lrelu, stride=stride2, name="d_c1", reuse=reuse) #32 shape=gan.flatten() gan.fully_connected_layer(1, None, name="d_l5") if dataDimension == 2: d2 = tf.constant(1., shape = [batch_size, tileSizeLow,tileSizeLow,64]) d3 = tf.constant(1., shape = [batch_size, int(tileSizeLow/2),int(tileSizeLow/2),128]) d4 = tf.constant(1., shape = [batch_size, int(tileSizeLow/2),int(tileSizeLow/2),256]) elif dataDimension == 3: d2 = tf.constant(1., shape = [batch_size, tileSizeLow,tileSizeLow,tileSizeLow,64]) d3 = tf.constant(1., shape = [batch_size, int(tileSizeLow/2),int(tileSizeLow/2),int(tileSizeLow/2),128]) d4 = tf.constant(1., shape = [batch_size, int(tileSizeLow/2),int(tileSizeLow/2),int(tileSizeLow/2),256]) print("\tDOFs: %d " % gan.getDOFs()) return gan.y(), d1, d2, d3, d4 #change used models for gen and disc here #other models in NNmodels.py gen_model = locals()[genModel] disc_model = locals()[discModel] disc_time_model = disc_binclass_cond_tempo # tempo dis currently fixed #set up GAN structure bn=batch_norm #training or testing for batch norm train = tf.placeholder(tf.bool) if not outputOnly: #setup for training gen_part = gen_model(x, use_batch_norm=bn, train=train) if use_spatialdisc: disc, dy1, dy2, dy3, dy4 = disc_model(x_disc, y, use_batch_norm=bn, train=train) gen, gy1, gy2, gy3, gy4 = disc_model(x_disc, gen_part, reuse=True, use_batch_norm=bn, train=train) if genValiImg > -1: sampler = gen_part else: #setup for generating output with trained model sampler = gen_model(x, use_batch_norm=bn, train=False) sys.stdout.flush() # --------------------------------------------- # TENSORFLOW SETUP # build the tensorflow graph for tensor(value) re-sampling (at pos) # value shape (batch, ..., res_x2, res_x1, channels) # pos shape (batch, ..., res_x2, res_x1, dim) def tensorResample(value, pos, name='Resample'): with tf.name_scope(name) as scope: pos_shape = pos.get_shape().as_list() dim = len(pos_shape) - 2 # batch and channels are ignored assert (dim == pos_shape[-1]) floors = tf.cast(tf.floor(pos - 0.5), tf.int32) ceils = floors + 1 # clamp min floors = tf.maximum(floors, tf.zeros_like(floors)) ceils = tf.maximum(ceils, tf.zeros_like(ceils)) # clamp max floors = tf.minimum(floors, tf.constant(value.get_shape().as_list()[1:dim + 1], dtype=tf.int32) - 1) ceils = tf.minimum(ceils, tf.constant(value.get_shape().as_list()[1:dim + 1], dtype=tf.int32) - 1) _broadcaster = tf.ones_like(ceils) cell_value_list = [] cell_weight_list = [] for axis_x in range(int(pow(2, dim))): # 3d, 0-7; 2d, 0-3;... condition_list = [bool(axis_x & int(pow(2, i))) for i in range(dim)] condition_ = (_broadcaster > 0) & condition_list axis_idx = tf.cast( tf.where(condition_, ceils, floors), tf.int32) # only support linear interpolation... axis_wei = 1.0 - tf.abs((pos - 0.5) - tf.cast(axis_idx, tf.float32)) # shape (..., res_x2, res_x1, dim) axis_wei = tf.reduce_prod(axis_wei, axis=-1, keep_dims=True) cell_weight_list.append(axis_wei) # single scalar(..., res_x2, res_x1, 1) first_idx = tf.ones_like(axis_wei, dtype=tf.int32) first_idx = tf.cumsum(first_idx, axis=0, exclusive=True) cell_value_list.append(tf.concat([first_idx, axis_idx], -1)) values_new = tf.gather_nd(value, cell_value_list[0]) * cell_weight_list[ 0] # broadcasting used, shape (..., res_x2, res_x1, channels ) for cell_idx in range(1, len(cell_value_list)): values_new = values_new + tf.gather_nd(value, cell_value_list[cell_idx]) * cell_weight_list[cell_idx] return values_new # shape (..., res_x2, res_x1, channels) if not outputOnly: #for discriminator [0,1] output if use_spatialdisc: disc_sigmoid = tf.reduce_mean(tf.nn.sigmoid(disc)) gen_sigmoid = tf.reduce_mean(tf.nn.sigmoid(gen)) # loss of the discriminator with real input disc_loss_disc = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=disc, labels=tf.ones_like(disc))) #loss of the discriminator with input from generator disc_loss_gen = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=gen, labels=tf.zeros_like(gen))) disc_loss_layer = k2_l1*tf.reduce_mean(tf.nn.l2_loss(dy1 - gy1)) + k2_l2*tf.reduce_mean(tf.nn.l2_loss(dy2 - gy2)) + k2_l3*tf.reduce_mean(tf.nn.l2_loss(dy3 - gy3)) + k2_l4*tf.reduce_mean(tf.nn.l2_loss(dy4 - gy4)) disc_loss = disc_loss_disc * weight_dld + disc_loss_gen #loss of the generator gen_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=gen, labels=tf.ones_like(gen))) else: gen_loss = tf.zeros([1]) disc_loss_layer = tf.zeros([1]) #additional generator losses gen_l2_loss = tf.nn.l2_loss(y - gen_part) gen_l1_loss = tf.reduce_mean(tf.abs(y - gen_part)) #use mean to normalize w.r.t. output dims. tf.reduce_sum(tf.abs(y - gen_part)) #uses sigmoid cross entropy and l1 - see cGAN paper gen_loss_complete = gen_loss + gen_l1_loss*kk + disc_loss_layer*kk2 # set up decaying learning rate, if enabled lr_global_step = tf.Variable(0, trainable=False) learning_rate_scalar = learning_rate if decayLR: learning_rate = tf.train.polynomial_decay(learning_rate, lr_global_step, trainingIters//2, learning_rate_scalar*0.05, power=1.1) update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) gen_update_ops = update_ops[:] ori_gen_update_ops = update_ops[:] #variables to be used in the different otimization steps vars = tf.trainable_variables() g_var = [var for var in vars if "g_" in var.name] if use_spatialdisc: dis_update_ops = update_ops[:] d_var = [var for var in vars if "d_" in var.name] if (useTempoD or useTempoL2):# temporal loss here disT_update_ops = [] ori_gen_loss_complete = gen_loss_complete # currently, the update_op gathering is not too nice and very sensitive to the operation order. # TODO: make it flexible! n_t = 3 device_str = '/device:GPU:0' if(dataDimension == 3): # have to use a second GPU! device_str = '/device:GPU:1' with tf.device(device_str): x_t = tf.placeholder(tf.float32, shape=[None, n_input]) gen_part_t = gen_model(x_t, reuse=True, use_batch_norm=bn, train=train) if(ADV_flag): y_pos = tf.placeholder(tf.float32, shape=[None, n_output * dataDimension]) if dataDimension == 2: gen_part_t_shape = tf.reshape(gen_part_t, shape=[-1, tileSizeHigh, tileSizeHigh, 1]) pos_array = tf.reshape(y_pos, shape=[-1, tileSizeHigh, tileSizeHigh, 2]) elif dataDimension == 3: # check in 3D gen_part_t_shape = tf.reshape(gen_part_t, shape=[-1, tileSizeHigh, tileSizeHigh, tileSizeHigh, 1]) pos_array = tf.reshape(y_pos, shape=[-1, tileSizeHigh, tileSizeHigh, tileSizeHigh, 3]) gen_part_t = tensorResample(gen_part_t_shape, pos_array) gen_part_t = tf.reshape(gen_part_t, shape = [-1, n_t, n_output]) gen_part_t = tf.transpose(gen_part_t, perm=[0, 2, 1]) # batch, n_output, channels if (useTempoL2): # l2 tempo_loss update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) for update_op in update_ops: if ("/g_" in update_op.name) and ("generator" in update_op.name) and (not ( update_op in gen_update_ops )): gen_update_ops.append(update_op) gen_part_t_list = tf.unstack(gen_part_t, axis = -1) # should have n_t dim tl_gen_loss = tf.reduce_mean( tf.square( gen_part_t_list[0] - gen_part_t_list[1] ) ) for ti in range( 1, n_t-1 ): tl_gen_loss = tl_gen_loss + tf.reduce_mean( tf.square( gen_part_t_list[ti] - gen_part_t_list[ti + 1] ) ) gen_loss_complete = gen_loss_complete + kktl * tl_gen_loss if (useTempoD): # real input for disc y_t = tf.placeholder(tf.float32, shape=[None, n_output]) if (ADV_flag): if dataDimension == 2: y_t_shape = tf.reshape(y_t, shape=[-1, tileSizeHigh, tileSizeHigh, 1]) elif dataDimension == 3: # check in 3D y_t_shape = tf.reshape(y_t, shape=[-1, tileSizeHigh, tileSizeHigh, tileSizeHigh, 1]) y_tR = tensorResample(y_t_shape, pos_array) else: y_tR = y_t y_tR =tf.reshape(y_tR, shape = [-1, n_t, n_output]) y_tR = tf.transpose(y_tR, perm=[0, 2, 1]) # batch, n_output, channels gen_t = disc_time_model(gen_part_t, n_t_channels = n_t, use_batch_norm=bn, train=train) update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) for update_op in update_ops: if ("/g_" in update_op.name) and ("generator" in update_op.name) and (not ( update_op in gen_update_ops )): gen_update_ops.append(update_op) disT_update_ops.append(update_op) if ("/t_" in update_op.name) and ("discriminatorTempo" in update_op.name): gen_update_ops.append(update_op) # discrimiinator for tempo only disc_t = disc_time_model(y_tR, n_t_channels = n_t, reuse=True, use_batch_norm=bn, train=train) update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) for update_op in update_ops: if ("/t_" in update_op.name) and ("discriminatorTempo" in update_op.name): disT_update_ops.append(update_op) t_disc_sigmoid = tf.reduce_mean(tf.nn.sigmoid(disc_t)) t_gen_sigmoid = tf.reduce_mean(tf.nn.sigmoid(gen_t)) vars = tf.trainable_variables() t_var = [var for var in vars if "t_" in var.name] # loss of the discriminator with real input t_disc_loss_disc = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits(logits=disc_t, labels=tf.ones_like(disc_t))) # loss of the discriminator with input from generator t_disc_loss_gen = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits(logits=gen_t, labels=tf.zeros_like(gen_t))) t_disc_loss = t_disc_loss_disc * weight_dld + t_disc_loss_gen t_gen_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=gen_t, labels=tf.ones_like(gen_t))) gen_loss_complete = gen_loss_complete + kkt * t_gen_loss with tf.control_dependencies(disT_update_ops): t_disc_optimizer = tf.train.AdamOptimizer(learning_rate, beta1=beta).minimize(t_disc_loss, var_list=t_var) with tf.control_dependencies(ori_gen_update_ops): # optimizer for generator, can only change variables of the generator, ori_gen_optimizer = tf.train.AdamOptimizer(learning_rate, beta1=beta).minimize(ori_gen_loss_complete, var_list=g_var) if use_spatialdisc: with tf.control_dependencies(dis_update_ops): #optimizer for discriminator, uses combined loss, can only change variables of the disriminator disc_optimizer_adam = tf.train.AdamOptimizer(learning_rate, beta1=beta) disc_optimizer = disc_optimizer_adam.minimize(disc_loss, var_list=d_var) with tf.control_dependencies(gen_update_ops): # optimizer for generator, can only change variables of the generator, gen_optimizer = tf.train.AdamOptimizer(learning_rate, beta1=beta).minimize(gen_loss_complete, var_list=g_var) # create session and saver config = tf.ConfigProto(allow_soft_placement=True) sess = tf.InteractiveSession(config = config) saver = tf.train.Saver(max_to_keep=maxToKeep) # init vars or load model if load_model_test == -1: sess.run(tf.global_variables_initializer()) else: saver.restore(sess, load_path) print("Model restored from %s." % load_path) if not outputOnly: # create a summary to monitor cost tensor #training losses if use_spatialdisc: lossTrain_disc = tf.summary.scalar("discriminator-loss train", disc_loss) lossTrain_gen = tf.summary.scalar("generator-loss train", gen_loss) #testing losses if use_spatialdisc: lossVali_disc_disc = tf.summary.scalar("discriminator-loss vali real", disc_loss_disc) lossVali_disc_gen = tf.summary.scalar("discriminator-loss vali generated", disc_loss_gen) lossVali_disc = tf.summary.scalar("discriminator-loss vali", disc_loss) lossVali_gen = tf.summary.scalar("generator-loss vali", gen_loss) #discriminator output [0,1] for real input if use_spatialdisc: outTrain_disc_real = tf.summary.scalar("discriminator-out train", disc_sigmoid) outTrain_disc_gen = tf.summary.scalar("generator-out train", gen_sigmoid) #discriminator output [0,1] for generated input if use_spatialdisc: outVali_disc_real = tf.summary.scalar("discriminator-out vali", disc_sigmoid) outVali_disc_gen = tf.summary.scalar("generator-out vali", gen_sigmoid) if(useTempoD): # all temporal losses # training losses, disc & gen lossTrain_disc_t = tf.summary.scalar("T discriminator-loss train", t_disc_loss) lossTrain_gen_t = tf.summary.scalar("T generator-loss train", t_gen_loss) # validation losses, discriminator( positive, negative ), generator lossVali_disc_disc_t = tf.summary.scalar("T discriminator-loss vali real", t_disc_loss_disc) lossVali_disc_gen_t = tf.summary.scalar("T discriminator-loss vali generated", t_disc_loss_gen) lossVali_disc_t = tf.summary.scalar("T discriminator-loss vali", t_disc_loss) lossVali_gen_t = tf.summary.scalar("T generator-loss vali", t_gen_loss) # discriminator output [0,1] for real input, during training outTrain_disc_real_t = tf.summary.scalar("T discriminator-out train", t_disc_sigmoid) # discriminator output [0,1] for generated input outTrain_disc_gen_t = tf.summary.scalar("T generator-out train", t_gen_sigmoid) # discriminator output [0,1] for real input, during validation outVali_disc_real_t = tf.summary.scalar("T discriminator-out vali", t_disc_sigmoid) # discriminator output [0,1] for generated input outVali_disc_gen_t = tf.summary.scalar("T generator-out vali", t_gen_sigmoid) if (useTempoL2): # all temporal losses lossTrain_gen_t_l = tf.summary.scalar("T generator-loss train l2", tl_gen_loss) lossVali_gen_t_l = tf.summary.scalar("T generator-loss vali l2", tl_gen_loss) merged_summary_op = tf.summary.merge_all() summary_writer = tf.summary.FileWriter(test_path, sess.graph) save_no = 0 tileSizeHi = upRes * tileSizeLow if dataDimension == 2: tilesPerImg = (simSizeHigh // tileSizeHi) ** 2 else: tilesPerImg = (simSizeHigh // tileSizeHi) ** 3 image_no = 0 if not outputOnly: os.makedirs(test_path+'test_img/') def addVorticity(Vel): if dataDimension == 2: vorout = np.zeros_like(Vel) for l in range(vorout.shape[0]): for i in range(1, vorout.shape[-3]-1): for j in range(1, vorout.shape[-2]-1): vorout[l][0][i][j][2] = 0.5 * ((Vel[l][0][i+1][j][1] - Vel[l][0][i-1][j][1]) - (Vel[l][0][i][j+1][0] - Vel[l][0][i][j-1][0])) else: vorout = np.zeros_like(Vel) for l in range(vorout.shape[0]): for i in range(1, vorout.shape[-4]-1): for j in range(1, vorout.shape[-3]-1): for k in range(1, vorout.shape[-2]-1): vorout[l][i][j][k][0] = 0.5 * ((Vel[l][i][j+1][k][2] - Vel[l][i][j-1][k][2]) - (Vel[l][i][j][k+1][1] - Vel[l][i][j][k-1][1])) vorout[l][i][j][k][1] = 0.5 * ((Vel[l][i][j][k+1][0] - Vel[l][i][j][k-1][0]) - (Vel[l][i+1][j][k][2] - Vel[l][i-1][j][k][2])) vorout[l][i][j][k][2] = 0.5 * ((Vel[l][i+1][j][k][1] - Vel[l][i-1][j][k][1]) - (Vel[l][i][j+1][k][0] - Vel[l][i][j-1][k][0])) return vorout def getInput(index = 1, randomtile = True, isTraining = True, batch_size = 1, useDataAugmentation = False, useVelocities = False, useVorticities = False): if randomtile == False: batch_xs, batch_ys = tiCr.getFrameTiles(index) else: batch_xs, batch_ys = tiCr.selectRandomTiles(selectionSize = batch_size, augment=useDataAugmentation) if useVelocities and useVorticities: Velinput = batch_xs[:,:,:,:,tiCr.c_lists[tc.DATA_KEY_LOW][tc.C_KEY_VELOCITY][0]] Vorinput = addVorticity(Velinput) batch_xs = np.concatenate((batch_xs, Vorinput), axis = 4) batch_xs = np.reshape(batch_xs, (-1, n_input)) batch_ys = np.reshape(batch_ys, (-1, n_output)) return batch_xs, batch_ys def getTempoinput(batch_size = 1, isTraining = True, useDataAugmentation = False, useVelocities = False, useVorticities = False, n_t = 3, dt=1.0, adv_flag = 1.0): batch_xts, batch_yts, batch_y_pos = tiCr.selectRandomTempoTiles(batch_size, isTraining, useDataAugmentation, n_t, dt, adv_flag) if useVelocities and useVorticities: real_batch_sz = batch_xts.shape[0] if( dataDimension == 2): batch_xts = np.reshape(batch_xts,[real_batch_sz,1,tileSizeLow,tileSizeLow,-1]) else: batch_xts = np.reshape(batch_xts,[real_batch_sz,tileSizeLow,tileSizeLow,tileSizeLow,-1]) Velinput = batch_xts[:,:,:,:,tiCr.c_lists[tc.DATA_KEY_LOW][tc.C_KEY_VELOCITY][0]] Vorinput = addVorticity(Velinput) batch_xts = np.concatenate((batch_xts, Vorinput), axis = 4) batch_xts = np.reshape(batch_xts,[real_batch_sz, -1]) return batch_xts, batch_yts, batch_y_pos #evaluate the generator (sampler) on the first step of the first simulation and output result def generateValiImage(sim_no = fromSim, frame_no = 1, outPath = test_path,imageindex = 0): if premadeTiles: #todo output for premadetiles pass else: if (not outputOnly): batch_xs, _ = getInput(randomtile = False, index = (sim_no-fromSim)*frameMax + frame_no, useVelocities = useVelocities, useVorticities = useVorticities) else: batch_xs = inputx[frame_no] resultTiles = [] for tileno in range(batch_xs.shape[0]): batch_xs_in = np.reshape(batch_xs[tileno],[-1, n_input]) results = sess.run(sampler, feed_dict={x: batch_xs_in, keep_prob: dropoutOutput, train: False}) resultTiles.extend(results) resultTiles = np.array(resultTiles) if dataDimension == 2: # resultTiles may have a different size imgSz = int(resultTiles.shape[1]**(1.0/2) + 0.5) resultTiles = np.reshape(resultTiles,[resultTiles.shape[0],imgSz,imgSz, 1]) else: imgSz = int(resultTiles.shape[1]**(1.0/3) + 0.5) resultTiles = np.reshape(resultTiles,[resultTiles.shape[0],imgSz,imgSz,imgSz]) tiles_in_image=[int(simSizeHigh/tileSizeHigh),int(simSizeHigh/tileSizeHigh)] tc.savePngsGrayscale(resultTiles,outPath, imageCounter=(imageindex+frameMin), tiles_in_image=tiles_in_image) def generate3DUni(sim_no = fromSim, frame_no = 1, outPath = test_path,imageindex = 0): if dataDimension == 2: print("ERROR: only for 3D Uni files output!") exit(1) if premadeTiles: #todo output for premadetiles pass else: if (overlap*2 > tileSizeLow) or (tileSizeLow > simLowLength): print("Wrong parameters for 3d output!") exit(1) batch_xs = inputx[frame_no] if useVelocities and useVorticities: batch_xs = np.reshape(batch_xs,[1,simLowLength,simLowWidth,simLowHeight,-1]) Velinput = batch_xs[:,:,:,:,tiCr.c_lists[tc.DATA_KEY_LOW][tc.C_KEY_VELOCITY][0]] Vorinput = addVorticity(Velinput) batch_xs = np.concatenate((batch_xs, Vorinput), axis = 4) batch_xs = np.reshape(batch_xs,[simLowLength,simLowWidth,simLowHeight,-1]) tiles = [] batch_xs=np.reshape(batch_xs,[simLowLength,simLowWidth,simLowHeight,-1]) lengthnum = ((simLowLength-overlap*2+tileSizeLow-overlap*2-1)//(tileSizeLow-overlap*2)) widthnum = ((simLowWidth-overlap*2+tileSizeLow-overlap*2-1)//(tileSizeLow-overlap*2)) heightnum = ((simLowHeight-overlap*2+tileSizeLow-overlap*2-1)//(tileSizeLow-overlap*2)) for i in range(lengthnum): for j in range(widthnum): for k in range(heightnum): ifrom = (tileSizeLow-overlap*2)*i ito = (tileSizeLow-overlap*2)*i+tileSizeLow jfrom = (tileSizeLow-overlap*2)*j jto = (tileSizeLow-overlap*2)*j+tileSizeLow kfrom = (tileSizeLow-overlap*2)*k kto = (tileSizeLow-overlap*2)*k+tileSizeLow if ito >simLowLength: ifrom = simLowLength-tileSizeLow ito = simLowLength if jto >simLowWidth: jfrom = simLowWidth-tileSizeLow jto = simLowWidth if kto >simLowHeight: kfrom = simLowHeight-tileSizeLow kto = simLowHeight low = batch_xs[ifrom:ito, jfrom:jto, kfrom:kto, :] tiles.append(low) batch_xs = np.array(tiles) resultTiles = [] for tileno in range(batch_xs.shape[0]): batch_xs_in = np.reshape(batch_xs[tileno],[-1, n_input]) results = sess.run(sampler, feed_dict={x: batch_xs_in, keep_prob: dropoutOutput, train : False}) results = np.array(results) resultTiles.extend(results) resultTiles = np.array(resultTiles) resulttiles = np.reshape(resultTiles,[resultTiles.shape[0],tileSizeHigh,tileSizeHigh,tileSizeHigh]) high = np.zeros([simLowLength*upRes,simLowWidth*upRes,simLowHeight*upRes]) for i in range(lengthnum): for j in range(widthnum): for k in range(heightnum): ihighfrom = (tileSizeLow-overlap*2)*upRes*(i-1)+(tileSizeLow-overlap)*upRes ihighto = ihighfrom + (tileSizeLow-overlap*2)*upRes jhighfrom = (tileSizeLow-overlap*2)*upRes*(j-1)+(tileSizeLow-overlap)*upRes jhighto = jhighfrom+(tileSizeLow-overlap*2)*upRes khighfrom = (tileSizeLow-overlap*2)*upRes*(k-1)+(tileSizeLow-overlap)*upRes khighto = khighfrom+(tileSizeLow-overlap*2)*upRes ifrom = overlap*upRes ito = (tileSizeLow-overlap)*upRes jfrom = overlap*upRes jto = (tileSizeLow-overlap)*upRes kfrom = overlap*upRes kto = (tileSizeLow-overlap)*upRes if i == 0: ifrom = 0 ito = (tileSizeLow-overlap)*upRes ihighfrom = 0 ihighto = (tileSizeLow-overlap)*upRes if j == 0: jfrom = 0 jto = (tileSizeLow-overlap)*upRes jhighfrom = 0 jhighto = (tileSizeLow-overlap)*upRes if k == 0: kfrom = 0 kto = (tileSizeLow-overlap)*upRes khighfrom = 0 khighto = (tileSizeLow-overlap)*upRes if i == lengthnum-1: ifrom = overlap*upRes ito = tileSizeLow*upRes ihighfrom = simLowLength*upRes-tileSizeLow*upRes+overlap*upRes ihighto = simLowLength*upRes if j == widthnum-1: jfrom = overlap*upRes jto = tileSizeLow*upRes jhighfrom = simLowWidth*upRes-tileSizeLow*upRes+overlap*upRes jhighto = simLowWidth*upRes if k == heightnum-1: kfrom = overlap*upRes kto = tileSizeLow*upRes khighfrom = simLowHeight*upRes-tileSizeLow*upRes+overlap*upRes khighto = simLowHeight*upRes high[ihighfrom: ihighto, jhighfrom:jhighto, khighfrom:khighto] = resulttiles[i*widthnum*heightnum+j*heightnum+k][ifrom:ito,jfrom:jto,kfrom:kto] high = np.reshape(high,[simLowLength*upRes,simLowWidth*upRes,simLowHeight*upRes]) head, _ = uniio.readUni(loadPath + "sim_%04d/density_high_%04d.uni"%(sim_no,frame_no+frameMin)) head['dimX'] = simLowHeight*upRes head['dimY'] = simLowWidth*upRes head['dimZ'] = simLowLength*upRes uniio.writeUni(outPath+'source_%04d.uni'%(frame_no+frameMin), head, high) def saveModel(cost, exampleOut=-1, imgPath = test_path): global save_no saver.save(sess, test_path + 'model_%04d.ckpt' % save_no) msg = 'Saved Model %04d with cost %f.' % (save_no, cost) if exampleOut > -1: generateValiImage(imageindex = save_no, outPath = imgPath) save_no += 1 return msg # write summary to test overview loaded_model = '' if not load_model_test == -1: loaded_model = ', Loaded %04d, %04d' % (load_model_test , load_model_no) with open(basePath + 'test_overview.log', "a") as text_file: if not outputOnly: text_file.write(test_path[-10:-1] + ': {}D, \"{}\"\n'.format(dataDimension, note)) text_file.write('\t{} Iters, gen: {}, disc: {}'.format(trainingIters, gen_model.__name__, disc_model.__name__) + loaded_model + '\n') text_file.write('\tgen-runs: {}, disc-runs: {}, lambda: {}, dropout: {:.4f}({:.4f})'.format(genRuns, discRuns, k, dropout, dropoutOutput) + '\n') else: text_file.write('Output:' + loaded_model + ' (' + test_path[-28:-1] + ')\n') text_file.write('\ttile size: {}, seed: {}, dropout-out: {:.4f}'.format(tileSizeLow, randSeed, dropoutOutput) + '\n') # --------------------------------------------- # --------------------------------------------- # START TRAINING training_duration = 0.0 cost = 0.0 if not outputOnly and trainGAN: try: print('\n*****TRAINING STARTED*****\n') print('(stop with ctrl-c)') avgCost_disc = 0 avgCost_gen = 0 avgL1Cost_gen = 0 avgOut_disc = 0 avgOut_gen = 0 avgValiCost_disc_real = 0 avgValiCost_disc_gen = 0 avgValiCost_gen = 0 avgValiOut_disc_real = 0 avgValiOut_disc_gen = 0 validations = 0 startTime = time.time() intervalTime = startTime lastOut = 1 lastSave = 1 lastCost = 1e10 saved = False saveMsg = '' kkin = k kk2in = k2 disc_cost = 0 gen_cost = 0 avgTemCost_gen = 0 avgTemCost_gen_l = 0 avgTemCost_disc = 0 kktin = kt kktin_l = kt_l avgOut_disc_t = 0 avgOut_gen_t = 0 avgValiCost_disc_real_t = 0 avgValiOut_disc_real_t = 0 avgValiCost_disc_gen_t = 0 avgValiOut_disc_gen_t = 0 avgValiCost_gen_t = 0 avgValiCost_gen_t_l = 0 for iteration in range(trainingIters): lrgs = max(0, iteration-(trainingIters//2)) # LR counter, start decay at half time... (if enabled) run_options = None; run_metadata = None if saveMD: run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) run_metadata = tf.RunMetadata() # TRAIN MODEL # discriminator variables; with real and generated input if use_spatialdisc: for runs in range(discRuns): batch_xs, batch_ys = getInput(batch_size = batch_size_disc, useDataAugmentation = useDataAugmentation, useVelocities = useVelocities, useVorticities = useVorticities) _, disc_cost, summary,disc_sig,gen_sig = sess.run([disc_optimizer, disc_loss, lossTrain_disc,disc_sigmoid,gen_sigmoid], feed_dict={x: batch_xs, x_disc: batch_xs, y: batch_ys, keep_prob: dropout, train: True, lr_global_step: lrgs} , options=run_options, run_metadata=run_metadata ) avgCost_disc += disc_cost summary_writer.add_summary(summary, iteration) if saveMD: summary_writer.add_run_metadata(run_metadata, 'dstep%d' % iteration) # temporal discriminator if(useTempoD): for runs in range(discRuns): batch_xts, batch_yts, batch_y_pos = getTempoinput(batch_size_disc, n_t = 3, dt=dt, useVelocities = useVelocities, useVorticities = useVorticities, useDataAugmentation = useDataAugmentation, adv_flag = ADV_flag) dict_train = {x_t:batch_xts, y_t:batch_yts, keep_prob: dropout, train: True} if(ADV_flag): dict_train[y_pos] = batch_y_pos _, t_disc_cost, summary, t_disc_sig, t_gen_sig = sess.run( [t_disc_optimizer, t_disc_loss, lossTrain_disc_t, t_disc_sigmoid, t_gen_sigmoid], feed_dict=dict_train) avgTemCost_disc += t_disc_cost summary_writer.add_summary(summary, iteration) # generator variables for runs in range(genRuns): batch_xs, batch_ys = getInput(batch_size = batch_size_disc, useDataAugmentation = useDataAugmentation, useVelocities = useVelocities, useVorticities = useVorticities) kkin = k_f*kkin kk2in = k2_f*kk2in # TODO a decay for weights, kktin = kt_f * kktin (kt_f<1.0) train_dict = {x: batch_xs, x_disc: batch_xs, y: batch_ys, keep_prob: dropout, train: True, kk: kkin, kk2: kk2in, lr_global_step: lrgs} if use_spatialdisc: getlist = [gen_optimizer, gen_loss, disc_loss_layer, gen_l1_loss, lossTrain_gen, gen_l2_loss] else: getlist = [gen_optimizer, gen_l1_loss, gen_l2_loss] if(useTempoD or useTempoL2): batch_xts, batch_yts, batch_y_pos = getTempoinput(batch_size_disc, n_t = 3, dt=dt, useVelocities = useVelocities, useVorticities = useVorticities, useDataAugmentation=useDataAugmentation, adv_flag = ADV_flag) train_dict[x_t] = batch_xts if(ADV_flag): train_dict[y_pos] = batch_y_pos if(useTempoD): train_dict[kkt] = kktin getlist.append(t_gen_loss) if(useTempoL2): train_dict[kktl] = kktin_l getlist.append(tl_gen_loss) result_list = sess.run(getlist, feed_dict=train_dict, options=run_options, run_metadata=run_metadata) if (useTempoD and (not useTempoL2)): if use_spatialdisc: _, gen_cost, layer_cost, gen_l1_cost, summary, gen_l2_cost, gen_tem_cost = result_list else: _, gen_l1_cost, gen_l2_cost, gen_tem_cost = result_list gen_tem_cost_l = 0 elif ((not useTempoD) and useTempoL2): if use_spatialdisc: _, gen_cost, layer_cost, gen_l1_cost, summary, gen_l2_cost, gen_tem_cost_l = result_list else: _, gen_l1_cost, gen_l2_cost, gen_tem_cost_l = result_list gen_tem_cost = 0 elif (useTempoD and useTempoL2): if use_spatialdisc: _, gen_cost, layer_cost, gen_l1_cost, summary, gen_l2_cost, gen_tem_cost, gen_tem_cost_l = result_list else: _, gen_l1_cost, gen_l2_cost, gen_tem_cost, gen_tem_cost_l = result_list else: if use_spatialdisc: _, gen_cost, layer_cost, gen_l1_cost, summary, gen_l2_cost = result_list else: _, gen_l1_cost, gen_l2_cost = result_list gen_tem_cost = 0 gen_tem_cost_l = 0 avgL1Cost_gen += gen_l1_cost avgTemCost_gen += gen_tem_cost avgTemCost_gen_l += gen_tem_cost_l if use_spatialdisc: avgCost_gen += gen_cost summary_writer.add_summary(summary, iteration) if saveMD: summary_writer.add_run_metadata(run_metadata, 'gstep%d' % iteration) # save model if ((disc_cost+gen_cost < lastCost) or alwaysSave) and (lastSave >= saveInterval): lastSave = 1 lastCost = disc_cost+gen_cost saveMsg = saveModel(lastCost) saved = True else: lastSave += 1 saved = False # validate model if (iteration + 1) % valiInterval == 0: if use_spatialdisc: # gather statistics from training batch_xs, batch_ys = getInput(batch_size = numValis, useVelocities = useVelocities, useVorticities = useVorticities) disc_out, summary_disc_out, gen_out, summary_gen_out = sess.run([disc_sigmoid, outTrain_disc_real, gen_sigmoid, outTrain_disc_gen], feed_dict={x: batch_xs, x_disc: batch_xs, y: batch_ys, keep_prob: dropout, train: False}) summary_writer.add_summary(summary_disc_out, iteration) summary_writer.add_summary(summary_gen_out, iteration) avgOut_disc += disc_out avgOut_gen += gen_out # validation starts here... # get vali data batch_xs, batch_ys = getInput(batch_size = numValis, isTraining=False, useVelocities = useVelocities, useVorticities = useVorticities) #disc with real imput disc_out_real, summary_vali_out, disc_vali_cost_real, summary_vali = sess.run([disc_sigmoid, outVali_disc_real, disc_loss_disc, lossVali_disc_disc], feed_dict={x: batch_xs, x_disc: batch_xs, y: batch_ys, keep_prob: dropoutOutput, train: False}) summary_writer.add_summary(summary_vali, iteration) summary_writer.add_summary(summary_vali_out, iteration) avgValiCost_disc_real += disc_vali_cost_real avgValiOut_disc_real += disc_out_real #disc with generated input disc_out_gen, summary_vali_out, disc_vali_cost_gen, summary_vali = sess.run([gen_sigmoid, outVali_disc_gen, disc_loss_gen, lossVali_disc_gen], feed_dict={x: batch_xs, x_disc: batch_xs, keep_prob: dropoutOutput, train: False}) summary_writer.add_summary(summary_vali, iteration) summary_writer.add_summary(summary_vali_out, iteration) avgValiCost_disc_gen += disc_vali_cost_gen avgValiOut_disc_gen += disc_out_gen if(useTempoD): # temporal logs # T disc output with training data batch_xts, batch_yts, batch_y_pos = getTempoinput(numValis, useVelocities = useVelocities, useVorticities = useVorticities, n_t = 3, dt=dt, adv_flag = ADV_flag) vali_dict = {x_t: batch_xts, y_t: batch_yts, keep_prob: dropout, train: False} if(ADV_flag): vali_dict[y_pos] = batch_y_pos t_disc_out, summary_disc_out_t, t_gen_out, summary_gen_out_t = sess.run( [t_disc_sigmoid, outTrain_disc_real_t, t_gen_sigmoid, outTrain_disc_gen_t], feed_dict=vali_dict) summary_writer.add_summary(summary_disc_out_t, iteration) summary_writer.add_summary(summary_gen_out_t, iteration) avgOut_disc_t += t_disc_out avgOut_gen_t += t_gen_out # validation data batch_xts, batch_yts, batch_y_pos = getTempoinput(numValis, isTraining=False, useVelocities = useVelocities, useVorticities = useVorticities, n_t = 3, dt=dt, adv_flag = ADV_flag) # disc with real input vali_dict = {x_t: batch_xts, y_t: batch_yts, keep_prob: dropout, train: False} if(ADV_flag): vali_dict[y_pos] = batch_y_pos t_disc_out_real, summary_vali_out_t, t_disc_vali_cost_real, summary_vali_t = sess.run( [t_disc_sigmoid, outVali_disc_real_t, t_disc_loss_disc, lossVali_disc_disc_t], feed_dict=vali_dict) summary_writer.add_summary(summary_vali_t, iteration) summary_writer.add_summary(summary_vali_out_t, iteration) avgValiCost_disc_real_t += t_disc_vali_cost_real avgValiOut_disc_real_t += t_disc_out_real # disc with generated input vali_dict = {x_t: batch_xts, y_t: batch_yts, keep_prob: dropout, train: False} if(ADV_flag): vali_dict[y_pos] = batch_y_pos t_disc_out_gen, summary_vali_out_t, t_disc_vali_cost_gen, summary_vali_t = sess.run( [t_gen_sigmoid, outVali_disc_gen_t, t_disc_loss_gen, lossVali_disc_gen_t], feed_dict=vali_dict) summary_writer.add_summary(summary_vali_t, iteration) summary_writer.add_summary(summary_vali_out_t, iteration) avgValiCost_disc_gen_t += t_disc_vali_cost_gen avgValiOut_disc_gen_t += t_disc_out_gen #gen train_dict = {x: batch_xs, x_disc: batch_xs, keep_prob: dropoutOutput, train: False} if (useTempoD or useTempoL2): # add tempo logs train_dict[x_t] = batch_xts if(ADV_flag): train_dict[y_pos] = batch_y_pos if (useTempoD): train_dict[kkt] = kktin if use_spatialdisc: gen_vali_cost, summary_vali, gen_tem_cost, summary_vali_gen \ = sess.run([gen_loss, lossVali_gen, t_gen_loss, lossVali_gen_t], feed_dict=train_dict) else: gen_tem_cost, summary_vali_gen \ = sess.run([t_gen_loss, lossVali_gen_t], feed_dict=train_dict) avgValiCost_gen_t += gen_tem_cost if (useTempoL2): train_dict[kktl] = kktin_l if use_spatialdisc: gen_vali_cost, summary_vali, gen_tem_cost, summary_vali_gen \ = sess.run([gen_loss, lossVali_gen, tl_gen_loss, lossVali_gen_t_l], feed_dict=train_dict) else: gen_tem_cost, summary_vali_gen \ = sess.run([tl_gen_loss, lossVali_gen_t_l], feed_dict=train_dict) avgValiCost_gen_t_l += gen_tem_cost summary_writer.add_summary(summary_vali_gen, iteration) else: if use_spatialdisc: gen_vali_cost, summary_vali = sess.run([gen_loss, lossVali_gen], feed_dict=train_dict) if use_spatialdisc: summary_writer.add_summary(summary_vali, iteration) avgValiCost_gen += gen_vali_cost validations += 1 # output statistics if (iteration + 1) % outputInterval == 0: # training average costs avgCost_disc /= (outputInterval * discRuns) avgCost_gen /= (outputInterval * genRuns) avgL1Cost_gen /= (outputInterval * genRuns) # validation average costs if not (validations == 0): avgOut_disc /= validations avgOut_gen /= validations avgValiCost_disc_real /= validations avgValiCost_disc_gen /= validations avgValiCost_gen /= validations avgValiOut_disc_real /= validations avgValiOut_disc_gen /= validations if(useTempoD): avgTemCost_gen /= (outputInterval * genRuns) avgTemCost_disc /= (outputInterval * discRuns) if( not validations == 0): avgOut_disc_t /= validations avgOut_gen_t /= validations avgValiCost_disc_real_t /= validations avgValiOut_disc_real_t /= validations avgValiCost_disc_gen_t /= validations avgValiOut_disc_gen_t /= validations avgValiCost_gen_t /= validations if (useTempoL2): avgTemCost_gen_l /= (outputInterval * genRuns) if (not validations == 0): avgValiCost_gen_t_l /= validations print('\nIter {:05d}/{}, Cost:'.format((iteration + 1), trainingIters)) print('\tdisc: loss: train_loss={:.6f} - vali-real={:.6f} - vali-generated={:.6f}, out: train={:.6f} - vali={:.6f}'. format(avgCost_disc, avgValiCost_disc_real, avgValiCost_disc_gen, avgOut_disc, avgValiOut_disc_real)) print('\tT D : loss[ -train (total={:.6f}), -vali (real&1={:.6f}) (generated&0={:.6f})]'. format(avgTemCost_disc, avgValiCost_disc_real_t, avgValiCost_disc_gen_t)) print('\t sigmoidout[ -vali (real&1={:.6f}) (generated&0={:.6f})'. format(avgValiOut_disc_real_t, avgValiOut_disc_gen_t)) print('\t gen: loss: train={:.6f} - L1(*k)={:.3f} - vali={:.6f}, DS out: train={:.6f} - vali={:.6f}' .format(avgCost_gen, avgL1Cost_gen * k, avgValiCost_gen, avgOut_gen, avgValiOut_disc_gen)) print('\t gen: loss[ -train (total Temp(*k)={:.6f}) -vali (total Temp(*k)={:.6f})], DT out: real={:.6f} - gen={:.6f}' .format(avgTemCost_gen * kt, avgValiCost_gen_t * kt, avgOut_disc_t, avgOut_gen_t)) if use_spatialdisc: print('\tdisc: loss: disc=%f'%(disc_sig)) print('\tgen: loss: gen=%f'%(gen_sig)) print('\t layer_cost: %f'%(layer_cost)) if(useTempoD): print('\tTdisc: loss: disc=%f' % (t_disc_sig)) print('\tTgen: loss: gen=%f' % (t_gen_sig)) if(useTempoD): print('\t tempo_cost: %f' % (gen_tem_cost)) print('\t l1_cost: %f'%(gen_l1_cost)) print('\t l2 tempo loss[ -train (total Temp(*k)={:.6f}) -vali (total Temp(*k)={:.6f})]' .format(avgTemCost_gen_l * kt_l, avgValiCost_gen_t_l * kt_l)) iterTime = (time.time() - startTime) / (iteration + 1) print('\t{} Iterations took {:.2f} seconds. (Est. next: {})'.format(outputInterval, (time.time() - intervalTime), time.ctime(time.time() + outputInterval * iterTime))) remainingTime = (trainingIters - iteration) * iterTime print('\tEstimated remaining time: {:.2f} minutes. (Est. end: {})'.format(remainingTime / 60.0, time.ctime(time.time() + remainingTime))) if saved: print('\t' + saveMsg) # print save massage here for clarity if genValiImg > -1: generateValiImage(outPath = test_path+'test_img/', imageindex = image_no) image_no +=1 sys.stdout.flush() intervalTime = time.time() avgCost_disc = 0 avgCost_gen = 0 avgL1Cost_gen = 0 avgOut_disc = 0 avgOut_gen = 0 avgValiCost_disc_real = 0 avgValiCost_disc_gen = 0 avgValiCost_gen = 0 avgValiOut_disc_real = 0 avgValiOut_disc_gen = 0 validations = 0 lastOut = 0 if(useTempoD): avgTemCost_gen = 0 avgTemCost_disc = 0 avgOut_disc_t = 0 avgOut_gen_t = 0 avgValiCost_disc_real_t = 0 avgValiOut_disc_real_t = 0 avgValiCost_disc_gen_t = 0 avgValiOut_disc_gen_t = 0 avgValiCost_gen_t = 0 if (useTempoL2): avgTemCost_gen_l = 0 avgValiCost_gen_t_l = 0 lastOut +=1 except KeyboardInterrupt: print("training interrupted") sys.stdout.flush() with open(basePath + 'test_overview.log', "a") as text_file: text_file.write('\ttraining interrupted after %d iters' % (iteration + 1) + '\n') print('\n*****TRAINING FINISHED*****') training_duration = (time.time() - startTime) / 60.0 print('Training needed %.02f minutes.' % (training_duration)) print('To apply the trained model, call the script with command line params: "out 1 load_model_test %d load_model_no %d" ' % (load_model_test_new, (save_no-1)) ) sys.stdout.flush() with open(basePath + 'test_overview.log', "a") as text_file: text_file.write('\ttraining duration: %.02f minutes' % training_duration + '\n') ### OUTPUT MODE ### elif outputOnly: print('*****OUTPUT ONLY*****') for layerno in range(0,frameMax-frameMin): print('Generating %d' % (layerno)) if dataDimension == 2: generateValiImage(fromSim,layerno,outPath = test_path, imageindex = layerno) else: generate3DUni(fromSim,layerno,outPath = test_path, imageindex = layerno) if outputGif and dataDimension == 2: #write gif print("Writing gif") tc.pngs_to_gif(test_path, start_idx=frameMin, end_idx=frameMax) print('Test finished, %d outputs written to %s.' % (frameMax-frameMin, test_path) )
[ "tensorflow.unstack", "paramhelpers.getNextGenericPath", "tensorflow.shape", "tensorflow.transpose", "numpy.array", "fluiddataloader.FluidDataLoader", "tensorflow.control_dependencies", "tensorflow.ones_like", "tensorflow.set_random_seed", "sys.path.append", "tensorflow.RunMetadata", "paramhel...
[((632, 659), 'sys.path.append', 'sys.path.append', (['"""../tools"""'], {}), "('../tools')\n", (647, 659), False, 'import sys\n'), ((1003, 1044), 'paramhelpers.getParam', 'ph.getParam', (['"""basePath"""', '"""../2ddata_gan/"""'], {}), "('basePath', '../2ddata_gan/')\n", (1014, 1044), True, 'import paramhelpers as ph\n'), ((1680, 1721), 'paramhelpers.getParam', 'ph.getParam', (['"""loadPath"""', '"""../2ddata_sim/"""'], {}), "('loadPath', '../2ddata_sim/')\n", (1691, 1721), True, 'import paramhelpers as ph\n'), ((2747, 2782), 'paramhelpers.getParam', 'ph.getParam', (['"""genModel"""', '"""gen_test"""'], {}), "('genModel', 'gen_test')\n", (2758, 2782), True, 'import paramhelpers as ph\n'), ((2828, 2865), 'paramhelpers.getParam', 'ph.getParam', (['"""discModel"""', '"""disc_test"""'], {}), "('discModel', 'disc_test')\n", (2839, 2865), True, 'import paramhelpers as ph\n'), ((7182, 7205), 'paramhelpers.getParam', 'ph.getParam', (['"""note"""', '""""""'], {}), "('note', '')\n", (7193, 7205), True, 'import paramhelpers as ph\n'), ((7835, 7857), 'paramhelpers.checkUnusedParams', 'ph.checkUnusedParams', ([], {}), '()\n', (7855, 7857), True, 'import paramhelpers as ph\n'), ((8701, 8764), 'numpy.linspace', 'np.linspace', (['fromSim', 'toSim', '(toSim - fromSim + 1)'], {'dtype': '"""int16"""'}), "(fromSim, toSim, toSim - fromSim + 1, dtype='int16')\n", (8712, 8764), True, 'import numpy as np\n'), ((10725, 10749), 'numpy.random.seed', 'np.random.seed', (['randSeed'], {}), '(randSeed)\n', (10739, 10749), True, 'import numpy as np\n'), ((10751, 10779), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['randSeed'], {}), '(randSeed)\n', (10769, 10779), True, 'import tensorflow as tf\n'), ((11827, 11847), 'paramhelpers.Logger', 'ph.Logger', (['test_path'], {}), '(test_path)\n', (11836, 11847), True, 'import paramhelpers as ph\n'), ((12020, 12061), 'paramhelpers.writeParams', 'ph.writeParams', (["(test_path + 'params.json')"], {}), "(test_path + 'params.json')\n", (12034, 12061), True, 'import paramhelpers as ph\n'), ((12495, 12544), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, n_input]'}), '(tf.float32, shape=[None, n_input])\n', (12509, 12544), True, 'import tensorflow as tf\n'), ((12582, 12631), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, n_input]'}), '(tf.float32, shape=[None, n_input])\n', (12596, 12631), True, 'import tensorflow as tf\n'), ((12659, 12709), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, n_output]'}), '(tf.float32, shape=[None, n_output])\n', (12673, 12709), True, 'import tensorflow as tf\n'), ((12716, 12742), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), '(tf.float32)\n', (12730, 12742), True, 'import tensorflow as tf\n'), ((12750, 12776), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), '(tf.float32)\n', (12764, 12776), True, 'import tensorflow as tf\n'), ((12784, 12810), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), '(tf.float32)\n', (12798, 12810), True, 'import tensorflow as tf\n'), ((12819, 12845), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), '(tf.float32)\n', (12833, 12845), True, 'import tensorflow as tf\n'), ((12890, 12916), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), '(tf.float32)\n', (12904, 12916), True, 'import tensorflow as tf\n'), ((22671, 22694), 'tensorflow.placeholder', 'tf.placeholder', (['tf.bool'], {}), '(tf.bool)\n', (22685, 22694), True, 'import tensorflow as tf\n'), ((23159, 23177), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (23175, 23177), False, 'import sys\n'), ((32550, 32591), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': '(True)'}), '(allow_soft_placement=True)\n', (32564, 32591), True, 'import tensorflow as tf\n'), ((32600, 32636), 'tensorflow.InteractiveSession', 'tf.InteractiveSession', ([], {'config': 'config'}), '(config=config)\n', (32621, 32636), True, 'import tensorflow as tf\n'), ((32648, 32685), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {'max_to_keep': 'maxToKeep'}), '(max_to_keep=maxToKeep)\n', (32662, 32685), True, 'import tensorflow as tf\n'), ((1065, 1091), 'paramhelpers.getParam', 'ph.getParam', (['"""randSeed"""', '(1)'], {}), "('randSeed', 1)\n", (1076, 1091), True, 'import paramhelpers as ph\n'), ((1159, 1193), 'paramhelpers.getParam', 'ph.getParam', (['"""load_model_test"""', '(-1)'], {}), "('load_model_test', -1)\n", (1170, 1193), True, 'import paramhelpers as ph\n'), ((1334, 1366), 'paramhelpers.getParam', 'ph.getParam', (['"""load_model_no"""', '(-1)'], {}), "('load_model_no', -1)\n", (1345, 1366), True, 'import paramhelpers as ph\n'), ((1428, 1454), 'paramhelpers.getParam', 'ph.getParam', (['"""simSize"""', '(64)'], {}), "('simSize', 64)\n", (1439, 1454), True, 'import paramhelpers as ph\n'), ((1508, 1535), 'paramhelpers.getParam', 'ph.getParam', (['"""tileSize"""', '(16)'], {}), "('tileSize', 16)\n", (1519, 1535), True, 'import paramhelpers as ph\n'), ((1584, 1606), 'paramhelpers.getParam', 'ph.getParam', (['"""dt"""', '(1.0)'], {}), "('dt', 1.0)\n", (1595, 1606), True, 'import paramhelpers as ph\n'), ((1768, 1796), 'paramhelpers.getParam', 'ph.getParam', (['"""fromSim"""', '(1000)'], {}), "('fromSim', 1000)\n", (1779, 1796), True, 'import paramhelpers as ph\n'), ((1862, 1886), 'paramhelpers.getParam', 'ph.getParam', (['"""toSim"""', '(-1)'], {}), "('toSim', -1)\n", (1873, 1886), True, 'import paramhelpers as ph\n'), ((1934, 1959), 'paramhelpers.getParam', 'ph.getParam', (['"""dataDim"""', '(2)'], {}), "('dataDim', 2)\n", (1945, 1959), True, 'import paramhelpers as ph\n'), ((2088, 2114), 'paramhelpers.getParam', 'ph.getParam', (['"""numOut"""', '(200)'], {}), "('numOut', 200)\n", (2099, 2114), True, 'import paramhelpers as ph\n'), ((2307, 2333), 'paramhelpers.getParam', 'ph.getParam', (['"""loadOut"""', '(-1)'], {}), "('loadOut', -1)\n", (2318, 2333), True, 'import paramhelpers as ph\n'), ((2936, 2971), 'paramhelpers.getParam', 'ph.getParam', (['"""learningRate"""', '(0.0002)'], {}), "('learningRate', 0.0002)\n", (2947, 2971), True, 'import paramhelpers as ph\n'), ((3076, 3103), 'paramhelpers.getParam', 'ph.getParam', (['"""dropout"""', '(1.0)'], {}), "('dropout', 1.0)\n", (3087, 3103), True, 'import paramhelpers as ph\n'), ((3190, 3227), 'paramhelpers.getParam', 'ph.getParam', (['"""dropoutOutput"""', 'dropout'], {}), "('dropoutOutput', dropout)\n", (3201, 3227), True, 'import paramhelpers as ph\n'), ((3323, 3353), 'paramhelpers.getParam', 'ph.getParam', (['"""adam_beta1"""', '(0.5)'], {}), "('adam_beta1', 0.5)\n", (3334, 3353), True, 'import paramhelpers as ph\n'), ((3414, 3444), 'paramhelpers.getParam', 'ph.getParam', (['"""weight_dld"""', '(1.0)'], {}), "('weight_dld', 1.0)\n", (3425, 3444), True, 'import paramhelpers as ph\n'), ((3496, 3522), 'paramhelpers.getParam', 'ph.getParam', (['"""lambda"""', '(1.0)'], {}), "('lambda', 1.0)\n", (3507, 3522), True, 'import paramhelpers as ph\n'), ((3594, 3621), 'paramhelpers.getParam', 'ph.getParam', (['"""lambda2"""', '(0.0)'], {}), "('lambda2', 0.0)\n", (3605, 3621), True, 'import paramhelpers as ph\n'), ((3698, 3726), 'paramhelpers.getParam', 'ph.getParam', (['"""lambda_f"""', '(1.0)'], {}), "('lambda_f', 1.0)\n", (3709, 3726), True, 'import paramhelpers as ph\n'), ((3774, 3803), 'paramhelpers.getParam', 'ph.getParam', (['"""lambda2_f"""', '(1.0)'], {}), "('lambda2_f', 1.0)\n", (3785, 3803), True, 'import paramhelpers as ph\n'), ((3855, 3885), 'paramhelpers.getParam', 'ph.getParam', (['"""lambda2_l1"""', '(1.0)'], {}), "('lambda2_l1', 1.0)\n", (3866, 3885), True, 'import paramhelpers as ph\n'), ((3975, 4005), 'paramhelpers.getParam', 'ph.getParam', (['"""lambda2_l2"""', '(1.0)'], {}), "('lambda2_l2', 1.0)\n", (3986, 4005), True, 'import paramhelpers as ph\n'), ((4095, 4125), 'paramhelpers.getParam', 'ph.getParam', (['"""lambda2_l3"""', '(1.0)'], {}), "('lambda2_l3', 1.0)\n", (4106, 4125), True, 'import paramhelpers as ph\n'), ((4215, 4245), 'paramhelpers.getParam', 'ph.getParam', (['"""lambda2_l4"""', '(1.0)'], {}), "('lambda2_l4', 1.0)\n", (4226, 4245), True, 'import paramhelpers as ph\n'), ((4332, 4360), 'paramhelpers.getParam', 'ph.getParam', (['"""lambda_t"""', '(1.0)'], {}), "('lambda_t', 1.0)\n", (4343, 4360), True, 'import paramhelpers as ph\n'), ((4444, 4475), 'paramhelpers.getParam', 'ph.getParam', (['"""lambda_t_l2"""', '(0.0)'], {}), "('lambda_t_l2', 0.0)\n", (4455, 4475), True, 'import paramhelpers as ph\n'), ((4587, 4616), 'paramhelpers.getParam', 'ph.getParam', (['"""batchSize"""', '(128)'], {}), "('batchSize', 128)\n", (4598, 4616), True, 'import paramhelpers as ph\n'), ((4732, 4772), 'paramhelpers.getParam', 'ph.getParam', (['"""batchSizeDisc"""', 'batch_size'], {}), "('batchSizeDisc', batch_size)\n", (4743, 4772), True, 'import paramhelpers as ph\n'), ((4847, 4886), 'paramhelpers.getParam', 'ph.getParam', (['"""batchSizeGen"""', 'batch_size'], {}), "('batchSizeGen', batch_size)\n", (4858, 4886), True, 'import paramhelpers as ph\n'), ((5073, 5109), 'paramhelpers.getParam', 'ph.getParam', (['"""trainingIters"""', '(100000)'], {}), "('trainingIters', 100000)\n", (5084, 5109), True, 'import paramhelpers as ph\n'), ((5153, 5179), 'paramhelpers.getParam', 'ph.getParam', (['"""discRuns"""', '(1)'], {}), "('discRuns', 1)\n", (5164, 5179), True, 'import paramhelpers as ph\n'), ((5265, 5290), 'paramhelpers.getParam', 'ph.getParam', (['"""genRuns"""', '(1)'], {}), "('genRuns', 1)\n", (5276, 5290), True, 'import paramhelpers as ph\n'), ((5487, 5516), 'paramhelpers.getParam', 'ph.getParam', (['"""bnDecay"""', '(0.999)'], {}), "('bnDecay', 0.999)\n", (5498, 5516), True, 'import paramhelpers as ph\n'), ((5574, 5610), 'paramhelpers.getParam', 'ph.getParam', (['"""use_spatialdisc"""', '(True)'], {}), "('use_spatialdisc', True)\n", (5585, 5610), True, 'import paramhelpers as ph\n'), ((5677, 5708), 'paramhelpers.getParam', 'ph.getParam', (['"""useVelocities"""', '(0)'], {}), "('useVelocities', 0)\n", (5688, 5708), True, 'import paramhelpers as ph\n'), ((5765, 5797), 'paramhelpers.getParam', 'ph.getParam', (['"""useVorticities"""', '(0)'], {}), "('useVorticities', 0)\n", (5776, 5797), True, 'import paramhelpers as ph\n'), ((5852, 5882), 'paramhelpers.getParam', 'ph.getParam', (['"""premadeTiles"""', '(0)'], {}), "('premadeTiles', 0)\n", (5863, 5882), True, 'import paramhelpers as ph\n'), ((5944, 5978), 'paramhelpers.getParam', 'ph.getParam', (['"""dataAugmentation"""', '(0)'], {}), "('dataAugmentation', 0)\n", (5955, 5978), True, 'import paramhelpers as ph\n'), ((6032, 6061), 'paramhelpers.getParam', 'ph.getParam', (['"""minScale"""', '(0.85)'], {}), "('minScale', 0.85)\n", (6043, 6061), True, 'import paramhelpers as ph\n'), ((6114, 6143), 'paramhelpers.getParam', 'ph.getParam', (['"""maxScale"""', '(1.15)'], {}), "('maxScale', 1.15)\n", (6125, 6143), True, 'import paramhelpers as ph\n'), ((6165, 6186), 'paramhelpers.getParam', 'ph.getParam', (['"""rot"""', '(2)'], {}), "('rot', 2)\n", (6176, 6186), True, 'import paramhelpers as ph\n'), ((6278, 6300), 'paramhelpers.getParam', 'ph.getParam', (['"""flip"""', '(1)'], {}), "('flip', 1)\n", (6289, 6300), True, 'import paramhelpers as ph\n'), ((6349, 6382), 'paramhelpers.getParam', 'ph.getParam', (['"""testPathStartNo"""', '(0)'], {}), "('testPathStartNo', 0)\n", (6360, 6382), True, 'import paramhelpers as ph\n'), ((6407, 6438), 'paramhelpers.getParam', 'ph.getParam', (['"""valiInterval"""', '(20)'], {}), "('valiInterval', 20)\n", (6418, 6438), True, 'import paramhelpers as ph\n'), ((6550, 6577), 'paramhelpers.getParam', 'ph.getParam', (['"""numValis"""', '(10)'], {}), "('numValis', 10)\n", (6561, 6577), True, 'import paramhelpers as ph\n'), ((6693, 6727), 'paramhelpers.getParam', 'ph.getParam', (['"""outputInterval"""', '(100)'], {}), "('outputInterval', 100)\n", (6704, 6727), True, 'import paramhelpers as ph\n'), ((6801, 6833), 'paramhelpers.getParam', 'ph.getParam', (['"""saveInterval"""', '(200)'], {}), "('saveInterval', 200)\n", (6812, 6833), True, 'import paramhelpers as ph\n'), ((6904, 6935), 'paramhelpers.getParam', 'ph.getParam', (['"""alwaysSave"""', '(True)'], {}), "('alwaysSave', True)\n", (6915, 6935), True, 'import paramhelpers as ph\n'), ((6965, 6990), 'paramhelpers.getParam', 'ph.getParam', (['"""keepMax"""', '(3)'], {}), "('keepMax', 3)\n", (6976, 6990), True, 'import paramhelpers as ph\n'), ((7076, 7105), 'paramhelpers.getParam', 'ph.getParam', (['"""genValiImg"""', '(-1)'], {}), "('genValiImg', -1)\n", (7087, 7105), True, 'import paramhelpers as ph\n'), ((7311, 7344), 'paramhelpers.getParam', 'ph.getParam', (['"""data_fraction"""', '(0.3)'], {}), "('data_fraction', 0.3)\n", (7322, 7344), True, 'import paramhelpers as ph\n'), ((7369, 7397), 'paramhelpers.getParam', 'ph.getParam', (['"""frameMax"""', '(200)'], {}), "('frameMax', 200)\n", (7380, 7397), True, 'import paramhelpers as ph\n'), ((7422, 7448), 'paramhelpers.getParam', 'ph.getParam', (['"""frameMin"""', '(0)'], {}), "('frameMin', 0)\n", (7433, 7448), True, 'import paramhelpers as ph\n'), ((7473, 7502), 'paramhelpers.getParam', 'ph.getParam', (['"""adv_flag"""', '(True)'], {}), "('adv_flag', True)\n", (7484, 7502), True, 'import paramhelpers as ph\n'), ((7602, 7632), 'paramhelpers.getParam', 'ph.getParam', (['"""saveMetaData"""', '(0)'], {}), "('saveMetaData', 0)\n", (7613, 7632), True, 'import paramhelpers as ph\n'), ((7746, 7771), 'paramhelpers.getParam', 'ph.getParam', (['"""overlap"""', '(3)'], {}), "('overlap', 3)\n", (7757, 7771), True, 'import paramhelpers as ph\n'), ((8662, 8688), 'numpy.append', 'np.append', (['mfl', '"""velocity"""'], {}), "(mfl, 'velocity')\n", (8671, 8688), True, 'import numpy as np\n'), ((9003, 9180), 'tilecreator_t.TileCreator', 'tc.TileCreator', ([], {'tileSizeLow': 'tileSizeLow', 'simSizeLow': 'simSizeLow', 'dim': 'dataDimension', 'dim_t': '(1)', 'channelLayout_low': 'channelLayout_low', 'upres': 'upRes', 'premadeTiles': 'premadeTiles'}), '(tileSizeLow=tileSizeLow, simSizeLow=simSizeLow, dim=\n dataDimension, dim_t=1, channelLayout_low=channelLayout_low, upres=\n upRes, premadeTiles=premadeTiles)\n', (9017, 9180), True, 'import tilecreator_t as tc\n'), ((9189, 9473), 'fluiddataloader.FluidDataLoader', 'FDL.FluidDataLoader', ([], {'print_info': '(1)', 'base_path': 'loadPath', 'filename': 'lowfilename', 'oldNamingScheme': '(False)', 'filename_y': 'highfilename', 'filename_index_min': 'frameMin', 'filename_index_max': 'frameMax', 'indices': 'dirIDs', 'data_fraction': 'data_fraction', 'multi_file_list': 'mfl', 'multi_file_list_y': 'mfh'}), '(print_info=1, base_path=loadPath, filename=lowfilename,\n oldNamingScheme=False, filename_y=highfilename, filename_index_min=\n frameMin, filename_index_max=frameMax, indices=dirIDs, data_fraction=\n data_fraction, multi_file_list=mfl, multi_file_list_y=mfh)\n', (9208, 9473), True, 'import fluiddataloader as FDL\n'), ((9530, 9549), 'numpy.append', 'np.append', (['mfl', 'mfl'], {}), '(mfl, mfl)\n', (9539, 9549), True, 'import numpy as np\n'), ((9557, 9582), 'numpy.append', 'np.append', (['mfl_tempo', 'mfl'], {}), '(mfl_tempo, mfl)\n', (9566, 9582), True, 'import numpy as np\n'), ((9704, 9723), 'numpy.append', 'np.append', (['mfh', 'mfh'], {}), '(mfh, mfh)\n', (9713, 9723), True, 'import numpy as np\n'), ((9731, 9756), 'numpy.append', 'np.append', (['mfh_tempo', 'mfh'], {}), '(mfh_tempo, mfh)\n', (9740, 9756), True, 'import numpy as np\n'), ((9876, 10053), 'tilecreator_t.TileCreator', 'tc.TileCreator', ([], {'tileSizeLow': 'tileSizeLow', 'simSizeLow': 'simSizeLow', 'dim': 'dataDimension', 'dim_t': '(3)', 'channelLayout_low': 'channelLayout_low', 'upres': 'upRes', 'premadeTiles': 'premadeTiles'}), '(tileSizeLow=tileSizeLow, simSizeLow=simSizeLow, dim=\n dataDimension, dim_t=3, channelLayout_low=channelLayout_low, upres=\n upRes, premadeTiles=premadeTiles)\n', (9890, 10053), True, 'import tilecreator_t as tc\n'), ((10062, 10365), 'fluiddataloader.FluidDataLoader', 'FDL.FluidDataLoader', ([], {'print_info': '(1)', 'base_path': 'loadPath', 'filename': 'lowfilename', 'oldNamingScheme': '(False)', 'filename_y': 'highfilename', 'filename_index_max': 'frameMax', 'indices': 'dirIDs', 'data_fraction': 'data_fraction', 'multi_file_list': 'mfl', 'multi_file_idxOff': 'mol', 'multi_file_list_y': 'mfh', 'multi_file_idxOff_y': 'moh'}), '(print_info=1, base_path=loadPath, filename=lowfilename,\n oldNamingScheme=False, filename_y=highfilename, filename_index_max=\n frameMax, indices=dirIDs, data_fraction=data_fraction, multi_file_list=\n mfl, multi_file_idxOff=mol, multi_file_list_y=mfh, multi_file_idxOff_y=moh)\n', (10081, 10365), True, 'import fluiddataloader as FDL\n'), ((11747, 11792), 'paramhelpers.getNextTestPath', 'ph.getNextTestPath', (['testPathStartNo', 'basePath'], {}), '(testPathStartNo, basePath)\n', (11765, 11792), True, 'import paramhelpers as ph\n'), ((12180, 12215), 'os.makedirs', 'os.makedirs', (["(test_path + '/zbu_src')"], {}), "(test_path + '/zbu_src')\n", (12191, 12215), False, 'import os\n'), ((12216, 12267), 'uniio.backupFile', 'uniio.backupFile', (['__file__', "(test_path + '/zbu_src/')"], {}), "(__file__, test_path + '/zbu_src/')\n", (12232, 12267), False, 'import uniio\n'), ((12268, 12338), 'uniio.backupFile', 'uniio.backupFile', (['"""../tools/tilecreator_t.py"""', "(test_path + '/zbu_src/')"], {}), "('../tools/tilecreator_t.py', test_path + '/zbu_src/')\n", (12284, 12338), False, 'import uniio\n'), ((12339, 12399), 'uniio.backupFile', 'uniio.backupFile', (['"""../tools/GAN.py"""', "(test_path + '/zbu_src/')"], {}), "('../tools/GAN.py', test_path + '/zbu_src/')\n", (12355, 12399), False, 'import uniio\n'), ((12401, 12473), 'uniio.backupFile', 'uniio.backupFile', (['"""../tools/fluiddataloader.py"""', "(test_path + '/zbu_src/')"], {}), "('../tools/fluiddataloader.py', test_path + '/zbu_src/')\n", (12417, 12473), False, 'import uniio\n'), ((26322, 26349), 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['(y - gen_part)'], {}), '(y - gen_part)\n', (26335, 26349), True, 'import tensorflow as tf\n'), ((26675, 26706), 'tensorflow.Variable', 'tf.Variable', (['(0)'], {'trainable': '(False)'}), '(0, trainable=False)\n', (26686, 26706), True, 'import tensorflow as tf\n'), ((26909, 26951), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.UPDATE_OPS'], {}), '(tf.GraphKeys.UPDATE_OPS)\n', (26926, 26951), True, 'import tensorflow as tf\n'), ((27092, 27116), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (27114, 27116), True, 'import tensorflow as tf\n'), ((35446, 35468), 'tensorflow.summary.merge_all', 'tf.summary.merge_all', ([], {}), '()\n', (35466, 35468), True, 'import tensorflow as tf\n'), ((35491, 35535), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['test_path', 'sess.graph'], {}), '(test_path, sess.graph)\n', (35512, 35535), True, 'import tensorflow as tf\n'), ((35750, 35786), 'os.makedirs', 'os.makedirs', (["(test_path + 'test_img/')"], {}), "(test_path + 'test_img/')\n", (35761, 35786), False, 'import os\n'), ((37330, 37365), 'numpy.reshape', 'np.reshape', (['batch_xs', '(-1, n_input)'], {}), '(batch_xs, (-1, n_input))\n', (37340, 37365), True, 'import numpy as np\n'), ((37379, 37415), 'numpy.reshape', 'np.reshape', (['batch_ys', '(-1, n_output)'], {}), '(batch_ys, (-1, n_output))\n', (37389, 37415), True, 'import numpy as np\n'), ((61369, 61387), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (61385, 61387), False, 'import sys\n'), ((908, 933), 'paramhelpers.getParam', 'ph.getParam', (['"""out"""', '(False)'], {}), "('out', False)\n", (919, 933), True, 'import paramhelpers as ph\n'), ((2192, 2221), 'paramhelpers.getParam', 'ph.getParam', (['"""saveOut"""', '(False)'], {}), "('saveOut', False)\n", (2203, 2221), True, 'import paramhelpers as ph\n'), ((2473, 2497), 'paramhelpers.getParam', 'ph.getParam', (['"""img"""', '(True)'], {}), "('img', True)\n", (2484, 2497), True, 'import paramhelpers as ph\n'), ((2545, 2570), 'paramhelpers.getParam', 'ph.getParam', (['"""gif"""', '(False)'], {}), "('gif', False)\n", (2556, 2570), True, 'import paramhelpers as ph\n'), ((2614, 2639), 'paramhelpers.getParam', 'ph.getParam', (['"""ref"""', '(False)'], {}), "('ref', False)\n", (2625, 2639), True, 'import paramhelpers as ph\n'), ((2992, 3021), 'paramhelpers.getParam', 'ph.getParam', (['"""decayLR"""', '(False)'], {}), "('decayLR', False)\n", (3003, 3021), True, 'import paramhelpers as ph\n'), ((4952, 4981), 'paramhelpers.getParam', 'ph.getParam', (['"""trainGAN"""', '(True)'], {}), "('trainGAN', True)\n", (4963, 4981), True, 'import paramhelpers as ph\n'), ((5373, 5403), 'paramhelpers.getParam', 'ph.getParam', (['"""batchNorm"""', '(True)'], {}), "('batchNorm', True)\n", (5384, 5403), True, 'import paramhelpers as ph\n'), ((9601, 9621), 'numpy.zeros', 'np.zeros', (['lowparalen'], {}), '(lowparalen)\n', (9609, 9621), True, 'import numpy as np\n'), ((9623, 9642), 'numpy.ones', 'np.ones', (['lowparalen'], {}), '(lowparalen)\n', (9630, 9642), True, 'import numpy as np\n'), ((9775, 9796), 'numpy.zeros', 'np.zeros', (['highparalen'], {}), '(highparalen)\n', (9783, 9796), True, 'import numpy as np\n'), ((9798, 9818), 'numpy.ones', 'np.ones', (['highparalen'], {}), '(highparalen)\n', (9805, 9818), True, 'import numpy as np\n'), ((11245, 11302), 'os.path.exists', 'os.path.exists', (["(basePath + 'test_%04d/' % load_model_test)"], {}), "(basePath + 'test_%04d/' % load_model_test)\n", (11259, 11302), False, 'import os\n'), ((11545, 11633), 'paramhelpers.getNextGenericPath', 'ph.getNextGenericPath', (['out_path_prefix', '(0)', "(basePath + 'test_%04d/' % load_model_test)"], {}), "(out_path_prefix, 0, basePath + 'test_%04d/' %\n load_model_test)\n", (11566, 11633), True, 'import paramhelpers as ph\n'), ((11657, 11702), 'paramhelpers.getNextTestPath', 'ph.getNextTestPath', (['testPathStartNo', 'basePath'], {}), '(testPathStartNo, basePath)\n', (11675, 11702), True, 'import paramhelpers as ph\n'), ((11998, 12017), 'paramhelpers.paramsToString', 'ph.paramsToString', ([], {}), '()\n', (12015, 12017), True, 'import paramhelpers as ph\n'), ((13853, 13869), 'tensorflow.add', 'tf.add', (['gc2', 'gs1'], {}), '(gc2, gs1)\n', (13859, 13869), True, 'import tensorflow as tf\n'), ((14045, 14088), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""generator"""'], {'reuse': 'reuse'}), "('generator', reuse=reuse)\n", (14062, 14088), True, 'import tensorflow as tf\n'), ((14412, 14420), 'GAN.GAN', 'GAN', (['_in'], {}), '(_in)\n', (14415, 14420), False, 'from GAN import GAN, lrelu\n'), ((14766, 14803), 'tensorflow.reshape', 'tf.reshape', (['ru4'], {'shape': '[-1, n_output]'}), '(ru4, shape=[-1, n_output])\n', (14776, 14803), True, 'import tensorflow as tf\n'), ((15469, 15516), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""discriminator"""'], {'reuse': 'reuse'}), "('discriminator', reuse=reuse)\n", (15486, 15516), True, 'import tensorflow as tf\n'), ((17964, 18016), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""discriminatorTempo"""'], {'reuse': 'reuse'}), "('discriminatorTempo', reuse=reuse)\n", (17981, 18016), True, 'import tensorflow as tf\n'), ((18474, 18505), 'GAN.GAN', 'GAN', (['in_high'], {'bn_decay': 'bn_decay'}), '(in_high, bn_decay=bn_decay)\n', (18477, 18505), False, 'from GAN import GAN, lrelu\n'), ((19445, 19493), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""generator-test"""'], {'reuse': 'reuse'}), "('generator-test', reuse=reuse)\n", (19462, 19493), True, 'import tensorflow as tf\n'), ((19815, 19823), 'GAN.GAN', 'GAN', (['_in'], {}), '(_in)\n', (19818, 19823), False, 'from GAN import GAN, lrelu\n'), ((20189, 20226), 'tensorflow.reshape', 'tf.reshape', (['inp'], {'shape': '[-1, n_output]'}), '(inp, shape=[-1, n_output])\n', (20199, 20226), True, 'import tensorflow as tf\n'), ((20470, 20522), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""discriminator_test"""'], {'reuse': 'reuse'}), "('discriminator_test', reuse=reuse)\n", (20487, 20522), True, 'import tensorflow as tf\n'), ((23479, 23498), 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), '(name)\n', (23492, 23498), True, 'import tensorflow as tf\n'), ((24085, 24104), 'tensorflow.ones_like', 'tf.ones_like', (['ceils'], {}), '(ceils)\n', (24097, 24104), True, 'import tensorflow as tf\n'), ((26224, 26237), 'tensorflow.zeros', 'tf.zeros', (['[1]'], {}), '([1])\n', (26232, 26237), True, 'import tensorflow as tf\n'), ((26259, 26272), 'tensorflow.zeros', 'tf.zeros', (['[1]'], {}), '([1])\n', (26267, 26272), True, 'import tensorflow as tf\n'), ((26381, 26401), 'tensorflow.abs', 'tf.abs', (['(y - gen_part)'], {}), '(y - gen_part)\n', (26387, 26401), True, 'import tensorflow as tf\n'), ((26779, 26899), 'tensorflow.train.polynomial_decay', 'tf.train.polynomial_decay', (['learning_rate', 'lr_global_step', '(trainingIters // 2)', '(learning_rate_scalar * 0.05)'], {'power': '(1.1)'}), '(learning_rate, lr_global_step, trainingIters // 2,\n learning_rate_scalar * 0.05, power=1.1)\n', (26804, 26899), True, 'import tensorflow as tf\n'), ((28441, 28490), 'tensorflow.reshape', 'tf.reshape', (['gen_part_t'], {'shape': '[-1, n_t, n_output]'}), '(gen_part_t, shape=[-1, n_t, n_output])\n', (28451, 28490), True, 'import tensorflow as tf\n'), ((28509, 28549), 'tensorflow.transpose', 'tf.transpose', (['gen_part_t'], {'perm': '[0, 2, 1]'}), '(gen_part_t, perm=[0, 2, 1])\n', (28521, 28549), True, 'import tensorflow as tf\n'), ((32282, 32321), 'tensorflow.control_dependencies', 'tf.control_dependencies', (['gen_update_ops'], {}), '(gen_update_ops)\n', (32305, 32321), True, 'import tensorflow as tf\n'), ((32753, 32786), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (32784, 32786), True, 'import tensorflow as tf\n'), ((33003, 33059), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""discriminator-loss train"""', 'disc_loss'], {}), "('discriminator-loss train', disc_loss)\n", (33020, 33059), True, 'import tensorflow as tf\n'), ((33084, 33135), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""generator-loss train"""', 'gen_loss'], {}), "('generator-loss train', gen_loss)\n", (33101, 33135), True, 'import tensorflow as tf\n'), ((33208, 33273), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""discriminator-loss vali real"""', 'disc_loss_disc'], {}), "('discriminator-loss vali real', disc_loss_disc)\n", (33225, 33273), True, 'import tensorflow as tf\n'), ((33299, 33368), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""discriminator-loss vali generated"""', 'disc_loss_gen'], {}), "('discriminator-loss vali generated', disc_loss_gen)\n", (33316, 33368), True, 'import tensorflow as tf\n'), ((33388, 33443), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""discriminator-loss vali"""', 'disc_loss'], {}), "('discriminator-loss vali', disc_loss)\n", (33405, 33443), True, 'import tensorflow as tf\n'), ((33464, 33514), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""generator-loss vali"""', 'gen_loss'], {}), "('generator-loss vali', gen_loss)\n", (33481, 33514), True, 'import tensorflow as tf\n'), ((33608, 33666), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""discriminator-out train"""', 'disc_sigmoid'], {}), "('discriminator-out train', disc_sigmoid)\n", (33625, 33666), True, 'import tensorflow as tf\n'), ((33690, 33743), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""generator-out train"""', 'gen_sigmoid'], {}), "('generator-out train', gen_sigmoid)\n", (33707, 33743), True, 'import tensorflow as tf\n'), ((33841, 33898), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""discriminator-out vali"""', 'disc_sigmoid'], {}), "('discriminator-out vali', disc_sigmoid)\n", (33858, 33898), True, 'import tensorflow as tf\n'), ((33921, 33973), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""generator-out vali"""', 'gen_sigmoid'], {}), "('generator-out vali', gen_sigmoid)\n", (33938, 33973), True, 'import tensorflow as tf\n'), ((34071, 34131), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""T discriminator-loss train"""', 't_disc_loss'], {}), "('T discriminator-loss train', t_disc_loss)\n", (34088, 34131), True, 'import tensorflow as tf\n'), ((34153, 34208), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""T generator-loss train"""', 't_gen_loss'], {}), "('T generator-loss train', t_gen_loss)\n", (34170, 34208), True, 'import tensorflow as tf\n'), ((34310, 34379), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""T discriminator-loss vali real"""', 't_disc_loss_disc'], {}), "('T discriminator-loss vali real', t_disc_loss_disc)\n", (34327, 34379), True, 'import tensorflow as tf\n'), ((34405, 34478), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""T discriminator-loss vali generated"""', 't_disc_loss_gen'], {}), "('T discriminator-loss vali generated', t_disc_loss_gen)\n", (34422, 34478), True, 'import tensorflow as tf\n'), ((34500, 34559), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""T discriminator-loss vali"""', 't_disc_loss'], {}), "('T discriminator-loss vali', t_disc_loss)\n", (34517, 34559), True, 'import tensorflow as tf\n'), ((34580, 34634), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""T generator-loss vali"""', 't_gen_loss'], {}), "('T generator-loss vali', t_gen_loss)\n", (34597, 34634), True, 'import tensorflow as tf\n'), ((34727, 34789), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""T discriminator-out train"""', 't_disc_sigmoid'], {}), "('T discriminator-out train', t_disc_sigmoid)\n", (34744, 34789), True, 'import tensorflow as tf\n'), ((34867, 34924), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""T generator-out train"""', 't_gen_sigmoid'], {}), "('T generator-out train', t_gen_sigmoid)\n", (34884, 34924), True, 'import tensorflow as tf\n'), ((35018, 35079), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""T discriminator-out vali"""', 't_disc_sigmoid'], {}), "('T discriminator-out vali', t_disc_sigmoid)\n", (35035, 35079), True, 'import tensorflow as tf\n'), ((35156, 35212), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""T generator-out vali"""', 't_gen_sigmoid'], {}), "('T generator-out vali', t_gen_sigmoid)\n", (35173, 35212), True, 'import tensorflow as tf\n'), ((35281, 35340), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""T generator-loss train l2"""', 'tl_gen_loss'], {}), "('T generator-loss train l2', tl_gen_loss)\n", (35298, 35340), True, 'import tensorflow as tf\n'), ((35363, 35421), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""T generator-loss vali l2"""', 'tl_gen_loss'], {}), "('T generator-loss vali l2', tl_gen_loss)\n", (35380, 35421), True, 'import tensorflow as tf\n'), ((35848, 35866), 'numpy.zeros_like', 'np.zeros_like', (['Vel'], {}), '(Vel)\n', (35861, 35866), True, 'import numpy as np\n'), ((36142, 36160), 'numpy.zeros_like', 'np.zeros_like', (['Vel'], {}), '(Vel)\n', (36155, 36160), True, 'import numpy as np\n'), ((37270, 37314), 'numpy.concatenate', 'np.concatenate', (['(batch_xs, Vorinput)'], {'axis': '(4)'}), '((batch_xs, Vorinput), axis=4)\n', (37284, 37314), True, 'import numpy as np\n'), ((38167, 38212), 'numpy.concatenate', 'np.concatenate', (['(batch_xts, Vorinput)'], {'axis': '(4)'}), '((batch_xts, Vorinput), axis=4)\n', (38181, 38212), True, 'import numpy as np\n'), ((38230, 38272), 'numpy.reshape', 'np.reshape', (['batch_xts', '[real_batch_sz, -1]'], {}), '(batch_xts, [real_batch_sz, -1])\n', (38240, 38272), True, 'import numpy as np\n'), ((39067, 39088), 'numpy.array', 'np.array', (['resultTiles'], {}), '(resultTiles)\n', (39075, 39088), True, 'import numpy as np\n'), ((39516, 39629), 'tilecreator_t.savePngsGrayscale', 'tc.savePngsGrayscale', (['resultTiles', 'outPath'], {'imageCounter': '(imageindex + frameMin)', 'tiles_in_image': 'tiles_in_image'}), '(resultTiles, outPath, imageCounter=imageindex +\n frameMin, tiles_in_image=tiles_in_image)\n', (39536, 39629), True, 'import tilecreator_t as tc\n'), ((40434, 40501), 'numpy.reshape', 'np.reshape', (['batch_xs', '[simLowLength, simLowWidth, simLowHeight, -1]'], {}), '(batch_xs, [simLowLength, simLowWidth, simLowHeight, -1])\n', (40444, 40501), True, 'import numpy as np\n'), ((41509, 41524), 'numpy.array', 'np.array', (['tiles'], {}), '(tiles)\n', (41517, 41524), True, 'import numpy as np\n'), ((41831, 41852), 'numpy.array', 'np.array', (['resultTiles'], {}), '(resultTiles)\n', (41839, 41852), True, 'import numpy as np\n'), ((41870, 41963), 'numpy.reshape', 'np.reshape', (['resultTiles', '[resultTiles.shape[0], tileSizeHigh, tileSizeHigh, tileSizeHigh]'], {}), '(resultTiles, [resultTiles.shape[0], tileSizeHigh, tileSizeHigh,\n tileSizeHigh])\n', (41880, 41963), True, 'import numpy as np\n'), ((41966, 42041), 'numpy.zeros', 'np.zeros', (['[simLowLength * upRes, simLowWidth * upRes, simLowHeight * upRes]'], {}), '([simLowLength * upRes, simLowWidth * upRes, simLowHeight * upRes])\n', (41974, 42041), True, 'import numpy as np\n'), ((43907, 43994), 'numpy.reshape', 'np.reshape', (['high', '[simLowLength * upRes, simLowWidth * upRes, simLowHeight * upRes]'], {}), '(high, [simLowLength * upRes, simLowWidth * upRes, simLowHeight *\n upRes])\n', (43917, 43994), True, 'import numpy as np\n'), ((43999, 44094), 'uniio.readUni', 'uniio.readUni', (["(loadPath + 'sim_%04d/density_high_%04d.uni' % (sim_no, frame_no + frameMin))"], {}), "(loadPath + 'sim_%04d/density_high_%04d.uni' % (sim_no, \n frame_no + frameMin))\n", (44012, 44094), False, 'import uniio\n'), ((44198, 44277), 'uniio.writeUni', 'uniio.writeUni', (["(outPath + 'source_%04d.uni' % (frame_no + frameMin))", 'head', 'high'], {}), "(outPath + 'source_%04d.uni' % (frame_no + frameMin), head, high)\n", (44212, 44277), False, 'import uniio\n'), ((45947, 45958), 'time.time', 'time.time', ([], {}), '()\n', (45956, 45958), False, 'import time\n'), ((9667, 9686), 'numpy.ones', 'np.ones', (['lowparalen'], {}), '(lowparalen)\n', (9674, 9686), True, 'import numpy as np\n'), ((9843, 9863), 'numpy.ones', 'np.ones', (['highparalen'], {}), '(highparalen)\n', (9850, 9863), True, 'import numpy as np\n'), ((14137, 14207), 'tensorflow.reshape', 'tf.reshape', (['_in'], {'shape': '[-1, tileSizeLow, tileSizeLow, n_inputChannels]'}), '(_in, shape=[-1, tileSizeLow, tileSizeLow, n_inputChannels])\n', (14147, 14207), True, 'import tensorflow as tf\n'), ((15556, 15572), 'tensorflow.shape', 'tf.shape', (['in_low'], {}), '(in_low)\n', (15564, 15572), True, 'import tensorflow as tf\n'), ((15800, 15862), 'tensorflow.reshape', 'tf.reshape', (['in_high'], {'shape': '[-1, tileSizeHigh, tileSizeHigh, 1]'}), '(in_high, shape=[-1, tileSizeHigh, tileSizeHigh, 1])\n', (15810, 15862), True, 'import tensorflow as tf\n'), ((16476, 16513), 'tensorflow.concat', 'tf.concat', (['[in_low, in_high]'], {'axis': '(-1)'}), '([in_low, in_high], axis=-1)\n', (16485, 16513), True, 'import tensorflow as tf\n'), ((18058, 18131), 'tensorflow.reshape', 'tf.reshape', (['in_high'], {'shape': '[-1, tileSizeHigh, tileSizeHigh, n_t_channels]'}), '(in_high, shape=[-1, tileSizeHigh, tileSizeHigh, n_t_channels])\n', (18068, 18131), True, 'import tensorflow as tf\n'), ((19540, 19610), 'tensorflow.reshape', 'tf.reshape', (['_in'], {'shape': '[-1, tileSizeLow, tileSizeLow, n_inputChannels]'}), '(_in, shape=[-1, tileSizeLow, tileSizeLow, n_inputChannels])\n', (19550, 19610), True, 'import tensorflow as tf\n'), ((20562, 20578), 'tensorflow.shape', 'tf.shape', (['in_low'], {}), '(in_low)\n', (20570, 20578), True, 'import tensorflow as tf\n'), ((20808, 20870), 'tensorflow.reshape', 'tf.reshape', (['in_high'], {'shape': '[-1, tileSizeHigh, tileSizeHigh, 1]'}), '(in_high, shape=[-1, tileSizeHigh, tileSizeHigh, 1])\n', (20818, 20870), True, 'import tensorflow as tf\n'), ((21448, 21485), 'tensorflow.concat', 'tf.concat', (['[in_low, in_high]'], {'axis': '(-1)'}), '([in_low, in_high], axis=-1)\n', (21457, 21485), True, 'import tensorflow as tf\n'), ((21718, 21784), 'tensorflow.constant', 'tf.constant', (['(1.0)'], {'shape': '[batch_size, tileSizeLow, tileSizeLow, 64]'}), '(1.0, shape=[batch_size, tileSizeLow, tileSizeLow, 64])\n', (21729, 21784), True, 'import tensorflow as tf\n'), ((23665, 23684), 'tensorflow.floor', 'tf.floor', (['(pos - 0.5)'], {}), '(pos - 0.5)\n', (23673, 23684), True, 'import tensorflow as tf\n'), ((23766, 23787), 'tensorflow.zeros_like', 'tf.zeros_like', (['floors'], {}), '(floors)\n', (23779, 23787), True, 'import tensorflow as tf\n'), ((23818, 23838), 'tensorflow.zeros_like', 'tf.zeros_like', (['ceils'], {}), '(ceils)\n', (23831, 23838), True, 'import tensorflow as tf\n'), ((24596, 24645), 'tensorflow.reduce_prod', 'tf.reduce_prod', (['axis_wei'], {'axis': '(-1)', 'keep_dims': '(True)'}), '(axis_wei, axis=-1, keep_dims=True)\n', (24610, 24645), True, 'import tensorflow as tf\n'), ((24741, 24779), 'tensorflow.ones_like', 'tf.ones_like', (['axis_wei'], {'dtype': 'tf.int32'}), '(axis_wei, dtype=tf.int32)\n', (24753, 24779), True, 'import tensorflow as tf\n'), ((24796, 24840), 'tensorflow.cumsum', 'tf.cumsum', (['first_idx'], {'axis': '(0)', 'exclusive': '(True)'}), '(first_idx, axis=0, exclusive=True)\n', (24805, 24840), True, 'import tensorflow as tf\n'), ((24924, 24963), 'tensorflow.gather_nd', 'tf.gather_nd', (['value', 'cell_value_list[0]'], {}), '(value, cell_value_list[0])\n', (24936, 24963), True, 'import tensorflow as tf\n'), ((25382, 25401), 'tensorflow.nn.sigmoid', 'tf.nn.sigmoid', (['disc'], {}), '(disc)\n', (25395, 25401), True, 'import tensorflow as tf\n'), ((25435, 25453), 'tensorflow.nn.sigmoid', 'tf.nn.sigmoid', (['gen'], {}), '(gen)\n', (25448, 25453), True, 'import tensorflow as tf\n'), ((27669, 27690), 'tensorflow.device', 'tf.device', (['device_str'], {}), '(device_str)\n', (27678, 27690), True, 'import tensorflow as tf\n'), ((27703, 27752), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, n_input]'}), '(tf.float32, shape=[None, n_input])\n', (27717, 27752), True, 'import tensorflow as tf\n'), ((27858, 27924), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, n_output * dataDimension]'}), '(tf.float32, shape=[None, n_output * dataDimension])\n', (27872, 27924), True, 'import tensorflow as tf\n'), ((28633, 28675), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.UPDATE_OPS'], {}), '(tf.GraphKeys.UPDATE_OPS)\n', (28650, 28675), True, 'import tensorflow as tf\n'), ((28888, 28919), 'tensorflow.unstack', 'tf.unstack', (['gen_part_t'], {'axis': '(-1)'}), '(gen_part_t, axis=-1)\n', (28898, 28919), True, 'import tensorflow as tf\n'), ((29299, 29349), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, n_output]'}), '(tf.float32, shape=[None, n_output])\n', (29313, 29349), True, 'import tensorflow as tf\n'), ((29695, 29738), 'tensorflow.reshape', 'tf.reshape', (['y_tR'], {'shape': '[-1, n_t, n_output]'}), '(y_tR, shape=[-1, n_t, n_output])\n', (29705, 29738), True, 'import tensorflow as tf\n'), ((29752, 29786), 'tensorflow.transpose', 'tf.transpose', (['y_tR'], {'perm': '[0, 2, 1]'}), '(y_tR, perm=[0, 2, 1])\n', (29764, 29786), True, 'import tensorflow as tf\n'), ((29934, 29976), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.UPDATE_OPS'], {}), '(tf.GraphKeys.UPDATE_OPS)\n', (29951, 29976), True, 'import tensorflow as tf\n'), ((30499, 30541), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.UPDATE_OPS'], {}), '(tf.GraphKeys.UPDATE_OPS)\n', (30516, 30541), True, 'import tensorflow as tf\n'), ((30829, 30853), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (30851, 30853), True, 'import tensorflow as tf\n'), ((31979, 32018), 'tensorflow.control_dependencies', 'tf.control_dependencies', (['dis_update_ops'], {}), '(dis_update_ops)\n', (32002, 32018), True, 'import tensorflow as tf\n'), ((32146, 32195), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['learning_rate'], {'beta1': 'beta'}), '(learning_rate, beta1=beta)\n', (32168, 32195), True, 'import tensorflow as tf\n'), ((37861, 37932), 'numpy.reshape', 'np.reshape', (['batch_xts', '[real_batch_sz, 1, tileSizeLow, tileSizeLow, -1]'], {}), '(batch_xts, [real_batch_sz, 1, tileSizeLow, tileSizeLow, -1])\n', (37871, 37932), True, 'import numpy as np\n'), ((37953, 38038), 'numpy.reshape', 'np.reshape', (['batch_xts', '[real_batch_sz, tileSizeLow, tileSizeLow, tileSizeLow, -1]'], {}), '(batch_xts, [real_batch_sz, tileSizeLow, tileSizeLow, tileSizeLow,\n -1])\n', (37963, 38038), True, 'import numpy as np\n'), ((38875, 38918), 'numpy.reshape', 'np.reshape', (['batch_xs[tileno]', '[-1, n_input]'], {}), '(batch_xs[tileno], [-1, n_input])\n', (38885, 38918), True, 'import numpy as np\n'), ((39226, 39290), 'numpy.reshape', 'np.reshape', (['resultTiles', '[resultTiles.shape[0], imgSz, imgSz, 1]'], {}), '(resultTiles, [resultTiles.shape[0], imgSz, imgSz, 1])\n', (39236, 39290), True, 'import numpy as np\n'), ((39368, 39436), 'numpy.reshape', 'np.reshape', (['resultTiles', '[resultTiles.shape[0], imgSz, imgSz, imgSz]'], {}), '(resultTiles, [resultTiles.shape[0], imgSz, imgSz, imgSz])\n', (39378, 39436), True, 'import numpy as np\n'), ((40078, 40148), 'numpy.reshape', 'np.reshape', (['batch_xs', '[1, simLowLength, simLowWidth, simLowHeight, -1]'], {}), '(batch_xs, [1, simLowLength, simLowWidth, simLowHeight, -1])\n', (40088, 40148), True, 'import numpy as np\n'), ((40282, 40326), 'numpy.concatenate', 'np.concatenate', (['(batch_xs, Vorinput)'], {'axis': '(4)'}), '((batch_xs, Vorinput), axis=4)\n', (40296, 40326), True, 'import numpy as np\n'), ((40344, 40411), 'numpy.reshape', 'np.reshape', (['batch_xs', '[simLowLength, simLowWidth, simLowHeight, -1]'], {}), '(batch_xs, [simLowLength, simLowWidth, simLowHeight, -1])\n', (40354, 40411), True, 'import numpy as np\n'), ((41606, 41649), 'numpy.reshape', 'np.reshape', (['batch_xs[tileno]', '[-1, n_input]'], {}), '(batch_xs[tileno], [-1, n_input])\n', (41616, 41649), True, 'import numpy as np\n'), ((41764, 41781), 'numpy.array', 'np.array', (['results'], {}), '(results)\n', (41772, 41781), True, 'import numpy as np\n'), ((60870, 60888), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (60886, 60888), False, 'import sys\n'), ((61105, 61116), 'time.time', 'time.time', ([], {}), '()\n', (61114, 61116), False, 'import time\n'), ((61971, 62034), 'tilecreator_t.pngs_to_gif', 'tc.pngs_to_gif', (['test_path'], {'start_idx': 'frameMin', 'end_idx': 'frameMax'}), '(test_path, start_idx=frameMin, end_idx=frameMax)\n', (61985, 62034), True, 'import tilecreator_t as tc\n'), ((14275, 14362), 'tensorflow.reshape', 'tf.reshape', (['_in'], {'shape': '[-1, tileSizeLow, tileSizeLow, tileSizeLow, n_inputChannels]'}), '(_in, shape=[-1, tileSizeLow, tileSizeLow, tileSizeLow,\n n_inputChannels])\n', (14285, 14362), True, 'import tensorflow as tf\n'), ((15955, 15971), 'tensorflow.shape', 'tf.shape', (['in_low'], {}), '(in_low)\n', (15963, 15971), True, 'import tensorflow as tf\n'), ((16236, 16312), 'tensorflow.reshape', 'tf.reshape', (['in_high'], {'shape': '[-1, tileSizeHigh, tileSizeHigh, tileSizeHigh, 1]'}), '(in_high, shape=[-1, tileSizeHigh, tileSizeHigh, tileSizeHigh, 1])\n', (16246, 16312), True, 'import tensorflow as tf\n'), ((18226, 18317), 'tensorflow.reshape', 'tf.reshape', (['in_high'], {'shape': '[-1, tileSizeHigh, tileSizeHigh, tileSizeHigh, n_t_channels]'}), '(in_high, shape=[-1, tileSizeHigh, tileSizeHigh, tileSizeHigh,\n n_t_channels])\n', (18236, 18317), True, 'import tensorflow as tf\n'), ((19678, 19765), 'tensorflow.reshape', 'tf.reshape', (['_in'], {'shape': '[-1, tileSizeLow, tileSizeLow, tileSizeLow, n_inputChannels]'}), '(_in, shape=[-1, tileSizeLow, tileSizeLow, tileSizeLow,\n n_inputChannels])\n', (19688, 19765), True, 'import tensorflow as tf\n'), ((20946, 20962), 'tensorflow.shape', 'tf.shape', (['in_low'], {}), '(in_low)\n', (20954, 20962), True, 'import tensorflow as tf\n'), ((21227, 21303), 'tensorflow.reshape', 'tf.reshape', (['in_high'], {'shape': '[-1, tileSizeHigh, tileSizeHigh, tileSizeHigh, 1]'}), '(in_high, shape=[-1, tileSizeHigh, tileSizeHigh, tileSizeHigh, 1])\n', (21237, 21303), True, 'import tensorflow as tf\n'), ((22002, 22081), 'tensorflow.constant', 'tf.constant', (['(1.0)'], {'shape': '[batch_size, tileSizeLow, tileSizeLow, tileSizeLow, 64]'}), '(1.0, shape=[batch_size, tileSizeLow, tileSizeLow, tileSizeLow, 64])\n', (22013, 22081), True, 'import tensorflow as tf\n'), ((24375, 24410), 'tensorflow.where', 'tf.where', (['condition_', 'ceils', 'floors'], {}), '(condition_, ceils, floors)\n', (24383, 24410), True, 'import tensorflow as tf\n'), ((24868, 24904), 'tensorflow.concat', 'tf.concat', (['[first_idx, axis_idx]', '(-1)'], {}), '([first_idx, axis_idx], -1)\n', (24877, 24904), True, 'import tensorflow as tf\n'), ((27976, 28041), 'tensorflow.reshape', 'tf.reshape', (['gen_part_t'], {'shape': '[-1, tileSizeHigh, tileSizeHigh, 1]'}), '(gen_part_t, shape=[-1, tileSizeHigh, tileSizeHigh, 1])\n', (27986, 28041), True, 'import tensorflow as tf\n'), ((28059, 28119), 'tensorflow.reshape', 'tf.reshape', (['y_pos'], {'shape': '[-1, tileSizeHigh, tileSizeHigh, 2]'}), '(y_pos, shape=[-1, tileSizeHigh, tileSizeHigh, 2])\n', (28069, 28119), True, 'import tensorflow as tf\n'), ((28978, 29028), 'tensorflow.square', 'tf.square', (['(gen_part_t_list[0] - gen_part_t_list[1])'], {}), '(gen_part_t_list[0] - gen_part_t_list[1])\n', (28987, 29028), True, 'import tensorflow as tf\n'), ((30738, 30759), 'tensorflow.nn.sigmoid', 'tf.nn.sigmoid', (['disc_t'], {}), '(disc_t)\n', (30751, 30759), True, 'import tensorflow as tf\n'), ((30796, 30816), 'tensorflow.nn.sigmoid', 'tf.nn.sigmoid', (['gen_t'], {}), '(gen_t)\n', (30809, 30816), True, 'import tensorflow as tf\n'), ((31536, 31576), 'tensorflow.control_dependencies', 'tf.control_dependencies', (['disT_update_ops'], {}), '(disT_update_ops)\n', (31559, 31576), True, 'import tensorflow as tf\n'), ((31705, 31748), 'tensorflow.control_dependencies', 'tf.control_dependencies', (['ori_gen_update_ops'], {}), '(ori_gen_update_ops)\n', (31728, 31748), True, 'import tensorflow as tf\n'), ((32416, 32465), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['learning_rate'], {'beta1': 'beta'}), '(learning_rate, beta1=beta)\n', (32438, 32465), True, 'import tensorflow as tf\n'), ((46679, 46730), 'tensorflow.RunOptions', 'tf.RunOptions', ([], {'trace_level': 'tf.RunOptions.FULL_TRACE'}), '(trace_level=tf.RunOptions.FULL_TRACE)\n', (46692, 46730), True, 'import tensorflow as tf\n'), ((46751, 46767), 'tensorflow.RunMetadata', 'tf.RunMetadata', ([], {}), '()\n', (46765, 46767), True, 'import tensorflow as tf\n'), ((60075, 60093), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (60091, 60093), False, 'import sys\n'), ((60114, 60125), 'time.time', 'time.time', ([], {}), '()\n', (60123, 60125), False, 'import time\n'), ((11912, 11922), 'os.uname', 'os.uname', ([], {}), '()\n', (11920, 11922), False, 'import os\n'), ((25133, 25179), 'tensorflow.gather_nd', 'tf.gather_nd', (['value', 'cell_value_list[cell_idx]'], {}), '(value, cell_value_list[cell_idx])\n', (25145, 25179), True, 'import tensorflow as tf\n'), ((25600, 25618), 'tensorflow.ones_like', 'tf.ones_like', (['disc'], {}), '(disc)\n', (25612, 25618), True, 'import tensorflow as tf\n'), ((25770, 25788), 'tensorflow.zeros_like', 'tf.zeros_like', (['gen'], {}), '(gen)\n', (25783, 25788), True, 'import tensorflow as tf\n'), ((25980, 26004), 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['(dy4 - gy4)'], {}), '(dy4 - gy4)\n', (25993, 26004), True, 'import tensorflow as tf\n'), ((26179, 26196), 'tensorflow.ones_like', 'tf.ones_like', (['gen'], {}), '(gen)\n', (26191, 26196), True, 'import tensorflow as tf\n'), ((28188, 28267), 'tensorflow.reshape', 'tf.reshape', (['gen_part_t'], {'shape': '[-1, tileSizeHigh, tileSizeHigh, tileSizeHigh, 1]'}), '(gen_part_t, shape=[-1, tileSizeHigh, tileSizeHigh, tileSizeHigh, 1])\n', (28198, 28267), True, 'import tensorflow as tf\n'), ((28285, 28359), 'tensorflow.reshape', 'tf.reshape', (['y_pos'], {'shape': '[-1, tileSizeHigh, tileSizeHigh, tileSizeHigh, 3]'}), '(y_pos, shape=[-1, tileSizeHigh, tileSizeHigh, tileSizeHigh, 3])\n', (28295, 28359), True, 'import tensorflow as tf\n'), ((29415, 29473), 'tensorflow.reshape', 'tf.reshape', (['y_t'], {'shape': '[-1, tileSizeHigh, tileSizeHigh, 1]'}), '(y_t, shape=[-1, tileSizeHigh, tileSizeHigh, 1])\n', (29425, 29473), True, 'import tensorflow as tf\n'), ((15666, 15725), 'tensorflow.reshape', 'tf.reshape', (['in_low'], {'shape': '[-1, tileSizeLow, tileSizeLow, 1]'}), '(in_low, shape=[-1, tileSizeLow, tileSizeLow, 1])\n', (15676, 15725), True, 'import tensorflow as tf\n'), ((20672, 20731), 'tensorflow.reshape', 'tf.reshape', (['in_low'], {'shape': '[-1, tileSizeLow, tileSizeLow, 1]'}), '(in_low, shape=[-1, tileSizeLow, tileSizeLow, 1])\n', (20682, 20731), True, 'import tensorflow as tf\n'), ((24514, 24543), 'tensorflow.cast', 'tf.cast', (['axis_idx', 'tf.float32'], {}), '(axis_idx, tf.float32)\n', (24521, 24543), True, 'import tensorflow as tf\n'), ((25931, 25955), 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['(dy3 - gy3)'], {}), '(dy3 - gy3)\n', (25944, 25955), True, 'import tensorflow as tf\n'), ((29115, 29171), 'tensorflow.square', 'tf.square', (['(gen_part_t_list[ti] - gen_part_t_list[ti + 1])'], {}), '(gen_part_t_list[ti] - gen_part_t_list[ti + 1])\n', (29124, 29171), True, 'import tensorflow as tf\n'), ((29537, 29609), 'tensorflow.reshape', 'tf.reshape', (['y_t'], {'shape': '[-1, tileSizeHigh, tileSizeHigh, tileSizeHigh, 1]'}), '(y_t, shape=[-1, tileSizeHigh, tileSizeHigh, tileSizeHigh, 1])\n', (29547, 29609), True, 'import tensorflow as tf\n'), ((31062, 31082), 'tensorflow.ones_like', 'tf.ones_like', (['disc_t'], {}), '(disc_t)\n', (31074, 31082), True, 'import tensorflow as tf\n'), ((31247, 31267), 'tensorflow.zeros_like', 'tf.zeros_like', (['gen_t'], {}), '(gen_t)\n', (31260, 31267), True, 'import tensorflow as tf\n'), ((31434, 31453), 'tensorflow.ones_like', 'tf.ones_like', (['gen_t'], {}), '(gen_t)\n', (31446, 31453), True, 'import tensorflow as tf\n'), ((31602, 31651), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['learning_rate'], {'beta1': 'beta'}), '(learning_rate, beta1=beta)\n', (31624, 31651), True, 'import tensorflow as tf\n'), ((31851, 31900), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['learning_rate'], {'beta1': 'beta'}), '(learning_rate, beta1=beta)\n', (31873, 31900), True, 'import tensorflow as tf\n'), ((59446, 59457), 'time.time', 'time.time', ([], {}), '()\n', (59455, 59457), False, 'import time\n'), ((16065, 16137), 'tensorflow.reshape', 'tf.reshape', (['in_low'], {'shape': '[-1, tileSizeLow, tileSizeLow, tileSizeLow, 1]'}), '(in_low, shape=[-1, tileSizeLow, tileSizeLow, tileSizeLow, 1])\n', (16075, 16137), True, 'import tensorflow as tf\n'), ((21056, 21128), 'tensorflow.reshape', 'tf.reshape', (['in_low'], {'shape': '[-1, tileSizeLow, tileSizeLow, tileSizeLow, 1]'}), '(in_low, shape=[-1, tileSizeLow, tileSizeLow, tileSizeLow, 1])\n', (21066, 21128), True, 'import tensorflow as tf\n'), ((25833, 25857), 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['(dy1 - gy1)'], {}), '(dy1 - gy1)\n', (25846, 25857), True, 'import tensorflow as tf\n'), ((25882, 25906), 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['(dy2 - gy2)'], {}), '(dy2 - gy2)\n', (25895, 25906), True, 'import tensorflow as tf\n'), ((59579, 59590), 'time.time', 'time.time', ([], {}), '()\n', (59588, 59590), False, 'import time\n'), ((59619, 59630), 'time.time', 'time.time', ([], {}), '()\n', (59628, 59630), False, 'import time\n'), ((59834, 59845), 'time.time', 'time.time', ([], {}), '()\n', (59843, 59845), False, 'import time\n')]
# Check the following urls for more info about Pan-STARRS: # # https://outerspace.stsci.edu/display/PANSTARRS/PS1+Image+Cutout+Service#PS1ImageCutoutService-ImportantFITSimageformat,WCS,andflux-scalingnotes # https://outerspace.stsci.edu/display/PANSTARRS/PS1+Stack+images#PS1Stackimages-Photometriccalibration # # For DES: # # https://des.ncsa.illinois.edu/releases/dr1/dr1-docs/processing # # For SDSS: # # https://www.sdss.org/dr12/algorithms/fluxcal/#SDSStoAB # https://data.sdss.org/datamodel/files/BOSS_PHOTOOBJ/frames/RERUN/RUN/CAMCOL/frame.html # # Some parts of this notebook are based on https://github.com/djones1040/PS1_surface_brightness/blob/master/Surface%20Brightness%20Tutorial.ipynb and codes from <NAME> import os import glob import subprocess import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib.patches import Ellipse import sep from astropy.io import fits from astropy.modeling import models, fitting from astropy import coordinates as coords, units as u, wcs from photutils import (CircularAnnulus, CircularAperture, aperture_photometry) from photutils.detection import DAOStarFinder import reproject from reproject.mosaicking import reproject_and_coadd from .utils import (get_survey_filters, extract_filters, check_survey_validity, check_filters_validity, calc_ext, calc_sky_unc) sep.set_sub_object_limit(1e4) # Masking Stars #------------------------------- def create_circular_mask(h, w, centre, radius): """Creates a circular mask of an image. Parameters ---------- h: int Image height. w: int Image width. centre: tuple-like Centre of the circular mask. radius: float Radius of the circular mask. Returns ------- mask: 2D bool-array Circular mask (inside the circle = `True`). """ Y, X = np.ogrid[:h, :w] dist_from_center = np.sqrt((X - centre[0])**2 + (Y-centre[1])**2) mask = dist_from_center <= radius return mask def inside_galaxy(star_center, gal_center, gal_r): """Checks whether a star is inside a galaxy. Parameters ========== star_center: tuple-like Centre of the star. gal_center: tuple-like Centre of the galaxy. gal_r: float Radius to define the galaxy size. Returns ======= condition: bool `True` if the star is inside the galaxy, `False` otherwise. """ dist_from_center = np.sqrt((star_center[0] - gal_center[0])**2 + (star_center[1] - gal_center[1])**2) condition = dist_from_center <= gal_r return condition def fit_2dgauss(star_data, x0=None, y0=None, plot_fit=False): """Fits a 2D gaussian to a star. Parameters ---------- star_data: 2D array Image data. x0: int, default `None` Star's x-axis centre. y0: int, default `None` Star's y-axis centre. plot_fit: bool, default `False` If `True`, the model fit is plotted with `r_in` and `r_out`. Returns ------- model_sigma: float 2D gaussian sigma parameter. The largest between sigma_x and sigma_y. """ # initial guess sigma = 0.5 amp = np.max(star_data) if (x0 is None) | (y0 is None): y0, x0 = np.unravel_index(np.argmax(star_data), star_data.shape) fitter = fitting.LevMarLSQFitter() gaussian_model = models.Gaussian2D(amp, x0, y0, sigma, sigma) gaussian_model.fixed['x_mean'] = True gaussian_model.fixed['y_mean'] = True gaussian_model.bounds['x_stddev'] = (0, 8) gaussian_model.bounds['y_stddev'] = (0, 8) yi, xi = np.indices(star_data.shape) model_result = fitter(gaussian_model, xi, yi, star_data) model_sigma = max([model_result.x_stddev.value, model_result.y_stddev.value]) if plot_fit: model_data = model_result(xi, yi) fig, ax = plt.subplots() ax.imshow(star_data, interpolation='nearest', cmap='gray', vmin=m-s, vmax=m+s, origin='lower') x_mean = model_result.x_mean.value y_mean = model_result.y_mean.value circle_in = plt.Circle((x_mean, y_mean), Rin_scale*model_sigma, facecolor ='none', edgecolor = 'red', linewidth = 2) circle_out = plt.Circle((x_mean, y_mean), Rout_scale*model_sigma, facecolor ='none', edgecolor = 'red', linewidth = 2) ax.add_patch(circle_in) ax.add_patch(circle_out) plt.show() return model_sigma def mask_image(data, apertures, bkg, gal_center=None, gal_r=None, plot_output=None): """Creates a mask of the stars with the mean value of the background around them. **Note**: the galaxy coordinates are (y, x). Parameters ---------- data: 2D array Image data. apertures: `photutils.aperture.circle.CircularAperture` Circular apertures of the stars. bkg: float Background level used to limit the aperture size to mask the stars. In other words, increase the aperture size of the mask until the mask value is <= 3*bkg to properly mask bright stars. gal_center: tuple-like, default `None` Centre of the galaxy (y, x) in pixels. gal_r: float, default `None` Radius to define the galaxy size. plot_output: str, default `None` If not `None`, saves the output plots with the masked stars with the given name. """ h, w = data.shape[:2] masked_data = data.copy() ring_scales = [3, 4, 5] # how many sigmas model_sigmas = [] skip_indeces = [] for i, aperture in enumerate(apertures): star_y, star_x = aperture.positions size = 10 xmin = max(int(star_x-2*size), 0) xmax = min(int(star_x+2*size), w) ymin = max(int(star_y-2*size), 0) ymax = min(int(star_y+2*size), h) # some stars close to the edges of the image fail, # but we can skip those anyway if (xmin<star_x<xmax) & (ymin<star_y<ymax): star_data = masked_data[xmin:xmax, ymin:ymax] else: skip_indeces.append(i) continue # skip this star # fit a gaussian to the star and get sigma x0, y0 = star_x-xmin, star_y-ymin model_sigma = fit_2dgauss(star_data) model_sigmas.append(model_sigma) if model_sigma==8: # 10 is the limit I putted in `fit_2dgauss` --> fit failed skip_indeces.append(i) continue # skip this star # check if the star is inside the galaxy aperture star_center = aperture.positions if (gal_center is None) or (gal_r is None): star_inside_galaxy = False else: star_inside_galaxy = inside_galaxy(star_center, gal_center, gal_r) if star_inside_galaxy: r_in = ring_scales[0]*model_sigma, r_mid = ring_scales[1]*model_sigma r_out = ring_scales[2]*model_sigma # calculate flux in outer ring (4-6 sigmas) ann = CircularAnnulus(aperture.positions, r_in=r_mid, r_out=r_out) ann_mean = aperture_photometry( data, ann)['aperture_sum'][0] / ann.area mask = create_circular_mask(h, w, star_center, r_in) # basically remove the failed fits and avoid large objects not_big_object = r_in<(gal_r/3) # do not mask the galaxy dist2gal = np.sum(np.abs(apertures.positions - gal_center), axis=1) gal_id = np.argmin(dist2gal) if not np.isnan(ann_mean) and not_big_object and i!=gal_id: masked_data[mask] = ann_mean else: skip_indeces.append(i) if plot_output is not None: m, s = np.nanmean(data), np.nanstd(data) fig, ax = plt.subplots(1, 3, figsize=(15, 10)) # reference image ax[0].imshow(data, interpolation='nearest', cmap='gray', vmin=m-s, vmax=m+s, origin='lower') ax[0].set_title('reference image') # apertures image ax[1].imshow(data, interpolation='nearest', cmap='gray', vmin=m-s, vmax=m+s, origin='lower') ax[1].set_title('apertures image') if (gal_center is not None) or (gal_r is not None): gal_circle = plt.Circle(gal_center, gal_r, ec='b', fill=False) ax[1].add_patch(gal_circle) # masked image ax[2].imshow(masked_data, interpolation='nearest', cmap='gray', vmin=m-s, vmax=m+s, origin='lower') ax[2].set_title('masked image') for i, (aperture, model_sigma) in enumerate(zip(apertures, model_sigmas)): if i not in skip_indeces: for scale in ring_scales: aperture.r = scale*model_sigma aperture.plot(ax[1], color='red', lw=1.5, alpha=0.5) plt.tight_layout() plt.savefig(plot_output) plt.close(fig) return masked_data, model_sigmas # Coadding images #------------------------------- def coadd_images(sn_name, filters='riz', work_dir='', survey='PS1'): """Reprojects and coadds images for the choosen filters for common-aperture photometry. Parameters ---------- sn_name: str SN name to be used for finding the images locally. filters: str, default `riz` Filters to use for the coadd image. work_dir: str, default '' Working directory where to find the objects' directories with the images. Default, current directory. survey: str, default `PS1` Survey to use as prefix for the images. Returns ------- A fits file with the coadded images is created with the filters used as the name of the file at the SN directory. """ init_dir = os.path.abspath('.') sn_dir = os.path.join(work_dir, sn_name) fits_files = [os.path.join(sn_dir, f'{survey}_{filt}.fits') for filt in filters] hdu_list = [] for fits_file in fits_files: fits_image = fits.open(fits_file) hdu_list.append(fits_image[0]) hdu_list = fits.HDUList(hdu_list) # use the last image as reference coadd = reproject_and_coadd(hdu_list, fits_image[0].header, reproject_function=reproject.reproject_interp) fits_image[0].data = coadd[0] outfile = os.path.join(sn_dir, f'{survey}_{filters}.fits') fits_image.writeto(outfile, overwrite=True) # Photometry #------------------------------- def extract_aperture_params(fits_file, host_ra, host_dec, threshold, bkg_sub=True): """Extracts aperture parameters of a galaxy. **Note:** the galaxy must be ideally centred in the image. Parameters ========== fits_file: str Path to the fits file. host_ra: float Host-galaxy Right ascension of the galaxy in degrees. host_dec: float Host-galaxy Declination of the galaxy in degrees. threshold: float Threshold used by `sep.extract()` to extract objects. bkg_sub: bool, default `True` If `True`, the image gets background subtracted. Returns ======= gal_object: numpy array Galaxy object extracted with `sep.extract()`. objects: numpy array All objects extracted with `sep.extract()`. """ img = fits.open(fits_file) header = img[0].header data = img[0].data img_wcs = wcs.WCS(header, naxis=2) data = data.astype(np.float64) bkg = sep.Background(data) bkg_rms = bkg.globalrms if bkg_sub: data_sub = np.copy(data - bkg) else: data_sub = np.copy(data) # extract objects with Source Extractor objects = sep.extract(data_sub, threshold, err=bkg_rms) # obtain the galaxy data (hopefully centred in the image) gal_coords = coords.SkyCoord(ra=host_ra*u.degree, dec=host_dec*u.degree) gal_x, gal_y = img_wcs.world_to_pixel(gal_coords) x_diff = np.abs(objects['x']-gal_x) y_diff = np.abs(objects['y']-gal_y) dist = np.sqrt(x_diff**2 + y_diff**2) gal_id = np.argmin(dist) gal_object = objects[gal_id:gal_id+1] return gal_object, objects def extract_global_photometry(fits_file, host_ra, host_dec, gal_object=None, mask_stars=True, threshold=3, bkg_sub=True, survey='PS1', plot_output=None): """Extracts PanSTARRS's global photometry of a galaxy. The use of `gal_object` is intended for common-aperture photometry. **Note:** the galaxy must be ideally centred in the image. Parameters ========== fits_file: str Path to the fits file. host_ra: float Host-galaxy Right ascension of the galaxy in degrees. host_dec: float Host-galaxy Declination of the galaxy in degrees. gal_object: numpy array, default `None` Galaxy object extracted with `extract_aperture_params()`. Use this for common-aperture photometry only. mask_stars: bool, default `True` If `True`, the stars identified inside the common aperture are masked with the mean value of the background around them. threshold: float, default `3` Threshold used by `sep.extract()` to extract objects. bkg_sub: bool, default `True` If `True`, the image gets background subtracted. survey: str, default `PS1` Survey to use for the zero-points. plot_output: str, default `None` If not `None`, saves the output plots with the given name. Returns ======= mag: float Aperture magnitude. mag_err: float Error on the aperture magnitude. """ check_survey_validity(survey) img = fits.open(fits_file) header = img[0].header data = img[0].data exptime = float(header['EXPTIME']) data = data.astype(np.float64) bkg = sep.Background(data) bkg_rms = bkg.globalrms if bkg_sub: data_sub = np.copy(data - bkg) else: data_sub = np.copy(data) if gal_object is None: # no common aperture gal_object, objects = extract_aperture_params(fits_file, host_ra, host_dec, threshold, bkg_sub) else: gal_object2, objects = extract_aperture_params(fits_file, host_ra, host_dec, threshold, bkg_sub) # sometimes, one of the filter images can be flipped, so the position of the # aperture from the coadd image might not match that of the filter image. This # is a workaround as we only need the semi-major and semi-minor axes. gal_object['x'] = gal_object2['x'] gal_object['y'] = gal_object2['y'] gal_object['theta'] = gal_object2['theta'] if mask_stars: # identify bright source..... #mean, median, std = sigma_clipped_stats(data_sub, sigma=3.0) #daofind = DAOStarFinder(fwhm=3.0, threshold=7.*std) # avoids bogus sources #sources = daofind(data_sub) #positions = np.transpose((sources['xcentroid'], sources['ycentroid'])) # ... or create apertures for the sources obtained with sep positions = np.transpose([objects['x'], objects['y']]) apertures = CircularAperture(positions, r=4) # the value of r is irrelevant # mask image gal_center = (gal_object['x'][0], gal_object['y'][0]) gal_r = (6/2)*gal_object['a'][0] # using the major-axis as radius if plot_output is not None: split_name = os.path.splitext(plot_output) plot_masking_output = f'{split_name[0]}_star_masking{split_name[1]}' else: plot_masking_output = None masked_data, model_sigmas = mask_image(data_sub, apertures, bkg_rms, gal_center, gal_r, plot_masking_output) data_sub = masked_data.copy() # aperture photometry # This uses what would be the default SExtractor parameters. # See https://sep.readthedocs.io/en/v1.1.x/apertures.html # NaNs are converted to mean values to avoid issues with the photometry. # The value used, might slightly affects the results (~ 0.0x mag). masked_data = np.nan_to_num(data_sub, nan=np.nanmean(data_sub)) kronrad, krflag = sep.kron_radius(masked_data, gal_object['x'], gal_object['y'], gal_object['a'], gal_object['b'], gal_object['theta'], 6.0) r_min = 1.75 # minimum diameter = 3.5 if kronrad*np.sqrt(gal_object['a']*gal_object['b']) < r_min: print(f'Warning: using circular photometry on {fits_file}') flux, flux_err, flag = sep.sum_circle(masked_data, gal_object['x'], gal_object['y'], r_min, err=bkg.globalrms, subpix=1) else: flux, flux_err, flag = sep.sum_ellipse(masked_data, gal_object['x'], gal_object['y'], gal_object['a'], gal_object['b'], gal_object['theta'], 2.5*kronrad, err=bkg.globalrms, subpix=1) zp_dict = {'PS1':25 + 2.5*np.log10(exptime), 'DES':30, 'SDSS':22.5} zp = zp_dict[survey] mag = -2.5*np.log10(flux) + zp mag_err = 2.5/np.log(10)*flux_err/flux if plot_output is not None: fig, ax = plt.subplots() m, s = np.nanmean(data_sub), np.nanstd(data_sub) im = ax.imshow(data_sub, interpolation='nearest', cmap='gray', vmin=m-s, vmax=m+s, origin='lower') e = Ellipse(xy=(gal_object['x'][0], gal_object['y'][0]), width=6*gal_object['a'][0], height=6*gal_object['b'][0], angle=gal_object['theta'][0]*180./np.pi) e.set_facecolor('none') e.set_edgecolor('red') ax.add_artist(e) plt.tight_layout() plt.savefig(plot_output) plt.close(fig) return mag[0], mag_err[0] def multi_global_photometry(name_list, host_ra_list, host_dec_list, work_dir='', filters=None, coadd=True, coadd_filters='riz', mask_stars=True, threshold=3, bkg_sub=True, survey="PS1", correct_extinction=True, plot_output=False): """Extract global photometry for multiple SNe. Parameters ========== name_list: list-like List of SN names. host_ra_list: list-like List of host-galaxy right ascensions in degrees. host_dec_list: list-like List of host-galaxy declinations in degrees. work_dir: str, default '' Working directory where to find the objects' directories with the images. Default, current directory. filters: str, defaul `None` Filters used to extract photometry. If `None`, use all the available filters for the given survey. coadd: bool, default `True` If `True`, a coadd image is created for common aperture. coadd_filters: str, default `riz` Filters to use for the coadd image. mask_stars: bool, default `True` If `True`, the stars identified inside the common aperture are masked with the mean value of the background around them. threshold: float, default `3` Threshold used by `sep.extract()` to extract objects. bkg_sub: bool, default `True` If `True`, the image gets background subtracted. survey: str, default `PS1` Survey to use for the zero-points. correct_extinction: bool, default `True` If `True`, the magnitudes are corrected for extinction. plot_output: bool, default `False` If `True`, saves the output plots. Returns ======= global_phot_df: DataFrame Dataframe with the photometry, errors and SN name. """ check_survey_validity(survey) check_filters_validity(filters, survey) if filters is None: filters = get_survey_filters(survey) # dictionary to save results mag_dict = {filt:[] for filt in filters} mag_err_dict = {filt+'_err':[] for filt in filters} mag_dict.update(mag_err_dict) results_dict = {'name':[], 'host_ra':[], 'host_dec':[]} results_dict.update(mag_dict) # filter funcstions for extinction correction filters_dict = extract_filters(filters, survey) for name, host_ra, host_dec in zip(name_list, host_ra_list, host_dec_list): sn_dir = os.path.join(work_dir, name) image_files = [os.path.join(sn_dir, f'{survey}_{filt}.fits') for filt in filters] if coadd: coadd_images(name, coadd_filters, work_dir, survey) coadd_file = os.path.join(sn_dir, f'{survey}_{coadd_filters}.fits') gal_object, _ = extract_aperture_params(coadd_file, host_ra, host_dec, threshold, bkg_sub) else: gal_object = None for image_file, filt in zip(image_files, filters): try: if plot_output: plot_output = os.path.join(sn_dir, f'global_{filt}.jpg') else: plot_output = None mag, mag_err = extract_global_photometry(image_file, host_ra, host_dec, gal_object, mask_stars, threshold, bkg_sub, survey, plot_output) if correct_extinction: wave = filters_dict[filt]['wave'] transmission = filters_dict[filt]['transmission'] A_ext = calc_ext(wave, transmission, host_ra, host_dec) mag -= A_ext results_dict[filt].append(mag) results_dict[filt+'_err'].append(mag_err) except Exception as message: results_dict[filt].append(np.nan) results_dict[filt+'_err'].append(np.nan) print(f'{name} failed with {filt} band: {message}') results_dict['name'].append(name) results_dict['host_ra'].append(host_ra) results_dict['host_dec'].append(host_dec) global_phot_df = pd.DataFrame(results_dict) return global_phot_df
[ "sep.sum_ellipse", "numpy.log10", "numpy.sqrt", "numpy.log", "numpy.nanmean", "sep.Background", "astropy.io.fits.open", "photutils.CircularAnnulus", "astropy.wcs.WCS", "numpy.max", "matplotlib.pyplot.close", "photutils.CircularAperture", "matplotlib.pyplot.subplots", "pandas.DataFrame", ...
[((1452, 1485), 'sep.set_sub_object_limit', 'sep.set_sub_object_limit', (['(10000.0)'], {}), '(10000.0)\n', (1476, 1485), False, 'import sep\n'), ((1996, 2048), 'numpy.sqrt', 'np.sqrt', (['((X - centre[0]) ** 2 + (Y - centre[1]) ** 2)'], {}), '((X - centre[0]) ** 2 + (Y - centre[1]) ** 2)\n', (2003, 2048), True, 'import numpy as np\n'), ((2555, 2645), 'numpy.sqrt', 'np.sqrt', (['((star_center[0] - gal_center[0]) ** 2 + (star_center[1] - gal_center[1]) ** 2)'], {}), '((star_center[0] - gal_center[0]) ** 2 + (star_center[1] -\n gal_center[1]) ** 2)\n', (2562, 2645), True, 'import numpy as np\n'), ((3326, 3343), 'numpy.max', 'np.max', (['star_data'], {}), '(star_data)\n', (3332, 3343), True, 'import numpy as np\n'), ((3501, 3526), 'astropy.modeling.fitting.LevMarLSQFitter', 'fitting.LevMarLSQFitter', ([], {}), '()\n', (3524, 3526), False, 'from astropy.modeling import models, fitting\n'), ((3548, 3592), 'astropy.modeling.models.Gaussian2D', 'models.Gaussian2D', (['amp', 'x0', 'y0', 'sigma', 'sigma'], {}), '(amp, x0, y0, sigma, sigma)\n', (3565, 3592), False, 'from astropy.modeling import models, fitting\n'), ((3785, 3812), 'numpy.indices', 'np.indices', (['star_data.shape'], {}), '(star_data.shape)\n', (3795, 3812), True, 'import numpy as np\n'), ((10332, 10352), 'os.path.abspath', 'os.path.abspath', (['"""."""'], {}), "('.')\n", (10347, 10352), False, 'import os\n'), ((10366, 10397), 'os.path.join', 'os.path.join', (['work_dir', 'sn_name'], {}), '(work_dir, sn_name)\n', (10378, 10397), False, 'import os\n'), ((10663, 10685), 'astropy.io.fits.HDUList', 'fits.HDUList', (['hdu_list'], {}), '(hdu_list)\n', (10675, 10685), False, 'from astropy.io import fits\n'), ((10736, 10839), 'reproject.mosaicking.reproject_and_coadd', 'reproject_and_coadd', (['hdu_list', 'fits_image[0].header'], {'reproject_function': 'reproject.reproject_interp'}), '(hdu_list, fits_image[0].header, reproject_function=\n reproject.reproject_interp)\n', (10755, 10839), False, 'from reproject.mosaicking import reproject_and_coadd\n'), ((10915, 10963), 'os.path.join', 'os.path.join', (['sn_dir', 'f"""{survey}_{filters}.fits"""'], {}), "(sn_dir, f'{survey}_{filters}.fits')\n", (10927, 10963), False, 'import os\n'), ((11873, 11893), 'astropy.io.fits.open', 'fits.open', (['fits_file'], {}), '(fits_file)\n', (11882, 11893), False, 'from astropy.io import fits\n'), ((11959, 11983), 'astropy.wcs.WCS', 'wcs.WCS', (['header'], {'naxis': '(2)'}), '(header, naxis=2)\n', (11966, 11983), False, 'from astropy import coordinates as coords, units as u, wcs\n'), ((12030, 12050), 'sep.Background', 'sep.Background', (['data'], {}), '(data)\n', (12044, 12050), False, 'import sep\n'), ((12236, 12281), 'sep.extract', 'sep.extract', (['data_sub', 'threshold'], {'err': 'bkg_rms'}), '(data_sub, threshold, err=bkg_rms)\n', (12247, 12281), False, 'import sep\n'), ((12362, 12425), 'astropy.coordinates.SkyCoord', 'coords.SkyCoord', ([], {'ra': '(host_ra * u.degree)', 'dec': '(host_dec * u.degree)'}), '(ra=host_ra * u.degree, dec=host_dec * u.degree)\n', (12377, 12425), True, 'from astropy import coordinates as coords, units as u, wcs\n'), ((12523, 12551), 'numpy.abs', 'np.abs', (["(objects['x'] - gal_x)"], {}), "(objects['x'] - gal_x)\n", (12529, 12551), True, 'import numpy as np\n'), ((12563, 12591), 'numpy.abs', 'np.abs', (["(objects['y'] - gal_y)"], {}), "(objects['y'] - gal_y)\n", (12569, 12591), True, 'import numpy as np\n'), ((12601, 12635), 'numpy.sqrt', 'np.sqrt', (['(x_diff ** 2 + y_diff ** 2)'], {}), '(x_diff ** 2 + y_diff ** 2)\n', (12608, 12635), True, 'import numpy as np\n'), ((12645, 12660), 'numpy.argmin', 'np.argmin', (['dist'], {}), '(dist)\n', (12654, 12660), True, 'import numpy as np\n'), ((14269, 14289), 'astropy.io.fits.open', 'fits.open', (['fits_file'], {}), '(fits_file)\n', (14278, 14289), False, 'from astropy.io import fits\n'), ((14426, 14446), 'sep.Background', 'sep.Background', (['data'], {}), '(data)\n', (14440, 14446), False, 'import sep\n'), ((17160, 17287), 'sep.kron_radius', 'sep.kron_radius', (['masked_data', "gal_object['x']", "gal_object['y']", "gal_object['a']", "gal_object['b']", "gal_object['theta']", '(6.0)'], {}), "(masked_data, gal_object['x'], gal_object['y'], gal_object[\n 'a'], gal_object['b'], gal_object['theta'], 6.0)\n", (17175, 17287), False, 'import sep\n'), ((24291, 24317), 'pandas.DataFrame', 'pd.DataFrame', (['results_dict'], {}), '(results_dict)\n', (24303, 24317), True, 'import pandas as pd\n'), ((4059, 4073), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (4071, 4073), True, 'import matplotlib.pyplot as plt\n'), ((4308, 4413), 'matplotlib.pyplot.Circle', 'plt.Circle', (['(x_mean, y_mean)', '(Rin_scale * model_sigma)'], {'facecolor': '"""none"""', 'edgecolor': '"""red"""', 'linewidth': '(2)'}), "((x_mean, y_mean), Rin_scale * model_sigma, facecolor='none',\n edgecolor='red', linewidth=2)\n", (4318, 4413), True, 'import matplotlib.pyplot as plt\n'), ((4496, 4602), 'matplotlib.pyplot.Circle', 'plt.Circle', (['(x_mean, y_mean)', '(Rout_scale * model_sigma)'], {'facecolor': '"""none"""', 'edgecolor': '"""red"""', 'linewidth': '(2)'}), "((x_mean, y_mean), Rout_scale * model_sigma, facecolor='none',\n edgecolor='red', linewidth=2)\n", (4506, 4602), True, 'import matplotlib.pyplot as plt\n'), ((4740, 4750), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4748, 4750), True, 'import matplotlib.pyplot as plt\n'), ((8229, 8265), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(3)'], {'figsize': '(15, 10)'}), '(1, 3, figsize=(15, 10))\n', (8241, 8265), True, 'import matplotlib.pyplot as plt\n'), ((9421, 9439), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (9437, 9439), True, 'import matplotlib.pyplot as plt\n'), ((9448, 9472), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_output'], {}), '(plot_output)\n', (9459, 9472), True, 'import matplotlib.pyplot as plt\n'), ((9481, 9495), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (9490, 9495), True, 'import matplotlib.pyplot as plt\n'), ((10416, 10461), 'os.path.join', 'os.path.join', (['sn_dir', 'f"""{survey}_{filt}.fits"""'], {}), "(sn_dir, f'{survey}_{filt}.fits')\n", (10428, 10461), False, 'import os\n'), ((10587, 10607), 'astropy.io.fits.open', 'fits.open', (['fits_file'], {}), '(fits_file)\n', (10596, 10607), False, 'from astropy.io import fits\n'), ((12114, 12133), 'numpy.copy', 'np.copy', (['(data - bkg)'], {}), '(data - bkg)\n', (12121, 12133), True, 'import numpy as np\n'), ((12163, 12176), 'numpy.copy', 'np.copy', (['data'], {}), '(data)\n', (12170, 12176), True, 'import numpy as np\n'), ((14510, 14529), 'numpy.copy', 'np.copy', (['(data - bkg)'], {}), '(data - bkg)\n', (14517, 14529), True, 'import numpy as np\n'), ((14559, 14572), 'numpy.copy', 'np.copy', (['data'], {}), '(data)\n', (14566, 14572), True, 'import numpy as np\n'), ((16051, 16093), 'numpy.transpose', 'np.transpose', (["[objects['x'], objects['y']]"], {}), "([objects['x'], objects['y']])\n", (16063, 16093), True, 'import numpy as np\n'), ((16115, 16147), 'photutils.CircularAperture', 'CircularAperture', (['positions'], {'r': '(4)'}), '(positions, r=4)\n', (16131, 16147), False, 'from photutils import CircularAnnulus, CircularAperture, aperture_photometry\n'), ((17719, 17821), 'sep.sum_circle', 'sep.sum_circle', (['masked_data', "gal_object['x']", "gal_object['y']", 'r_min'], {'err': 'bkg.globalrms', 'subpix': '(1)'}), "(masked_data, gal_object['x'], gal_object['y'], r_min, err=\n bkg.globalrms, subpix=1)\n", (17733, 17821), False, 'import sep\n'), ((18088, 18259), 'sep.sum_ellipse', 'sep.sum_ellipse', (['masked_data', "gal_object['x']", "gal_object['y']", "gal_object['a']", "gal_object['b']", "gal_object['theta']", '(2.5 * kronrad)'], {'err': 'bkg.globalrms', 'subpix': '(1)'}), "(masked_data, gal_object['x'], gal_object['y'], gal_object[\n 'a'], gal_object['b'], gal_object['theta'], 2.5 * kronrad, err=bkg.\n globalrms, subpix=1)\n", (18103, 18259), False, 'import sep\n'), ((18874, 18888), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (18886, 18888), True, 'import matplotlib.pyplot as plt\n'), ((19135, 19304), 'matplotlib.patches.Ellipse', 'Ellipse', ([], {'xy': "(gal_object['x'][0], gal_object['y'][0])", 'width': "(6 * gal_object['a'][0])", 'height': "(6 * gal_object['b'][0])", 'angle': "(gal_object['theta'][0] * 180.0 / np.pi)"}), "(xy=(gal_object['x'][0], gal_object['y'][0]), width=6 * gal_object[\n 'a'][0], height=6 * gal_object['b'][0], angle=gal_object['theta'][0] * \n 180.0 / np.pi)\n", (19142, 19304), False, 'from matplotlib.patches import Ellipse\n'), ((19444, 19462), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (19460, 19462), True, 'import matplotlib.pyplot as plt\n'), ((19471, 19495), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_output'], {}), '(plot_output)\n', (19482, 19495), True, 'import matplotlib.pyplot as plt\n'), ((19504, 19518), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (19513, 19518), True, 'import matplotlib.pyplot as plt\n'), ((22055, 22083), 'os.path.join', 'os.path.join', (['work_dir', 'name'], {}), '(work_dir, name)\n', (22067, 22083), False, 'import os\n'), ((3414, 3434), 'numpy.argmax', 'np.argmax', (['star_data'], {}), '(star_data)\n', (3423, 3434), True, 'import numpy as np\n'), ((7406, 7466), 'photutils.CircularAnnulus', 'CircularAnnulus', (['aperture.positions'], {'r_in': 'r_mid', 'r_out': 'r_out'}), '(aperture.positions, r_in=r_mid, r_out=r_out)\n', (7421, 7466), False, 'from photutils import CircularAnnulus, CircularAperture, aperture_photometry\n'), ((7933, 7952), 'numpy.argmin', 'np.argmin', (['dist2gal'], {}), '(dist2gal)\n', (7942, 7952), True, 'import numpy as np\n'), ((8176, 8192), 'numpy.nanmean', 'np.nanmean', (['data'], {}), '(data)\n', (8186, 8192), True, 'import numpy as np\n'), ((8194, 8209), 'numpy.nanstd', 'np.nanstd', (['data'], {}), '(data)\n', (8203, 8209), True, 'import numpy as np\n'), ((8738, 8787), 'matplotlib.pyplot.Circle', 'plt.Circle', (['gal_center', 'gal_r'], {'ec': '"""b"""', 'fill': '(False)'}), "(gal_center, gal_r, ec='b', fill=False)\n", (8748, 8787), True, 'import matplotlib.pyplot as plt\n'), ((16401, 16430), 'os.path.splitext', 'os.path.splitext', (['plot_output'], {}), '(plot_output)\n', (16417, 16430), False, 'import os\n'), ((17116, 17136), 'numpy.nanmean', 'np.nanmean', (['data_sub'], {}), '(data_sub)\n', (17126, 17136), True, 'import numpy as np\n'), ((17570, 17612), 'numpy.sqrt', 'np.sqrt', (["(gal_object['a'] * gal_object['b'])"], {}), "(gal_object['a'] * gal_object['b'])\n", (17577, 17612), True, 'import numpy as np\n'), ((18760, 18774), 'numpy.log10', 'np.log10', (['flux'], {}), '(flux)\n', (18768, 18774), True, 'import numpy as np\n'), ((18904, 18924), 'numpy.nanmean', 'np.nanmean', (['data_sub'], {}), '(data_sub)\n', (18914, 18924), True, 'import numpy as np\n'), ((18926, 18945), 'numpy.nanstd', 'np.nanstd', (['data_sub'], {}), '(data_sub)\n', (18935, 18945), True, 'import numpy as np\n'), ((22107, 22152), 'os.path.join', 'os.path.join', (['sn_dir', 'f"""{survey}_{filt}.fits"""'], {}), "(sn_dir, f'{survey}_{filt}.fits')\n", (22119, 22152), False, 'import os\n'), ((22334, 22388), 'os.path.join', 'os.path.join', (['sn_dir', 'f"""{survey}_{coadd_filters}.fits"""'], {}), "(sn_dir, f'{survey}_{coadd_filters}.fits')\n", (22346, 22388), False, 'import os\n'), ((7862, 7902), 'numpy.abs', 'np.abs', (['(apertures.positions - gal_center)'], {}), '(apertures.positions - gal_center)\n', (7868, 7902), True, 'import numpy as np\n'), ((18647, 18664), 'numpy.log10', 'np.log10', (['exptime'], {}), '(exptime)\n', (18655, 18664), True, 'import numpy as np\n'), ((18798, 18808), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (18804, 18808), True, 'import numpy as np\n'), ((7973, 7991), 'numpy.isnan', 'np.isnan', (['ann_mean'], {}), '(ann_mean)\n', (7981, 7991), True, 'import numpy as np\n'), ((22783, 22825), 'os.path.join', 'os.path.join', (['sn_dir', 'f"""global_{filt}.jpg"""'], {}), "(sn_dir, f'global_{filt}.jpg')\n", (22795, 22825), False, 'import os\n'), ((7524, 7554), 'photutils.aperture_photometry', 'aperture_photometry', (['data', 'ann'], {}), '(data, ann)\n', (7543, 7554), False, 'from photutils import CircularAnnulus, CircularAperture, aperture_photometry\n')]
import torch import numpy as np import time import tqdm from .data_transforms import TransformedDataset def test_unc_model(model, dataset, device, batch_size=1, **forward_kwargs): pin_memory = True if device == torch.device("cpu"): pin_memory = False dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=4, pin_memory=pin_memory) dataset_size = len(dataset) metrics = [] unc_list = [] times_per_item = [] metric_name = "metric" # Iterate over data. for inputs, labels in tqdm.tqdm(dataloader): inputs = inputs.to(device, non_blocking=True) labels = labels.to(device, non_blocking=True) # forward # track history if only in train start = time.time() outputs, uncs = model(inputs, **forward_kwargs) end = time.time() times_per_item.append( (end - start)/inputs.shape[0] ) metric = torch.stack( [dist.metric(label) for (dist,label) in zip(outputs,labels)] ) metrics.append( metric.cpu().detach().numpy() ) unc_list.append( uncs.cpu().detach().numpy() ) results = { "metric_name": metric_name, "metrics": np.concatenate(metrics), "uncs": np.concatenate(unc_list), "time_per_item": np.mean(times_per_item), "time_per_item_std": np.std(times_per_item) / np.sqrt(dataset_size), } return results def process_datasets(dataset_class, dataset_args, unc_model, device, test_fn=test_unc_model, N=1000, **forward_kwargs): """ calls test_fn(unc_model, dataset) for every dataset in datasets """ results = {} for name in dataset_args: print("Testing", name) print(N) dataset = dataset_class(name,N=N) results[name] = test_fn(unc_model, dataset, device, **forward_kwargs) return results def transform_sweep(dataset, transforms, unc_model, device, test_fn=test_unc_model, **forward_kwargs): """ calls test_fn(unc_model, dataset, device, **forward_kwargs) on dataset as well as transformed versions of that dataset, augmenting the passed in dataset with each transform in transforms (a dictionary with entries: "transform_name": transform """ results = {} print("Testing original dataset") results["original"] = test_fn(unc_model, dataset, device, **forward_kwargs) for name, transform in transforms.items(): print("Testing", name) dataset = TransformedDataset(dataset, transform) results[name] = test_fn(unc_model, dataset, device, **forward_kwargs) return results
[ "numpy.mean", "numpy.sqrt", "numpy.std", "tqdm.tqdm", "numpy.concatenate", "torch.utils.data.DataLoader", "time.time", "torch.device" ]
[((288, 404), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset'], {'batch_size': 'batch_size', 'shuffle': '(False)', 'num_workers': '(4)', 'pin_memory': 'pin_memory'}), '(dataset, batch_size=batch_size, shuffle=False,\n num_workers=4, pin_memory=pin_memory)\n', (315, 404), False, 'import torch\n'), ((630, 651), 'tqdm.tqdm', 'tqdm.tqdm', (['dataloader'], {}), '(dataloader)\n', (639, 651), False, 'import tqdm\n'), ((222, 241), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (234, 241), False, 'import torch\n'), ((841, 852), 'time.time', 'time.time', ([], {}), '()\n', (850, 852), False, 'import time\n'), ((923, 934), 'time.time', 'time.time', ([], {}), '()\n', (932, 934), False, 'import time\n'), ((1300, 1323), 'numpy.concatenate', 'np.concatenate', (['metrics'], {}), '(metrics)\n', (1314, 1323), True, 'import numpy as np\n'), ((1341, 1365), 'numpy.concatenate', 'np.concatenate', (['unc_list'], {}), '(unc_list)\n', (1355, 1365), True, 'import numpy as np\n'), ((1392, 1415), 'numpy.mean', 'np.mean', (['times_per_item'], {}), '(times_per_item)\n', (1399, 1415), True, 'import numpy as np\n'), ((1446, 1468), 'numpy.std', 'np.std', (['times_per_item'], {}), '(times_per_item)\n', (1452, 1468), True, 'import numpy as np\n'), ((1471, 1492), 'numpy.sqrt', 'np.sqrt', (['dataset_size'], {}), '(dataset_size)\n', (1478, 1492), True, 'import numpy as np\n')]
def Poisson(lambd, N): """ Devuelve una lista con elementos que siguen la distribución de Poisson Parameters ---------- lambd : int Es la tasa de la distribución N : int Número de puntos, tiempo trancurrido Returns ------- list Lista de valores "k" para una distribución de Poisson que siga los parámetros """ import numpy as np from math import factorial # Creo la distribución acumulada de Poisson, la muestreo hasta un k igual a 3 sigma de # Poisson maxk = 3*lambd Poisson = np.empty(maxk) for ij in range(maxk): Numerador = (lambd**(ij))*np.exp(-lambd) Poisson[ij] = Numerador/factorial(ij) ij = ij + 1 Acum = np.cumsum(Poisson) # Distribución de probabilidad acumulada # Creo la distribución K que sigue la distribución de Poisson mediante "Acum" Nums = np.random.random(N) # Números aleatorios en [0,1] K = [] ij = 0 # Recorre el arreglo Nums while ij<len(Nums): ik = 0 # Recorre el arreglo Acum while ik<maxk: if ik==0 and Nums[ij]<Acum[0]: # Caso cero K.append(ik) if ik>0 and Nums[ij]<Acum[ik] and Nums[ij]>Acum[ik-1]: K.append(ik) ik = ik + 1 ij = ij + 1 return K
[ "numpy.random.random", "math.factorial", "numpy.exp", "numpy.empty", "numpy.cumsum" ]
[((573, 587), 'numpy.empty', 'np.empty', (['maxk'], {}), '(maxk)\n', (581, 587), True, 'import numpy as np\n'), ((741, 759), 'numpy.cumsum', 'np.cumsum', (['Poisson'], {}), '(Poisson)\n', (750, 759), True, 'import numpy as np\n'), ((899, 918), 'numpy.random.random', 'np.random.random', (['N'], {}), '(N)\n', (915, 918), True, 'import numpy as np\n'), ((649, 663), 'numpy.exp', 'np.exp', (['(-lambd)'], {}), '(-lambd)\n', (655, 663), True, 'import numpy as np\n'), ((696, 709), 'math.factorial', 'factorial', (['ij'], {}), '(ij)\n', (705, 709), False, 'from math import factorial\n')]
import numpy as np import numbers import six import datetime import pyarrow as pa MAX_LENGTH = 50 def _trim_string(value): if len(value) > MAX_LENGTH: value = repr(value[:MAX_LENGTH-3])[:-1] + '...' return value def _format_value(value): # print("value = ", value, type(value), isinstance(value, numbers.Number)) if isinstance(value, pa.lib.Scalar): value = value.as_py() if value is None: return '--' else: return _trim_string(str(value)) if isinstance(value, str): return _trim_string(str(value)) elif isinstance(value, bytes): value = _trim_string(repr(value)) elif isinstance(value, np.ma.core.MaskedConstant): return str(value) elif isinstance(value, np.datetime64): if np.isnat(value): value = 'NaT' else: value = ' '.join(str(value).split('T')) return value elif isinstance(value, np.timedelta64): if np.isnat(value): value = 'NaT' else: tmp = datetime.timedelta(seconds=value / np.timedelta64(1, 's')) ms = tmp.microseconds s = np.mod(tmp.seconds, 60) m = np.mod(tmp.seconds//60, 60) h = tmp.seconds // 3600 d = tmp.days if ms: value = str('%i days %+02i:%02i:%02i.%i' % (d,h,m,s,ms)) else: value = str('%i days %+02i:%02i:%02i' % (d,h,m,s)) return value elif isinstance(value, numbers.Number): value = str(value) else: value = repr(value) value = _trim_string(value) return value
[ "numpy.timedelta64", "numpy.isnat", "numpy.mod" ]
[((800, 815), 'numpy.isnat', 'np.isnat', (['value'], {}), '(value)\n', (808, 815), True, 'import numpy as np\n'), ((985, 1000), 'numpy.isnat', 'np.isnat', (['value'], {}), '(value)\n', (993, 1000), True, 'import numpy as np\n'), ((1169, 1192), 'numpy.mod', 'np.mod', (['tmp.seconds', '(60)'], {}), '(tmp.seconds, 60)\n', (1175, 1192), True, 'import numpy as np\n'), ((1209, 1238), 'numpy.mod', 'np.mod', (['(tmp.seconds // 60)', '(60)'], {}), '(tmp.seconds // 60, 60)\n', (1215, 1238), True, 'import numpy as np\n'), ((1095, 1117), 'numpy.timedelta64', 'np.timedelta64', (['(1)', '"""s"""'], {}), "(1, 's')\n", (1109, 1117), True, 'import numpy as np\n')]
import numpy as np import matplotlib.pyplot as plt years = 501 eaten = np.loadtxt(f'./data/eaten-{years}.txt') cow = eaten[:,0] sheep = eaten[:,1] print(cow.shape) print(sheep.shape) # kg/只 MASS = [ [753, 87.5, 3.94625], [0, 0, 0], [0, 0, 0] ] # calorie/kg # 所有能量都按照 million 计算 ENERGY_PER_MASS = np.array([ [1250000, 1180000, 1020000], [0, 0, 0], [0, 0, 0] ]) / 1e6 # 只/km^2 DENSITY = [ [3.4130, 9.4514, 0], [0, 0, 0], [0, 0, 0] ] def cal_v(): constant = 365 v_cow = 1 * ENERGY_PER_MASS[0][0] * MASS[0][0] * DENSITY[0][0] / constant v_sheep = 8 * ENERGY_PER_MASS[0][1] * MASS[0][1] * DENSITY[0][1] / constant return (v_cow, v_sheep) energy_per_two_day = cow * ENERGY_PER_MASS[0][0] * MASS[0][0] + sheep * ENERGY_PER_MASS[0][1] * MASS[0][1] (v_cow, v_sheep) = cal_v() s_area = energy_per_two_day / (v_cow + v_sheep) * 3 fig, axes = plt.subplots( nrows=1, ncols=1, figsize=(12, 8) ) axes.set_xlabel('Age/year') axes.set_ylabel(r'Area/$km^2$') axes.set_title('Minimum area required to support the three dragons') axes.plot(np.arange(years), s_area, c='pink') import save_fig as sf sf.save_to_file(f'area-{years}')
[ "numpy.array", "save_fig.save_to_file", "numpy.loadtxt", "matplotlib.pyplot.subplots", "numpy.arange" ]
[((72, 111), 'numpy.loadtxt', 'np.loadtxt', (['f"""./data/eaten-{years}.txt"""'], {}), "(f'./data/eaten-{years}.txt')\n", (82, 111), True, 'import numpy as np\n'), ((892, 939), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(1)', 'ncols': '(1)', 'figsize': '(12, 8)'}), '(nrows=1, ncols=1, figsize=(12, 8))\n', (904, 939), True, 'import matplotlib.pyplot as plt\n'), ((1147, 1179), 'save_fig.save_to_file', 'sf.save_to_file', (['f"""area-{years}"""'], {}), "(f'area-{years}')\n", (1162, 1179), True, 'import save_fig as sf\n'), ((311, 372), 'numpy.array', 'np.array', (['[[1250000, 1180000, 1020000], [0, 0, 0], [0, 0, 0]]'], {}), '([[1250000, 1180000, 1020000], [0, 0, 0], [0, 0, 0]])\n', (319, 372), True, 'import numpy as np\n'), ((1089, 1105), 'numpy.arange', 'np.arange', (['years'], {}), '(years)\n', (1098, 1105), True, 'import numpy as np\n')]
from math import cos, pi from scipy import signal import scipy.signal as sig import matplotlib.pyplot as plt import numpy plt.close('all') Fs = 5000 #Sample Frequ sample = 5000 #Number of Samples f = 100 #Sig gen Frequ n = 2 #Order of Filter rs = 30 #only for Cheby fc = 100 #Cut Frequ w_c = 2*fc/Fs #Digital Frequ -> 0 - 0.5 [b,a] = sig.iirfilter(n,w_c ,0,rs, btype="lowpass", analog=False, ftype="butter") [w,h] = sig.freqz(b,a,2000) w = Fs*w/(2*pi) h_db = 20*numpy.log10(abs(h)) plt.figure() plt.plot(w, h_db);plt.xlabel('Frequency(Hz)') plt.ylabel('Magnitude(db)') plt.grid('ON') plt.show() print(a,b) x = numpy.arange(sample) y = numpy.sin(2 * numpy.pi * f * x / Fs) plt.plot(x, y) plt.xlabel('sample(n)') plt.ylabel('voltage(V)') plt.show()
[ "matplotlib.pyplot.grid", "scipy.signal.iirfilter", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "matplotlib.pyplot.close", "matplotlib.pyplot.figure", "numpy.sin", "scipy.signal.freqz", "numpy.arange", "matplotlib.pyplot.show" ]
[((129, 145), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (138, 145), True, 'import matplotlib.pyplot as plt\n'), ((424, 499), 'scipy.signal.iirfilter', 'sig.iirfilter', (['n', 'w_c', '(0)', 'rs'], {'btype': '"""lowpass"""', 'analog': '(False)', 'ftype': '"""butter"""'}), "(n, w_c, 0, rs, btype='lowpass', analog=False, ftype='butter')\n", (437, 499), True, 'import scipy.signal as sig\n'), ((509, 530), 'scipy.signal.freqz', 'sig.freqz', (['b', 'a', '(2000)'], {}), '(b, a, 2000)\n', (518, 530), True, 'import scipy.signal as sig\n'), ((580, 592), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (590, 592), True, 'import matplotlib.pyplot as plt\n'), ((594, 611), 'matplotlib.pyplot.plot', 'plt.plot', (['w', 'h_db'], {}), '(w, h_db)\n', (602, 611), True, 'import matplotlib.pyplot as plt\n'), ((612, 639), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Frequency(Hz)"""'], {}), "('Frequency(Hz)')\n", (622, 639), True, 'import matplotlib.pyplot as plt\n'), ((641, 668), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Magnitude(db)"""'], {}), "('Magnitude(db)')\n", (651, 668), True, 'import matplotlib.pyplot as plt\n'), ((670, 684), 'matplotlib.pyplot.grid', 'plt.grid', (['"""ON"""'], {}), "('ON')\n", (678, 684), True, 'import matplotlib.pyplot as plt\n'), ((686, 696), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (694, 696), True, 'import matplotlib.pyplot as plt\n'), ((716, 736), 'numpy.arange', 'numpy.arange', (['sample'], {}), '(sample)\n', (728, 736), False, 'import numpy\n'), ((742, 778), 'numpy.sin', 'numpy.sin', (['(2 * numpy.pi * f * x / Fs)'], {}), '(2 * numpy.pi * f * x / Fs)\n', (751, 778), False, 'import numpy\n'), ((780, 794), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {}), '(x, y)\n', (788, 794), True, 'import matplotlib.pyplot as plt\n'), ((796, 819), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""sample(n)"""'], {}), "('sample(n)')\n", (806, 819), True, 'import matplotlib.pyplot as plt\n'), ((821, 845), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""voltage(V)"""'], {}), "('voltage(V)')\n", (831, 845), True, 'import matplotlib.pyplot as plt\n'), ((847, 857), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (855, 857), True, 'import matplotlib.pyplot as plt\n')]
# Copyright (c) 2003-2019 by <NAME> # # TreeCorr is free software: redistribution and use in source and binary forms, # with or without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions, and the disclaimer given in the accompanying LICENSE # file. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions, and the disclaimer given in the documentation # and/or other materials provided with the distribution. from __future__ import print_function import numpy as np import treecorr import os import coord import fitsio from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer from test_helper import is_ccw, is_ccw_3d @timer def test_log_binning(): import math # Test some basic properties of the base class def check_arrays(nnn): np.testing.assert_almost_equal(nnn.bin_size * nnn.nbins, math.log(nnn.max_sep/nnn.min_sep)) np.testing.assert_almost_equal(nnn.ubin_size * nnn.nubins, nnn.max_u-nnn.min_u) np.testing.assert_almost_equal(nnn.vbin_size * nnn.nvbins, nnn.max_v-nnn.min_v) #print('logr = ',nnn.logr1d) np.testing.assert_equal(nnn.logr1d.shape, (nnn.nbins,) ) np.testing.assert_almost_equal(nnn.logr1d[0], math.log(nnn.min_sep) + 0.5*nnn.bin_size) np.testing.assert_almost_equal(nnn.logr1d[-1], math.log(nnn.max_sep) - 0.5*nnn.bin_size) np.testing.assert_equal(nnn.logr.shape, (nnn.nbins, nnn.nubins, 2*nnn.nvbins) ) np.testing.assert_almost_equal(nnn.logr[:,0,0], nnn.logr1d) np.testing.assert_almost_equal(nnn.logr[:,-1,-1], nnn.logr1d) assert len(nnn.logr) == nnn.nbins #print('u = ',nnn.u1d) np.testing.assert_equal(nnn.u1d.shape, (nnn.nubins,) ) np.testing.assert_almost_equal(nnn.u1d[0], nnn.min_u + 0.5*nnn.ubin_size) np.testing.assert_almost_equal(nnn.u1d[-1], nnn.max_u - 0.5*nnn.ubin_size) np.testing.assert_equal(nnn.u.shape, (nnn.nbins, nnn.nubins, 2*nnn.nvbins) ) np.testing.assert_almost_equal(nnn.u[0,:,0], nnn.u1d) np.testing.assert_almost_equal(nnn.u[-1,:,-1], nnn.u1d) #print('v = ',nnn.v1d) np.testing.assert_equal(nnn.v1d.shape, (2*nnn.nvbins,) ) np.testing.assert_almost_equal(nnn.v1d[0], -nnn.max_v + 0.5*nnn.vbin_size) np.testing.assert_almost_equal(nnn.v1d[-1], nnn.max_v - 0.5*nnn.vbin_size) np.testing.assert_almost_equal(nnn.v1d[nnn.nvbins], nnn.min_v + 0.5*nnn.vbin_size) np.testing.assert_almost_equal(nnn.v1d[nnn.nvbins-1], -nnn.min_v - 0.5*nnn.vbin_size) np.testing.assert_equal(nnn.v.shape, (nnn.nbins, nnn.nubins, 2*nnn.nvbins) ) np.testing.assert_almost_equal(nnn.v[0,0,:], nnn.v1d) np.testing.assert_almost_equal(nnn.v[-1,-1,:], nnn.v1d) def check_defaultuv(nnn): assert nnn.min_u == 0. assert nnn.max_u == 1. assert nnn.nubins == np.ceil(1./nnn.ubin_size) assert nnn.min_v == 0. assert nnn.max_v == 1. assert nnn.nvbins == np.ceil(1./nnn.vbin_size) # Check the different ways to set up the binning: # Omit bin_size nnn = treecorr.NNNCorrelation(min_sep=5, max_sep=20, nbins=20, bin_type='LogRUV') #print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins) #print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins) #print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins) assert nnn.min_sep == 5. assert nnn.max_sep == 20. assert nnn.nbins == 20 check_defaultuv(nnn) check_arrays(nnn) # Specify min, max, n for u,v too. nnn = treecorr.NNNCorrelation(min_sep=5, max_sep=20, nbins=20, min_u=0.2, max_u=0.9, nubins=12, min_v=0., max_v=0.2, nvbins=2) #print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins) #print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins) #print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins) assert nnn.min_sep == 5. assert nnn.max_sep == 20. assert nnn.nbins == 20 assert nnn.min_u == 0.2 assert nnn.max_u == 0.9 assert nnn.nubins == 12 assert nnn.min_v == 0. assert nnn.max_v == 0.2 assert nnn.nvbins == 2 check_arrays(nnn) # Omit min_sep nnn = treecorr.NNNCorrelation(max_sep=20, nbins=20, bin_size=0.1) #print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins) #print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins) #print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins) assert nnn.bin_size == 0.1 assert nnn.max_sep == 20. assert nnn.nbins == 20 check_defaultuv(nnn) check_arrays(nnn) # Specify max, n, bs for u,v too. nnn = treecorr.NNNCorrelation(max_sep=20, nbins=20, bin_size=0.1, max_u=0.9, nubins=3, ubin_size=0.05, max_v=0.4, nvbins=4, vbin_size=0.05) #print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins) #print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins) #print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins) assert nnn.bin_size == 0.1 assert nnn.max_sep == 20. assert nnn.nbins == 20 assert np.isclose(nnn.ubin_size, 0.05) assert np.isclose(nnn.min_u, 0.75) assert nnn.max_u == 0.9 assert nnn.nubins == 3 assert np.isclose(nnn.vbin_size, 0.05) assert np.isclose(nnn.min_v, 0.2) assert nnn.max_v == 0.4 assert nnn.nvbins == 4 check_arrays(nnn) # Omit max_sep nnn = treecorr.NNNCorrelation(min_sep=5, nbins=20, bin_size=0.1) #print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins) #print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins) #print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins) assert nnn.bin_size == 0.1 assert nnn.min_sep == 5. assert nnn.nbins == 20 check_defaultuv(nnn) check_arrays(nnn) # Specify min, n, bs for u,v too. nnn = treecorr.NNNCorrelation(min_sep=5, nbins=20, bin_size=0.1, min_u=0.7, nubins=4, ubin_size=0.05, min_v=0.2, nvbins=4, vbin_size=0.05) #print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins) #print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins) #print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins) assert nnn.min_sep == 5. assert nnn.bin_size == 0.1 assert nnn.nbins == 20 assert nnn.min_u == 0.7 assert np.isclose(nnn.ubin_size, 0.05) assert nnn.nubins == 4 assert nnn.min_v == 0.2 assert nnn.max_v == 0.4 assert np.isclose(nnn.vbin_size, 0.05) assert nnn.nvbins == 4 check_arrays(nnn) # Omit nbins nnn = treecorr.NNNCorrelation(min_sep=5, max_sep=20, bin_size=0.1) #print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins) #print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins) #print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins) assert nnn.bin_size <= 0.1 assert nnn.min_sep == 5. assert nnn.max_sep == 20. check_defaultuv(nnn) check_arrays(nnn) # Specify min, max, bs for u,v too. nnn = treecorr.NNNCorrelation(min_sep=5, max_sep=20, bin_size=0.1, min_u=0.2, max_u=0.9, ubin_size=0.03, min_v=0.1, max_v=0.3, vbin_size=0.07) #print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins) #print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins) #print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins) assert nnn.min_sep == 5. assert nnn.max_sep == 20. assert nnn.bin_size <= 0.1 assert nnn.min_u == 0.2 assert nnn.max_u == 0.9 assert nnn.nubins == 24 assert np.isclose(nnn.ubin_size, 0.7/24) assert nnn.min_v == 0.1 assert nnn.max_v == 0.3 assert nnn.nvbins == 3 assert np.isclose(nnn.vbin_size, 0.2/3) check_arrays(nnn) # If only one of min/max v are set, respect that nnn = treecorr.NNNCorrelation(min_sep=5, max_sep=20, bin_size=0.1, min_u=0.2, ubin_size=0.03, min_v=0.2, vbin_size=0.07) #print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins) #print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins) #print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins) assert nnn.min_u == 0.2 assert nnn.max_u == 1. assert nnn.nubins == 27 assert np.isclose(nnn.ubin_size, 0.8/27) assert nnn.min_v == 0.2 assert nnn.max_v == 1. assert nnn.nvbins == 12 assert np.isclose(nnn.vbin_size, 0.8/12) check_arrays(nnn) nnn = treecorr.NNNCorrelation(min_sep=5, max_sep=20, bin_size=0.1, max_u=0.2, ubin_size=0.03, max_v=0.2, vbin_size=0.07) #print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins) #print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins) #print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins) assert nnn.min_u == 0. assert nnn.max_u == 0.2 assert nnn.nubins == 7 assert np.isclose(nnn.ubin_size, 0.2/7) assert nnn.min_v == 0. assert nnn.max_v == 0.2 assert nnn.nvbins == 3 assert np.isclose(nnn.vbin_size, 0.2/3) check_arrays(nnn) # If only vbin_size is set for v, automatically figure out others. # (And if necessary adjust the bin_size down a bit.) nnn = treecorr.NNNCorrelation(min_sep=5, max_sep=20, bin_size=0.1, ubin_size=0.3, vbin_size=0.3) #print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins) #print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins) #print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins) assert nnn.bin_size <= 0.1 assert nnn.min_sep == 5. assert nnn.max_sep == 20. assert nnn.min_u == 0. assert nnn.max_u == 1. assert nnn.nubins == 4 assert np.isclose(nnn.ubin_size, 0.25) assert nnn.min_v == 0. assert nnn.max_v == 1. assert nnn.nvbins == 4 assert np.isclose(nnn.vbin_size, 0.25) check_arrays(nnn) # If only nvbins is set for v, automatically figure out others. nnn = treecorr.NNNCorrelation(min_sep=5, max_sep=20, bin_size=0.1, nubins=5, nvbins=5) #print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins) #print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins) #print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins) assert nnn.bin_size <= 0.1 assert nnn.min_sep == 5. assert nnn.max_sep == 20. assert nnn.min_u == 0. assert nnn.max_u == 1. assert nnn.nubins == 5 assert np.isclose(nnn.ubin_size,0.2) assert nnn.min_v == 0. assert nnn.max_v == 1. assert nnn.nvbins == 5 assert np.isclose(nnn.vbin_size,0.2) check_arrays(nnn) # If both nvbins and vbin_size are set, set min/max automatically nnn = treecorr.NNNCorrelation(min_sep=5, max_sep=20, bin_size=0.1, ubin_size=0.1, nubins=5, vbin_size=0.1, nvbins=5) #print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins) #print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins) #print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins) assert nnn.bin_size <= 0.1 assert nnn.min_sep == 5. assert nnn.max_sep == 20. assert nnn.ubin_size == 0.1 assert nnn.nubins == 5 assert nnn.max_u == 1. assert np.isclose(nnn.min_u,0.5) assert nnn.vbin_size == 0.1 assert nnn.nvbins == 5 assert nnn.min_v == 0. assert np.isclose(nnn.max_v,0.5) check_arrays(nnn) assert_raises(TypeError, treecorr.NNNCorrelation) assert_raises(TypeError, treecorr.NNNCorrelation, min_sep=5) assert_raises(TypeError, treecorr.NNNCorrelation, max_sep=20) assert_raises(TypeError, treecorr.NNNCorrelation, bin_size=0.1) assert_raises(TypeError, treecorr.NNNCorrelation, nbins=20) assert_raises(TypeError, treecorr.NNNCorrelation, min_sep=5, max_sep=20) assert_raises(TypeError, treecorr.NNNCorrelation, min_sep=5, bin_size=0.1) assert_raises(TypeError, treecorr.NNNCorrelation, min_sep=5, nbins=20) assert_raises(TypeError, treecorr.NNNCorrelation, max_sep=20, bin_size=0.1) assert_raises(TypeError, treecorr.NNNCorrelation, max_sep=20, nbins=20) assert_raises(TypeError, treecorr.NNNCorrelation, bin_size=0.1, nbins=20) assert_raises(TypeError, treecorr.NNNCorrelation, min_sep=5, max_sep=20, bin_size=0.1, nbins=20) assert_raises(ValueError, treecorr.NNNCorrelation, min_sep=20, max_sep=5, bin_size=0.1) assert_raises(ValueError, treecorr.NNNCorrelation, min_sep=20, max_sep=5, nbins=20) assert_raises(ValueError, treecorr.NNNCorrelation, min_sep=20, max_sep=5, nbins=20, bin_type='Log') assert_raises(ValueError, treecorr.NNNCorrelation, min_sep=20, max_sep=5, nbins=20, bin_type='Linear') assert_raises(ValueError, treecorr.NNNCorrelation, min_sep=20, max_sep=5, nbins=20, bin_type='TwoD') assert_raises(ValueError, treecorr.NNNCorrelation, min_sep=20, max_sep=5, nbins=20, bin_type='Invalid') assert_raises(TypeError, treecorr.NNNCorrelation, min_sep=5, max_sep=20, bin_size=0.1, min_u=0.3, max_u=0.9, ubin_size=0.1, nubins=6) assert_raises(ValueError, treecorr.NNNCorrelation, min_sep=5, max_sep=20, bin_size=0.1, min_u=0.9, max_u=0.3) assert_raises(ValueError, treecorr.NNNCorrelation, min_sep=5, max_sep=20, bin_size=0.1, min_u=-0.1, max_u=0.3) assert_raises(ValueError, treecorr.NNNCorrelation, min_sep=5, max_sep=20, bin_size=0.1, min_u=0.1, max_u=1.3) assert_raises(TypeError, treecorr.NNNCorrelation, min_sep=5, max_sep=20, bin_size=0.1, min_v=0.1, max_v=0.9, vbin_size=0.1, nvbins=9) assert_raises(ValueError, treecorr.NNNCorrelation, min_sep=5, max_sep=20, bin_size=0.1, min_v=0.9, max_v=0.3) assert_raises(ValueError, treecorr.NNNCorrelation, min_sep=5, max_sep=20, bin_size=0.1, min_v=-0.1, max_v=0.3) assert_raises(ValueError, treecorr.NNNCorrelation, min_sep=5, max_sep=20, bin_size=0.1, min_v=0.1, max_v=1.3) assert_raises(ValueError, treecorr.NNNCorrelation, min_sep=20, max_sep=5, nbins=20, split_method='invalid') # Check the use of sep_units # radians nnn = treecorr.NNNCorrelation(min_sep=5, max_sep=20, nbins=20, sep_units='radians') #print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins) #print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins) #print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins) np.testing.assert_almost_equal(nnn.min_sep, 5.) np.testing.assert_almost_equal(nnn.max_sep, 20.) np.testing.assert_almost_equal(nnn._min_sep, 5.) np.testing.assert_almost_equal(nnn._max_sep, 20.) assert nnn.min_sep == 5. assert nnn.max_sep == 20. assert nnn.nbins == 20 check_defaultuv(nnn) check_arrays(nnn) # arcsec nnn = treecorr.NNNCorrelation(min_sep=5, max_sep=20, nbins=20, sep_units='arcsec') #print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins) #print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins) #print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins) np.testing.assert_almost_equal(nnn.min_sep, 5.) np.testing.assert_almost_equal(nnn.max_sep, 20.) np.testing.assert_almost_equal(nnn._min_sep, 5. * math.pi/180/3600) np.testing.assert_almost_equal(nnn._max_sep, 20. * math.pi/180/3600) assert nnn.nbins == 20 np.testing.assert_almost_equal(nnn.bin_size * nnn.nbins, math.log(nnn.max_sep/nnn.min_sep)) # Note that logr is in the separation units, not radians. np.testing.assert_almost_equal(nnn.logr[0], math.log(5) + 0.5*nnn.bin_size) np.testing.assert_almost_equal(nnn.logr[-1], math.log(20) - 0.5*nnn.bin_size) assert len(nnn.logr) == nnn.nbins check_defaultuv(nnn) # arcmin nnn = treecorr.NNNCorrelation(min_sep=5, max_sep=20, nbins=20, sep_units='arcmin') #print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins) #print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins) #print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins) np.testing.assert_almost_equal(nnn.min_sep, 5.) np.testing.assert_almost_equal(nnn.max_sep, 20.) np.testing.assert_almost_equal(nnn._min_sep, 5. * math.pi/180/60) np.testing.assert_almost_equal(nnn._max_sep, 20. * math.pi/180/60) assert nnn.nbins == 20 np.testing.assert_almost_equal(nnn.bin_size * nnn.nbins, math.log(nnn.max_sep/nnn.min_sep)) np.testing.assert_almost_equal(nnn.logr[0], math.log(5) + 0.5*nnn.bin_size) np.testing.assert_almost_equal(nnn.logr[-1], math.log(20) - 0.5*nnn.bin_size) assert len(nnn.logr) == nnn.nbins check_defaultuv(nnn) # degrees nnn = treecorr.NNNCorrelation(min_sep=5, max_sep=20, nbins=20, sep_units='degrees') #print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins) #print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins) #print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins) np.testing.assert_almost_equal(nnn.min_sep, 5.) np.testing.assert_almost_equal(nnn.max_sep, 20.) np.testing.assert_almost_equal(nnn._min_sep, 5. * math.pi/180) np.testing.assert_almost_equal(nnn._max_sep, 20. * math.pi/180) assert nnn.nbins == 20 np.testing.assert_almost_equal(nnn.bin_size * nnn.nbins, math.log(nnn.max_sep/nnn.min_sep)) np.testing.assert_almost_equal(nnn.logr[0], math.log(5) + 0.5*nnn.bin_size) np.testing.assert_almost_equal(nnn.logr[-1], math.log(20) - 0.5*nnn.bin_size) assert len(nnn.logr) == nnn.nbins check_defaultuv(nnn) # hours nnn = treecorr.NNNCorrelation(min_sep=5, max_sep=20, nbins=20, sep_units='hours') #print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins) #print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins) #print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins) np.testing.assert_almost_equal(nnn.min_sep, 5.) np.testing.assert_almost_equal(nnn.max_sep, 20.) np.testing.assert_almost_equal(nnn._min_sep, 5. * math.pi/12) np.testing.assert_almost_equal(nnn._max_sep, 20. * math.pi/12) assert nnn.nbins == 20 np.testing.assert_almost_equal(nnn.bin_size * nnn.nbins, math.log(nnn.max_sep/nnn.min_sep)) np.testing.assert_almost_equal(nnn.logr[0], math.log(5) + 0.5*nnn.bin_size) np.testing.assert_almost_equal(nnn.logr[-1], math.log(20) - 0.5*nnn.bin_size) assert len(nnn.logr) == nnn.nbins check_defaultuv(nnn) # Check bin_slop # Start with default behavior nnn = treecorr.NNNCorrelation(min_sep=5, nbins=14, bin_size=0.1, min_u=0., max_u=0.9, ubin_size=0.03, min_v=0., max_v=0.21, vbin_size=0.07) #print(nnn.bin_size,nnn.bin_slop,nnn.b) #print(nnn.ubin_size,nnn.bu) #print(nnn.vbin_size,nnn.bv) assert nnn.bin_slop == 1.0 assert nnn.bin_size == 0.1 assert np.isclose(nnn.ubin_size, 0.03) assert np.isclose(nnn.vbin_size, 0.07) np.testing.assert_almost_equal(nnn.b, 0.1) np.testing.assert_almost_equal(nnn.bu, 0.03) np.testing.assert_almost_equal(nnn.bv, 0.07) # Explicitly set bin_slop=1.0 does the same thing. nnn = treecorr.NNNCorrelation(min_sep=5, nbins=14, bin_size=0.1, bin_slop=1.0, min_u=0., max_u=0.9, ubin_size=0.03, min_v=0., max_v=0.21, vbin_size=0.07) #print(nnn.bin_size,nnn.bin_slop,nnn.b) #print(nnn.ubin_size,nnn.bu) #print(nnn.vbin_size,nnn.bv) assert nnn.bin_slop == 1.0 assert nnn.bin_size == 0.1 assert np.isclose(nnn.ubin_size, 0.03) assert np.isclose(nnn.vbin_size, 0.07) np.testing.assert_almost_equal(nnn.b, 0.1) np.testing.assert_almost_equal(nnn.bu, 0.03) np.testing.assert_almost_equal(nnn.bv, 0.07) # Use a smaller bin_slop nnn = treecorr.NNNCorrelation(min_sep=5, nbins=14, bin_size=0.1, bin_slop=0.2, min_u=0., max_u=0.9, ubin_size=0.03, min_v=0., max_v=0.21, vbin_size=0.07) #print(nnn.bin_size,nnn.bin_slop,nnn.b) #print(nnn.ubin_size,nnn.bu) #print(nnn.vbin_size,nnn.bv) assert nnn.bin_slop == 0.2 assert nnn.bin_size == 0.1 assert np.isclose(nnn.ubin_size, 0.03) assert np.isclose(nnn.vbin_size, 0.07) np.testing.assert_almost_equal(nnn.b, 0.02) np.testing.assert_almost_equal(nnn.bu, 0.006) np.testing.assert_almost_equal(nnn.bv, 0.014) # Use bin_slop == 0 nnn = treecorr.NNNCorrelation(min_sep=5, nbins=14, bin_size=0.1, bin_slop=0.0, min_u=0., max_u=0.9, ubin_size=0.03, min_v=0., max_v=0.21, vbin_size=0.07) #print(nnn.bin_size,nnn.bin_slop,nnn.b) #print(nnn.ubin_size,nnn.bu) #print(nnn.vbin_size,nnn.bv) assert nnn.bin_slop == 0.0 assert nnn.bin_size == 0.1 assert np.isclose(nnn.ubin_size, 0.03) assert np.isclose(nnn.vbin_size, 0.07) np.testing.assert_almost_equal(nnn.b, 0.0) np.testing.assert_almost_equal(nnn.bu, 0.0) np.testing.assert_almost_equal(nnn.bv, 0.0) # Bigger bin_slop nnn = treecorr.NNNCorrelation(min_sep=5, nbins=14, bin_size=0.1, bin_slop=2.0, min_u=0., max_u=0.9, ubin_size=0.03, min_v=0., max_v=0.21, vbin_size=0.07, verbose=0) #print(nnn.bin_size,nnn.bin_slop,nnn.b) #print(nnn.ubin_size,nnn.bu) #print(nnn.vbin_size,nnn.bv) assert nnn.bin_slop == 2.0 assert nnn.bin_size == 0.1 assert np.isclose(nnn.ubin_size, 0.03) assert np.isclose(nnn.vbin_size, 0.07) np.testing.assert_almost_equal(nnn.b, 0.2) np.testing.assert_almost_equal(nnn.bu, 0.06) np.testing.assert_almost_equal(nnn.bv, 0.14) # With bin_size > 0.1, explicit bin_slop=1.0 is accepted. nnn = treecorr.NNNCorrelation(min_sep=5, nbins=14, bin_size=0.4, bin_slop=1.0, min_u=0., max_u=0.9, ubin_size=0.03, min_v=0., max_v=0.21, vbin_size=0.07, verbose=0) #print(nnn.bin_size,nnn.bin_slop,nnn.b) #print(nnn.ubin_size,nnn.bu) #print(nnn.vbin_size,nnn.bv) assert nnn.bin_slop == 1.0 assert nnn.bin_size == 0.4 assert np.isclose(nnn.ubin_size, 0.03) assert np.isclose(nnn.vbin_size, 0.07) np.testing.assert_almost_equal(nnn.b, 0.4) np.testing.assert_almost_equal(nnn.bu, 0.03) np.testing.assert_almost_equal(nnn.bv, 0.07) # But implicit bin_slop is reduced so that b = 0.1 nnn = treecorr.NNNCorrelation(min_sep=5, nbins=14, bin_size=0.4, min_u=0., max_u=0.9, ubin_size=0.03, min_v=0., max_v=0.21, vbin_size=0.07) #print(nnn.bin_size,nnn.bin_slop,nnn.b) #print(nnn.ubin_size,nnn.bu) #print(nnn.vbin_size,nnn.bv) assert nnn.bin_size == 0.4 assert np.isclose(nnn.ubin_size, 0.03) assert np.isclose(nnn.vbin_size, 0.07) np.testing.assert_almost_equal(nnn.b, 0.1) np.testing.assert_almost_equal(nnn.bu, 0.03) np.testing.assert_almost_equal(nnn.bv, 0.07) np.testing.assert_almost_equal(nnn.bin_slop, 0.25) # Separately for each of the three parameters nnn = treecorr.NNNCorrelation(min_sep=5, nbins=14, bin_size=0.05, min_u=0., max_u=0.9, ubin_size=0.3, min_v=0., max_v=0.17, vbin_size=0.17) #print(nnn.bin_size,nnn.bin_slop,nnn.b) #print(nnn.ubin_size,nnn.bu) #print(nnn.vbin_size,nnn.bv) assert nnn.bin_size == 0.05 assert np.isclose(nnn.ubin_size, 0.3) assert np.isclose(nnn.vbin_size, 0.17) np.testing.assert_almost_equal(nnn.b, 0.05) np.testing.assert_almost_equal(nnn.bu, 0.1) np.testing.assert_almost_equal(nnn.bv, 0.1) np.testing.assert_almost_equal(nnn.bin_slop, 1.0) # The stored bin_slop is just for lnr @timer def test_direct_count_auto(): # If the catalogs are small enough, we can do a direct count of the number of triangles # to see if comes out right. This should exactly match the treecorr code if bin_slop=0. ngal = 50 s = 10. rng = np.random.RandomState(8675309) x = rng.normal(0,s, (ngal,) ) y = rng.normal(0,s, (ngal,) ) cat = treecorr.Catalog(x=x, y=y) min_sep = 1. max_sep = 50. nbins = 50 min_u = 0.13 max_u = 0.89 nubins = 10 min_v = 0.13 max_v = 0.59 nvbins = 10 ddd = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, brute=True, verbose=1) ddd.process(cat) log_min_sep = np.log(min_sep) log_max_sep = np.log(max_sep) true_ntri = np.zeros( (nbins, nubins, 2*nvbins) ) bin_size = (log_max_sep - log_min_sep) / nbins ubin_size = (max_u-min_u) / nubins vbin_size = (max_v-min_v) / nvbins for i in range(ngal): for j in range(i+1,ngal): for k in range(j+1,ngal): dij = np.sqrt((x[i]-x[j])**2 + (y[i]-y[j])**2) dik = np.sqrt((x[i]-x[k])**2 + (y[i]-y[k])**2) djk = np.sqrt((x[j]-x[k])**2 + (y[j]-y[k])**2) if dij == 0.: continue if dik == 0.: continue if djk == 0.: continue if dij < dik: if dik < djk: d3 = dij; d2 = dik; d1 = djk ccw = is_ccw(x[i],y[i],x[j],y[j],x[k],y[k]) elif dij < djk: d3 = dij; d2 = djk; d1 = dik ccw = is_ccw(x[j],y[j],x[i],y[i],x[k],y[k]) else: d3 = djk; d2 = dij; d1 = dik ccw = is_ccw(x[j],y[j],x[k],y[k],x[i],y[i]) else: if dij < djk: d3 = dik; d2 = dij; d1 = djk ccw = is_ccw(x[i],y[i],x[k],y[k],x[j],y[j]) elif dik < djk: d3 = dik; d2 = djk; d1 = dij ccw = is_ccw(x[k],y[k],x[i],y[i],x[j],y[j]) else: d3 = djk; d2 = dik; d1 = dij ccw = is_ccw(x[k],y[k],x[j],y[j],x[i],y[i]) r = d2 u = d3/d2 v = (d1-d2)/d3 if r < min_sep or r >= max_sep: continue if u < min_u or u >= max_u: continue if v < min_v or v >= max_v: continue if not ccw: v = -v kr = int(np.floor( (np.log(r)-log_min_sep) / bin_size )) ku = int(np.floor( (u-min_u) / ubin_size )) if v > 0: kv = int(np.floor( (v-min_v) / vbin_size )) + nvbins else: kv = int(np.floor( (v-(-max_v)) / vbin_size )) assert 0 <= kr < nbins assert 0 <= ku < nubins assert 0 <= kv < 2*nvbins true_ntri[kr,ku,kv] += 1 nz = np.where((ddd.ntri > 0) | (true_ntri > 0)) print('non-zero at:') print(nz) print('d1 = ',ddd.meand1[nz]) print('d2 = ',ddd.meand2[nz]) print('d3 = ',ddd.meand3[nz]) print('rnom = ',ddd.rnom[nz]) print('u = ',ddd.u[nz]) print('v = ',ddd.v[nz]) print('ddd.ntri = ',ddd.ntri[nz]) print('true_ntri = ',true_ntri[nz]) print('diff = ',ddd.ntri[nz] - true_ntri[nz]) np.testing.assert_array_equal(ddd.ntri, true_ntri) # Check that running via the corr3 script works correctly. file_name = os.path.join('data','nnn_direct_data.dat') with open(file_name, 'w') as fid: for i in range(ngal): fid.write(('%.20f %.20f\n')%(x[i],y[i])) L = 10*s nrand = ngal rx = (rng.random_sample(nrand)-0.5) * L ry = (rng.random_sample(nrand)-0.5) * L rcat = treecorr.Catalog(x=rx, y=ry) rand_file_name = os.path.join('data','nnn_direct_rand.dat') with open(rand_file_name, 'w') as fid: for i in range(nrand): fid.write(('%.20f %.20f\n')%(rx[i],ry[i])) rrr = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, brute=True, verbose=0, rng=rng) rrr.process(rcat) zeta, varzeta = ddd.calculateZeta(rrr) # Semi-gratuitous check of BinnedCorr3.rng access. assert rrr.rng is rng assert ddd.rng is not rng # First do this via the corr3 function. config = treecorr.config.read_config('configs/nnn_direct.yaml') logger = treecorr.config.setup_logger(0) treecorr.corr3(config, logger) corr3_output = np.genfromtxt(os.path.join('output','nnn_direct.out'), names=True, skip_header=1) print('corr3_output = ',corr3_output) print('corr3_output.dtype = ',corr3_output.dtype) print('rnom = ',ddd.rnom.flatten()) print(' ',corr3_output['r_nom']) np.testing.assert_allclose(corr3_output['r_nom'], ddd.rnom.flatten(), rtol=1.e-3) print('unom = ',ddd.u.flatten()) print(' ',corr3_output['u_nom']) np.testing.assert_allclose(corr3_output['u_nom'], ddd.u.flatten(), rtol=1.e-3) print('vnom = ',ddd.v.flatten()) print(' ',corr3_output['v_nom']) np.testing.assert_allclose(corr3_output['v_nom'], ddd.v.flatten(), rtol=1.e-3) print('DDD = ',ddd.ntri.flatten()) print(' ',corr3_output['DDD']) np.testing.assert_allclose(corr3_output['DDD'], ddd.ntri.flatten(), rtol=1.e-3) np.testing.assert_allclose(corr3_output['ntri'], ddd.ntri.flatten(), rtol=1.e-3) print('RRR = ',rrr.ntri.flatten()) print(' ',corr3_output['RRR']) np.testing.assert_allclose(corr3_output['RRR'], rrr.ntri.flatten(), rtol=1.e-3) print('zeta = ',zeta.flatten()) print('from corr3 output = ',corr3_output['zeta']) print('diff = ',corr3_output['zeta']-zeta.flatten()) diff_index = np.where(np.abs(corr3_output['zeta']-zeta.flatten()) > 1.e-5)[0] print('different at ',diff_index) print('zeta[diffs] = ',zeta.flatten()[diff_index]) print('corr3.zeta[diffs] = ',corr3_output['zeta'][diff_index]) print('diff[diffs] = ',zeta.flatten()[diff_index] - corr3_output['zeta'][diff_index]) np.testing.assert_allclose(corr3_output['zeta'], zeta.flatten(), rtol=1.e-3) np.testing.assert_allclose(corr3_output['sigma_zeta'], np.sqrt(varzeta).flatten(), rtol=1.e-3) # Now calling out to the external corr3 executable. # This is the only time we test the corr3 executable. All other tests use corr3 function. import subprocess corr3_exe = get_script_name('corr3') p = subprocess.Popen( [corr3_exe,"configs/nnn_direct.yaml","verbose=0"] ) p.communicate() corr3_output = np.genfromtxt(os.path.join('output','nnn_direct.out'), names=True, skip_header=1) np.testing.assert_allclose(corr3_output['zeta'], zeta.flatten(), rtol=1.e-3) # Also check compensated drr = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, brute=True, verbose=0) rdd = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, brute=True, verbose=0) drr.process(cat, rcat) rdd.process(rcat, cat) zeta, varzeta = ddd.calculateZeta(rrr,drr,rdd) config['nnn_statistic'] = 'compensated' treecorr.corr3(config, logger) corr3_output = np.genfromtxt(os.path.join('output','nnn_direct.out'), names=True, skip_header=1) np.testing.assert_allclose(corr3_output['r_nom'], ddd.rnom.flatten(), rtol=1.e-3) np.testing.assert_allclose(corr3_output['u_nom'], ddd.u.flatten(), rtol=1.e-3) np.testing.assert_allclose(corr3_output['v_nom'], ddd.v.flatten(), rtol=1.e-3) np.testing.assert_allclose(corr3_output['DDD'], ddd.ntri.flatten(), rtol=1.e-3) np.testing.assert_allclose(corr3_output['ntri'], ddd.ntri.flatten(), rtol=1.e-3) print('rrr.tot = ',rrr.tot) print('ddd.tot = ',ddd.tot) print('drr.tot = ',drr.tot) print('rdd.tot = ',rdd.tot) rrrf = ddd.tot / rrr.tot drrf = ddd.tot / drr.tot rddf = ddd.tot / rdd.tot np.testing.assert_allclose(corr3_output['RRR'], rrr.ntri.flatten() * rrrf, rtol=1.e-3) np.testing.assert_allclose(corr3_output['DRR'], drr.ntri.flatten() * drrf, rtol=1.e-3) np.testing.assert_allclose(corr3_output['RDD'], rdd.ntri.flatten() * rddf, rtol=1.e-3) np.testing.assert_allclose(corr3_output['zeta'], zeta.flatten(), rtol=1.e-3) np.testing.assert_allclose(corr3_output['sigma_zeta'], np.sqrt(varzeta).flatten(), rtol=1.e-3) # Repeat with binslop = 0, since the code flow is different from bture=True ddd = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, bin_slop=0, verbose=1) ddd.process(cat) #print('ddd.ntri = ',ddd.ntri) #print('true_ntri => ',true_ntri) #print('diff = ',ddd.ntri - true_ntri) np.testing.assert_array_equal(ddd.ntri, true_ntri) # And again with no top-level recursion ddd = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, bin_slop=0, verbose=1, max_top=0) ddd.process(cat) #print('ddd.ntri = ',ddd.ntri) #print('true_ntri => ',true_ntri) #print('diff = ',ddd.ntri - true_ntri) np.testing.assert_array_equal(ddd.ntri, true_ntri) # And compare to the cross correlation # Here, we get 6x as much, since each triangle is discovered 6 times. ddd.clear() ddd.process(cat,cat,cat, num_threads=2) #print('ddd.ntri = ',ddd.ntri) #print('true_ntri => ',true_ntri) #print('diff = ',ddd.ntri - true_ntri) np.testing.assert_array_equal(ddd.ntri, 6*true_ntri) # With the real CrossCorrelation class, each of the 6 correlations should end up being # the same thing (without the extra factor of 6). dddc = treecorr.NNNCrossCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, bin_slop=0, verbose=1, max_top=0) dddc.process(cat,cat,cat, num_threads=2) # All 6 correlations are equal. for d in [dddc.n1n2n3, dddc.n1n3n2, dddc.n2n1n3, dddc.n2n3n1, dddc.n3n1n2, dddc.n3n2n1]: #print('ddd.ntri = ',ddd.ntri) #print('true_ntri => ',true_ntri) #print('diff = ',ddd.ntri - true_ntri) np.testing.assert_array_equal(d.ntri, true_ntri) # Or with 2 argument version, finds each triangle 3 times. ddd.process(cat,cat, num_threads=2) np.testing.assert_array_equal(ddd.ntri, 3*true_ntri) # Again, NNNCrossCorrelation gets it right in each permutation. dddc.process(cat,cat, num_threads=2) for d in [dddc.n1n2n3, dddc.n1n3n2, dddc.n2n1n3, dddc.n2n3n1, dddc.n3n1n2, dddc.n3n2n1]: np.testing.assert_array_equal(d.ntri, true_ntri) # Invalid to omit file_name config['verbose'] = 0 del config['file_name'] with assert_raises(TypeError): treecorr.corr3(config) config['file_name'] = 'data/nnn_direct_data.dat' # OK to not have rand_file_name # Also, check the automatic setting of output_dots=True when verbose=2. # It's not too annoying if we also set max_top = 0. del config['rand_file_name'] config['verbose'] = 2 config['max_top'] = 0 treecorr.corr3(config) data = np.genfromtxt(config['nnn_file_name'], names=True, skip_header=1) np.testing.assert_array_equal(data['ntri'], true_ntri.flatten()) assert 'zeta' not in data.dtype.names # Check a few basic operations with a NNNCorrelation object. do_pickle(ddd) ddd2 = ddd.copy() ddd2 += ddd np.testing.assert_allclose(ddd2.ntri, 2*ddd.ntri) np.testing.assert_allclose(ddd2.weight, 2*ddd.weight) np.testing.assert_allclose(ddd2.meand1, 2*ddd.meand1) np.testing.assert_allclose(ddd2.meand2, 2*ddd.meand2) np.testing.assert_allclose(ddd2.meand3, 2*ddd.meand3) np.testing.assert_allclose(ddd2.meanlogd1, 2*ddd.meanlogd1) np.testing.assert_allclose(ddd2.meanlogd2, 2*ddd.meanlogd2) np.testing.assert_allclose(ddd2.meanlogd3, 2*ddd.meanlogd3) np.testing.assert_allclose(ddd2.meanu, 2*ddd.meanu) np.testing.assert_allclose(ddd2.meanv, 2*ddd.meanv) ddd2.clear() ddd2 += ddd np.testing.assert_allclose(ddd2.ntri, ddd.ntri) np.testing.assert_allclose(ddd2.weight, ddd.weight) np.testing.assert_allclose(ddd2.meand1, ddd.meand1) np.testing.assert_allclose(ddd2.meand2, ddd.meand2) np.testing.assert_allclose(ddd2.meand3, ddd.meand3) np.testing.assert_allclose(ddd2.meanlogd1, ddd.meanlogd1) np.testing.assert_allclose(ddd2.meanlogd2, ddd.meanlogd2) np.testing.assert_allclose(ddd2.meanlogd3, ddd.meanlogd3) np.testing.assert_allclose(ddd2.meanu, ddd.meanu) np.testing.assert_allclose(ddd2.meanv, ddd.meanv) ascii_name = 'output/nnn_ascii.txt' ddd.write(ascii_name, precision=16) ddd3 = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins) ddd3.read(ascii_name) np.testing.assert_allclose(ddd3.ntri, ddd.ntri) np.testing.assert_allclose(ddd3.weight, ddd.weight) np.testing.assert_allclose(ddd3.meand1, ddd.meand1) np.testing.assert_allclose(ddd3.meand2, ddd.meand2) np.testing.assert_allclose(ddd3.meand3, ddd.meand3) np.testing.assert_allclose(ddd3.meanlogd1, ddd.meanlogd1) np.testing.assert_allclose(ddd3.meanlogd2, ddd.meanlogd2) np.testing.assert_allclose(ddd3.meanlogd3, ddd.meanlogd3) np.testing.assert_allclose(ddd3.meanu, ddd.meanu) np.testing.assert_allclose(ddd3.meanv, ddd.meanv) with assert_raises(TypeError): ddd2 += config ddd4 = treecorr.NNNCorrelation(min_sep=min_sep/2, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins) with assert_raises(ValueError): ddd2 += ddd4 ddd5 = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep*2, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins) with assert_raises(ValueError): ddd2 += ddd5 ddd6 = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins*2, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins) with assert_raises(ValueError): ddd2 += ddd6 ddd7 = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u-0.1, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins) with assert_raises(ValueError): ddd2 += ddd7 ddd8 = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u+0.1, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins) with assert_raises(ValueError): ddd2 += ddd8 ddd9 = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins*2, min_v=min_v, max_v=max_v, nvbins=nvbins) with assert_raises(ValueError): ddd2 += ddd9 ddd10 = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v-0.1, max_v=max_v, nvbins=nvbins) with assert_raises(ValueError): ddd2 += ddd10 ddd11 = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v+0.1, nvbins=nvbins) with assert_raises(ValueError): ddd2 += ddd11 ddd12 = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins*2) with assert_raises(ValueError): ddd2 += ddd12 # Check that adding results with different coords or metric emits a warning. cat2 = treecorr.Catalog(x=x, y=y, z=x) with CaptureLog() as cl: ddd13 = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, logger=cl.logger) ddd13.process_auto(cat2) ddd13 += ddd2 print(cl.output) assert "Detected a change in catalog coordinate systems" in cl.output with CaptureLog() as cl: ddd14 = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, logger=cl.logger) ddd14.process_auto(cat2, metric='Arc') ddd14 += ddd2 assert "Detected a change in metric" in cl.output fits_name = 'output/nnn_fits.fits' ddd.write(fits_name) ddd15 = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins) ddd15.read(fits_name) np.testing.assert_allclose(ddd15.ntri, ddd.ntri) np.testing.assert_allclose(ddd15.weight, ddd.weight) np.testing.assert_allclose(ddd15.meand1, ddd.meand1) np.testing.assert_allclose(ddd15.meand2, ddd.meand2) np.testing.assert_allclose(ddd15.meand3, ddd.meand3) np.testing.assert_allclose(ddd15.meanlogd1, ddd.meanlogd1) np.testing.assert_allclose(ddd15.meanlogd2, ddd.meanlogd2) np.testing.assert_allclose(ddd15.meanlogd3, ddd.meanlogd3) np.testing.assert_allclose(ddd15.meanu, ddd.meanu) np.testing.assert_allclose(ddd15.meanv, ddd.meanv) @timer def test_direct_count_cross(): # If the catalogs are small enough, we can do a direct count of the number of triangles # to see if comes out right. This should exactly match the treecorr code if brute=True ngal = 50 s = 10. rng = np.random.RandomState(8675309) x1 = rng.normal(0,s, (ngal,) ) y1 = rng.normal(0,s, (ngal,) ) cat1 = treecorr.Catalog(x=x1, y=y1) x2 = rng.normal(0,s, (ngal,) ) y2 = rng.normal(0,s, (ngal,) ) cat2 = treecorr.Catalog(x=x2, y=y2) x3 = rng.normal(0,s, (ngal,) ) y3 = rng.normal(0,s, (ngal,) ) cat3 = treecorr.Catalog(x=x3, y=y3) min_sep = 1. max_sep = 50. nbins = 50 min_u = 0.13 max_u = 0.89 nubins = 10 min_v = 0.13 max_v = 0.59 nvbins = 10 ddd = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, brute=True, verbose=1) ddd.process(cat1, cat2, cat3) #print('ddd.ntri = ',ddd.ntri) log_min_sep = np.log(min_sep) log_max_sep = np.log(max_sep) true_ntri_123 = np.zeros( (nbins, nubins, 2*nvbins) ) true_ntri_132 = np.zeros( (nbins, nubins, 2*nvbins) ) true_ntri_213 = np.zeros( (nbins, nubins, 2*nvbins) ) true_ntri_231 = np.zeros( (nbins, nubins, 2*nvbins) ) true_ntri_312 = np.zeros( (nbins, nubins, 2*nvbins) ) true_ntri_321 = np.zeros( (nbins, nubins, 2*nvbins) ) bin_size = (log_max_sep - log_min_sep) / nbins ubin_size = (max_u-min_u) / nubins vbin_size = (max_v-min_v) / nvbins for i in range(ngal): for j in range(ngal): for k in range(ngal): dij = np.sqrt((x1[i]-x2[j])**2 + (y1[i]-y2[j])**2) dik = np.sqrt((x1[i]-x3[k])**2 + (y1[i]-y3[k])**2) djk = np.sqrt((x2[j]-x3[k])**2 + (y2[j]-y3[k])**2) if dij == 0.: continue if dik == 0.: continue if djk == 0.: continue if dij < dik: if dik < djk: d3 = dij; d2 = dik; d1 = djk ccw = is_ccw(x1[i],y1[i],x2[j],y2[j],x3[k],y3[k]) true_ntri = true_ntri_123 elif dij < djk: d3 = dij; d2 = djk; d1 = dik ccw = is_ccw(x2[j],y2[j],x1[i],y1[i],x3[k],y3[k]) true_ntri = true_ntri_213 else: d3 = djk; d2 = dij; d1 = dik ccw = is_ccw(x2[j],y2[j],x3[k],y3[k],x1[i],y1[i]) true_ntri = true_ntri_231 else: if dij < djk: d3 = dik; d2 = dij; d1 = djk ccw = is_ccw(x1[i],y1[i],x3[k],y3[k],x2[j],y2[j]) true_ntri = true_ntri_132 elif dik < djk: d3 = dik; d2 = djk; d1 = dij ccw = is_ccw(x3[k],y3[k],x1[i],y1[i],x2[j],y2[j]) true_ntri = true_ntri_312 else: d3 = djk; d2 = dik; d1 = dij ccw = is_ccw(x3[k],y3[k],x2[j],y2[j],x1[i],y1[i]) true_ntri = true_ntri_321 r = d2 u = d3/d2 v = (d1-d2)/d3 if r < min_sep or r >= max_sep: continue if u < min_u or u >= max_u: continue if v < min_v or v >= max_v: continue if not ccw: v = -v kr = int(np.floor( (np.log(r)-log_min_sep) / bin_size )) ku = int(np.floor( (u-min_u) / ubin_size )) if v > 0: kv = int(np.floor( (v-min_v) / vbin_size )) + nvbins else: kv = int(np.floor( (v-(-max_v)) / vbin_size )) assert 0 <= kr < nbins assert 0 <= ku < nubins assert 0 <= kv < 2*nvbins true_ntri[kr,ku,kv] += 1 # With the regular NNNCorrelation class, we end up with the sum of all permutations. true_ntri_sum = true_ntri_123 + true_ntri_132 + true_ntri_213 + true_ntri_231 +\ true_ntri_312 + true_ntri_321 #print('true_ntri = ',true_ntri_sum) #print('diff = ',ddd.ntri - true_ntri_sum) np.testing.assert_array_equal(ddd.ntri, true_ntri_sum) # Now repeat with the full CrossCorrelation class, which distinguishes the permutations. dddc = treecorr.NNNCrossCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, brute=True, verbose=1) dddc.process(cat1, cat2, cat3) #print('true_ntri_123 = ',true_ntri_123) #print('diff = ',dddc.n1n2n3.ntri - true_ntri_123) np.testing.assert_array_equal(dddc.n1n2n3.ntri, true_ntri_123) np.testing.assert_array_equal(dddc.n1n3n2.ntri, true_ntri_132) np.testing.assert_array_equal(dddc.n2n1n3.ntri, true_ntri_213) np.testing.assert_array_equal(dddc.n2n3n1.ntri, true_ntri_231) np.testing.assert_array_equal(dddc.n3n1n2.ntri, true_ntri_312) np.testing.assert_array_equal(dddc.n3n2n1.ntri, true_ntri_321) # Repeat with binslop = 0 ddd = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, bin_slop=0, verbose=1) ddd.process(cat1, cat2, cat3) #print('binslop > 0: ddd.ntri = ',ddd.ntri) #print('diff = ',ddd.ntri - true_ntri_sum) np.testing.assert_array_equal(ddd.ntri, true_ntri_sum) # And again with no top-level recursion ddd = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, bin_slop=0, verbose=1, max_top=0) ddd.process(cat1, cat2, cat3) #print('max_top = 0: ddd.ntri = ',ddd.ntri) #print('true_ntri = ',true_ntri_sum) #print('diff = ',ddd.ntri - true_ntri_sum) np.testing.assert_array_equal(ddd.ntri, true_ntri_sum) # Error to have cat3, but not cat2 with assert_raises(ValueError): ddd.process(cat1, cat3=cat3) # Check a few basic operations with a NNCrossCorrelation object. do_pickle(dddc) dddc2 = dddc.copy() dddc2 += dddc for perm in ['n1n2n3', 'n1n3n2', 'n2n1n3', 'n2n3n1', 'n3n1n2', 'n3n2n1']: d2 = getattr(dddc2, perm) d1 = getattr(dddc, perm) np.testing.assert_allclose(d2.ntri, 2*d1.ntri) np.testing.assert_allclose(d2.ntri, 2*d1.ntri) np.testing.assert_allclose(d2.ntri, 2*d1.ntri) np.testing.assert_allclose(d2.ntri, 2*d1.ntri) np.testing.assert_allclose(d2.ntri, 2*d1.ntri) np.testing.assert_allclose(d2.ntri, 2*d1.ntri) np.testing.assert_allclose(d2.meand1, 2*d1.meand1) np.testing.assert_allclose(d2.meand2, 2*d1.meand2) np.testing.assert_allclose(d2.meand3, 2*d1.meand3) np.testing.assert_allclose(d2.meanlogd1, 2*d1.meanlogd1) np.testing.assert_allclose(d2.meanlogd2, 2*d1.meanlogd2) np.testing.assert_allclose(d2.meanlogd3, 2*d1.meanlogd3) np.testing.assert_allclose(d2.meanu, 2*d1.meanu) np.testing.assert_allclose(d2.meanv, 2*d1.meanv) dddc2.clear() dddc2 += dddc for perm in ['n1n2n3', 'n1n3n2', 'n2n1n3', 'n2n3n1', 'n3n1n2', 'n3n2n1']: d2 = getattr(dddc2, perm) d1 = getattr(dddc, perm) np.testing.assert_allclose(d2.ntri, d1.ntri) np.testing.assert_allclose(d2.ntri, d1.ntri) np.testing.assert_allclose(d2.ntri, d1.ntri) np.testing.assert_allclose(d2.ntri, d1.ntri) np.testing.assert_allclose(d2.ntri, d1.ntri) np.testing.assert_allclose(d2.ntri, d1.ntri) np.testing.assert_allclose(d2.meand1, d1.meand1) np.testing.assert_allclose(d2.meand2, d1.meand2) np.testing.assert_allclose(d2.meand3, d1.meand3) np.testing.assert_allclose(d2.meanlogd1, d1.meanlogd1) np.testing.assert_allclose(d2.meanlogd2, d1.meanlogd2) np.testing.assert_allclose(d2.meanlogd3, d1.meanlogd3) np.testing.assert_allclose(d2.meanu, d1.meanu) np.testing.assert_allclose(d2.meanv, d1.meanv) with assert_raises(TypeError): dddc2 += {} # not an NNNCrossCorrelation with assert_raises(TypeError): dddc2 += ddd # not an NNNCrossCorrelation dddc4 = treecorr.NNNCrossCorrelation(min_sep=min_sep/2, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins) with assert_raises(ValueError): dddc2 += dddc4 # binning doesn't match # Test I/O ascii_name = 'output/nnnc_ascii.txt' dddc.write(ascii_name, precision=16) dddc3 = treecorr.NNNCrossCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins) dddc3.read(ascii_name) for perm in ['n1n2n3', 'n1n3n2', 'n2n1n3', 'n2n3n1', 'n3n1n2', 'n3n2n1']: d2 = getattr(dddc3, perm) d1 = getattr(dddc, perm) np.testing.assert_allclose(d2.ntri, d1.ntri) np.testing.assert_allclose(d2.ntri, d1.ntri) np.testing.assert_allclose(d2.ntri, d1.ntri) np.testing.assert_allclose(d2.ntri, d1.ntri) np.testing.assert_allclose(d2.ntri, d1.ntri) np.testing.assert_allclose(d2.ntri, d1.ntri) np.testing.assert_allclose(d2.meand1, d1.meand1) np.testing.assert_allclose(d2.meand2, d1.meand2) np.testing.assert_allclose(d2.meand3, d1.meand3) np.testing.assert_allclose(d2.meanlogd1, d1.meanlogd1) np.testing.assert_allclose(d2.meanlogd2, d1.meanlogd2) np.testing.assert_allclose(d2.meanlogd3, d1.meanlogd3) np.testing.assert_allclose(d2.meanu, d1.meanu) np.testing.assert_allclose(d2.meanv, d1.meanv) fits_name = 'output/nnnc_fits.fits' dddc.write(fits_name) dddc4 = treecorr.NNNCrossCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins) dddc4.read(fits_name) for perm in ['n1n2n3', 'n1n3n2', 'n2n1n3', 'n2n3n1', 'n3n1n2', 'n3n2n1']: d2 = getattr(dddc4, perm) d1 = getattr(dddc, perm) np.testing.assert_allclose(d2.ntri, d1.ntri) np.testing.assert_allclose(d2.ntri, d1.ntri) np.testing.assert_allclose(d2.ntri, d1.ntri) np.testing.assert_allclose(d2.ntri, d1.ntri) np.testing.assert_allclose(d2.ntri, d1.ntri) np.testing.assert_allclose(d2.ntri, d1.ntri) np.testing.assert_allclose(d2.meand1, d1.meand1) np.testing.assert_allclose(d2.meand2, d1.meand2) np.testing.assert_allclose(d2.meand3, d1.meand3) np.testing.assert_allclose(d2.meanlogd1, d1.meanlogd1) np.testing.assert_allclose(d2.meanlogd2, d1.meanlogd2) np.testing.assert_allclose(d2.meanlogd3, d1.meanlogd3) np.testing.assert_allclose(d2.meanu, d1.meanu) np.testing.assert_allclose(d2.meanv, d1.meanv) try: import h5py except ImportError: print('Skipping hdf5 output file, since h5py not installed.') return hdf5_name = 'output/nnnc_hdf5.hdf5' dddc.write(hdf5_name) dddc5 = treecorr.NNNCrossCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins) dddc5.read(hdf5_name) for perm in ['n1n2n3', 'n1n3n2', 'n2n1n3', 'n2n3n1', 'n3n1n2', 'n3n2n1']: d2 = getattr(dddc5, perm) d1 = getattr(dddc, perm) np.testing.assert_allclose(d2.ntri, d1.ntri) np.testing.assert_allclose(d2.ntri, d1.ntri) np.testing.assert_allclose(d2.ntri, d1.ntri) np.testing.assert_allclose(d2.ntri, d1.ntri) np.testing.assert_allclose(d2.ntri, d1.ntri) np.testing.assert_allclose(d2.ntri, d1.ntri) np.testing.assert_allclose(d2.meand1, d1.meand1) np.testing.assert_allclose(d2.meand2, d1.meand2) np.testing.assert_allclose(d2.meand3, d1.meand3) np.testing.assert_allclose(d2.meanlogd1, d1.meanlogd1) np.testing.assert_allclose(d2.meanlogd2, d1.meanlogd2) np.testing.assert_allclose(d2.meanlogd3, d1.meanlogd3) np.testing.assert_allclose(d2.meanu, d1.meanu) np.testing.assert_allclose(d2.meanv, d1.meanv) @timer def test_direct_count_cross12(): # Check the 1-2 cross correlation ngal = 50 s = 10. rng = np.random.RandomState(8675309) x1 = rng.normal(0,s, (ngal,) ) y1 = rng.normal(0,s, (ngal,) ) cat1 = treecorr.Catalog(x=x1, y=y1) x2 = rng.normal(0,s, (ngal,) ) y2 = rng.normal(0,s, (ngal,) ) cat2 = treecorr.Catalog(x=x2, y=y2) min_sep = 1. max_sep = 50. nbins = 50 min_u = 0.13 max_u = 0.89 nubins = 10 min_v = 0.13 max_v = 0.59 nvbins = 10 ddd = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, brute=True, verbose=1) ddd.process(cat1, cat2) log_min_sep = np.log(min_sep) log_max_sep = np.log(max_sep) true_ntri_122 = np.zeros( (nbins, nubins, 2*nvbins) ) true_ntri_212 = np.zeros( (nbins, nubins, 2*nvbins) ) true_ntri_221 = np.zeros( (nbins, nubins, 2*nvbins) ) bin_size = (log_max_sep - log_min_sep) / nbins ubin_size = (max_u-min_u) / nubins vbin_size = (max_v-min_v) / nvbins for i in range(ngal): for j in range(ngal): for k in range(j+1,ngal): dij = np.sqrt((x1[i]-x2[j])**2 + (y1[i]-y2[j])**2) dik = np.sqrt((x1[i]-x2[k])**2 + (y1[i]-y2[k])**2) djk = np.sqrt((x2[j]-x2[k])**2 + (y2[j]-y2[k])**2) if dij == 0.: continue if dik == 0.: continue if djk == 0.: continue if dij < dik: if dik < djk: d3 = dij; d2 = dik; d1 = djk ccw = is_ccw(x1[i],y1[i],x2[j],y2[j],x2[k],y2[k]) true_ntri = true_ntri_122 elif dij < djk: d3 = dij; d2 = djk; d1 = dik ccw = is_ccw(x2[j],y2[j],x1[i],y1[i],x2[k],y2[k]) true_ntri = true_ntri_212 else: d3 = djk; d2 = dij; d1 = dik ccw = is_ccw(x2[j],y2[j],x2[k],y2[k],x1[i],y1[i]) true_ntri = true_ntri_221 else: if dij < djk: d3 = dik; d2 = dij; d1 = djk ccw = is_ccw(x1[i],y1[i],x2[k],y2[k],x2[j],y2[j]) true_ntri = true_ntri_122 elif dik < djk: d3 = dik; d2 = djk; d1 = dij ccw = is_ccw(x2[k],y2[k],x1[i],y1[i],x2[j],y2[j]) true_ntri = true_ntri_212 else: d3 = djk; d2 = dik; d1 = dij ccw = is_ccw(x2[k],y2[k],x2[j],y2[j],x1[i],y1[i]) true_ntri = true_ntri_221 r = d2 u = d3/d2 v = (d1-d2)/d3 if r < min_sep or r >= max_sep: continue if u < min_u or u >= max_u: continue if v < min_v or v >= max_v: continue if not ccw: v = -v kr = int(np.floor( (np.log(r)-log_min_sep) / bin_size )) ku = int(np.floor( (u-min_u) / ubin_size )) if v > 0: kv = int(np.floor( (v-min_v) / vbin_size )) + nvbins else: kv = int(np.floor( (v-(-max_v)) / vbin_size )) assert 0 <= kr < nbins assert 0 <= ku < nubins assert 0 <= kv < 2*nvbins true_ntri[kr,ku,kv] += 1 # With the regular NNNCorrelation class, we end up with the sum of all permutations. true_ntri_sum = true_ntri_122 + true_ntri_212 + true_ntri_221 #print('ddd.ntri = ',ddd.ntri) #print('true_ntri = ',true_ntri_sum) #print('diff = ',ddd.ntri - true_ntri_sum) np.testing.assert_array_equal(ddd.ntri, true_ntri_sum) # Now repeat with the full CrossCorrelation class, which distinguishes the permutations. dddc = treecorr.NNNCrossCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, brute=True, verbose=1) dddc.process(cat1, cat2) #print('true_ntri_122 = ',true_ntri_122) #print('diff = ',dddc.n1n2n3.ntri - true_ntri_122) np.testing.assert_array_equal(dddc.n1n2n3.ntri, true_ntri_122) np.testing.assert_array_equal(dddc.n1n3n2.ntri, true_ntri_122) np.testing.assert_array_equal(dddc.n2n1n3.ntri, true_ntri_212) np.testing.assert_array_equal(dddc.n2n3n1.ntri, true_ntri_221) np.testing.assert_array_equal(dddc.n3n1n2.ntri, true_ntri_212) np.testing.assert_array_equal(dddc.n3n2n1.ntri, true_ntri_221) # Repeat with binslop = 0 ddd = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, bin_slop=0, verbose=1) ddd.process(cat1, cat2) #print('binslop > 0: ddd.ntri = ',ddd.ntri) #print('diff = ',ddd.ntri - true_ntri_sum) np.testing.assert_array_equal(ddd.ntri, true_ntri_sum) # And again with no top-level recursion ddd = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, bin_slop=0, verbose=1, max_top=0) ddd.process(cat1, cat2) #print('max_top = 0: ddd.ntri = ',ddd.ntri) #print('true_ntri = ',true_ntri_sum) #print('diff = ',ddd.ntri - true_ntri_sum) np.testing.assert_array_equal(ddd.ntri, true_ntri_sum) # Split into patches to test the list-based version of the code. cat1 = treecorr.Catalog(x=x1, y=y1, npatch=10) cat2 = treecorr.Catalog(x=x2, y=y2, npatch=10) ddd.process(cat1, cat2) np.testing.assert_array_equal(ddd.ntri, true_ntri_sum) dddc.process(cat1, cat2) np.testing.assert_array_equal(dddc.n1n2n3.ntri, true_ntri_122) np.testing.assert_array_equal(dddc.n1n3n2.ntri, true_ntri_122) np.testing.assert_array_equal(dddc.n2n1n3.ntri, true_ntri_212) np.testing.assert_array_equal(dddc.n2n3n1.ntri, true_ntri_221) np.testing.assert_array_equal(dddc.n3n1n2.ntri, true_ntri_212) np.testing.assert_array_equal(dddc.n3n2n1.ntri, true_ntri_221) @timer def test_direct_spherical(): # Repeat in spherical coords ngal = 50 s = 10. rng = np.random.RandomState(8675309) x = rng.normal(0,s, (ngal,) ) y = rng.normal(0,s, (ngal,) ) + 200 # Put everything at large y, so small angle on sky z = rng.normal(0,s, (ngal,) ) w = rng.random_sample(ngal) ra, dec = coord.CelestialCoord.xyz_to_radec(x,y,z) cat = treecorr.Catalog(ra=ra, dec=dec, ra_units='rad', dec_units='rad', w=w) min_sep = 1. bin_size = 0.2 nrbins = 10 nubins = 5 nvbins = 5 ddd = treecorr.NNNCorrelation(min_sep=min_sep, bin_size=bin_size, nbins=nrbins, sep_units='deg', brute=True) ddd.process(cat, num_threads=2) r = np.sqrt(x**2 + y**2 + z**2) x /= r; y /= r; z /= r true_ntri = np.zeros((nrbins, nubins, 2*nvbins), dtype=int) true_weight = np.zeros((nrbins, nubins, 2*nvbins), dtype=float) rad_min_sep = min_sep * coord.degrees / coord.radians for i in range(ngal): for j in range(i+1,ngal): for k in range(j+1,ngal): d12 = np.sqrt((x[i]-x[j])**2 + (y[i]-y[j])**2 + (z[i]-z[j])**2) d23 = np.sqrt((x[j]-x[k])**2 + (y[j]-y[k])**2 + (z[j]-z[k])**2) d31 = np.sqrt((x[k]-x[i])**2 + (y[k]-y[i])**2 + (z[k]-z[i])**2) d3, d2, d1 = sorted([d12, d23, d31]) rindex = np.floor(np.log(d2/rad_min_sep) / bin_size).astype(int) if rindex < 0 or rindex >= nrbins: continue if [d1, d2, d3] == [d23, d31, d12]: ii,jj,kk = i,j,k elif [d1, d2, d3] == [d23, d12, d31]: ii,jj,kk = i,k,j elif [d1, d2, d3] == [d31, d12, d23]: ii,jj,kk = j,k,i elif [d1, d2, d3] == [d31, d23, d12]: ii,jj,kk = j,i,k elif [d1, d2, d3] == [d12, d23, d31]: ii,jj,kk = k,i,j elif [d1, d2, d3] == [d12, d31, d23]: ii,jj,kk = k,j,i else: assert False # Now use ii, jj, kk rather than i,j,k, to get the indices # that correspond to the points in the right order. u = d3/d2 v = (d1-d2)/d3 if ( ((x[jj]-x[ii])*(y[kk]-y[ii]) - (x[kk]-x[ii])*(y[jj]-y[ii])) * z[ii] + ((y[jj]-y[ii])*(z[kk]-z[ii]) - (y[kk]-y[ii])*(z[jj]-z[ii])) * x[ii] + ((z[jj]-z[ii])*(x[kk]-x[ii]) - (z[kk]-z[ii])*(x[jj]-x[ii])) * y[ii] ) > 0: v = -v uindex = np.floor(u / bin_size).astype(int) assert 0 <= uindex < nubins vindex = np.floor((v+1) / bin_size).astype(int) assert 0 <= vindex < 2*nvbins www = w[i] * w[j] * w[k] true_ntri[rindex,uindex,vindex] += 1 true_weight[rindex,uindex,vindex] += www np.testing.assert_array_equal(ddd.ntri, true_ntri) np.testing.assert_allclose(ddd.weight, true_weight, rtol=1.e-5, atol=1.e-8) # Check that running via the corr3 script works correctly. config = treecorr.config.read_config('configs/nnn_direct_spherical.yaml') cat.write(config['file_name']) treecorr.corr3(config) data = fitsio.read(config['nnn_file_name']) np.testing.assert_allclose(data['r_nom'], ddd.rnom.flatten()) np.testing.assert_allclose(data['u_nom'], ddd.u.flatten()) np.testing.assert_allclose(data['v_nom'], ddd.v.flatten()) np.testing.assert_allclose(data['ntri'], ddd.ntri.flatten()) np.testing.assert_allclose(data['DDD'], ddd.weight.flatten()) # Repeat with binslop = 0 # And don't do any top-level recursion so we actually test not going to the leaves. ddd = treecorr.NNNCorrelation(min_sep=min_sep, bin_size=bin_size, nbins=nrbins, sep_units='deg', bin_slop=0, max_top=0) ddd.process(cat) np.testing.assert_array_equal(ddd.ntri, true_ntri) np.testing.assert_allclose(ddd.weight, true_weight, rtol=1.e-5, atol=1.e-8) @timer def test_direct_arc(): # Repeat the spherical test with metric='Arc' ngal = 5 s = 10. rng = np.random.RandomState(8675309) x = rng.normal(0,s, (ngal,) ) y = rng.normal(0,s, (ngal,) ) + 200 # Large angles this time. z = rng.normal(0,s, (ngal,) ) w = rng.random_sample(ngal) ra, dec = coord.CelestialCoord.xyz_to_radec(x,y,z) cat = treecorr.Catalog(ra=ra, dec=dec, ra_units='rad', dec_units='rad', w=w) min_sep = 1. max_sep = 180. nrbins = 50 nubins = 5 nvbins = 5 bin_size = np.log((max_sep / min_sep)) / nrbins ubin_size = 0.2 vbin_size = 0.2 ddd = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nrbins, nubins=nubins, ubin_size=ubin_size, nvbins=nvbins, vbin_size=vbin_size, sep_units='deg', brute=True) ddd.process(cat, metric='Arc') r = np.sqrt(x**2 + y**2 + z**2) x /= r; y /= r; z /= r true_ntri = np.zeros((nrbins, nubins, 2*nvbins), dtype=int) true_weight = np.zeros((nrbins, nubins, 2*nvbins), dtype=float) c = [coord.CelestialCoord(r*coord.radians, d*coord.radians) for (r,d) in zip(ra, dec)] for i in range(ngal): for j in range(i+1,ngal): for k in range(j+1,ngal): d12 = c[i].distanceTo(c[j]) / coord.degrees d23 = c[j].distanceTo(c[k]) / coord.degrees d31 = c[k].distanceTo(c[i]) / coord.degrees d3, d2, d1 = sorted([d12, d23, d31]) rindex = np.floor(np.log(d2/min_sep) / bin_size).astype(int) if rindex < 0 or rindex >= nrbins: continue if [d1, d2, d3] == [d23, d31, d12]: ii,jj,kk = i,j,k elif [d1, d2, d3] == [d23, d12, d31]: ii,jj,kk = i,k,j elif [d1, d2, d3] == [d31, d12, d23]: ii,jj,kk = j,k,i elif [d1, d2, d3] == [d31, d23, d12]: ii,jj,kk = j,i,k elif [d1, d2, d3] == [d12, d23, d31]: ii,jj,kk = k,i,j elif [d1, d2, d3] == [d12, d31, d23]: ii,jj,kk = k,j,i else: assert False # Now use ii, jj, kk rather than i,j,k, to get the indices # that correspond to the points in the right order. u = d3/d2 v = (d1-d2)/d3 if ( ((x[jj]-x[ii])*(y[kk]-y[ii]) - (x[kk]-x[ii])*(y[jj]-y[ii])) * z[ii] + ((y[jj]-y[ii])*(z[kk]-z[ii]) - (y[kk]-y[ii])*(z[jj]-z[ii])) * x[ii] + ((z[jj]-z[ii])*(x[kk]-x[ii]) - (z[kk]-z[ii])*(x[jj]-x[ii])) * y[ii] ) > 0: v = -v uindex = np.floor(u / ubin_size).astype(int) assert 0 <= uindex < nubins vindex = np.floor((v+1) / vbin_size).astype(int) assert 0 <= vindex < 2*nvbins www = w[i] * w[j] * w[k] true_ntri[rindex,uindex,vindex] += 1 true_weight[rindex,uindex,vindex] += www np.testing.assert_array_equal(ddd.ntri, true_ntri) np.testing.assert_allclose(ddd.weight, true_weight, rtol=1.e-5, atol=1.e-8) # Check that running via the corr3 script works correctly. config = treecorr.config.read_config('configs/nnn_direct_arc.yaml') cat.write(config['file_name']) treecorr.corr3(config) data = fitsio.read(config['nnn_file_name']) np.testing.assert_allclose(data['r_nom'], ddd.rnom.flatten()) np.testing.assert_allclose(data['u_nom'], ddd.u.flatten()) np.testing.assert_allclose(data['v_nom'], ddd.v.flatten()) np.testing.assert_allclose(data['ntri'], ddd.ntri.flatten()) np.testing.assert_allclose(data['DDD'], ddd.weight.flatten()) # Repeat with binslop = 0 # And don't do any top-level recursion so we actually test not going to the leaves. ddd = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nrbins, nubins=nubins, ubin_size=ubin_size, nvbins=nvbins, vbin_size=vbin_size, sep_units='deg', bin_slop=0, max_top=0) ddd.process(cat) np.testing.assert_array_equal(ddd.ntri, true_ntri) np.testing.assert_allclose(ddd.weight, true_weight, rtol=1.e-5, atol=1.e-8) @timer def test_direct_partial(): # Test the two ways to only use parts of a catalog: ngal = 100 s = 10. rng = np.random.RandomState(8675309) x1 = rng.normal(0,s, (ngal,) ) y1 = rng.normal(0,s, (ngal,) ) cat1a = treecorr.Catalog(x=x1, y=y1, first_row=28, last_row=84) x2 = rng.normal(0,s, (ngal,) ) y2 = rng.normal(0,s, (ngal,) ) cat2a = treecorr.Catalog(x=x2, y=y2, first_row=48, last_row=99) x3 = rng.normal(0,s, (ngal,) ) y3 = rng.normal(0,s, (ngal,) ) cat3a = treecorr.Catalog(x=x3, y=y3, first_row=22, last_row=67) min_sep = 1. max_sep = 50. nbins = 50 min_u = 0.13 max_u = 0.89 nubins = 10 min_v = 0.13 max_v = 0.59 nvbins = 10 ddda = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, brute=True) ddda.process(cat1a, cat2a, cat3a) #print('ddda.ntri = ',ddda.ntri) log_min_sep = np.log(min_sep) log_max_sep = np.log(max_sep) true_ntri_123 = np.zeros( (nbins, nubins, 2*nvbins) ) true_ntri_132 = np.zeros( (nbins, nubins, 2*nvbins) ) true_ntri_213 = np.zeros( (nbins, nubins, 2*nvbins) ) true_ntri_231 = np.zeros( (nbins, nubins, 2*nvbins) ) true_ntri_312 = np.zeros( (nbins, nubins, 2*nvbins) ) true_ntri_321 = np.zeros( (nbins, nubins, 2*nvbins) ) bin_size = (log_max_sep - log_min_sep) / nbins ubin_size = (max_u-min_u) / nubins vbin_size = (max_v-min_v) / nvbins for i in range(27,84): for j in range(47,99): for k in range(21,67): dij = np.sqrt((x1[i]-x2[j])**2 + (y1[i]-y2[j])**2) dik = np.sqrt((x1[i]-x3[k])**2 + (y1[i]-y3[k])**2) djk = np.sqrt((x2[j]-x3[k])**2 + (y2[j]-y3[k])**2) if dij == 0.: continue if dik == 0.: continue if djk == 0.: continue if dij < dik: if dik < djk: d3 = dij; d2 = dik; d1 = djk ccw = is_ccw(x1[i],y1[i],x2[j],y2[j],x3[k],y3[k]) true_ntri = true_ntri_123 elif dij < djk: d3 = dij; d2 = djk; d1 = dik ccw = is_ccw(x2[j],y2[j],x1[i],y1[i],x3[k],y3[k]) true_ntri = true_ntri_213 else: d3 = djk; d2 = dij; d1 = dik ccw = is_ccw(x2[j],y2[j],x3[k],y3[k],x1[i],y1[i]) true_ntri = true_ntri_231 else: if dij < djk: d3 = dik; d2 = dij; d1 = djk ccw = is_ccw(x1[i],y1[i],x3[k],y3[k],x2[j],y2[j]) true_ntri = true_ntri_132 elif dik < djk: d3 = dik; d2 = djk; d1 = dij ccw = is_ccw(x3[k],y3[k],x1[i],y1[i],x2[j],y2[j]) true_ntri = true_ntri_312 else: d3 = djk; d2 = dik; d1 = dij ccw = is_ccw(x3[k],y3[k],x2[j],y2[j],x1[i],y1[i]) true_ntri = true_ntri_321 assert d1 >= d2 >= d3 r = d2 u = d3/d2 v = (d1-d2)/d3 if r < min_sep or r >= max_sep: continue if u < min_u or u >= max_u: continue if v < min_v or v >= max_v: continue if not ccw: v = -v kr = int(np.floor( (np.log(r)-log_min_sep) / bin_size )) ku = int(np.floor( (u-min_u) / ubin_size )) if v > 0: kv = int(np.floor( (v-min_v) / vbin_size )) + nvbins else: kv = int(np.floor( (v-(-max_v)) / vbin_size )) assert 0 <= kr < nbins assert 0 <= ku < nubins assert 0 <= kv < 2*nvbins true_ntri[kr,ku,kv] += 1 true_ntri_sum = true_ntri_123 + true_ntri_132 + true_ntri_213 + true_ntri_231 +\ true_ntri_312 + true_ntri_321 print('true_ntri = ',true_ntri_sum) print('diff = ',ddda.ntri - true_ntri_sum) np.testing.assert_array_equal(ddda.ntri, true_ntri_sum) # Now with real CrossCorrelation ddda = treecorr.NNNCrossCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, brute=True) ddda.process(cat1a, cat2a, cat3a) #print('132 = ',ddda.n1n3n2.ntri) #print('true 132 = ',true_ntri_132) #print('213 = ',ddda.n2n1n3.ntri) #print('true 213 = ',true_ntri_213) #print('231 = ',ddda.n2n3n1.ntri) #print('true 231 = ',true_ntri_231) #print('311 = ',ddda.n3n1n2.ntri) #print('true 312 = ',true_ntri_312) #print('321 = ',ddda.n3n2n1.ntri) #print('true 321 = ',true_ntri_321) np.testing.assert_array_equal(ddda.n1n2n3.ntri, true_ntri_123) np.testing.assert_array_equal(ddda.n1n3n2.ntri, true_ntri_132) np.testing.assert_array_equal(ddda.n2n1n3.ntri, true_ntri_213) np.testing.assert_array_equal(ddda.n2n3n1.ntri, true_ntri_231) np.testing.assert_array_equal(ddda.n3n1n2.ntri, true_ntri_312) np.testing.assert_array_equal(ddda.n3n2n1.ntri, true_ntri_321) # Now check that we get the same thing with all the points, but with w=0 for the ones # we don't want. w1 = np.zeros(ngal) w1[27:84] = 1. w2 = np.zeros(ngal) w2[47:99] = 1. w3 = np.zeros(ngal) w3[21:67] = 1. cat1b = treecorr.Catalog(x=x1, y=y1, w=w1) cat2b = treecorr.Catalog(x=x2, y=y2, w=w2) cat3b = treecorr.Catalog(x=x3, y=y3, w=w3) dddb = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, brute=True) dddb.process(cat1b, cat2b, cat3b) #print('dddb.ntri = ',dddb.ntri) #print('diff = ',dddb.ntri - true_ntri_sum) np.testing.assert_array_equal(dddb.ntri, true_ntri_sum) dddb = treecorr.NNNCrossCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, brute=True) dddb.process(cat1b, cat2b, cat3b) #print('dddb.n1n2n3.ntri = ',dddb.n1n2n3.ntri) #print('diff = ',dddb.n1n2n3.ntri - true_ntri) np.testing.assert_array_equal(dddb.n1n2n3.ntri, true_ntri_123) np.testing.assert_array_equal(dddb.n1n3n2.ntri, true_ntri_132) np.testing.assert_array_equal(dddb.n2n1n3.ntri, true_ntri_213) np.testing.assert_array_equal(dddb.n2n3n1.ntri, true_ntri_231) np.testing.assert_array_equal(dddb.n3n1n2.ntri, true_ntri_312) np.testing.assert_array_equal(dddb.n3n2n1.ntri, true_ntri_321) @timer def test_direct_3d_auto(): # This is the same as test_direct_count_auto, but using the 3d correlations ngal = 50 s = 10. rng = np.random.RandomState(8675309) x = rng.normal(312, s, (ngal,) ) y = rng.normal(728, s, (ngal,) ) z = rng.normal(-932, s, (ngal,) ) r = np.sqrt( x*x + y*y + z*z ) dec = np.arcsin(z/r) ra = np.arctan2(y,x) cat = treecorr.Catalog(ra=ra, dec=dec, r=r, ra_units='rad', dec_units='rad') min_sep = 1. max_sep = 50. nbins = 50 min_u = 0.13 max_u = 0.89 nubins = 10 min_v = 0.13 max_v = 0.59 nvbins = 10 ddd = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, brute=True, verbose=1) ddd.process(cat) #print('ddd.ntri = ',ddd.ntri) log_min_sep = np.log(min_sep) log_max_sep = np.log(max_sep) true_ntri = np.zeros( (nbins, nubins, 2*nvbins) ) bin_size = (log_max_sep - log_min_sep) / nbins ubin_size = (max_u-min_u) / nubins vbin_size = (max_v-min_v) / nvbins for i in range(ngal): for j in range(i+1,ngal): for k in range(j+1,ngal): dij = np.sqrt((x[i]-x[j])**2 + (y[i]-y[j])**2 + (z[i]-z[j])**2) dik = np.sqrt((x[i]-x[k])**2 + (y[i]-y[k])**2 + (z[i]-z[k])**2) djk = np.sqrt((x[j]-x[k])**2 + (y[j]-y[k])**2 + (z[j]-z[k])**2) if dij == 0.: continue if dik == 0.: continue if djk == 0.: continue if dij < dik: if dik < djk: d3 = dij; d2 = dik; d1 = djk ccw = is_ccw_3d(x[i],y[i],z[i],x[j],y[j],z[j],x[k],y[k],z[k]) elif dij < djk: d3 = dij; d2 = djk; d1 = dik ccw = is_ccw_3d(x[j],y[j],z[j],x[i],y[i],z[i],x[k],y[k],z[k]) else: d3 = djk; d2 = dij; d1 = dik ccw = is_ccw_3d(x[j],y[j],z[j],x[k],y[k],z[k],x[i],y[i],z[i]) else: if dij < djk: d3 = dik; d2 = dij; d1 = djk ccw = is_ccw_3d(x[i],y[i],z[i],x[k],y[k],z[k],x[j],y[j],z[j]) elif dik < djk: d3 = dik; d2 = djk; d1 = dij ccw = is_ccw_3d(x[k],y[k],z[k],x[i],y[i],z[i],x[j],y[j],z[j]) else: d3 = djk; d2 = dik; d1 = dij ccw = is_ccw_3d(x[k],y[k],z[k],x[j],y[j],z[j],x[i],y[i],z[i]) r = d2 u = d3/d2 v = (d1-d2)/d3 if r < min_sep or r >= max_sep: continue if u < min_u or u >= max_u: continue if v < min_v or v >= max_v: continue if not ccw: v = -v kr = int(np.floor( (np.log(r)-log_min_sep) / bin_size )) ku = int(np.floor( (u-min_u) / ubin_size )) if v > 0: kv = int(np.floor( (v-min_v) / vbin_size )) + nvbins else: kv = int(np.floor( (v-(-max_v)) / vbin_size )) assert 0 <= kr < nbins assert 0 <= ku < nubins assert 0 <= kv < 2*nvbins true_ntri[kr,ku,kv] += 1 #print('true_ntri => ',true_ntri) #print('diff = ',ddd.ntri - true_ntri) np.testing.assert_array_equal(ddd.ntri, true_ntri) # Repeat with binslop = 0 ddd = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, bin_slop=0, verbose=1) ddd.process(cat) #print('ddd.ntri = ',ddd.ntri) #print('diff = ',ddd.ntri - true_ntri) np.testing.assert_array_equal(ddd.ntri, true_ntri) # And again with no top-level recursion ddd = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, bin_slop=0, verbose=1, max_top=0) ddd.process(cat) #print('ddd.ntri = ',ddd.ntri) #print('true_ntri => ',true_ntri) #print('diff = ',ddd.ntri - true_ntri) np.testing.assert_array_equal(ddd.ntri, true_ntri) # And compare to the cross correlation # Here, we get 6x as much, since each triangle is discovered 6 times. ddd.clear() ddd.process(cat,cat,cat) #print('ddd.ntri = ',ddd.ntri) #print('true_ntri => ',true_ntri) #print('diff = ',ddd.ntri - true_ntri) np.testing.assert_array_equal(ddd.ntri, 6*true_ntri) dddc = treecorr.NNNCrossCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, bin_slop=0, verbose=1, max_top=0) dddc.process(cat,cat,cat) #print('ddd.ntri = ',ddd.ntri) #print('true_ntri => ',true_ntri) #print('diff = ',ddd.ntri - true_ntri) np.testing.assert_array_equal(dddc.n1n2n3.ntri, true_ntri) np.testing.assert_array_equal(dddc.n1n3n2.ntri, true_ntri) np.testing.assert_array_equal(dddc.n2n1n3.ntri, true_ntri) np.testing.assert_array_equal(dddc.n2n3n1.ntri, true_ntri) np.testing.assert_array_equal(dddc.n3n1n2.ntri, true_ntri) np.testing.assert_array_equal(dddc.n3n2n1.ntri, true_ntri) # Also compare to using x,y,z rather than ra,dec,r cat = treecorr.Catalog(x=x, y=y, z=z) ddd.process(cat) np.testing.assert_array_equal(ddd.ntri, true_ntri) @timer def test_direct_3d_cross(): # This is the same as test_direct_count_cross, but using the 3d correlations ngal = 50 s = 10. rng = np.random.RandomState(8675309) x1 = rng.normal(312, s, (ngal,) ) y1 = rng.normal(728, s, (ngal,) ) z1 = rng.normal(-932, s, (ngal,) ) r1 = np.sqrt( x1*x1 + y1*y1 + z1*z1 ) dec1 = np.arcsin(z1/r1) ra1 = np.arctan2(y1,x1) cat1 = treecorr.Catalog(ra=ra1, dec=dec1, r=r1, ra_units='rad', dec_units='rad') x2 = rng.normal(312, s, (ngal,) ) y2 = rng.normal(728, s, (ngal,) ) z2 = rng.normal(-932, s, (ngal,) ) r2 = np.sqrt( x2*x2 + y2*y2 + z2*z2 ) dec2 = np.arcsin(z2/r2) ra2 = np.arctan2(y2,x2) cat2 = treecorr.Catalog(ra=ra2, dec=dec2, r=r2, ra_units='rad', dec_units='rad') x3 = rng.normal(312, s, (ngal,) ) y3 = rng.normal(728, s, (ngal,) ) z3 = rng.normal(-932, s, (ngal,) ) r3 = np.sqrt( x3*x3 + y3*y3 + z3*z3 ) dec3 = np.arcsin(z3/r3) ra3 = np.arctan2(y3,x3) cat3 = treecorr.Catalog(ra=ra3, dec=dec3, r=r3, ra_units='rad', dec_units='rad') min_sep = 1. max_sep = 50. nbins = 50 min_u = 0.13 max_u = 0.89 nubins = 10 min_v = 0.13 max_v = 0.59 nvbins = 10 ddd = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, brute=True, verbose=1) ddd.process(cat1, cat2, cat3) #print('ddd.ntri = ',ddd.ntri) log_min_sep = np.log(min_sep) log_max_sep = np.log(max_sep) true_ntri_123 = np.zeros( (nbins, nubins, 2*nvbins) ) true_ntri_132 = np.zeros( (nbins, nubins, 2*nvbins) ) true_ntri_213 = np.zeros( (nbins, nubins, 2*nvbins) ) true_ntri_231 = np.zeros( (nbins, nubins, 2*nvbins) ) true_ntri_312 = np.zeros( (nbins, nubins, 2*nvbins) ) true_ntri_321 = np.zeros( (nbins, nubins, 2*nvbins) ) bin_size = (log_max_sep - log_min_sep) / nbins ubin_size = (max_u-min_u) / nubins vbin_size = (max_v-min_v) / nvbins for i in range(ngal): for j in range(ngal): for k in range(ngal): djk = np.sqrt((x2[j]-x3[k])**2 + (y2[j]-y3[k])**2 + (z2[j]-z3[k])**2) dik = np.sqrt((x1[i]-x3[k])**2 + (y1[i]-y3[k])**2 + (z1[i]-z3[k])**2) dij = np.sqrt((x1[i]-x2[j])**2 + (y1[i]-y2[j])**2 + (z1[i]-z2[j])**2) if dij == 0.: continue if dik == 0.: continue if djk == 0.: continue if dij < dik: if dik < djk: d3 = dij; d2 = dik; d1 = djk ccw = is_ccw_3d(x1[i],y1[i],z1[i],x2[j],y2[j],z2[j],x3[k],y3[k],z3[k]) true_ntri = true_ntri_123 elif dij < djk: d3 = dij; d2 = djk; d1 = dik ccw = is_ccw_3d(x2[j],y2[j],z2[j],x1[i],y1[i],z1[i],x3[k],y3[k],z3[k]) true_ntri = true_ntri_213 else: d3 = djk; d2 = dij; d1 = dik ccw = is_ccw_3d(x2[j],y2[j],z2[j],x3[k],y3[k],z3[k],x1[i],y1[i],z1[i]) true_ntri = true_ntri_231 else: if dij < djk: d3 = dik; d2 = dij; d1 = djk ccw = is_ccw_3d(x1[i],y1[i],z1[i],x3[k],y3[k],z3[k],x2[j],y2[j],z2[j]) true_ntri = true_ntri_132 elif dik < djk: d3 = dik; d2 = djk; d1 = dij ccw = is_ccw_3d(x3[k],y3[k],z3[k],x1[i],y1[i],z1[i],x2[j],y2[j],z2[j]) true_ntri = true_ntri_312 else: d3 = djk; d2 = dik; d1 = dij ccw = is_ccw_3d(x3[k],y3[k],z3[k],x2[j],y2[j],z2[j],x1[i],y1[i],z1[i]) true_ntri = true_ntri_321 r = d2 u = d3/d2 v = (d1-d2)/d3 if r < min_sep or r >= max_sep: continue if u < min_u or u >= max_u: continue if v < min_v or v >= max_v: continue if not ccw: v = -v kr = int(np.floor( (np.log(r)-log_min_sep) / bin_size )) ku = int(np.floor( (u-min_u) / ubin_size )) if v > 0: kv = int(np.floor( (v-min_v) / vbin_size )) + nvbins else: kv = int(np.floor( (v-(-max_v)) / vbin_size )) assert 0 <= kr < nbins assert 0 <= ku < nubins assert 0 <= kv < 2*nvbins true_ntri[kr,ku,kv] += 1 # With the regular NNNCorrelation class, we end up with the sum of all permutations. true_ntri_sum = true_ntri_123 + true_ntri_132 + true_ntri_213 + true_ntri_231 +\ true_ntri_312 + true_ntri_321 #print('true_ntri = ',true_ntri_sum) #print('diff = ',ddd.ntri - true_ntri_sum) np.testing.assert_array_equal(ddd.ntri, true_ntri_sum) # Now repeat with the full CrossCorrelation class, which distinguishes the permutations. ddd = treecorr.NNNCrossCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, brute=True, verbose=1) ddd.process(cat1, cat2, cat3) #print('true_ntri = ',true_ntri_123) #print('diff = ',ddd.n1n2n3.ntri - true_ntri_123) np.testing.assert_array_equal(ddd.n1n2n3.ntri, true_ntri_123) np.testing.assert_array_equal(ddd.n1n3n2.ntri, true_ntri_132) np.testing.assert_array_equal(ddd.n2n1n3.ntri, true_ntri_213) np.testing.assert_array_equal(ddd.n2n3n1.ntri, true_ntri_231) np.testing.assert_array_equal(ddd.n3n1n2.ntri, true_ntri_312) np.testing.assert_array_equal(ddd.n3n2n1.ntri, true_ntri_321) # Repeat with binslop = 0 ddd = treecorr.NNNCrossCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, bin_slop=0, verbose=1) ddd.process(cat1, cat2, cat3) #print('binslop = 0: ddd.n1n2n3.ntri = ',ddd.n1n2n3.ntri) #print('diff = ',ddd.n1n2n3.ntri - true_ntri_123) np.testing.assert_array_equal(ddd.n1n2n3.ntri, true_ntri_123) np.testing.assert_array_equal(ddd.n1n3n2.ntri, true_ntri_132) np.testing.assert_array_equal(ddd.n2n1n3.ntri, true_ntri_213) np.testing.assert_array_equal(ddd.n2n3n1.ntri, true_ntri_231) np.testing.assert_array_equal(ddd.n3n1n2.ntri, true_ntri_312) np.testing.assert_array_equal(ddd.n3n2n1.ntri, true_ntri_321) # And again with no top-level recursion ddd = treecorr.NNNCrossCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v, nvbins=nvbins, bin_slop=0, verbose=1, max_top=0) ddd.process(cat1, cat2, cat3) #print('max_top = 0: ddd.n1n2n3.ntri = ',ddd.n1n2n3n.ntri) #print('true_ntri = ',true_ntri_123) #print('diff = ',ddd.n1n2n3.ntri - true_ntri_123) np.testing.assert_array_equal(ddd.n1n2n3.ntri, true_ntri_123) np.testing.assert_array_equal(ddd.n1n3n2.ntri, true_ntri_132) np.testing.assert_array_equal(ddd.n2n1n3.ntri, true_ntri_213) np.testing.assert_array_equal(ddd.n2n3n1.ntri, true_ntri_231) np.testing.assert_array_equal(ddd.n3n1n2.ntri, true_ntri_312) np.testing.assert_array_equal(ddd.n3n2n1.ntri, true_ntri_321) # Also compare to using x,y,z rather than ra,dec,r cat1 = treecorr.Catalog(x=x1, y=y1, z=z1) cat2 = treecorr.Catalog(x=x2, y=y2, z=z2) cat3 = treecorr.Catalog(x=x3, y=y3, z=z3) ddd.process(cat1, cat2, cat3) np.testing.assert_array_equal(ddd.n1n2n3.ntri, true_ntri_123) np.testing.assert_array_equal(ddd.n1n3n2.ntri, true_ntri_132) np.testing.assert_array_equal(ddd.n2n1n3.ntri, true_ntri_213) np.testing.assert_array_equal(ddd.n2n3n1.ntri, true_ntri_231) np.testing.assert_array_equal(ddd.n3n1n2.ntri, true_ntri_312) np.testing.assert_array_equal(ddd.n3n2n1.ntri, true_ntri_321) @timer def test_nnn(): # Use a simple probability distribution for the galaxies: # # n(r) = (2pi s^2)^-1 exp(-r^2/2s^2) # # The Fourier transform is: n~(k) = exp(-s^2 k^2/2) # B(k1,k2) = <n~(k1) n~(k2) n~(-k1-k2)> # = exp(-s^2 (|k1|^2 + |k2|^2 - k1.k2)) # = exp(-s^2 (|k1|^2 + |k2|^2 + |k3|^2)/2) # # zeta(r1,r2) = (1/2pi)^4 int(d^2k1 int(d^2k2 exp(ik1.x1) exp(ik2.x2) B(k1,k2) )) # = exp(-(x1^2 + y1^2 + x2^2 + y2^2 - x1x2 - y1y2)/3s^2) / 12 pi^2 s^4 # = exp(-(d1^2 + d2^2 + d3^2)/6s^2) / 12 pi^2 s^4 # # This is also derivable as: # zeta(r1,r2) = int(dx int(dy n(x,y) n(x+x1,y+y1) n(x+x2,y+y2))) # which is also analytically integrable and gives the same answer. # # However, we need to correct for the uniform density background, so the real result # is this minus 1/L^4 divided by 1/L^4. So: # # zeta(r1,r2) = 1/(12 pi^2) (L/s)^4 exp(-(d1^2+d2^2+d3^2)/6s^2) - 1 # Doing the full correlation function takes a long time. Here, we just test a small range # of separations and a moderate range for u, v, which gives us a variety of triangle lengths. s = 10. if __name__ == "__main__": ngal = 20000 nrand = 2 * ngal L = 50. * s # Not infinity, so this introduces some error. Our integrals were to infinity. tol_factor = 1 else: ngal = 2000 nrand = ngal L = 20. * s tol_factor = 5 rng = np.random.RandomState(8675309) x = rng.normal(0,s, (ngal,) ) y = rng.normal(0,s, (ngal,) ) min_sep = 11. max_sep = 13. nbins = 2 min_u = 0.6 max_u = 0.9 nubins = 3 min_v = 0.5 max_v = 0.9 nvbins = 5 cat = treecorr.Catalog(x=x, y=y, x_units='arcmin', y_units='arcmin') ddd = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, min_v=min_v, max_v=max_v, nubins=nubins, nvbins=nvbins, sep_units='arcmin', verbose=1) ddd.process(cat) #print('ddd.ntri = ',ddd.ntri) # log(<d>) != <logd>, but it should be close: print('meanlogd1 - log(meand1) = ',ddd.meanlogd1 - np.log(ddd.meand1)) print('meanlogd2 - log(meand2) = ',ddd.meanlogd2 - np.log(ddd.meand2)) print('meanlogd3 - log(meand3) = ',ddd.meanlogd3 - np.log(ddd.meand3)) print('meand3 / meand2 = ',ddd.meand3 / ddd.meand2) print('meanu = ',ddd.meanu) print('max diff = ',np.max(np.abs(ddd.meand3/ddd.meand2 -ddd.meanu))) print('max rel diff = ',np.max(np.abs((ddd.meand3/ddd.meand2 -ddd.meanu)/ddd.meanu))) print('(meand1 - meand2)/meand3 = ',(ddd.meand1-ddd.meand2) / ddd.meand3) print('meanv = ',ddd.meanv) print('max diff = ',np.max(np.abs((ddd.meand1-ddd.meand2)/ddd.meand3 -np.abs(ddd.meanv)))) print('max rel diff = ', np.max(np.abs(((ddd.meand1-ddd.meand2)/ddd.meand3-np.abs(ddd.meanv))/ddd.meanv))) np.testing.assert_allclose(ddd.meanlogd1, np.log(ddd.meand1), rtol=1.e-3) np.testing.assert_allclose(ddd.meanlogd2, np.log(ddd.meand2), rtol=1.e-3) np.testing.assert_allclose(ddd.meanlogd3, np.log(ddd.meand3), rtol=1.e-3) np.testing.assert_allclose(ddd.meand3/ddd.meand2, ddd.meanu, rtol=1.e-5 * tol_factor) np.testing.assert_allclose((ddd.meand1-ddd.meand2)/ddd.meand3, np.abs(ddd.meanv), rtol=1.e-5 * tol_factor, atol=1.e-5 * tol_factor) np.testing.assert_allclose(ddd.meanlogd3-ddd.meanlogd2, np.log(ddd.meanu), atol=1.e-3 * tol_factor) np.testing.assert_allclose(np.log(ddd.meand1-ddd.meand2)-ddd.meanlogd3, np.log(np.abs(ddd.meanv)), atol=2.e-3 * tol_factor) rx = (rng.random_sample(nrand)-0.5) * L ry = (rng.random_sample(nrand)-0.5) * L rand = treecorr.Catalog(x=rx,y=ry, x_units='arcmin', y_units='arcmin') rrr = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, min_v=min_v, max_v=max_v, nubins=nubins, nvbins=nvbins, sep_units='arcmin', verbose=1) rrr.process(rand) #print('rrr.ntri = ',rrr.ntri) d1 = ddd.meand1 d2 = ddd.meand2 d3 = ddd.meand3 #print('rnom = ',np.exp(ddd.logr)) #print('unom = ',ddd.u) #print('vnom = ',ddd.v) #print('d1 = ',d1) #print('d2 = ',d2) #print('d3 = ',d3) true_zeta = (1./(12.*np.pi**2)) * (L/s)**4 * np.exp(-(d1**2+d2**2+d3**2)/(6.*s**2)) - 1. zeta, varzeta = ddd.calculateZeta(rrr) print('zeta = ',zeta) print('true_zeta = ',true_zeta) print('ratio = ',zeta / true_zeta) print('diff = ',zeta - true_zeta) print('max rel diff = ',np.max(np.abs((zeta - true_zeta)/true_zeta))) np.testing.assert_allclose(zeta, true_zeta, rtol=0.1*tol_factor) np.testing.assert_allclose(np.log(np.abs(zeta)), np.log(np.abs(true_zeta)), atol=0.1*tol_factor) # Check that we get the same result using the corr3 function cat.write(os.path.join('data','nnn_data.dat')) rand.write(os.path.join('data','nnn_rand.dat')) config = treecorr.config.read_config('configs/nnn.yaml') config['verbose'] = 0 treecorr.corr3(config) corr3_output = np.genfromtxt(os.path.join('output','nnn.out'), names=True, skip_header=1) print('zeta = ',zeta) print('from corr3 output = ',corr3_output['zeta']) print('ratio = ',corr3_output['zeta']/zeta.flatten()) print('diff = ',corr3_output['zeta']-zeta.flatten()) np.testing.assert_allclose(corr3_output['zeta'], zeta.flatten(), rtol=1.e-3) # Check the fits write option out_file_name1 = os.path.join('output','nnn_out1.fits') ddd.write(out_file_name1) data = fitsio.read(out_file_name1) np.testing.assert_almost_equal(data['r_nom'], np.exp(ddd.logr).flatten()) np.testing.assert_almost_equal(data['u_nom'], ddd.u.flatten()) np.testing.assert_almost_equal(data['v_nom'], ddd.v.flatten()) np.testing.assert_almost_equal(data['meand1'], ddd.meand1.flatten()) np.testing.assert_almost_equal(data['meanlogd1'], ddd.meanlogd1.flatten()) np.testing.assert_almost_equal(data['meand2'], ddd.meand2.flatten()) np.testing.assert_almost_equal(data['meanlogd2'], ddd.meanlogd2.flatten()) np.testing.assert_almost_equal(data['meand3'], ddd.meand3.flatten()) np.testing.assert_almost_equal(data['meanlogd3'], ddd.meanlogd3.flatten()) np.testing.assert_almost_equal(data['meanu'], ddd.meanu.flatten()) np.testing.assert_almost_equal(data['meanv'], ddd.meanv.flatten()) np.testing.assert_almost_equal(data['ntri'], ddd.ntri.flatten()) header = fitsio.read_header(out_file_name1, 1) np.testing.assert_almost_equal(header['tot']/ddd.tot, 1.) out_file_name2 = os.path.join('output','nnn_out2.fits') ddd.write(out_file_name2, rrr) data = fitsio.read(out_file_name2) np.testing.assert_almost_equal(data['r_nom'], np.exp(ddd.logr).flatten()) np.testing.assert_almost_equal(data['u_nom'], ddd.u.flatten()) np.testing.assert_almost_equal(data['v_nom'], ddd.v.flatten()) np.testing.assert_almost_equal(data['meand1'], ddd.meand1.flatten()) np.testing.assert_almost_equal(data['meanlogd1'], ddd.meanlogd1.flatten()) np.testing.assert_almost_equal(data['meand2'], ddd.meand2.flatten()) np.testing.assert_almost_equal(data['meanlogd2'], ddd.meanlogd2.flatten()) np.testing.assert_almost_equal(data['meand3'], ddd.meand3.flatten()) np.testing.assert_almost_equal(data['meanlogd3'], ddd.meanlogd3.flatten()) np.testing.assert_almost_equal(data['meanu'], ddd.meanu.flatten()) np.testing.assert_almost_equal(data['meanv'], ddd.meanv.flatten()) np.testing.assert_almost_equal(data['zeta'], zeta.flatten()) np.testing.assert_almost_equal(data['sigma_zeta'], np.sqrt(varzeta).flatten()) np.testing.assert_almost_equal(data['DDD'], ddd.ntri.flatten()) np.testing.assert_almost_equal(data['RRR'], rrr.ntri.flatten() * (ddd.tot / rrr.tot)) header = fitsio.read_header(out_file_name2, 1) np.testing.assert_almost_equal(header['tot']/ddd.tot, 1.) # Check the read function # Note: These don't need the flatten. The read function should reshape them to the right shape. ddd2 = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, min_v=min_v, max_v=max_v, nubins=nubins, nvbins=nvbins, sep_units='arcmin', verbose=1) ddd2.read(out_file_name1) np.testing.assert_almost_equal(ddd2.logr, ddd.logr) np.testing.assert_almost_equal(ddd2.u, ddd.u) np.testing.assert_almost_equal(ddd2.v, ddd.v) np.testing.assert_almost_equal(ddd2.meand1, ddd.meand1) np.testing.assert_almost_equal(ddd2.meanlogd1, ddd.meanlogd1) np.testing.assert_almost_equal(ddd2.meand2, ddd.meand2) np.testing.assert_almost_equal(ddd2.meanlogd2, ddd.meanlogd2) np.testing.assert_almost_equal(ddd2.meand3, ddd.meand3) np.testing.assert_almost_equal(ddd2.meanlogd3, ddd.meanlogd3) np.testing.assert_almost_equal(ddd2.meanu, ddd.meanu) np.testing.assert_almost_equal(ddd2.meanv, ddd.meanv) np.testing.assert_almost_equal(ddd2.ntri, ddd.ntri) np.testing.assert_almost_equal(ddd2.tot/ddd.tot, 1.) assert ddd2.coords == ddd.coords assert ddd2.metric == ddd.metric assert ddd2.sep_units == ddd.sep_units assert ddd2.bin_type == ddd.bin_type ddd2.read(out_file_name2) np.testing.assert_almost_equal(ddd2.logr, ddd.logr) np.testing.assert_almost_equal(ddd2.u, ddd.u) np.testing.assert_almost_equal(ddd2.v, ddd.v) np.testing.assert_almost_equal(ddd2.meand1, ddd.meand1) np.testing.assert_almost_equal(ddd2.meanlogd1, ddd.meanlogd1) np.testing.assert_almost_equal(ddd2.meand2, ddd.meand2) np.testing.assert_almost_equal(ddd2.meanlogd2, ddd.meanlogd2) np.testing.assert_almost_equal(ddd2.meand3, ddd.meand3) np.testing.assert_almost_equal(ddd2.meanlogd3, ddd.meanlogd3) np.testing.assert_almost_equal(ddd2.meanu, ddd.meanu) np.testing.assert_almost_equal(ddd2.meanv, ddd.meanv) np.testing.assert_almost_equal(ddd2.ntri, ddd.ntri) np.testing.assert_almost_equal(ddd2.tot/ddd.tot, 1.) assert ddd2.coords == ddd.coords assert ddd2.metric == ddd.metric assert ddd2.sep_units == ddd.sep_units assert ddd2.bin_type == ddd.bin_type # Check the hdf5 write option try: import h5py # noqa: F401 except ImportError: print('Skipping hdf5 output file, since h5py not installed.') else: out_file_name3 = os.path.join('output','nnn_out3.hdf5') ddd.write(out_file_name3, rrr) with h5py.File(out_file_name3, 'r') as hdf: data = hdf['/'] np.testing.assert_almost_equal(data['r_nom'], np.exp(ddd.logr).flatten()) np.testing.assert_almost_equal(data['u_nom'], ddd.u.flatten()) np.testing.assert_almost_equal(data['v_nom'], ddd.v.flatten()) np.testing.assert_almost_equal(data['meand1'], ddd.meand1.flatten()) np.testing.assert_almost_equal(data['meanlogd1'], ddd.meanlogd1.flatten()) np.testing.assert_almost_equal(data['meand2'], ddd.meand2.flatten()) np.testing.assert_almost_equal(data['meanlogd2'], ddd.meanlogd2.flatten()) np.testing.assert_almost_equal(data['meand3'], ddd.meand3.flatten()) np.testing.assert_almost_equal(data['meanlogd3'], ddd.meanlogd3.flatten()) np.testing.assert_almost_equal(data['meanu'], ddd.meanu.flatten()) np.testing.assert_almost_equal(data['meanv'], ddd.meanv.flatten()) np.testing.assert_almost_equal(data['ntri'], ddd.ntri.flatten()) np.testing.assert_almost_equal(data['zeta'], zeta.flatten()) np.testing.assert_almost_equal(data['sigma_zeta'], np.sqrt(varzeta).flatten()) np.testing.assert_almost_equal(data['DDD'], ddd.ntri.flatten()) np.testing.assert_almost_equal(data['RRR'], rrr.ntri.flatten() * (ddd.tot / rrr.tot)) attrs = data.attrs np.testing.assert_almost_equal(attrs['tot']/ddd.tot, 1.) ddd3 = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, min_v=min_v, max_v=max_v, nubins=nubins, nvbins=nvbins, sep_units='arcmin', verbose=1) ddd3.read(out_file_name3) np.testing.assert_almost_equal(ddd3.logr, ddd.logr) np.testing.assert_almost_equal(ddd3.u, ddd.u) np.testing.assert_almost_equal(ddd3.v, ddd.v) np.testing.assert_almost_equal(ddd3.meand1, ddd.meand1) np.testing.assert_almost_equal(ddd3.meanlogd1, ddd.meanlogd1) np.testing.assert_almost_equal(ddd3.meand2, ddd.meand2) np.testing.assert_almost_equal(ddd3.meanlogd2, ddd.meanlogd2) np.testing.assert_almost_equal(ddd3.meand3, ddd.meand3) np.testing.assert_almost_equal(ddd3.meanlogd3, ddd.meanlogd3) np.testing.assert_almost_equal(ddd3.meanu, ddd.meanu) np.testing.assert_almost_equal(ddd3.meanv, ddd.meanv) np.testing.assert_almost_equal(ddd3.ntri, ddd.ntri) np.testing.assert_almost_equal(ddd3.tot/ddd.tot, 1.) assert ddd3.coords == ddd.coords assert ddd3.metric == ddd.metric assert ddd3.sep_units == ddd.sep_units assert ddd3.bin_type == ddd.bin_type # Test compensated zeta # First just check the mechanics. # If we don't actually do all the cross terms, then compensated is the same as simple. zeta2, varzeta2 = ddd.calculateZeta(rrr,drr=rrr,rdd=rrr) print('fake compensated zeta = ',zeta2) np.testing.assert_allclose(zeta2, zeta) # Error to not have one of rrr, drr, rdd. with assert_raises(TypeError): ddd.calculateZeta(drr=rrr,rdd=rrr) with assert_raises(TypeError): ddd.calculateZeta(rrr,rdd=rrr) with assert_raises(TypeError): ddd.calculateZeta(rrr,drr=rrr) rrr2 = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, min_v=min_v, max_v=max_v, nubins=nubins, nvbins=nvbins, sep_units='arcmin') # Error if any of them haven't been run yet. with assert_raises(ValueError): ddd.calculateZeta(rrr2,drr=rrr,rdd=rrr) with assert_raises(ValueError): ddd.calculateZeta(rrr,drr=rrr2,rdd=rrr) with assert_raises(ValueError): ddd.calculateZeta(rrr,drr=rrr,rdd=rrr2) out_file_name3 = os.path.join('output','nnn_out3.fits') with assert_raises(TypeError): ddd.write(out_file_name3,drr=rrr,rdd=rrr) with assert_raises(TypeError): ddd.write(out_file_name3,rrr=rrr,rdd=rrr) with assert_raises(TypeError): ddd.write(out_file_name3,rrr=rrr,drr=rrr) # It's too slow to test the real calculation in nosetests runs, so we stop here if not main. if __name__ != '__main__': return # This version computes the three-point function after subtracting off the appropriate # two-point functions xi(d1) + xi(d2) + xi(d3), where [cf. test_nn() in test_nn.py] # xi(r) = 1/4pi (L/s)^2 exp(-r^2/4s^2) - 1 drr = ddd.copy() rdd = ddd.copy() drr.process(cat,rand) rdd.process(rand,cat) zeta, varzeta = ddd.calculateZeta(rrr,drr,rdd) print('compensated zeta = ',zeta) xi1 = (1./(4.*np.pi)) * (L/s)**2 * np.exp(-d1**2/(4.*s**2)) - 1. xi2 = (1./(4.*np.pi)) * (L/s)**2 * np.exp(-d2**2/(4.*s**2)) - 1. xi3 = (1./(4.*np.pi)) * (L/s)**2 * np.exp(-d3**2/(4.*s**2)) - 1. print('xi1 = ',xi1) print('xi2 = ',xi2) print('xi3 = ',xi3) print('true_zeta + xi1 + xi2 + xi3 = ',true_zeta) true_zeta -= xi1 + xi2 + xi3 print('true_zeta => ',true_zeta) print('ratio = ',zeta / true_zeta) print('diff = ',zeta - true_zeta) print('max rel diff = ',np.max(np.abs((zeta - true_zeta)/true_zeta))) np.testing.assert_allclose(zeta, true_zeta, rtol=0.1*tol_factor) np.testing.assert_allclose(np.log(np.abs(zeta)), np.log(np.abs(true_zeta)), atol=0.1*tol_factor) out_file_name3 = os.path.join('output','nnn_out3.fits') ddd.write(out_file_name3, rrr,drr,rdd) data = fitsio.read(out_file_name3) np.testing.assert_almost_equal(data['r_nom'], np.exp(ddd.logr).flatten()) np.testing.assert_almost_equal(data['u_nom'], ddd.u.flatten()) np.testing.assert_almost_equal(data['v_nom'], ddd.v.flatten()) np.testing.assert_almost_equal(data['meand1'], ddd.meand1.flatten()) np.testing.assert_almost_equal(data['meanlogd1'], ddd.meanlogd1.flatten()) np.testing.assert_almost_equal(data['meand2'], ddd.meand2.flatten()) np.testing.assert_almost_equal(data['meanlogd2'], ddd.meanlogd2.flatten()) np.testing.assert_almost_equal(data['meand3'], ddd.meand3.flatten()) np.testing.assert_almost_equal(data['meanlogd3'], ddd.meanlogd3.flatten()) np.testing.assert_almost_equal(data['meanu'], ddd.meanu.flatten()) np.testing.assert_almost_equal(data['meanv'], ddd.meanv.flatten()) np.testing.assert_almost_equal(data['zeta'], zeta.flatten()) np.testing.assert_almost_equal(data['sigma_zeta'], np.sqrt(varzeta).flatten()) np.testing.assert_almost_equal(data['DDD'], ddd.ntri.flatten()) np.testing.assert_almost_equal(data['RRR'], rrr.ntri.flatten() * (ddd.tot / rrr.tot)) np.testing.assert_almost_equal(data['DRR'], drr.ntri.flatten() * (ddd.tot / drr.tot)) np.testing.assert_almost_equal(data['RDD'], rdd.ntri.flatten() * (ddd.tot / rdd.tot)) header = fitsio.read_header(out_file_name3, 1) np.testing.assert_almost_equal(header['tot']/ddd.tot, 1.) ddd2.read(out_file_name3) np.testing.assert_almost_equal(ddd2.logr, ddd.logr) np.testing.assert_almost_equal(ddd2.u, ddd.u) np.testing.assert_almost_equal(ddd2.v, ddd.v) np.testing.assert_almost_equal(ddd2.meand1, ddd.meand1) np.testing.assert_almost_equal(ddd2.meanlogd1, ddd.meanlogd1) np.testing.assert_almost_equal(ddd2.meand2, ddd.meand2) np.testing.assert_almost_equal(ddd2.meanlogd2, ddd.meanlogd2) np.testing.assert_almost_equal(ddd2.meand3, ddd.meand3) np.testing.assert_almost_equal(ddd2.meanlogd3, ddd.meanlogd3) np.testing.assert_almost_equal(ddd2.meanu, ddd.meanu) np.testing.assert_almost_equal(ddd2.meanv, ddd.meanv) np.testing.assert_almost_equal(ddd2.ntri, ddd.ntri) np.testing.assert_almost_equal(ddd2.tot/ddd.tot, 1.) assert ddd2.coords == ddd.coords assert ddd2.metric == ddd.metric assert ddd2.sep_units == ddd.sep_units assert ddd2.bin_type == ddd.bin_type config = treecorr.config.read_config('configs/nnn_compensated.yaml') config['verbose'] = 0 treecorr.corr3(config) corr3_outfile = os.path.join('output','nnn_compensated.fits') corr3_output = fitsio.read(corr3_outfile) print('zeta = ',zeta) print('from corr3 output = ',corr3_output['zeta']) print('ratio = ',corr3_output['zeta']/zeta.flatten()) print('diff = ',corr3_output['zeta']-zeta.flatten()) np.testing.assert_almost_equal(corr3_output['r_nom'], np.exp(ddd.logr).flatten()) np.testing.assert_almost_equal(corr3_output['u_nom'], ddd.u.flatten()) np.testing.assert_almost_equal(corr3_output['v_nom'], ddd.v.flatten()) np.testing.assert_almost_equal(corr3_output['meand1'], ddd.meand1.flatten()) np.testing.assert_almost_equal(corr3_output['meanlogd1'], ddd.meanlogd1.flatten()) np.testing.assert_almost_equal(corr3_output['meand2'], ddd.meand2.flatten()) np.testing.assert_almost_equal(corr3_output['meanlogd2'], ddd.meanlogd2.flatten()) np.testing.assert_almost_equal(corr3_output['meand3'], ddd.meand3.flatten()) np.testing.assert_almost_equal(corr3_output['meanlogd3'], ddd.meanlogd3.flatten()) np.testing.assert_almost_equal(corr3_output['meanu'], ddd.meanu.flatten()) np.testing.assert_almost_equal(corr3_output['meanv'], ddd.meanv.flatten()) np.testing.assert_almost_equal(corr3_output['zeta'], zeta.flatten()) np.testing.assert_almost_equal(corr3_output['sigma_zeta'], np.sqrt(varzeta).flatten()) np.testing.assert_almost_equal(corr3_output['DDD'], ddd.ntri.flatten()) np.testing.assert_almost_equal(corr3_output['RRR'], rrr.ntri.flatten() * (ddd.tot / rrr.tot)) np.testing.assert_almost_equal(corr3_output['DRR'], drr.ntri.flatten() * (ddd.tot / drr.tot)) np.testing.assert_almost_equal(corr3_output['RDD'], rdd.ntri.flatten() * (ddd.tot / rdd.tot)) header = fitsio.read_header(corr3_outfile, 1) np.testing.assert_almost_equal(header['tot']/ddd.tot, 1.) @timer def test_3d(): # For this one, build a Gaussian cloud around some random point in 3D space and do the # correlation function in 3D. # # The 3D Fourier transform is: n~(k) = exp(-s^2 k^2/2) # B(k1,k2) = <n~(k1) n~(k2) n~(-k1-k2)> # = exp(-s^2 (|k1|^2 + |k2|^2 - k1.k2)) # = exp(-s^2 (|k1|^2 + |k2|^2 + |k3|^2)/2) # as before, except now k1,k2 are 3d vectors, not 2d. # # zeta(r1,r2) = (1/2pi)^4 int(d^2k1 int(d^2k2 exp(ik1.x1) exp(ik2.x2) B(k1,k2) )) # = exp(-(x1^2 + y1^2 + x2^2 + y2^2 - x1x2 - y1y2)/3s^2) / 12 pi^2 s^4 # = exp(-(d1^2 + d2^2 + d3^2)/6s^2) / 24 sqrt(3) pi^3 s^6 # # And again, this is also derivable as: # zeta(r1,r2) = int(dx int(dy int(dz n(x,y,z) n(x+x1,y+y1,z+z1) n(x+x2,y+y2,z+z2))) # which is also analytically integrable and gives the same answer. # # However, we need to correct for the uniform density background, so the real result # is this minus 1/L^6 divided by 1/L^6. So: # # zeta(r1,r2) = 1/(24 sqrt(3) pi^3) (L/s)^4 exp(-(d1^2+d2^2+d3^2)/6s^2) - 1 # Doing the full correlation function takes a long time. Here, we just test a small range # of separations and a moderate range for u, v, which gives us a variety of triangle lengths. xcen = 823 # Mpc maybe? ycen = 342 zcen = -672 s = 10. if __name__ == "__main__": ngal = 5000 nrand = 20 * ngal L = 50. * s tol_factor = 1 else: ngal = 1000 nrand = 5 * ngal L = 20. * s tol_factor = 5 rng = np.random.RandomState(8675309) x = rng.normal(xcen, s, (ngal,) ) y = rng.normal(ycen, s, (ngal,) ) z = rng.normal(zcen, s, (ngal,) ) r = np.sqrt(x*x+y*y+z*z) dec = np.arcsin(z/r) * (coord.radians / coord.degrees) ra = np.arctan2(y,x) * (coord.radians / coord.degrees) min_sep = 10. max_sep = 20. nbins = 8 min_u = 0.9 max_u = 1.0 nubins = 1 min_v = 0. max_v = 0.05 nvbins = 1 cat = treecorr.Catalog(ra=ra, dec=dec, r=r, ra_units='deg', dec_units='deg') ddd = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, min_v=min_v, max_v=max_v, nubins=nubins, nvbins=nvbins, verbose=1) ddd.process(cat) print('ddd.ntri = ',ddd.ntri.flatten()) rx = (rng.random_sample(nrand)-0.5) * L + xcen ry = (rng.random_sample(nrand)-0.5) * L + ycen rz = (rng.random_sample(nrand)-0.5) * L + zcen rr = np.sqrt(rx*rx+ry*ry+rz*rz) rdec = np.arcsin(rz/rr) * (coord.radians / coord.degrees) rra = np.arctan2(ry,rx) * (coord.radians / coord.degrees) rand = treecorr.Catalog(ra=rra, dec=rdec, r=rr, ra_units='deg', dec_units='deg') rrr = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, min_v=min_v, max_v=max_v, nubins=nubins, nvbins=nvbins, verbose=1) rrr.process(rand) print('rrr.ntri = ',rrr.ntri.flatten()) d1 = ddd.meand1 d2 = ddd.meand2 d3 = ddd.meand3 print('rnom = ',np.exp(ddd.logr).flatten()) print('unom = ',ddd.u.flatten()) print('vnom = ',ddd.v.flatten()) print('d1 = ',d1.flatten()) print('d2 = ',d2.flatten()) print('d3 = ',d3.flatten()) true_zeta = ((1./(24.*np.sqrt(3)*np.pi**3)) * (L/s)**6 * np.exp(-(d1**2+d2**2+d3**2)/(6.*s**2)) - 1.) zeta, varzeta = ddd.calculateZeta(rrr) print('zeta = ',zeta.flatten()) print('true_zeta = ',true_zeta.flatten()) print('ratio = ',(zeta / true_zeta).flatten()) print('diff = ',(zeta - true_zeta).flatten()) print('max rel diff = ',np.max(np.abs((zeta - true_zeta)/true_zeta))) np.testing.assert_allclose(zeta, true_zeta, rtol=0.1*tol_factor) np.testing.assert_allclose(np.log(np.abs(zeta)), np.log(np.abs(true_zeta)), atol=0.1*tol_factor) # Check that we get the same result using the corr3 functin: cat.write(os.path.join('data','nnn_3d_data.dat')) rand.write(os.path.join('data','nnn_3d_rand.dat')) config = treecorr.config.read_config('configs/nnn_3d.yaml') config['verbose'] = 0 treecorr.corr3(config) corr3_output = np.genfromtxt(os.path.join('output','nnn_3d.out'), names=True, skip_header=1) print('zeta = ',zeta.flatten()) print('from corr3 output = ',corr3_output['zeta']) print('ratio = ',corr3_output['zeta']/zeta.flatten()) print('diff = ',corr3_output['zeta']-zeta.flatten()) np.testing.assert_allclose(corr3_output['zeta'], zeta.flatten(), rtol=1.e-3) # Check that we get the same thing when using x,y,z rather than ra,dec,r cat = treecorr.Catalog(x=x, y=y, z=z) rand = treecorr.Catalog(x=rx, y=ry, z=rz) ddd.process(cat) rrr.process(rand) zeta, varzeta = ddd.calculateZeta(rrr) np.testing.assert_allclose(zeta, true_zeta, rtol=0.1*tol_factor) np.testing.assert_allclose(np.log(np.abs(zeta)), np.log(np.abs(true_zeta)), atol=0.1*tol_factor) @timer def test_list(): # Test that we can use a list of files for either data or rand or both. data_cats = [] rand_cats = [] ncats = 3 ngal = 100 nrand = 2 * ngal s = 10. L = 50. * s rng = np.random.RandomState(8675309) min_sep = 30. max_sep = 50. nbins = 3 min_u = 0 max_u = 0.2 nubins = 2 min_v = 0.5 max_v = 0.9 nvbins = 2 x = rng.normal(0,s, (ngal,ncats) ) y = rng.normal(0,s, (ngal,ncats) ) data_cats = [ treecorr.Catalog(x=x[:,k], y=y[:,k]) for k in range(ncats) ] rx = (rng.random_sample((nrand,ncats))-0.5) * L ry = (rng.random_sample((nrand,ncats))-0.5) * L rand_cats = [ treecorr.Catalog(x=rx[:,k], y=ry[:,k]) for k in range(ncats) ] ddd = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, min_v=min_v, max_v=max_v, nubins=nubins, nvbins=nvbins, bin_slop=0.1, verbose=1) ddd.process(data_cats) print('From multiple catalogs: ddd.ntri = ',ddd.ntri) print('tot = ',ddd.tot) # Now do the same thing with one big catalog dddx = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, min_v=min_v, max_v=max_v, nubins=nubins, nvbins=nvbins, bin_slop=0.1, verbose=1) data_catx = treecorr.Catalog(x=x.reshape( (ngal*ncats,) ), y=y.reshape( (ngal*ncats,) )) dddx.process(data_catx) print('From single catalog: dddx.ntri = ',dddx.ntri) print('tot = ',dddx.tot) # Only test to rtol=0.1, since there are now differences between the auto and cross related # to how they characterize triangles especially when d1 ~= d2 or d2 ~= d3. np.testing.assert_allclose(ddd.ntri, dddx.ntri, rtol=0.1) np.testing.assert_allclose(ddd.tot, dddx.tot) rrr = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, min_v=min_v, max_v=max_v, nubins=nubins, nvbins=nvbins, bin_slop=0.1, verbose=1) rrr.process(rand_cats) print('rrr.ntri = ',rrr.ntri) rrrx = treecorr.NNNCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins, min_u=min_u, max_u=max_u, min_v=min_v, max_v=max_v, nubins=nubins, nvbins=nvbins, bin_slop=0.1, verbose=1) rand_catx = treecorr.Catalog(x=rx.reshape( (nrand*ncats,) ), y=ry.reshape( (nrand*ncats,) )) rrrx.process(rand_catx) print('rrrx.ntri = ',rrrx.ntri) np.testing.assert_allclose(rrr.ntri, rrrx.ntri, rtol=0.1) np.testing.assert_allclose(rrr.tot, rrrx.tot) zeta, varzeta = ddd.calculateZeta(rrr) zetax, varzetax = dddx.calculateZeta(rrrx) print('zeta = ',zeta) print('zetax = ',zetax) #print('ratio = ',zeta/zetax) #print('diff = ',zeta-zetax) np.testing.assert_allclose(zeta, zetax, rtol=0.1) # Check that we get the same result using the corr3 function: file_list = [] rand_file_list = [] for k in range(ncats): file_name = os.path.join('data','nnn_list_data%d.dat'%k) data_cats[k].write(file_name) file_list.append(file_name) rand_file_name = os.path.join('data','nnn_list_rand%d.dat'%k) rand_cats[k].write(rand_file_name) rand_file_list.append(rand_file_name) list_name = os.path.join('data','nnn_list_data_files.txt') with open(list_name, 'w') as fid: for file_name in file_list: fid.write('%s\n'%file_name) rand_list_name = os.path.join('data','nnn_list_rand_files.txt') with open(rand_list_name, 'w') as fid: for file_name in rand_file_list: fid.write('%s\n'%file_name) file_namex = os.path.join('data','nnn_list_datax.dat') data_catx.write(file_namex) rand_file_namex = os.path.join('data','nnn_list_randx.dat') rand_catx.write(rand_file_namex) config = treecorr.config.read_config('configs/nnn_list1.yaml') config['verbose'] = 0 config['bin_slop'] = 0.1 treecorr.corr3(config) corr3_output = np.genfromtxt(os.path.join('output','nnn_list1.out'), names=True, skip_header=1) print('zeta = ',zeta) print('from corr3 output = ',corr3_output['zeta']) print('ratio = ',corr3_output['zeta']/zeta.flatten()) print('diff = ',corr3_output['zeta']-zeta.flatten()) np.testing.assert_allclose(corr3_output['zeta'], zeta.flatten(), rtol=1.e-3) config = treecorr.config.read_config('configs/nnn_list2.json') config['verbose'] = 0 config['bin_slop'] = 0.1 treecorr.corr3(config) corr3_output = np.genfromtxt(os.path.join('output','nnn_list2.out'), names=True, skip_header=1) print('zeta = ',zeta) print('from corr3 output = ',corr3_output['zeta']) print('ratio = ',corr3_output['zeta']/zeta.flatten()) print('diff = ',corr3_output['zeta']-zeta.flatten()) np.testing.assert_allclose(corr3_output['zeta'], zeta.flatten(), rtol=0.05) config = treecorr.config.read_config('configs/nnn_list3.params') config['verbose'] = 0 config['bin_slop'] = 0.1 treecorr.corr3(config) corr3_output = np.genfromtxt(os.path.join('output','nnn_list3.out'), names=True, skip_header=1) print('zeta = ',zeta) print('from corr3 output = ',corr3_output['zeta']) print('ratio = ',corr3_output['zeta']/zeta.flatten()) print('diff = ',corr3_output['zeta']-zeta.flatten()) np.testing.assert_allclose(corr3_output['zeta'], zeta.flatten(), rtol=0.05) config = treecorr.config.read_config('configs/nnn_list4.config', file_type='params') config['verbose'] = 0 config['bin_slop'] = 0.1 treecorr.corr3(config) corr3_output = np.genfromtxt(os.path.join('output','nnn_list4.out'), names=True, skip_header=1) print('zeta = ',zeta) print('from corr3 output = ',corr3_output['zeta']) print('ratio = ',corr3_output['zeta']/zeta.flatten()) print('diff = ',corr3_output['zeta']-zeta.flatten()) np.testing.assert_allclose(corr3_output['zeta'], zeta.flatten(), rtol=1.e-3) if __name__ == '__main__': test_log_binning() test_direct_count_auto() test_direct_count_cross() test_direct_count_cross12() test_direct_spherical() test_direct_arc() test_direct_partial() test_direct_3d_auto() test_direct_3d_cross() test_nnn() test_3d() test_list()
[ "numpy.sqrt", "numpy.testing.assert_equal", "numpy.log", "math.log", "treecorr.NNNCrossCorrelation", "numpy.arctan2", "test_helper.get_script_name", "test_helper.do_pickle", "numpy.genfromtxt", "numpy.random.RandomState", "test_helper.is_ccw", "numpy.where", "subprocess.Popen", "numpy.test...
[((3284, 3359), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': '(5)', 'max_sep': '(20)', 'nbins': '(20)', 'bin_type': '"""LogRUV"""'}), "(min_sep=5, max_sep=20, nbins=20, bin_type='LogRUV')\n", (3307, 3359), False, 'import treecorr\n'), ((3716, 3842), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': '(5)', 'max_sep': '(20)', 'nbins': '(20)', 'min_u': '(0.2)', 'max_u': '(0.9)', 'nubins': '(12)', 'min_v': '(0.0)', 'max_v': '(0.2)', 'nvbins': '(2)'}), '(min_sep=5, max_sep=20, nbins=20, min_u=0.2, max_u=\n 0.9, nubins=12, min_v=0.0, max_v=0.2, nvbins=2)\n', (3739, 3842), False, 'import treecorr\n'), ((4382, 4441), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'max_sep': '(20)', 'nbins': '(20)', 'bin_size': '(0.1)'}), '(max_sep=20, nbins=20, bin_size=0.1)\n', (4405, 4441), False, 'import treecorr\n'), ((4799, 4936), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'max_sep': '(20)', 'nbins': '(20)', 'bin_size': '(0.1)', 'max_u': '(0.9)', 'nubins': '(3)', 'ubin_size': '(0.05)', 'max_v': '(0.4)', 'nvbins': '(4)', 'vbin_size': '(0.05)'}), '(max_sep=20, nbins=20, bin_size=0.1, max_u=0.9,\n nubins=3, ubin_size=0.05, max_v=0.4, nvbins=4, vbin_size=0.05)\n', (4822, 4936), False, 'import treecorr\n'), ((5273, 5304), 'numpy.isclose', 'np.isclose', (['nnn.ubin_size', '(0.05)'], {}), '(nnn.ubin_size, 0.05)\n', (5283, 5304), True, 'import numpy as np\n'), ((5316, 5343), 'numpy.isclose', 'np.isclose', (['nnn.min_u', '(0.75)'], {}), '(nnn.min_u, 0.75)\n', (5326, 5343), True, 'import numpy as np\n'), ((5410, 5441), 'numpy.isclose', 'np.isclose', (['nnn.vbin_size', '(0.05)'], {}), '(nnn.vbin_size, 0.05)\n', (5420, 5441), True, 'import numpy as np\n'), ((5453, 5479), 'numpy.isclose', 'np.isclose', (['nnn.min_v', '(0.2)'], {}), '(nnn.min_v, 0.2)\n', (5463, 5479), True, 'import numpy as np\n'), ((5587, 5645), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': '(5)', 'nbins': '(20)', 'bin_size': '(0.1)'}), '(min_sep=5, nbins=20, bin_size=0.1)\n', (5610, 5645), False, 'import treecorr\n'), ((6001, 6137), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': '(5)', 'nbins': '(20)', 'bin_size': '(0.1)', 'min_u': '(0.7)', 'nubins': '(4)', 'ubin_size': '(0.05)', 'min_v': '(0.2)', 'nvbins': '(4)', 'vbin_size': '(0.05)'}), '(min_sep=5, nbins=20, bin_size=0.1, min_u=0.7,\n nubins=4, ubin_size=0.05, min_v=0.2, nvbins=4, vbin_size=0.05)\n', (6024, 6137), False, 'import treecorr\n'), ((6501, 6532), 'numpy.isclose', 'np.isclose', (['nnn.ubin_size', '(0.05)'], {}), '(nnn.ubin_size, 0.05)\n', (6511, 6532), True, 'import numpy as np\n'), ((6627, 6658), 'numpy.isclose', 'np.isclose', (['nnn.vbin_size', '(0.05)'], {}), '(nnn.vbin_size, 0.05)\n', (6637, 6658), True, 'import numpy as np\n'), ((6736, 6796), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': '(5)', 'max_sep': '(20)', 'bin_size': '(0.1)'}), '(min_sep=5, max_sep=20, bin_size=0.1)\n', (6759, 6796), False, 'import treecorr\n'), ((7157, 7297), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': '(5)', 'max_sep': '(20)', 'bin_size': '(0.1)', 'min_u': '(0.2)', 'max_u': '(0.9)', 'ubin_size': '(0.03)', 'min_v': '(0.1)', 'max_v': '(0.3)', 'vbin_size': '(0.07)'}), '(min_sep=5, max_sep=20, bin_size=0.1, min_u=0.2,\n max_u=0.9, ubin_size=0.03, min_v=0.1, max_v=0.3, vbin_size=0.07)\n', (7180, 7297), False, 'import treecorr\n'), ((7720, 7755), 'numpy.isclose', 'np.isclose', (['nnn.ubin_size', '(0.7 / 24)'], {}), '(nnn.ubin_size, 0.7 / 24)\n', (7730, 7755), True, 'import numpy as np\n'), ((7848, 7882), 'numpy.isclose', 'np.isclose', (['nnn.vbin_size', '(0.2 / 3)'], {}), '(nnn.vbin_size, 0.2 / 3)\n', (7858, 7882), True, 'import numpy as np\n'), ((7967, 8085), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': '(5)', 'max_sep': '(20)', 'bin_size': '(0.1)', 'min_u': '(0.2)', 'ubin_size': '(0.03)', 'min_v': '(0.2)', 'vbin_size': '(0.07)'}), '(min_sep=5, max_sep=20, bin_size=0.1, min_u=0.2,\n ubin_size=0.03, min_v=0.2, vbin_size=0.07)\n', (7990, 8085), False, 'import treecorr\n'), ((8417, 8452), 'numpy.isclose', 'np.isclose', (['nnn.ubin_size', '(0.8 / 27)'], {}), '(nnn.ubin_size, 0.8 / 27)\n', (8427, 8452), True, 'import numpy as np\n'), ((8545, 8580), 'numpy.isclose', 'np.isclose', (['nnn.vbin_size', '(0.8 / 12)'], {}), '(nnn.vbin_size, 0.8 / 12)\n', (8555, 8580), True, 'import numpy as np\n'), ((8611, 8729), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': '(5)', 'max_sep': '(20)', 'bin_size': '(0.1)', 'max_u': '(0.2)', 'ubin_size': '(0.03)', 'max_v': '(0.2)', 'vbin_size': '(0.07)'}), '(min_sep=5, max_sep=20, bin_size=0.1, max_u=0.2,\n ubin_size=0.03, max_v=0.2, vbin_size=0.07)\n', (8634, 8729), False, 'import treecorr\n'), ((9060, 9094), 'numpy.isclose', 'np.isclose', (['nnn.ubin_size', '(0.2 / 7)'], {}), '(nnn.ubin_size, 0.2 / 7)\n', (9070, 9094), True, 'import numpy as np\n'), ((9186, 9220), 'numpy.isclose', 'np.isclose', (['nnn.vbin_size', '(0.2 / 3)'], {}), '(nnn.vbin_size, 0.2 / 3)\n', (9196, 9220), True, 'import numpy as np\n'), ((9380, 9474), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': '(5)', 'max_sep': '(20)', 'bin_size': '(0.1)', 'ubin_size': '(0.3)', 'vbin_size': '(0.3)'}), '(min_sep=5, max_sep=20, bin_size=0.1, ubin_size=0.3,\n vbin_size=0.3)\n', (9403, 9474), False, 'import treecorr\n'), ((9860, 9891), 'numpy.isclose', 'np.isclose', (['nnn.ubin_size', '(0.25)'], {}), '(nnn.ubin_size, 0.25)\n', (9870, 9891), True, 'import numpy as np\n'), ((9984, 10015), 'numpy.isclose', 'np.isclose', (['nnn.vbin_size', '(0.25)'], {}), '(nnn.vbin_size, 0.25)\n', (9994, 10015), True, 'import numpy as np\n'), ((10117, 10202), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': '(5)', 'max_sep': '(20)', 'bin_size': '(0.1)', 'nubins': '(5)', 'nvbins': '(5)'}), '(min_sep=5, max_sep=20, bin_size=0.1, nubins=5, nvbins=5\n )\n', (10140, 10202), False, 'import treecorr\n'), ((10587, 10617), 'numpy.isclose', 'np.isclose', (['nnn.ubin_size', '(0.2)'], {}), '(nnn.ubin_size, 0.2)\n', (10597, 10617), True, 'import numpy as np\n'), ((10709, 10739), 'numpy.isclose', 'np.isclose', (['nnn.vbin_size', '(0.2)'], {}), '(nnn.vbin_size, 0.2)\n', (10719, 10739), True, 'import numpy as np\n'), ((10842, 10956), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': '(5)', 'max_sep': '(20)', 'bin_size': '(0.1)', 'ubin_size': '(0.1)', 'nubins': '(5)', 'vbin_size': '(0.1)', 'nvbins': '(5)'}), '(min_sep=5, max_sep=20, bin_size=0.1, ubin_size=0.1,\n nubins=5, vbin_size=0.1, nvbins=5)\n', (10865, 10956), False, 'import treecorr\n'), ((11381, 11407), 'numpy.isclose', 'np.isclose', (['nnn.min_u', '(0.5)'], {}), '(nnn.min_u, 0.5)\n', (11391, 11407), True, 'import numpy as np\n'), ((11504, 11530), 'numpy.isclose', 'np.isclose', (['nnn.max_v', '(0.5)'], {}), '(nnn.max_v, 0.5)\n', (11514, 11530), True, 'import numpy as np\n'), ((11557, 11606), 'test_helper.assert_raises', 'assert_raises', (['TypeError', 'treecorr.NNNCorrelation'], {}), '(TypeError, treecorr.NNNCorrelation)\n', (11570, 11606), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((11611, 11671), 'test_helper.assert_raises', 'assert_raises', (['TypeError', 'treecorr.NNNCorrelation'], {'min_sep': '(5)'}), '(TypeError, treecorr.NNNCorrelation, min_sep=5)\n', (11624, 11671), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((11676, 11737), 'test_helper.assert_raises', 'assert_raises', (['TypeError', 'treecorr.NNNCorrelation'], {'max_sep': '(20)'}), '(TypeError, treecorr.NNNCorrelation, max_sep=20)\n', (11689, 11737), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((11742, 11805), 'test_helper.assert_raises', 'assert_raises', (['TypeError', 'treecorr.NNNCorrelation'], {'bin_size': '(0.1)'}), '(TypeError, treecorr.NNNCorrelation, bin_size=0.1)\n', (11755, 11805), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((11810, 11869), 'test_helper.assert_raises', 'assert_raises', (['TypeError', 'treecorr.NNNCorrelation'], {'nbins': '(20)'}), '(TypeError, treecorr.NNNCorrelation, nbins=20)\n', (11823, 11869), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((11874, 11946), 'test_helper.assert_raises', 'assert_raises', (['TypeError', 'treecorr.NNNCorrelation'], {'min_sep': '(5)', 'max_sep': '(20)'}), '(TypeError, treecorr.NNNCorrelation, min_sep=5, max_sep=20)\n', (11887, 11946), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((11951, 12025), 'test_helper.assert_raises', 'assert_raises', (['TypeError', 'treecorr.NNNCorrelation'], {'min_sep': '(5)', 'bin_size': '(0.1)'}), '(TypeError, treecorr.NNNCorrelation, min_sep=5, bin_size=0.1)\n', (11964, 12025), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((12030, 12100), 'test_helper.assert_raises', 'assert_raises', (['TypeError', 'treecorr.NNNCorrelation'], {'min_sep': '(5)', 'nbins': '(20)'}), '(TypeError, treecorr.NNNCorrelation, min_sep=5, nbins=20)\n', (12043, 12100), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((12105, 12180), 'test_helper.assert_raises', 'assert_raises', (['TypeError', 'treecorr.NNNCorrelation'], {'max_sep': '(20)', 'bin_size': '(0.1)'}), '(TypeError, treecorr.NNNCorrelation, max_sep=20, bin_size=0.1)\n', (12118, 12180), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((12185, 12256), 'test_helper.assert_raises', 'assert_raises', (['TypeError', 'treecorr.NNNCorrelation'], {'max_sep': '(20)', 'nbins': '(20)'}), '(TypeError, treecorr.NNNCorrelation, max_sep=20, nbins=20)\n', (12198, 12256), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((12261, 12334), 'test_helper.assert_raises', 'assert_raises', (['TypeError', 'treecorr.NNNCorrelation'], {'bin_size': '(0.1)', 'nbins': '(20)'}), '(TypeError, treecorr.NNNCorrelation, bin_size=0.1, nbins=20)\n', (12274, 12334), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((12339, 12439), 'test_helper.assert_raises', 'assert_raises', (['TypeError', 'treecorr.NNNCorrelation'], {'min_sep': '(5)', 'max_sep': '(20)', 'bin_size': '(0.1)', 'nbins': '(20)'}), '(TypeError, treecorr.NNNCorrelation, min_sep=5, max_sep=20,\n bin_size=0.1, nbins=20)\n', (12352, 12439), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((12440, 12531), 'test_helper.assert_raises', 'assert_raises', (['ValueError', 'treecorr.NNNCorrelation'], {'min_sep': '(20)', 'max_sep': '(5)', 'bin_size': '(0.1)'}), '(ValueError, treecorr.NNNCorrelation, min_sep=20, max_sep=5,\n bin_size=0.1)\n', (12453, 12531), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((12532, 12619), 'test_helper.assert_raises', 'assert_raises', (['ValueError', 'treecorr.NNNCorrelation'], {'min_sep': '(20)', 'max_sep': '(5)', 'nbins': '(20)'}), '(ValueError, treecorr.NNNCorrelation, min_sep=20, max_sep=5,\n nbins=20)\n', (12545, 12619), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((12620, 12723), 'test_helper.assert_raises', 'assert_raises', (['ValueError', 'treecorr.NNNCorrelation'], {'min_sep': '(20)', 'max_sep': '(5)', 'nbins': '(20)', 'bin_type': '"""Log"""'}), "(ValueError, treecorr.NNNCorrelation, min_sep=20, max_sep=5,\n nbins=20, bin_type='Log')\n", (12633, 12723), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((12742, 12848), 'test_helper.assert_raises', 'assert_raises', (['ValueError', 'treecorr.NNNCorrelation'], {'min_sep': '(20)', 'max_sep': '(5)', 'nbins': '(20)', 'bin_type': '"""Linear"""'}), "(ValueError, treecorr.NNNCorrelation, min_sep=20, max_sep=5,\n nbins=20, bin_type='Linear')\n", (12755, 12848), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((12867, 12971), 'test_helper.assert_raises', 'assert_raises', (['ValueError', 'treecorr.NNNCorrelation'], {'min_sep': '(20)', 'max_sep': '(5)', 'nbins': '(20)', 'bin_type': '"""TwoD"""'}), "(ValueError, treecorr.NNNCorrelation, min_sep=20, max_sep=5,\n nbins=20, bin_type='TwoD')\n", (12880, 12971), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((12990, 13097), 'test_helper.assert_raises', 'assert_raises', (['ValueError', 'treecorr.NNNCorrelation'], {'min_sep': '(20)', 'max_sep': '(5)', 'nbins': '(20)', 'bin_type': '"""Invalid"""'}), "(ValueError, treecorr.NNNCorrelation, min_sep=20, max_sep=5,\n nbins=20, bin_type='Invalid')\n", (13003, 13097), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((13116, 13253), 'test_helper.assert_raises', 'assert_raises', (['TypeError', 'treecorr.NNNCorrelation'], {'min_sep': '(5)', 'max_sep': '(20)', 'bin_size': '(0.1)', 'min_u': '(0.3)', 'max_u': '(0.9)', 'ubin_size': '(0.1)', 'nubins': '(6)'}), '(TypeError, treecorr.NNNCorrelation, min_sep=5, max_sep=20,\n bin_size=0.1, min_u=0.3, max_u=0.9, ubin_size=0.1, nubins=6)\n', (13129, 13253), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((13272, 13385), 'test_helper.assert_raises', 'assert_raises', (['ValueError', 'treecorr.NNNCorrelation'], {'min_sep': '(5)', 'max_sep': '(20)', 'bin_size': '(0.1)', 'min_u': '(0.9)', 'max_u': '(0.3)'}), '(ValueError, treecorr.NNNCorrelation, min_sep=5, max_sep=20,\n bin_size=0.1, min_u=0.9, max_u=0.3)\n', (13285, 13385), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((13404, 13518), 'test_helper.assert_raises', 'assert_raises', (['ValueError', 'treecorr.NNNCorrelation'], {'min_sep': '(5)', 'max_sep': '(20)', 'bin_size': '(0.1)', 'min_u': '(-0.1)', 'max_u': '(0.3)'}), '(ValueError, treecorr.NNNCorrelation, min_sep=5, max_sep=20,\n bin_size=0.1, min_u=-0.1, max_u=0.3)\n', (13417, 13518), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((13537, 13650), 'test_helper.assert_raises', 'assert_raises', (['ValueError', 'treecorr.NNNCorrelation'], {'min_sep': '(5)', 'max_sep': '(20)', 'bin_size': '(0.1)', 'min_u': '(0.1)', 'max_u': '(1.3)'}), '(ValueError, treecorr.NNNCorrelation, min_sep=5, max_sep=20,\n bin_size=0.1, min_u=0.1, max_u=1.3)\n', (13550, 13650), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((13669, 13806), 'test_helper.assert_raises', 'assert_raises', (['TypeError', 'treecorr.NNNCorrelation'], {'min_sep': '(5)', 'max_sep': '(20)', 'bin_size': '(0.1)', 'min_v': '(0.1)', 'max_v': '(0.9)', 'vbin_size': '(0.1)', 'nvbins': '(9)'}), '(TypeError, treecorr.NNNCorrelation, min_sep=5, max_sep=20,\n bin_size=0.1, min_v=0.1, max_v=0.9, vbin_size=0.1, nvbins=9)\n', (13682, 13806), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((13825, 13938), 'test_helper.assert_raises', 'assert_raises', (['ValueError', 'treecorr.NNNCorrelation'], {'min_sep': '(5)', 'max_sep': '(20)', 'bin_size': '(0.1)', 'min_v': '(0.9)', 'max_v': '(0.3)'}), '(ValueError, treecorr.NNNCorrelation, min_sep=5, max_sep=20,\n bin_size=0.1, min_v=0.9, max_v=0.3)\n', (13838, 13938), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((13957, 14071), 'test_helper.assert_raises', 'assert_raises', (['ValueError', 'treecorr.NNNCorrelation'], {'min_sep': '(5)', 'max_sep': '(20)', 'bin_size': '(0.1)', 'min_v': '(-0.1)', 'max_v': '(0.3)'}), '(ValueError, treecorr.NNNCorrelation, min_sep=5, max_sep=20,\n bin_size=0.1, min_v=-0.1, max_v=0.3)\n', (13970, 14071), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((14090, 14203), 'test_helper.assert_raises', 'assert_raises', (['ValueError', 'treecorr.NNNCorrelation'], {'min_sep': '(5)', 'max_sep': '(20)', 'bin_size': '(0.1)', 'min_v': '(0.1)', 'max_v': '(1.3)'}), '(ValueError, treecorr.NNNCorrelation, min_sep=5, max_sep=20,\n bin_size=0.1, min_v=0.1, max_v=1.3)\n', (14103, 14203), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((14222, 14333), 'test_helper.assert_raises', 'assert_raises', (['ValueError', 'treecorr.NNNCorrelation'], {'min_sep': '(20)', 'max_sep': '(5)', 'nbins': '(20)', 'split_method': '"""invalid"""'}), "(ValueError, treecorr.NNNCorrelation, min_sep=20, max_sep=5,\n nbins=20, split_method='invalid')\n", (14235, 14333), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((14406, 14483), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': '(5)', 'max_sep': '(20)', 'nbins': '(20)', 'sep_units': '"""radians"""'}), "(min_sep=5, max_sep=20, nbins=20, sep_units='radians')\n", (14429, 14483), False, 'import treecorr\n'), ((14661, 14709), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.min_sep', '(5.0)'], {}), '(nnn.min_sep, 5.0)\n', (14691, 14709), True, 'import numpy as np\n'), ((14713, 14762), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.max_sep', '(20.0)'], {}), '(nnn.max_sep, 20.0)\n', (14743, 14762), True, 'import numpy as np\n'), ((14766, 14815), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn._min_sep', '(5.0)'], {}), '(nnn._min_sep, 5.0)\n', (14796, 14815), True, 'import numpy as np\n'), ((14819, 14869), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn._max_sep', '(20.0)'], {}), '(nnn._max_sep, 20.0)\n', (14849, 14869), True, 'import numpy as np\n'), ((15026, 15102), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': '(5)', 'max_sep': '(20)', 'nbins': '(20)', 'sep_units': '"""arcsec"""'}), "(min_sep=5, max_sep=20, nbins=20, sep_units='arcsec')\n", (15049, 15102), False, 'import treecorr\n'), ((15280, 15328), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.min_sep', '(5.0)'], {}), '(nnn.min_sep, 5.0)\n', (15310, 15328), True, 'import numpy as np\n'), ((15332, 15381), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.max_sep', '(20.0)'], {}), '(nnn.max_sep, 20.0)\n', (15362, 15381), True, 'import numpy as np\n'), ((15385, 15457), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn._min_sep', '(5.0 * math.pi / 180 / 3600)'], {}), '(nnn._min_sep, 5.0 * math.pi / 180 / 3600)\n', (15415, 15457), True, 'import numpy as np\n'), ((15457, 15530), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn._max_sep', '(20.0 * math.pi / 180 / 3600)'], {}), '(nnn._max_sep, 20.0 * math.pi / 180 / 3600)\n', (15487, 15530), True, 'import numpy as np\n'), ((15960, 16036), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': '(5)', 'max_sep': '(20)', 'nbins': '(20)', 'sep_units': '"""arcmin"""'}), "(min_sep=5, max_sep=20, nbins=20, sep_units='arcmin')\n", (15983, 16036), False, 'import treecorr\n'), ((16214, 16262), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.min_sep', '(5.0)'], {}), '(nnn.min_sep, 5.0)\n', (16244, 16262), True, 'import numpy as np\n'), ((16266, 16315), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.max_sep', '(20.0)'], {}), '(nnn.max_sep, 20.0)\n', (16296, 16315), True, 'import numpy as np\n'), ((16319, 16389), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn._min_sep', '(5.0 * math.pi / 180 / 60)'], {}), '(nnn._min_sep, 5.0 * math.pi / 180 / 60)\n', (16349, 16389), True, 'import numpy as np\n'), ((16389, 16460), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn._max_sep', '(20.0 * math.pi / 180 / 60)'], {}), '(nnn._max_sep, 20.0 * math.pi / 180 / 60)\n', (16419, 16460), True, 'import numpy as np\n'), ((16829, 16906), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': '(5)', 'max_sep': '(20)', 'nbins': '(20)', 'sep_units': '"""degrees"""'}), "(min_sep=5, max_sep=20, nbins=20, sep_units='degrees')\n", (16852, 16906), False, 'import treecorr\n'), ((17084, 17132), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.min_sep', '(5.0)'], {}), '(nnn.min_sep, 5.0)\n', (17114, 17132), True, 'import numpy as np\n'), ((17136, 17185), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.max_sep', '(20.0)'], {}), '(nnn.max_sep, 20.0)\n', (17166, 17185), True, 'import numpy as np\n'), ((17189, 17254), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn._min_sep', '(5.0 * math.pi / 180)'], {}), '(nnn._min_sep, 5.0 * math.pi / 180)\n', (17219, 17254), True, 'import numpy as np\n'), ((17256, 17322), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn._max_sep', '(20.0 * math.pi / 180)'], {}), '(nnn._max_sep, 20.0 * math.pi / 180)\n', (17286, 17322), True, 'import numpy as np\n'), ((17691, 17766), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': '(5)', 'max_sep': '(20)', 'nbins': '(20)', 'sep_units': '"""hours"""'}), "(min_sep=5, max_sep=20, nbins=20, sep_units='hours')\n", (17714, 17766), False, 'import treecorr\n'), ((17944, 17992), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.min_sep', '(5.0)'], {}), '(nnn.min_sep, 5.0)\n', (17974, 17992), True, 'import numpy as np\n'), ((17996, 18045), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.max_sep', '(20.0)'], {}), '(nnn.max_sep, 20.0)\n', (18026, 18045), True, 'import numpy as np\n'), ((18049, 18113), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn._min_sep', '(5.0 * math.pi / 12)'], {}), '(nnn._min_sep, 5.0 * math.pi / 12)\n', (18079, 18113), True, 'import numpy as np\n'), ((18115, 18180), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn._max_sep', '(20.0 * math.pi / 12)'], {}), '(nnn._max_sep, 20.0 * math.pi / 12)\n', (18145, 18180), True, 'import numpy as np\n'), ((18592, 18732), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': '(5)', 'nbins': '(14)', 'bin_size': '(0.1)', 'min_u': '(0.0)', 'max_u': '(0.9)', 'ubin_size': '(0.03)', 'min_v': '(0.0)', 'max_v': '(0.21)', 'vbin_size': '(0.07)'}), '(min_sep=5, nbins=14, bin_size=0.1, min_u=0.0, max_u\n =0.9, ubin_size=0.03, min_v=0.0, max_v=0.21, vbin_size=0.07)\n', (18615, 18732), False, 'import treecorr\n'), ((18977, 19008), 'numpy.isclose', 'np.isclose', (['nnn.ubin_size', '(0.03)'], {}), '(nnn.ubin_size, 0.03)\n', (18987, 19008), True, 'import numpy as np\n'), ((19020, 19051), 'numpy.isclose', 'np.isclose', (['nnn.vbin_size', '(0.07)'], {}), '(nnn.vbin_size, 0.07)\n', (19030, 19051), True, 'import numpy as np\n'), ((19056, 19098), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.b', '(0.1)'], {}), '(nnn.b, 0.1)\n', (19086, 19098), True, 'import numpy as np\n'), ((19103, 19147), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.bu', '(0.03)'], {}), '(nnn.bu, 0.03)\n', (19133, 19147), True, 'import numpy as np\n'), ((19152, 19196), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.bv', '(0.07)'], {}), '(nnn.bv, 0.07)\n', (19182, 19196), True, 'import numpy as np\n'), ((19263, 19421), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': '(5)', 'nbins': '(14)', 'bin_size': '(0.1)', 'bin_slop': '(1.0)', 'min_u': '(0.0)', 'max_u': '(0.9)', 'ubin_size': '(0.03)', 'min_v': '(0.0)', 'max_v': '(0.21)', 'vbin_size': '(0.07)'}), '(min_sep=5, nbins=14, bin_size=0.1, bin_slop=1.0,\n min_u=0.0, max_u=0.9, ubin_size=0.03, min_v=0.0, max_v=0.21, vbin_size=0.07\n )\n', (19286, 19421), False, 'import treecorr\n'), ((19662, 19693), 'numpy.isclose', 'np.isclose', (['nnn.ubin_size', '(0.03)'], {}), '(nnn.ubin_size, 0.03)\n', (19672, 19693), True, 'import numpy as np\n'), ((19705, 19736), 'numpy.isclose', 'np.isclose', (['nnn.vbin_size', '(0.07)'], {}), '(nnn.vbin_size, 0.07)\n', (19715, 19736), True, 'import numpy as np\n'), ((19741, 19783), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.b', '(0.1)'], {}), '(nnn.b, 0.1)\n', (19771, 19783), True, 'import numpy as np\n'), ((19788, 19832), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.bu', '(0.03)'], {}), '(nnn.bu, 0.03)\n', (19818, 19832), True, 'import numpy as np\n'), ((19837, 19881), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.bv', '(0.07)'], {}), '(nnn.bv, 0.07)\n', (19867, 19881), True, 'import numpy as np\n'), ((19922, 20080), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': '(5)', 'nbins': '(14)', 'bin_size': '(0.1)', 'bin_slop': '(0.2)', 'min_u': '(0.0)', 'max_u': '(0.9)', 'ubin_size': '(0.03)', 'min_v': '(0.0)', 'max_v': '(0.21)', 'vbin_size': '(0.07)'}), '(min_sep=5, nbins=14, bin_size=0.1, bin_slop=0.2,\n min_u=0.0, max_u=0.9, ubin_size=0.03, min_v=0.0, max_v=0.21, vbin_size=0.07\n )\n', (19945, 20080), False, 'import treecorr\n'), ((20321, 20352), 'numpy.isclose', 'np.isclose', (['nnn.ubin_size', '(0.03)'], {}), '(nnn.ubin_size, 0.03)\n', (20331, 20352), True, 'import numpy as np\n'), ((20364, 20395), 'numpy.isclose', 'np.isclose', (['nnn.vbin_size', '(0.07)'], {}), '(nnn.vbin_size, 0.07)\n', (20374, 20395), True, 'import numpy as np\n'), ((20400, 20443), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.b', '(0.02)'], {}), '(nnn.b, 0.02)\n', (20430, 20443), True, 'import numpy as np\n'), ((20448, 20493), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.bu', '(0.006)'], {}), '(nnn.bu, 0.006)\n', (20478, 20493), True, 'import numpy as np\n'), ((20498, 20543), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.bv', '(0.014)'], {}), '(nnn.bv, 0.014)\n', (20528, 20543), True, 'import numpy as np\n'), ((20579, 20737), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': '(5)', 'nbins': '(14)', 'bin_size': '(0.1)', 'bin_slop': '(0.0)', 'min_u': '(0.0)', 'max_u': '(0.9)', 'ubin_size': '(0.03)', 'min_v': '(0.0)', 'max_v': '(0.21)', 'vbin_size': '(0.07)'}), '(min_sep=5, nbins=14, bin_size=0.1, bin_slop=0.0,\n min_u=0.0, max_u=0.9, ubin_size=0.03, min_v=0.0, max_v=0.21, vbin_size=0.07\n )\n', (20602, 20737), False, 'import treecorr\n'), ((20978, 21009), 'numpy.isclose', 'np.isclose', (['nnn.ubin_size', '(0.03)'], {}), '(nnn.ubin_size, 0.03)\n', (20988, 21009), True, 'import numpy as np\n'), ((21021, 21052), 'numpy.isclose', 'np.isclose', (['nnn.vbin_size', '(0.07)'], {}), '(nnn.vbin_size, 0.07)\n', (21031, 21052), True, 'import numpy as np\n'), ((21057, 21099), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.b', '(0.0)'], {}), '(nnn.b, 0.0)\n', (21087, 21099), True, 'import numpy as np\n'), ((21104, 21147), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.bu', '(0.0)'], {}), '(nnn.bu, 0.0)\n', (21134, 21147), True, 'import numpy as np\n'), ((21152, 21195), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.bv', '(0.0)'], {}), '(nnn.bv, 0.0)\n', (21182, 21195), True, 'import numpy as np\n'), ((21229, 21398), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': '(5)', 'nbins': '(14)', 'bin_size': '(0.1)', 'bin_slop': '(2.0)', 'min_u': '(0.0)', 'max_u': '(0.9)', 'ubin_size': '(0.03)', 'min_v': '(0.0)', 'max_v': '(0.21)', 'vbin_size': '(0.07)', 'verbose': '(0)'}), '(min_sep=5, nbins=14, bin_size=0.1, bin_slop=2.0,\n min_u=0.0, max_u=0.9, ubin_size=0.03, min_v=0.0, max_v=0.21, vbin_size=\n 0.07, verbose=0)\n', (21252, 21398), False, 'import treecorr\n'), ((21639, 21670), 'numpy.isclose', 'np.isclose', (['nnn.ubin_size', '(0.03)'], {}), '(nnn.ubin_size, 0.03)\n', (21649, 21670), True, 'import numpy as np\n'), ((21682, 21713), 'numpy.isclose', 'np.isclose', (['nnn.vbin_size', '(0.07)'], {}), '(nnn.vbin_size, 0.07)\n', (21692, 21713), True, 'import numpy as np\n'), ((21718, 21760), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.b', '(0.2)'], {}), '(nnn.b, 0.2)\n', (21748, 21760), True, 'import numpy as np\n'), ((21765, 21809), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.bu', '(0.06)'], {}), '(nnn.bu, 0.06)\n', (21795, 21809), True, 'import numpy as np\n'), ((21814, 21858), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.bv', '(0.14)'], {}), '(nnn.bv, 0.14)\n', (21844, 21858), True, 'import numpy as np\n'), ((21932, 22101), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': '(5)', 'nbins': '(14)', 'bin_size': '(0.4)', 'bin_slop': '(1.0)', 'min_u': '(0.0)', 'max_u': '(0.9)', 'ubin_size': '(0.03)', 'min_v': '(0.0)', 'max_v': '(0.21)', 'vbin_size': '(0.07)', 'verbose': '(0)'}), '(min_sep=5, nbins=14, bin_size=0.4, bin_slop=1.0,\n min_u=0.0, max_u=0.9, ubin_size=0.03, min_v=0.0, max_v=0.21, vbin_size=\n 0.07, verbose=0)\n', (21955, 22101), False, 'import treecorr\n'), ((22342, 22373), 'numpy.isclose', 'np.isclose', (['nnn.ubin_size', '(0.03)'], {}), '(nnn.ubin_size, 0.03)\n', (22352, 22373), True, 'import numpy as np\n'), ((22385, 22416), 'numpy.isclose', 'np.isclose', (['nnn.vbin_size', '(0.07)'], {}), '(nnn.vbin_size, 0.07)\n', (22395, 22416), True, 'import numpy as np\n'), ((22421, 22463), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.b', '(0.4)'], {}), '(nnn.b, 0.4)\n', (22451, 22463), True, 'import numpy as np\n'), ((22468, 22512), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.bu', '(0.03)'], {}), '(nnn.bu, 0.03)\n', (22498, 22512), True, 'import numpy as np\n'), ((22517, 22561), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.bv', '(0.07)'], {}), '(nnn.bv, 0.07)\n', (22547, 22561), True, 'import numpy as np\n'), ((22628, 22768), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': '(5)', 'nbins': '(14)', 'bin_size': '(0.4)', 'min_u': '(0.0)', 'max_u': '(0.9)', 'ubin_size': '(0.03)', 'min_v': '(0.0)', 'max_v': '(0.21)', 'vbin_size': '(0.07)'}), '(min_sep=5, nbins=14, bin_size=0.4, min_u=0.0, max_u\n =0.9, ubin_size=0.03, min_v=0.0, max_v=0.21, vbin_size=0.07)\n', (22651, 22768), False, 'import treecorr\n'), ((22982, 23013), 'numpy.isclose', 'np.isclose', (['nnn.ubin_size', '(0.03)'], {}), '(nnn.ubin_size, 0.03)\n', (22992, 23013), True, 'import numpy as np\n'), ((23025, 23056), 'numpy.isclose', 'np.isclose', (['nnn.vbin_size', '(0.07)'], {}), '(nnn.vbin_size, 0.07)\n', (23035, 23056), True, 'import numpy as np\n'), ((23061, 23103), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.b', '(0.1)'], {}), '(nnn.b, 0.1)\n', (23091, 23103), True, 'import numpy as np\n'), ((23108, 23152), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.bu', '(0.03)'], {}), '(nnn.bu, 0.03)\n', (23138, 23152), True, 'import numpy as np\n'), ((23157, 23201), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.bv', '(0.07)'], {}), '(nnn.bv, 0.07)\n', (23187, 23201), True, 'import numpy as np\n'), ((23206, 23256), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.bin_slop', '(0.25)'], {}), '(nnn.bin_slop, 0.25)\n', (23236, 23256), True, 'import numpy as np\n'), ((23318, 23457), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': '(5)', 'nbins': '(14)', 'bin_size': '(0.05)', 'min_u': '(0.0)', 'max_u': '(0.9)', 'ubin_size': '(0.3)', 'min_v': '(0.0)', 'max_v': '(0.17)', 'vbin_size': '(0.17)'}), '(min_sep=5, nbins=14, bin_size=0.05, min_u=0.0,\n max_u=0.9, ubin_size=0.3, min_v=0.0, max_v=0.17, vbin_size=0.17)\n', (23341, 23457), False, 'import treecorr\n'), ((23673, 23703), 'numpy.isclose', 'np.isclose', (['nnn.ubin_size', '(0.3)'], {}), '(nnn.ubin_size, 0.3)\n', (23683, 23703), True, 'import numpy as np\n'), ((23715, 23746), 'numpy.isclose', 'np.isclose', (['nnn.vbin_size', '(0.17)'], {}), '(nnn.vbin_size, 0.17)\n', (23725, 23746), True, 'import numpy as np\n'), ((23751, 23794), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.b', '(0.05)'], {}), '(nnn.b, 0.05)\n', (23781, 23794), True, 'import numpy as np\n'), ((23799, 23842), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.bu', '(0.1)'], {}), '(nnn.bu, 0.1)\n', (23829, 23842), True, 'import numpy as np\n'), ((23847, 23890), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.bv', '(0.1)'], {}), '(nnn.bv, 0.1)\n', (23877, 23890), True, 'import numpy as np\n'), ((23895, 23944), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.bin_slop', '(1.0)'], {}), '(nnn.bin_slop, 1.0)\n', (23925, 23944), True, 'import numpy as np\n'), ((24243, 24273), 'numpy.random.RandomState', 'np.random.RandomState', (['(8675309)'], {}), '(8675309)\n', (24264, 24273), True, 'import numpy as np\n'), ((24352, 24378), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'x': 'x', 'y': 'y'}), '(x=x, y=y)\n', (24368, 24378), False, 'import treecorr\n'), ((24541, 24724), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'brute': '(True)', 'verbose': '(1)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, brute=True, verbose=1)\n', (24564, 24724), False, 'import treecorr\n'), ((24859, 24874), 'numpy.log', 'np.log', (['min_sep'], {}), '(min_sep)\n', (24865, 24874), True, 'import numpy as np\n'), ((24893, 24908), 'numpy.log', 'np.log', (['max_sep'], {}), '(max_sep)\n', (24899, 24908), True, 'import numpy as np\n'), ((24925, 24962), 'numpy.zeros', 'np.zeros', (['(nbins, nubins, 2 * nvbins)'], {}), '((nbins, nubins, 2 * nvbins))\n', (24933, 24962), True, 'import numpy as np\n'), ((27258, 27300), 'numpy.where', 'np.where', (['((ddd.ntri > 0) | (true_ntri > 0))'], {}), '((ddd.ntri > 0) | (true_ntri > 0))\n', (27266, 27300), True, 'import numpy as np\n'), ((27665, 27715), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.ntri', 'true_ntri'], {}), '(ddd.ntri, true_ntri)\n', (27694, 27715), True, 'import numpy as np\n'), ((27796, 27839), 'os.path.join', 'os.path.join', (['"""data"""', '"""nnn_direct_data.dat"""'], {}), "('data', 'nnn_direct_data.dat')\n", (27808, 27839), False, 'import os\n'), ((28089, 28117), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'x': 'rx', 'y': 'ry'}), '(x=rx, y=ry)\n', (28105, 28117), False, 'import treecorr\n'), ((28139, 28182), 'os.path.join', 'os.path.join', (['"""data"""', '"""nnn_direct_rand.dat"""'], {}), "('data', 'nnn_direct_rand.dat')\n", (28151, 28182), False, 'import os\n'), ((28321, 28513), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'brute': '(True)', 'verbose': '(0)', 'rng': 'rng'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, brute=True, verbose=0, rng=rng)\n', (28344, 28513), False, 'import treecorr\n'), ((28843, 28897), 'treecorr.config.read_config', 'treecorr.config.read_config', (['"""configs/nnn_direct.yaml"""'], {}), "('configs/nnn_direct.yaml')\n", (28870, 28897), False, 'import treecorr\n'), ((28911, 28942), 'treecorr.config.setup_logger', 'treecorr.config.setup_logger', (['(0)'], {}), '(0)\n', (28939, 28942), False, 'import treecorr\n'), ((28947, 28977), 'treecorr.corr3', 'treecorr.corr3', (['config', 'logger'], {}), '(config, logger)\n', (28961, 28977), False, 'import treecorr\n'), ((30967, 30991), 'test_helper.get_script_name', 'get_script_name', (['"""corr3"""'], {}), "('corr3')\n", (30982, 30991), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((31000, 31069), 'subprocess.Popen', 'subprocess.Popen', (["[corr3_exe, 'configs/nnn_direct.yaml', 'verbose=0']"], {}), "([corr3_exe, 'configs/nnn_direct.yaml', 'verbose=0'])\n", (31016, 31069), False, 'import subprocess\n'), ((31348, 31531), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'brute': '(True)', 'verbose': '(0)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, brute=True, verbose=0)\n', (31371, 31531), False, 'import treecorr\n'), ((31636, 31819), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'brute': '(True)', 'verbose': '(0)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, brute=True, verbose=0)\n', (31659, 31819), False, 'import treecorr\n'), ((32068, 32098), 'treecorr.corr3', 'treecorr.corr3', (['config', 'logger'], {}), '(config, logger)\n', (32082, 32098), False, 'import treecorr\n'), ((33380, 33563), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'bin_slop': '(0)', 'verbose': '(1)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, bin_slop=0, verbose=1)\n', (33403, 33563), False, 'import treecorr\n'), ((33799, 33849), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.ntri', 'true_ntri'], {}), '(ddd.ntri, true_ntri)\n', (33828, 33849), True, 'import numpy as np\n'), ((33905, 34099), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'bin_slop': '(0)', 'verbose': '(1)', 'max_top': '(0)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, bin_slop=0, verbose=1, max_top=0)\n', (33928, 34099), False, 'import treecorr\n'), ((34335, 34385), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.ntri', 'true_ntri'], {}), '(ddd.ntri, true_ntri)\n', (34364, 34385), True, 'import numpy as np\n'), ((34684, 34738), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.ntri', '(6 * true_ntri)'], {}), '(ddd.ntri, 6 * true_ntri)\n', (34713, 34738), True, 'import numpy as np\n'), ((34894, 35093), 'treecorr.NNNCrossCorrelation', 'treecorr.NNNCrossCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'bin_slop': '(0)', 'verbose': '(1)', 'max_top': '(0)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, bin_slop=0, verbose=1, max_top=0)\n', (34922, 35093), False, 'import treecorr\n'), ((35670, 35724), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.ntri', '(3 * true_ntri)'], {}), '(ddd.ntri, 3 * true_ntri)\n', (35699, 35724), True, 'import numpy as np\n'), ((36447, 36469), 'treecorr.corr3', 'treecorr.corr3', (['config'], {}), '(config)\n', (36461, 36469), False, 'import treecorr\n'), ((36481, 36546), 'numpy.genfromtxt', 'np.genfromtxt', (["config['nnn_file_name']"], {'names': '(True)', 'skip_header': '(1)'}), "(config['nnn_file_name'], names=True, skip_header=1)\n", (36494, 36546), True, 'import numpy as np\n'), ((36728, 36742), 'test_helper.do_pickle', 'do_pickle', (['ddd'], {}), '(ddd)\n', (36737, 36742), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((36786, 36837), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd2.ntri', '(2 * ddd.ntri)'], {}), '(ddd2.ntri, 2 * ddd.ntri)\n', (36812, 36837), True, 'import numpy as np\n'), ((36840, 36895), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd2.weight', '(2 * ddd.weight)'], {}), '(ddd2.weight, 2 * ddd.weight)\n', (36866, 36895), True, 'import numpy as np\n'), ((36898, 36953), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd2.meand1', '(2 * ddd.meand1)'], {}), '(ddd2.meand1, 2 * ddd.meand1)\n', (36924, 36953), True, 'import numpy as np\n'), ((36956, 37011), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd2.meand2', '(2 * ddd.meand2)'], {}), '(ddd2.meand2, 2 * ddd.meand2)\n', (36982, 37011), True, 'import numpy as np\n'), ((37014, 37069), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd2.meand3', '(2 * ddd.meand3)'], {}), '(ddd2.meand3, 2 * ddd.meand3)\n', (37040, 37069), True, 'import numpy as np\n'), ((37072, 37133), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd2.meanlogd1', '(2 * ddd.meanlogd1)'], {}), '(ddd2.meanlogd1, 2 * ddd.meanlogd1)\n', (37098, 37133), True, 'import numpy as np\n'), ((37136, 37197), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd2.meanlogd2', '(2 * ddd.meanlogd2)'], {}), '(ddd2.meanlogd2, 2 * ddd.meanlogd2)\n', (37162, 37197), True, 'import numpy as np\n'), ((37200, 37261), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd2.meanlogd3', '(2 * ddd.meanlogd3)'], {}), '(ddd2.meanlogd3, 2 * ddd.meanlogd3)\n', (37226, 37261), True, 'import numpy as np\n'), ((37264, 37317), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd2.meanu', '(2 * ddd.meanu)'], {}), '(ddd2.meanu, 2 * ddd.meanu)\n', (37290, 37317), True, 'import numpy as np\n'), ((37320, 37373), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd2.meanv', '(2 * ddd.meanv)'], {}), '(ddd2.meanv, 2 * ddd.meanv)\n', (37346, 37373), True, 'import numpy as np\n'), ((37410, 37457), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd2.ntri', 'ddd.ntri'], {}), '(ddd2.ntri, ddd.ntri)\n', (37436, 37457), True, 'import numpy as np\n'), ((37462, 37513), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd2.weight', 'ddd.weight'], {}), '(ddd2.weight, ddd.weight)\n', (37488, 37513), True, 'import numpy as np\n'), ((37518, 37569), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd2.meand1', 'ddd.meand1'], {}), '(ddd2.meand1, ddd.meand1)\n', (37544, 37569), True, 'import numpy as np\n'), ((37574, 37625), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd2.meand2', 'ddd.meand2'], {}), '(ddd2.meand2, ddd.meand2)\n', (37600, 37625), True, 'import numpy as np\n'), ((37630, 37681), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd2.meand3', 'ddd.meand3'], {}), '(ddd2.meand3, ddd.meand3)\n', (37656, 37681), True, 'import numpy as np\n'), ((37686, 37743), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd2.meanlogd1', 'ddd.meanlogd1'], {}), '(ddd2.meanlogd1, ddd.meanlogd1)\n', (37712, 37743), True, 'import numpy as np\n'), ((37748, 37805), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd2.meanlogd2', 'ddd.meanlogd2'], {}), '(ddd2.meanlogd2, ddd.meanlogd2)\n', (37774, 37805), True, 'import numpy as np\n'), ((37810, 37867), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd2.meanlogd3', 'ddd.meanlogd3'], {}), '(ddd2.meanlogd3, ddd.meanlogd3)\n', (37836, 37867), True, 'import numpy as np\n'), ((37872, 37921), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd2.meanu', 'ddd.meanu'], {}), '(ddd2.meanu, ddd.meanu)\n', (37898, 37921), True, 'import numpy as np\n'), ((37926, 37975), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd2.meanv', 'ddd.meanv'], {}), '(ddd2.meanv, ddd.meanv)\n', (37952, 37975), True, 'import numpy as np\n'), ((38068, 38228), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins)\n', (38091, 38228), False, 'import treecorr\n'), ((38321, 38368), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd3.ntri', 'ddd.ntri'], {}), '(ddd3.ntri, ddd.ntri)\n', (38347, 38368), True, 'import numpy as np\n'), ((38373, 38424), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd3.weight', 'ddd.weight'], {}), '(ddd3.weight, ddd.weight)\n', (38399, 38424), True, 'import numpy as np\n'), ((38429, 38480), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd3.meand1', 'ddd.meand1'], {}), '(ddd3.meand1, ddd.meand1)\n', (38455, 38480), True, 'import numpy as np\n'), ((38485, 38536), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd3.meand2', 'ddd.meand2'], {}), '(ddd3.meand2, ddd.meand2)\n', (38511, 38536), True, 'import numpy as np\n'), ((38541, 38592), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd3.meand3', 'ddd.meand3'], {}), '(ddd3.meand3, ddd.meand3)\n', (38567, 38592), True, 'import numpy as np\n'), ((38597, 38654), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd3.meanlogd1', 'ddd.meanlogd1'], {}), '(ddd3.meanlogd1, ddd.meanlogd1)\n', (38623, 38654), True, 'import numpy as np\n'), ((38659, 38716), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd3.meanlogd2', 'ddd.meanlogd2'], {}), '(ddd3.meanlogd2, ddd.meanlogd2)\n', (38685, 38716), True, 'import numpy as np\n'), ((38721, 38778), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd3.meanlogd3', 'ddd.meanlogd3'], {}), '(ddd3.meanlogd3, ddd.meanlogd3)\n', (38747, 38778), True, 'import numpy as np\n'), ((38783, 38832), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd3.meanu', 'ddd.meanu'], {}), '(ddd3.meanu, ddd.meanu)\n', (38809, 38832), True, 'import numpy as np\n'), ((38837, 38886), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd3.meanv', 'ddd.meanv'], {}), '(ddd3.meanv, ddd.meanv)\n', (38863, 38886), True, 'import numpy as np\n'), ((38957, 39121), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': '(min_sep / 2)', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins'}), '(min_sep=min_sep / 2, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins)\n', (38980, 39121), False, 'import treecorr\n'), ((39250, 39414), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': '(max_sep * 2)', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins'}), '(min_sep=min_sep, max_sep=max_sep * 2, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins)\n', (39273, 39414), False, 'import treecorr\n'), ((39543, 39707), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': '(nbins * 2)', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins * 2,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins)\n', (39566, 39707), False, 'import treecorr\n'), ((39836, 40002), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': '(min_u - 0.1)', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u - 0.1, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins)\n', (39859, 40002), False, 'import treecorr\n'), ((40131, 40297), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': '(max_u + 0.1)', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u + 0.1, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins)\n', (40154, 40297), False, 'import treecorr\n'), ((40426, 40590), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': '(nubins * 2)', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins * 2, min_v=min_v, max_v=max_v,\n nvbins=nvbins)\n', (40449, 40590), False, 'import treecorr\n'), ((40720, 40886), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': '(min_v - 0.1)', 'max_v': 'max_v', 'nvbins': 'nvbins'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v - 0.1, max_v=max_v,\n nvbins=nvbins)\n', (40743, 40886), False, 'import treecorr\n'), ((41019, 41185), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': '(max_v + 0.1)', 'nvbins': 'nvbins'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v + 0.1,\n nvbins=nvbins)\n', (41042, 41185), False, 'import treecorr\n'), ((41318, 41482), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': '(nvbins * 2)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins * 2)\n', (41341, 41482), False, 'import treecorr\n'), ((41696, 41727), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'x': 'x', 'y': 'y', 'z': 'x'}), '(x=x, y=y, z=x)\n', (41712, 41727), False, 'import treecorr\n'), ((42751, 42911), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins)\n', (42774, 42911), False, 'import treecorr\n'), ((43004, 43052), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd15.ntri', 'ddd.ntri'], {}), '(ddd15.ntri, ddd.ntri)\n', (43030, 43052), True, 'import numpy as np\n'), ((43057, 43109), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd15.weight', 'ddd.weight'], {}), '(ddd15.weight, ddd.weight)\n', (43083, 43109), True, 'import numpy as np\n'), ((43114, 43166), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd15.meand1', 'ddd.meand1'], {}), '(ddd15.meand1, ddd.meand1)\n', (43140, 43166), True, 'import numpy as np\n'), ((43171, 43223), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd15.meand2', 'ddd.meand2'], {}), '(ddd15.meand2, ddd.meand2)\n', (43197, 43223), True, 'import numpy as np\n'), ((43228, 43280), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd15.meand3', 'ddd.meand3'], {}), '(ddd15.meand3, ddd.meand3)\n', (43254, 43280), True, 'import numpy as np\n'), ((43285, 43343), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd15.meanlogd1', 'ddd.meanlogd1'], {}), '(ddd15.meanlogd1, ddd.meanlogd1)\n', (43311, 43343), True, 'import numpy as np\n'), ((43348, 43406), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd15.meanlogd2', 'ddd.meanlogd2'], {}), '(ddd15.meanlogd2, ddd.meanlogd2)\n', (43374, 43406), True, 'import numpy as np\n'), ((43411, 43469), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd15.meanlogd3', 'ddd.meanlogd3'], {}), '(ddd15.meanlogd3, ddd.meanlogd3)\n', (43437, 43469), True, 'import numpy as np\n'), ((43474, 43524), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd15.meanu', 'ddd.meanu'], {}), '(ddd15.meanu, ddd.meanu)\n', (43500, 43524), True, 'import numpy as np\n'), ((43529, 43579), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd15.meanv', 'ddd.meanv'], {}), '(ddd15.meanv, ddd.meanv)\n', (43555, 43579), True, 'import numpy as np\n'), ((43840, 43870), 'numpy.random.RandomState', 'np.random.RandomState', (['(8675309)'], {}), '(8675309)\n', (43861, 43870), True, 'import numpy as np\n'), ((43952, 43980), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'x': 'x1', 'y': 'y1'}), '(x=x1, y=y1)\n', (43968, 43980), False, 'import treecorr\n'), ((44062, 44090), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'x': 'x2', 'y': 'y2'}), '(x=x2, y=y2)\n', (44078, 44090), False, 'import treecorr\n'), ((44172, 44200), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'x': 'x3', 'y': 'y3'}), '(x=x3, y=y3)\n', (44188, 44200), False, 'import treecorr\n'), ((44363, 44546), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'brute': '(True)', 'verbose': '(1)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, brute=True, verbose=1)\n', (44386, 44546), False, 'import treecorr\n'), ((44729, 44744), 'numpy.log', 'np.log', (['min_sep'], {}), '(min_sep)\n', (44735, 44744), True, 'import numpy as np\n'), ((44763, 44778), 'numpy.log', 'np.log', (['max_sep'], {}), '(max_sep)\n', (44769, 44778), True, 'import numpy as np\n'), ((44799, 44836), 'numpy.zeros', 'np.zeros', (['(nbins, nubins, 2 * nvbins)'], {}), '((nbins, nubins, 2 * nvbins))\n', (44807, 44836), True, 'import numpy as np\n'), ((44857, 44894), 'numpy.zeros', 'np.zeros', (['(nbins, nubins, 2 * nvbins)'], {}), '((nbins, nubins, 2 * nvbins))\n', (44865, 44894), True, 'import numpy as np\n'), ((44915, 44952), 'numpy.zeros', 'np.zeros', (['(nbins, nubins, 2 * nvbins)'], {}), '((nbins, nubins, 2 * nvbins))\n', (44923, 44952), True, 'import numpy as np\n'), ((44973, 45010), 'numpy.zeros', 'np.zeros', (['(nbins, nubins, 2 * nvbins)'], {}), '((nbins, nubins, 2 * nvbins))\n', (44981, 45010), True, 'import numpy as np\n'), ((45031, 45068), 'numpy.zeros', 'np.zeros', (['(nbins, nubins, 2 * nvbins)'], {}), '((nbins, nubins, 2 * nvbins))\n', (45039, 45068), True, 'import numpy as np\n'), ((45089, 45126), 'numpy.zeros', 'np.zeros', (['(nbins, nubins, 2 * nvbins)'], {}), '((nbins, nubins, 2 * nvbins))\n', (45097, 45126), True, 'import numpy as np\n'), ((48061, 48115), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.ntri', 'true_ntri_sum'], {}), '(ddd.ntri, true_ntri_sum)\n', (48090, 48115), True, 'import numpy as np\n'), ((48221, 48409), 'treecorr.NNNCrossCorrelation', 'treecorr.NNNCrossCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'brute': '(True)', 'verbose': '(1)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, brute=True, verbose=1)\n', (48249, 48409), False, 'import treecorr\n'), ((48662, 48724), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddc.n1n2n3.ntri', 'true_ntri_123'], {}), '(dddc.n1n2n3.ntri, true_ntri_123)\n', (48691, 48724), True, 'import numpy as np\n'), ((48729, 48791), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddc.n1n3n2.ntri', 'true_ntri_132'], {}), '(dddc.n1n3n2.ntri, true_ntri_132)\n', (48758, 48791), True, 'import numpy as np\n'), ((48796, 48858), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddc.n2n1n3.ntri', 'true_ntri_213'], {}), '(dddc.n2n1n3.ntri, true_ntri_213)\n', (48825, 48858), True, 'import numpy as np\n'), ((48863, 48925), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddc.n2n3n1.ntri', 'true_ntri_231'], {}), '(dddc.n2n3n1.ntri, true_ntri_231)\n', (48892, 48925), True, 'import numpy as np\n'), ((48930, 48992), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddc.n3n1n2.ntri', 'true_ntri_312'], {}), '(dddc.n3n1n2.ntri, true_ntri_312)\n', (48959, 48992), True, 'import numpy as np\n'), ((48997, 49059), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddc.n3n2n1.ntri', 'true_ntri_321'], {}), '(dddc.n3n2n1.ntri, true_ntri_321)\n', (49026, 49059), True, 'import numpy as np\n'), ((49101, 49284), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'bin_slop': '(0)', 'verbose': '(1)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, bin_slop=0, verbose=1)\n', (49124, 49284), False, 'import treecorr\n'), ((49512, 49566), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.ntri', 'true_ntri_sum'], {}), '(ddd.ntri, true_ntri_sum)\n', (49541, 49566), True, 'import numpy as np\n'), ((49622, 49816), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'bin_slop': '(0)', 'verbose': '(1)', 'max_top': '(0)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, bin_slop=0, verbose=1, max_top=0)\n', (49645, 49816), False, 'import treecorr\n'), ((50085, 50139), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.ntri', 'true_ntri_sum'], {}), '(ddd.ntri, true_ntri_sum)\n', (50114, 50139), True, 'import numpy as np\n'), ((50327, 50342), 'test_helper.do_pickle', 'do_pickle', (['dddc'], {}), '(dddc)\n', (50336, 50342), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((52508, 52679), 'treecorr.NNNCrossCorrelation', 'treecorr.NNNCrossCorrelation', ([], {'min_sep': '(min_sep / 2)', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins'}), '(min_sep=min_sep / 2, max_sep=max_sep, nbins=\n nbins, min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=\n max_v, nvbins=nvbins)\n', (52536, 52679), False, 'import treecorr\n'), ((52944, 53109), 'treecorr.NNNCrossCorrelation', 'treecorr.NNNCrossCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins)\n', (52972, 53109), False, 'import treecorr\n'), ((54223, 54388), 'treecorr.NNNCrossCorrelation', 'treecorr.NNNCrossCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins)\n', (54251, 54388), False, 'import treecorr\n'), ((55640, 55805), 'treecorr.NNNCrossCorrelation', 'treecorr.NNNCrossCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins)\n', (55668, 55805), False, 'import treecorr\n'), ((56955, 56985), 'numpy.random.RandomState', 'np.random.RandomState', (['(8675309)'], {}), '(8675309)\n', (56976, 56985), True, 'import numpy as np\n'), ((57067, 57095), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'x': 'x1', 'y': 'y1'}), '(x=x1, y=y1)\n', (57083, 57095), False, 'import treecorr\n'), ((57177, 57205), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'x': 'x2', 'y': 'y2'}), '(x=x2, y=y2)\n', (57193, 57205), False, 'import treecorr\n'), ((57368, 57551), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'brute': '(True)', 'verbose': '(1)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, brute=True, verbose=1)\n', (57391, 57551), False, 'import treecorr\n'), ((57693, 57708), 'numpy.log', 'np.log', (['min_sep'], {}), '(min_sep)\n', (57699, 57708), True, 'import numpy as np\n'), ((57727, 57742), 'numpy.log', 'np.log', (['max_sep'], {}), '(max_sep)\n', (57733, 57742), True, 'import numpy as np\n'), ((57763, 57800), 'numpy.zeros', 'np.zeros', (['(nbins, nubins, 2 * nvbins)'], {}), '((nbins, nubins, 2 * nvbins))\n', (57771, 57800), True, 'import numpy as np\n'), ((57821, 57858), 'numpy.zeros', 'np.zeros', (['(nbins, nubins, 2 * nvbins)'], {}), '((nbins, nubins, 2 * nvbins))\n', (57829, 57858), True, 'import numpy as np\n'), ((57879, 57916), 'numpy.zeros', 'np.zeros', (['(nbins, nubins, 2 * nvbins)'], {}), '((nbins, nubins, 2 * nvbins))\n', (57887, 57916), True, 'import numpy as np\n'), ((60829, 60883), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.ntri', 'true_ntri_sum'], {}), '(ddd.ntri, true_ntri_sum)\n', (60858, 60883), True, 'import numpy as np\n'), ((60989, 61177), 'treecorr.NNNCrossCorrelation', 'treecorr.NNNCrossCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'brute': '(True)', 'verbose': '(1)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, brute=True, verbose=1)\n', (61017, 61177), False, 'import treecorr\n'), ((61424, 61486), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddc.n1n2n3.ntri', 'true_ntri_122'], {}), '(dddc.n1n2n3.ntri, true_ntri_122)\n', (61453, 61486), True, 'import numpy as np\n'), ((61491, 61553), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddc.n1n3n2.ntri', 'true_ntri_122'], {}), '(dddc.n1n3n2.ntri, true_ntri_122)\n', (61520, 61553), True, 'import numpy as np\n'), ((61558, 61620), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddc.n2n1n3.ntri', 'true_ntri_212'], {}), '(dddc.n2n1n3.ntri, true_ntri_212)\n', (61587, 61620), True, 'import numpy as np\n'), ((61625, 61687), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddc.n2n3n1.ntri', 'true_ntri_221'], {}), '(dddc.n2n3n1.ntri, true_ntri_221)\n', (61654, 61687), True, 'import numpy as np\n'), ((61692, 61754), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddc.n3n1n2.ntri', 'true_ntri_212'], {}), '(dddc.n3n1n2.ntri, true_ntri_212)\n', (61721, 61754), True, 'import numpy as np\n'), ((61759, 61821), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddc.n3n2n1.ntri', 'true_ntri_221'], {}), '(dddc.n3n2n1.ntri, true_ntri_221)\n', (61788, 61821), True, 'import numpy as np\n'), ((61863, 62046), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'bin_slop': '(0)', 'verbose': '(1)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, bin_slop=0, verbose=1)\n', (61886, 62046), False, 'import treecorr\n'), ((62268, 62322), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.ntri', 'true_ntri_sum'], {}), '(ddd.ntri, true_ntri_sum)\n', (62297, 62322), True, 'import numpy as np\n'), ((62378, 62572), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'bin_slop': '(0)', 'verbose': '(1)', 'max_top': '(0)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, bin_slop=0, verbose=1, max_top=0)\n', (62401, 62572), False, 'import treecorr\n'), ((62835, 62889), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.ntri', 'true_ntri_sum'], {}), '(ddd.ntri, true_ntri_sum)\n', (62864, 62889), True, 'import numpy as np\n'), ((62971, 63010), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'x': 'x1', 'y': 'y1', 'npatch': '(10)'}), '(x=x1, y=y1, npatch=10)\n', (62987, 63010), False, 'import treecorr\n'), ((63022, 63061), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'x': 'x2', 'y': 'y2', 'npatch': '(10)'}), '(x=x2, y=y2, npatch=10)\n', (63038, 63061), False, 'import treecorr\n'), ((63095, 63149), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.ntri', 'true_ntri_sum'], {}), '(ddd.ntri, true_ntri_sum)\n', (63124, 63149), True, 'import numpy as np\n'), ((63184, 63246), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddc.n1n2n3.ntri', 'true_ntri_122'], {}), '(dddc.n1n2n3.ntri, true_ntri_122)\n', (63213, 63246), True, 'import numpy as np\n'), ((63251, 63313), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddc.n1n3n2.ntri', 'true_ntri_122'], {}), '(dddc.n1n3n2.ntri, true_ntri_122)\n', (63280, 63313), True, 'import numpy as np\n'), ((63318, 63380), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddc.n2n1n3.ntri', 'true_ntri_212'], {}), '(dddc.n2n1n3.ntri, true_ntri_212)\n', (63347, 63380), True, 'import numpy as np\n'), ((63385, 63447), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddc.n2n3n1.ntri', 'true_ntri_221'], {}), '(dddc.n2n3n1.ntri, true_ntri_221)\n', (63414, 63447), True, 'import numpy as np\n'), ((63452, 63514), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddc.n3n1n2.ntri', 'true_ntri_212'], {}), '(dddc.n3n1n2.ntri, true_ntri_212)\n', (63481, 63514), True, 'import numpy as np\n'), ((63519, 63581), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddc.n3n2n1.ntri', 'true_ntri_221'], {}), '(dddc.n3n2n1.ntri, true_ntri_221)\n', (63548, 63581), True, 'import numpy as np\n'), ((63690, 63720), 'numpy.random.RandomState', 'np.random.RandomState', (['(8675309)'], {}), '(8675309)\n', (63711, 63720), True, 'import numpy as np\n'), ((63928, 63970), 'coord.CelestialCoord.xyz_to_radec', 'coord.CelestialCoord.xyz_to_radec', (['x', 'y', 'z'], {}), '(x, y, z)\n', (63961, 63970), False, 'import coord\n'), ((63980, 64050), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'ra': 'ra', 'dec': 'dec', 'ra_units': '"""rad"""', 'dec_units': '"""rad"""', 'w': 'w'}), "(ra=ra, dec=dec, ra_units='rad', dec_units='rad', w=w)\n", (63996, 64050), False, 'import treecorr\n'), ((64144, 64250), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'bin_size': 'bin_size', 'nbins': 'nrbins', 'sep_units': '"""deg"""', 'brute': '(True)'}), "(min_sep=min_sep, bin_size=bin_size, nbins=nrbins,\n sep_units='deg', brute=True)\n", (64167, 64250), False, 'import treecorr\n'), ((64326, 64359), 'numpy.sqrt', 'np.sqrt', (['(x ** 2 + y ** 2 + z ** 2)'], {}), '(x ** 2 + y ** 2 + z ** 2)\n', (64333, 64359), True, 'import numpy as np\n'), ((64400, 64449), 'numpy.zeros', 'np.zeros', (['(nrbins, nubins, 2 * nvbins)'], {'dtype': 'int'}), '((nrbins, nubins, 2 * nvbins), dtype=int)\n', (64408, 64449), True, 'import numpy as np\n'), ((64466, 64517), 'numpy.zeros', 'np.zeros', (['(nrbins, nubins, 2 * nvbins)'], {'dtype': 'float'}), '((nrbins, nubins, 2 * nvbins), dtype=float)\n', (64474, 64517), True, 'import numpy as np\n'), ((66446, 66496), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.ntri', 'true_ntri'], {}), '(ddd.ntri, true_ntri)\n', (66475, 66496), True, 'import numpy as np\n'), ((66501, 66576), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd.weight', 'true_weight'], {'rtol': '(1e-05)', 'atol': '(1e-08)'}), '(ddd.weight, true_weight, rtol=1e-05, atol=1e-08)\n', (66527, 66576), True, 'import numpy as np\n'), ((66654, 66718), 'treecorr.config.read_config', 'treecorr.config.read_config', (['"""configs/nnn_direct_spherical.yaml"""'], {}), "('configs/nnn_direct_spherical.yaml')\n", (66681, 66718), False, 'import treecorr\n'), ((66758, 66780), 'treecorr.corr3', 'treecorr.corr3', (['config'], {}), '(config)\n', (66772, 66780), False, 'import treecorr\n'), ((66792, 66828), 'fitsio.read', 'fitsio.read', (["config['nnn_file_name']"], {}), "(config['nnn_file_name'])\n", (66803, 66828), False, 'import fitsio\n'), ((67281, 67398), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'bin_size': 'bin_size', 'nbins': 'nrbins', 'sep_units': '"""deg"""', 'bin_slop': '(0)', 'max_top': '(0)'}), "(min_sep=min_sep, bin_size=bin_size, nbins=nrbins,\n sep_units='deg', bin_slop=0, max_top=0)\n", (67304, 67398), False, 'import treecorr\n'), ((67454, 67504), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.ntri', 'true_ntri'], {}), '(ddd.ntri, true_ntri)\n', (67483, 67504), True, 'import numpy as np\n'), ((67509, 67584), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd.weight', 'true_weight'], {'rtol': '(1e-05)', 'atol': '(1e-08)'}), '(ddd.weight, true_weight, rtol=1e-05, atol=1e-08)\n', (67535, 67584), True, 'import numpy as np\n'), ((67703, 67733), 'numpy.random.RandomState', 'np.random.RandomState', (['(8675309)'], {}), '(8675309)\n', (67724, 67733), True, 'import numpy as np\n'), ((67916, 67958), 'coord.CelestialCoord.xyz_to_radec', 'coord.CelestialCoord.xyz_to_radec', (['x', 'y', 'z'], {}), '(x, y, z)\n', (67949, 67958), False, 'import coord\n'), ((67968, 68038), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'ra': 'ra', 'dec': 'dec', 'ra_units': '"""rad"""', 'dec_units': '"""rad"""', 'w': 'w'}), "(ra=ra, dec=dec, ra_units='rad', dec_units='rad', w=w)\n", (67984, 68038), False, 'import treecorr\n'), ((68224, 68404), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nrbins', 'nubins': 'nubins', 'ubin_size': 'ubin_size', 'nvbins': 'nvbins', 'vbin_size': 'vbin_size', 'sep_units': '"""deg"""', 'brute': '(True)'}), "(min_sep=min_sep, max_sep=max_sep, nbins=nrbins,\n nubins=nubins, ubin_size=ubin_size, nvbins=nvbins, vbin_size=vbin_size,\n sep_units='deg', brute=True)\n", (68247, 68404), False, 'import treecorr\n'), ((68543, 68576), 'numpy.sqrt', 'np.sqrt', (['(x ** 2 + y ** 2 + z ** 2)'], {}), '(x ** 2 + y ** 2 + z ** 2)\n', (68550, 68576), True, 'import numpy as np\n'), ((68617, 68666), 'numpy.zeros', 'np.zeros', (['(nrbins, nubins, 2 * nvbins)'], {'dtype': 'int'}), '((nrbins, nubins, 2 * nvbins), dtype=int)\n', (68625, 68666), True, 'import numpy as np\n'), ((68683, 68734), 'numpy.zeros', 'np.zeros', (['(nrbins, nubins, 2 * nvbins)'], {'dtype': 'float'}), '((nrbins, nubins, 2 * nvbins), dtype=float)\n', (68691, 68734), True, 'import numpy as np\n'), ((70634, 70684), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.ntri', 'true_ntri'], {}), '(ddd.ntri, true_ntri)\n', (70663, 70684), True, 'import numpy as np\n'), ((70689, 70764), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd.weight', 'true_weight'], {'rtol': '(1e-05)', 'atol': '(1e-08)'}), '(ddd.weight, true_weight, rtol=1e-05, atol=1e-08)\n', (70715, 70764), True, 'import numpy as np\n'), ((70842, 70900), 'treecorr.config.read_config', 'treecorr.config.read_config', (['"""configs/nnn_direct_arc.yaml"""'], {}), "('configs/nnn_direct_arc.yaml')\n", (70869, 70900), False, 'import treecorr\n'), ((70940, 70962), 'treecorr.corr3', 'treecorr.corr3', (['config'], {}), '(config)\n', (70954, 70962), False, 'import treecorr\n'), ((70974, 71010), 'fitsio.read', 'fitsio.read', (["config['nnn_file_name']"], {}), "(config['nnn_file_name'])\n", (70985, 71010), False, 'import fitsio\n'), ((71463, 71654), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nrbins', 'nubins': 'nubins', 'ubin_size': 'ubin_size', 'nvbins': 'nvbins', 'vbin_size': 'vbin_size', 'sep_units': '"""deg"""', 'bin_slop': '(0)', 'max_top': '(0)'}), "(min_sep=min_sep, max_sep=max_sep, nbins=nrbins,\n nubins=nubins, ubin_size=ubin_size, nvbins=nvbins, vbin_size=vbin_size,\n sep_units='deg', bin_slop=0, max_top=0)\n", (71486, 71654), False, 'import treecorr\n'), ((71774, 71824), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.ntri', 'true_ntri'], {}), '(ddd.ntri, true_ntri)\n', (71803, 71824), True, 'import numpy as np\n'), ((71829, 71904), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd.weight', 'true_weight'], {'rtol': '(1e-05)', 'atol': '(1e-08)'}), '(ddd.weight, true_weight, rtol=1e-05, atol=1e-08)\n', (71855, 71904), True, 'import numpy as np\n'), ((72035, 72065), 'numpy.random.RandomState', 'np.random.RandomState', (['(8675309)'], {}), '(8675309)\n', (72056, 72065), True, 'import numpy as np\n'), ((72148, 72203), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'x': 'x1', 'y': 'y1', 'first_row': '(28)', 'last_row': '(84)'}), '(x=x1, y=y1, first_row=28, last_row=84)\n', (72164, 72203), False, 'import treecorr\n'), ((72286, 72341), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'x': 'x2', 'y': 'y2', 'first_row': '(48)', 'last_row': '(99)'}), '(x=x2, y=y2, first_row=48, last_row=99)\n', (72302, 72341), False, 'import treecorr\n'), ((72424, 72479), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'x': 'x3', 'y': 'y3', 'first_row': '(22)', 'last_row': '(67)'}), '(x=x3, y=y3, first_row=22, last_row=67)\n', (72440, 72479), False, 'import treecorr\n'), ((72643, 72815), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'brute': '(True)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, brute=True)\n', (72666, 72815), False, 'import treecorr\n'), ((73007, 73022), 'numpy.log', 'np.log', (['min_sep'], {}), '(min_sep)\n', (73013, 73022), True, 'import numpy as np\n'), ((73041, 73056), 'numpy.log', 'np.log', (['max_sep'], {}), '(max_sep)\n', (73047, 73056), True, 'import numpy as np\n'), ((73077, 73114), 'numpy.zeros', 'np.zeros', (['(nbins, nubins, 2 * nvbins)'], {}), '((nbins, nubins, 2 * nvbins))\n', (73085, 73114), True, 'import numpy as np\n'), ((73135, 73172), 'numpy.zeros', 'np.zeros', (['(nbins, nubins, 2 * nvbins)'], {}), '((nbins, nubins, 2 * nvbins))\n', (73143, 73172), True, 'import numpy as np\n'), ((73193, 73230), 'numpy.zeros', 'np.zeros', (['(nbins, nubins, 2 * nvbins)'], {}), '((nbins, nubins, 2 * nvbins))\n', (73201, 73230), True, 'import numpy as np\n'), ((73251, 73288), 'numpy.zeros', 'np.zeros', (['(nbins, nubins, 2 * nvbins)'], {}), '((nbins, nubins, 2 * nvbins))\n', (73259, 73288), True, 'import numpy as np\n'), ((73309, 73346), 'numpy.zeros', 'np.zeros', (['(nbins, nubins, 2 * nvbins)'], {}), '((nbins, nubins, 2 * nvbins))\n', (73317, 73346), True, 'import numpy as np\n'), ((73367, 73404), 'numpy.zeros', 'np.zeros', (['(nbins, nubins, 2 * nvbins)'], {}), '((nbins, nubins, 2 * nvbins))\n', (73375, 73404), True, 'import numpy as np\n'), ((76290, 76345), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddda.ntri', 'true_ntri_sum'], {}), '(ddda.ntri, true_ntri_sum)\n', (76319, 76345), True, 'import numpy as np\n'), ((76395, 76572), 'treecorr.NNNCrossCorrelation', 'treecorr.NNNCrossCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'brute': '(True)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, brute=True)\n', (76423, 76572), False, 'import treecorr\n'), ((77117, 77179), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddda.n1n2n3.ntri', 'true_ntri_123'], {}), '(ddda.n1n2n3.ntri, true_ntri_123)\n', (77146, 77179), True, 'import numpy as np\n'), ((77184, 77246), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddda.n1n3n2.ntri', 'true_ntri_132'], {}), '(ddda.n1n3n2.ntri, true_ntri_132)\n', (77213, 77246), True, 'import numpy as np\n'), ((77251, 77313), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddda.n2n1n3.ntri', 'true_ntri_213'], {}), '(ddda.n2n1n3.ntri, true_ntri_213)\n', (77280, 77313), True, 'import numpy as np\n'), ((77318, 77380), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddda.n2n3n1.ntri', 'true_ntri_231'], {}), '(ddda.n2n3n1.ntri, true_ntri_231)\n', (77347, 77380), True, 'import numpy as np\n'), ((77385, 77447), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddda.n3n1n2.ntri', 'true_ntri_312'], {}), '(ddda.n3n1n2.ntri, true_ntri_312)\n', (77414, 77447), True, 'import numpy as np\n'), ((77452, 77514), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddda.n3n2n1.ntri', 'true_ntri_321'], {}), '(ddda.n3n2n1.ntri, true_ntri_321)\n', (77481, 77514), True, 'import numpy as np\n'), ((77636, 77650), 'numpy.zeros', 'np.zeros', (['ngal'], {}), '(ngal)\n', (77644, 77650), True, 'import numpy as np\n'), ((77679, 77693), 'numpy.zeros', 'np.zeros', (['ngal'], {}), '(ngal)\n', (77687, 77693), True, 'import numpy as np\n'), ((77722, 77736), 'numpy.zeros', 'np.zeros', (['ngal'], {}), '(ngal)\n', (77730, 77736), True, 'import numpy as np\n'), ((77768, 77802), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'x': 'x1', 'y': 'y1', 'w': 'w1'}), '(x=x1, y=y1, w=w1)\n', (77784, 77802), False, 'import treecorr\n'), ((77815, 77849), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'x': 'x2', 'y': 'y2', 'w': 'w2'}), '(x=x2, y=y2, w=w2)\n', (77831, 77849), False, 'import treecorr\n'), ((77862, 77896), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'x': 'x3', 'y': 'y3', 'w': 'w3'}), '(x=x3, y=y3, w=w3)\n', (77878, 77896), False, 'import treecorr\n'), ((77908, 78080), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'brute': '(True)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, brute=True)\n', (77931, 78080), False, 'import treecorr\n'), ((78305, 78360), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddb.ntri', 'true_ntri_sum'], {}), '(dddb.ntri, true_ntri_sum)\n', (78334, 78360), True, 'import numpy as np\n'), ((78373, 78550), 'treecorr.NNNCrossCorrelation', 'treecorr.NNNCrossCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'brute': '(True)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, brute=True)\n', (78401, 78550), False, 'import treecorr\n'), ((78807, 78869), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddb.n1n2n3.ntri', 'true_ntri_123'], {}), '(dddb.n1n2n3.ntri, true_ntri_123)\n', (78836, 78869), True, 'import numpy as np\n'), ((78874, 78936), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddb.n1n3n2.ntri', 'true_ntri_132'], {}), '(dddb.n1n3n2.ntri, true_ntri_132)\n', (78903, 78936), True, 'import numpy as np\n'), ((78941, 79003), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddb.n2n1n3.ntri', 'true_ntri_213'], {}), '(dddb.n2n1n3.ntri, true_ntri_213)\n', (78970, 79003), True, 'import numpy as np\n'), ((79008, 79070), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddb.n2n3n1.ntri', 'true_ntri_231'], {}), '(dddb.n2n3n1.ntri, true_ntri_231)\n', (79037, 79070), True, 'import numpy as np\n'), ((79075, 79137), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddb.n3n1n2.ntri', 'true_ntri_312'], {}), '(dddb.n3n1n2.ntri, true_ntri_312)\n', (79104, 79137), True, 'import numpy as np\n'), ((79142, 79204), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddb.n3n2n1.ntri', 'true_ntri_321'], {}), '(dddb.n3n2n1.ntri, true_ntri_321)\n', (79171, 79204), True, 'import numpy as np\n'), ((79357, 79387), 'numpy.random.RandomState', 'np.random.RandomState', (['(8675309)'], {}), '(8675309)\n', (79378, 79387), True, 'import numpy as np\n'), ((79508, 79538), 'numpy.sqrt', 'np.sqrt', (['(x * x + y * y + z * z)'], {}), '(x * x + y * y + z * z)\n', (79515, 79538), True, 'import numpy as np\n'), ((79545, 79561), 'numpy.arcsin', 'np.arcsin', (['(z / r)'], {}), '(z / r)\n', (79554, 79561), True, 'import numpy as np\n'), ((79569, 79585), 'numpy.arctan2', 'np.arctan2', (['y', 'x'], {}), '(y, x)\n', (79579, 79585), True, 'import numpy as np\n'), ((79595, 79665), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'ra': 'ra', 'dec': 'dec', 'r': 'r', 'ra_units': '"""rad"""', 'dec_units': '"""rad"""'}), "(ra=ra, dec=dec, r=r, ra_units='rad', dec_units='rad')\n", (79611, 79665), False, 'import treecorr\n'), ((79827, 80010), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'brute': '(True)', 'verbose': '(1)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, brute=True, verbose=1)\n', (79850, 80010), False, 'import treecorr\n'), ((80180, 80195), 'numpy.log', 'np.log', (['min_sep'], {}), '(min_sep)\n', (80186, 80195), True, 'import numpy as np\n'), ((80214, 80229), 'numpy.log', 'np.log', (['max_sep'], {}), '(max_sep)\n', (80220, 80229), True, 'import numpy as np\n'), ((80246, 80283), 'numpy.zeros', 'np.zeros', (['(nbins, nubins, 2 * nvbins)'], {}), '((nbins, nubins, 2 * nvbins))\n', (80254, 80283), True, 'import numpy as np\n'), ((82814, 82864), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.ntri', 'true_ntri'], {}), '(ddd.ntri, true_ntri)\n', (82843, 82864), True, 'import numpy as np\n'), ((82906, 83089), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'bin_slop': '(0)', 'verbose': '(1)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, bin_slop=0, verbose=1)\n', (82929, 83089), False, 'import treecorr\n'), ((83287, 83337), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.ntri', 'true_ntri'], {}), '(ddd.ntri, true_ntri)\n', (83316, 83337), True, 'import numpy as np\n'), ((83393, 83587), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'bin_slop': '(0)', 'verbose': '(1)', 'max_top': '(0)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, bin_slop=0, verbose=1, max_top=0)\n', (83416, 83587), False, 'import treecorr\n'), ((83823, 83873), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.ntri', 'true_ntri'], {}), '(ddd.ntri, true_ntri)\n', (83852, 83873), True, 'import numpy as np\n'), ((84157, 84211), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.ntri', '(6 * true_ntri)'], {}), '(ddd.ntri, 6 * true_ntri)\n', (84186, 84211), True, 'import numpy as np\n'), ((84222, 84421), 'treecorr.NNNCrossCorrelation', 'treecorr.NNNCrossCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'bin_slop': '(0)', 'verbose': '(1)', 'max_top': '(0)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, bin_slop=0, verbose=1, max_top=0)\n', (84250, 84421), False, 'import treecorr\n'), ((84681, 84739), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddc.n1n2n3.ntri', 'true_ntri'], {}), '(dddc.n1n2n3.ntri, true_ntri)\n', (84710, 84739), True, 'import numpy as np\n'), ((84744, 84802), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddc.n1n3n2.ntri', 'true_ntri'], {}), '(dddc.n1n3n2.ntri, true_ntri)\n', (84773, 84802), True, 'import numpy as np\n'), ((84807, 84865), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddc.n2n1n3.ntri', 'true_ntri'], {}), '(dddc.n2n1n3.ntri, true_ntri)\n', (84836, 84865), True, 'import numpy as np\n'), ((84870, 84928), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddc.n2n3n1.ntri', 'true_ntri'], {}), '(dddc.n2n3n1.ntri, true_ntri)\n', (84899, 84928), True, 'import numpy as np\n'), ((84933, 84991), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddc.n3n1n2.ntri', 'true_ntri'], {}), '(dddc.n3n1n2.ntri, true_ntri)\n', (84962, 84991), True, 'import numpy as np\n'), ((84996, 85054), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dddc.n3n2n1.ntri', 'true_ntri'], {}), '(dddc.n3n2n1.ntri, true_ntri)\n', (85025, 85054), True, 'import numpy as np\n'), ((85121, 85152), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'x': 'x', 'y': 'y', 'z': 'z'}), '(x=x, y=y, z=z)\n', (85137, 85152), False, 'import treecorr\n'), ((85178, 85228), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.ntri', 'true_ntri'], {}), '(ddd.ntri, true_ntri)\n', (85207, 85228), True, 'import numpy as np\n'), ((85384, 85414), 'numpy.random.RandomState', 'np.random.RandomState', (['(8675309)'], {}), '(8675309)\n', (85405, 85414), True, 'import numpy as np\n'), ((85539, 85575), 'numpy.sqrt', 'np.sqrt', (['(x1 * x1 + y1 * y1 + z1 * z1)'], {}), '(x1 * x1 + y1 * y1 + z1 * z1)\n', (85546, 85575), True, 'import numpy as np\n'), ((85583, 85601), 'numpy.arcsin', 'np.arcsin', (['(z1 / r1)'], {}), '(z1 / r1)\n', (85592, 85601), True, 'import numpy as np\n'), ((85610, 85628), 'numpy.arctan2', 'np.arctan2', (['y1', 'x1'], {}), '(y1, x1)\n', (85620, 85628), True, 'import numpy as np\n'), ((85639, 85712), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'ra': 'ra1', 'dec': 'dec1', 'r': 'r1', 'ra_units': '"""rad"""', 'dec_units': '"""rad"""'}), "(ra=ra1, dec=dec1, r=r1, ra_units='rad', dec_units='rad')\n", (85655, 85712), False, 'import treecorr\n'), ((85838, 85874), 'numpy.sqrt', 'np.sqrt', (['(x2 * x2 + y2 * y2 + z2 * z2)'], {}), '(x2 * x2 + y2 * y2 + z2 * z2)\n', (85845, 85874), True, 'import numpy as np\n'), ((85882, 85900), 'numpy.arcsin', 'np.arcsin', (['(z2 / r2)'], {}), '(z2 / r2)\n', (85891, 85900), True, 'import numpy as np\n'), ((85909, 85927), 'numpy.arctan2', 'np.arctan2', (['y2', 'x2'], {}), '(y2, x2)\n', (85919, 85927), True, 'import numpy as np\n'), ((85938, 86011), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'ra': 'ra2', 'dec': 'dec2', 'r': 'r2', 'ra_units': '"""rad"""', 'dec_units': '"""rad"""'}), "(ra=ra2, dec=dec2, r=r2, ra_units='rad', dec_units='rad')\n", (85954, 86011), False, 'import treecorr\n'), ((86137, 86173), 'numpy.sqrt', 'np.sqrt', (['(x3 * x3 + y3 * y3 + z3 * z3)'], {}), '(x3 * x3 + y3 * y3 + z3 * z3)\n', (86144, 86173), True, 'import numpy as np\n'), ((86181, 86199), 'numpy.arcsin', 'np.arcsin', (['(z3 / r3)'], {}), '(z3 / r3)\n', (86190, 86199), True, 'import numpy as np\n'), ((86208, 86226), 'numpy.arctan2', 'np.arctan2', (['y3', 'x3'], {}), '(y3, x3)\n', (86218, 86226), True, 'import numpy as np\n'), ((86237, 86310), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'ra': 'ra3', 'dec': 'dec3', 'r': 'r3', 'ra_units': '"""rad"""', 'dec_units': '"""rad"""'}), "(ra=ra3, dec=dec3, r=r3, ra_units='rad', dec_units='rad')\n", (86253, 86310), False, 'import treecorr\n'), ((86472, 86655), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'brute': '(True)', 'verbose': '(1)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, brute=True, verbose=1)\n', (86495, 86655), False, 'import treecorr\n'), ((86838, 86853), 'numpy.log', 'np.log', (['min_sep'], {}), '(min_sep)\n', (86844, 86853), True, 'import numpy as np\n'), ((86872, 86887), 'numpy.log', 'np.log', (['max_sep'], {}), '(max_sep)\n', (86878, 86887), True, 'import numpy as np\n'), ((86908, 86945), 'numpy.zeros', 'np.zeros', (['(nbins, nubins, 2 * nvbins)'], {}), '((nbins, nubins, 2 * nvbins))\n', (86916, 86945), True, 'import numpy as np\n'), ((86966, 87003), 'numpy.zeros', 'np.zeros', (['(nbins, nubins, 2 * nvbins)'], {}), '((nbins, nubins, 2 * nvbins))\n', (86974, 87003), True, 'import numpy as np\n'), ((87024, 87061), 'numpy.zeros', 'np.zeros', (['(nbins, nubins, 2 * nvbins)'], {}), '((nbins, nubins, 2 * nvbins))\n', (87032, 87061), True, 'import numpy as np\n'), ((87082, 87119), 'numpy.zeros', 'np.zeros', (['(nbins, nubins, 2 * nvbins)'], {}), '((nbins, nubins, 2 * nvbins))\n', (87090, 87119), True, 'import numpy as np\n'), ((87140, 87177), 'numpy.zeros', 'np.zeros', (['(nbins, nubins, 2 * nvbins)'], {}), '((nbins, nubins, 2 * nvbins))\n', (87148, 87177), True, 'import numpy as np\n'), ((87198, 87235), 'numpy.zeros', 'np.zeros', (['(nbins, nubins, 2 * nvbins)'], {}), '((nbins, nubins, 2 * nvbins))\n', (87206, 87235), True, 'import numpy as np\n'), ((90353, 90407), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.ntri', 'true_ntri_sum'], {}), '(ddd.ntri, true_ntri_sum)\n', (90382, 90407), True, 'import numpy as np\n'), ((90512, 90700), 'treecorr.NNNCrossCorrelation', 'treecorr.NNNCrossCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'brute': '(True)', 'verbose': '(1)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, brute=True, verbose=1)\n', (90540, 90700), False, 'import treecorr\n'), ((90943, 91004), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.n1n2n3.ntri', 'true_ntri_123'], {}), '(ddd.n1n2n3.ntri, true_ntri_123)\n', (90972, 91004), True, 'import numpy as np\n'), ((91009, 91070), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.n1n3n2.ntri', 'true_ntri_132'], {}), '(ddd.n1n3n2.ntri, true_ntri_132)\n', (91038, 91070), True, 'import numpy as np\n'), ((91075, 91136), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.n2n1n3.ntri', 'true_ntri_213'], {}), '(ddd.n2n1n3.ntri, true_ntri_213)\n', (91104, 91136), True, 'import numpy as np\n'), ((91141, 91202), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.n2n3n1.ntri', 'true_ntri_231'], {}), '(ddd.n2n3n1.ntri, true_ntri_231)\n', (91170, 91202), True, 'import numpy as np\n'), ((91207, 91268), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.n3n1n2.ntri', 'true_ntri_312'], {}), '(ddd.n3n1n2.ntri, true_ntri_312)\n', (91236, 91268), True, 'import numpy as np\n'), ((91273, 91334), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.n3n2n1.ntri', 'true_ntri_321'], {}), '(ddd.n3n2n1.ntri, true_ntri_321)\n', (91302, 91334), True, 'import numpy as np\n'), ((91376, 91564), 'treecorr.NNNCrossCorrelation', 'treecorr.NNNCrossCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'bin_slop': '(0)', 'verbose': '(1)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, bin_slop=0, verbose=1)\n', (91404, 91564), False, 'import treecorr\n'), ((91828, 91889), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.n1n2n3.ntri', 'true_ntri_123'], {}), '(ddd.n1n2n3.ntri, true_ntri_123)\n', (91857, 91889), True, 'import numpy as np\n'), ((91894, 91955), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.n1n3n2.ntri', 'true_ntri_132'], {}), '(ddd.n1n3n2.ntri, true_ntri_132)\n', (91923, 91955), True, 'import numpy as np\n'), ((91960, 92021), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.n2n1n3.ntri', 'true_ntri_213'], {}), '(ddd.n2n1n3.ntri, true_ntri_213)\n', (91989, 92021), True, 'import numpy as np\n'), ((92026, 92087), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.n2n3n1.ntri', 'true_ntri_231'], {}), '(ddd.n2n3n1.ntri, true_ntri_231)\n', (92055, 92087), True, 'import numpy as np\n'), ((92092, 92153), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.n3n1n2.ntri', 'true_ntri_312'], {}), '(ddd.n3n1n2.ntri, true_ntri_312)\n', (92121, 92153), True, 'import numpy as np\n'), ((92158, 92219), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.n3n2n1.ntri', 'true_ntri_321'], {}), '(ddd.n3n2n1.ntri, true_ntri_321)\n', (92187, 92219), True, 'import numpy as np\n'), ((92275, 92474), 'treecorr.NNNCrossCorrelation', 'treecorr.NNNCrossCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'bin_slop': '(0)', 'verbose': '(1)', 'max_top': '(0)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, bin_slop=0, verbose=1, max_top=0)\n', (92303, 92474), False, 'import treecorr\n'), ((92780, 92841), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.n1n2n3.ntri', 'true_ntri_123'], {}), '(ddd.n1n2n3.ntri, true_ntri_123)\n', (92809, 92841), True, 'import numpy as np\n'), ((92846, 92907), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.n1n3n2.ntri', 'true_ntri_132'], {}), '(ddd.n1n3n2.ntri, true_ntri_132)\n', (92875, 92907), True, 'import numpy as np\n'), ((92912, 92973), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.n2n1n3.ntri', 'true_ntri_213'], {}), '(ddd.n2n1n3.ntri, true_ntri_213)\n', (92941, 92973), True, 'import numpy as np\n'), ((92978, 93039), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.n2n3n1.ntri', 'true_ntri_231'], {}), '(ddd.n2n3n1.ntri, true_ntri_231)\n', (93007, 93039), True, 'import numpy as np\n'), ((93044, 93105), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.n3n1n2.ntri', 'true_ntri_312'], {}), '(ddd.n3n1n2.ntri, true_ntri_312)\n', (93073, 93105), True, 'import numpy as np\n'), ((93110, 93171), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.n3n2n1.ntri', 'true_ntri_321'], {}), '(ddd.n3n2n1.ntri, true_ntri_321)\n', (93139, 93171), True, 'import numpy as np\n'), ((93239, 93273), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'x': 'x1', 'y': 'y1', 'z': 'z1'}), '(x=x1, y=y1, z=z1)\n', (93255, 93273), False, 'import treecorr\n'), ((93285, 93319), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'x': 'x2', 'y': 'y2', 'z': 'z2'}), '(x=x2, y=y2, z=z2)\n', (93301, 93319), False, 'import treecorr\n'), ((93331, 93365), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'x': 'x3', 'y': 'y3', 'z': 'z3'}), '(x=x3, y=y3, z=z3)\n', (93347, 93365), False, 'import treecorr\n'), ((93404, 93465), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.n1n2n3.ntri', 'true_ntri_123'], {}), '(ddd.n1n2n3.ntri, true_ntri_123)\n', (93433, 93465), True, 'import numpy as np\n'), ((93470, 93531), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.n1n3n2.ntri', 'true_ntri_132'], {}), '(ddd.n1n3n2.ntri, true_ntri_132)\n', (93499, 93531), True, 'import numpy as np\n'), ((93536, 93597), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.n2n1n3.ntri', 'true_ntri_213'], {}), '(ddd.n2n1n3.ntri, true_ntri_213)\n', (93565, 93597), True, 'import numpy as np\n'), ((93602, 93663), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.n2n3n1.ntri', 'true_ntri_231'], {}), '(ddd.n2n3n1.ntri, true_ntri_231)\n', (93631, 93663), True, 'import numpy as np\n'), ((93668, 93729), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.n3n1n2.ntri', 'true_ntri_312'], {}), '(ddd.n3n1n2.ntri, true_ntri_312)\n', (93697, 93729), True, 'import numpy as np\n'), ((93734, 93795), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ddd.n3n2n1.ntri', 'true_ntri_321'], {}), '(ddd.n3n2n1.ntri, true_ntri_321)\n', (93763, 93795), True, 'import numpy as np\n'), ((95302, 95332), 'numpy.random.RandomState', 'np.random.RandomState', (['(8675309)'], {}), '(8675309)\n', (95323, 95332), True, 'import numpy as np\n'), ((95556, 95618), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'x': 'x', 'y': 'y', 'x_units': '"""arcmin"""', 'y_units': '"""arcmin"""'}), "(x=x, y=y, x_units='arcmin', y_units='arcmin')\n", (95572, 95618), False, 'import treecorr\n'), ((95629, 95820), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'min_v': 'min_v', 'max_v': 'max_v', 'nubins': 'nubins', 'nvbins': 'nvbins', 'sep_units': '"""arcmin"""', 'verbose': '(1)'}), "(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, min_v=min_v, max_v=max_v, nubins=nubins,\n nvbins=nvbins, sep_units='arcmin', verbose=1)\n", (95652, 95820), False, 'import treecorr\n'), ((97063, 97154), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['(ddd.meand3 / ddd.meand2)', 'ddd.meanu'], {'rtol': '(1e-05 * tol_factor)'}), '(ddd.meand3 / ddd.meand2, ddd.meanu, rtol=1e-05 *\n tol_factor)\n', (97089, 97154), True, 'import numpy as np\n'), ((97719, 97783), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'x': 'rx', 'y': 'ry', 'x_units': '"""arcmin"""', 'y_units': '"""arcmin"""'}), "(x=rx, y=ry, x_units='arcmin', y_units='arcmin')\n", (97735, 97783), False, 'import treecorr\n'), ((97793, 97984), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'min_v': 'min_v', 'max_v': 'max_v', 'nubins': 'nubins', 'nvbins': 'nvbins', 'sep_units': '"""arcmin"""', 'verbose': '(1)'}), "(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, min_v=min_v, max_v=max_v, nubins=nubins,\n nvbins=nvbins, sep_units='arcmin', verbose=1)\n", (97816, 97984), False, 'import treecorr\n'), ((98715, 98781), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['zeta', 'true_zeta'], {'rtol': '(0.1 * tol_factor)'}), '(zeta, true_zeta, rtol=0.1 * tol_factor)\n', (98741, 98781), True, 'import numpy as np\n'), ((99097, 99144), 'treecorr.config.read_config', 'treecorr.config.read_config', (['"""configs/nnn.yaml"""'], {}), "('configs/nnn.yaml')\n", (99124, 99144), False, 'import treecorr\n'), ((99175, 99197), 'treecorr.corr3', 'treecorr.corr3', (['config'], {}), '(config)\n', (99189, 99197), False, 'import treecorr\n'), ((99625, 99664), 'os.path.join', 'os.path.join', (['"""output"""', '"""nnn_out1.fits"""'], {}), "('output', 'nnn_out1.fits')\n", (99637, 99664), False, 'import os\n'), ((99705, 99732), 'fitsio.read', 'fitsio.read', (['out_file_name1'], {}), '(out_file_name1)\n', (99716, 99732), False, 'import fitsio\n'), ((100625, 100662), 'fitsio.read_header', 'fitsio.read_header', (['out_file_name1', '(1)'], {}), '(out_file_name1, 1)\n', (100643, 100662), False, 'import fitsio\n'), ((100667, 100727), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["(header['tot'] / ddd.tot)", '(1.0)'], {}), "(header['tot'] / ddd.tot, 1.0)\n", (100697, 100727), True, 'import numpy as np\n'), ((100747, 100786), 'os.path.join', 'os.path.join', (['"""output"""', '"""nnn_out2.fits"""'], {}), "('output', 'nnn_out2.fits')\n", (100759, 100786), False, 'import os\n'), ((100832, 100859), 'fitsio.read', 'fitsio.read', (['out_file_name2'], {}), '(out_file_name2)\n', (100843, 100859), False, 'import fitsio\n'), ((101989, 102026), 'fitsio.read_header', 'fitsio.read_header', (['out_file_name2', '(1)'], {}), '(out_file_name2, 1)\n', (102007, 102026), False, 'import fitsio\n'), ((102031, 102091), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["(header['tot'] / ddd.tot)", '(1.0)'], {}), "(header['tot'] / ddd.tot, 1.0)\n", (102061, 102091), True, 'import numpy as np\n'), ((102231, 102422), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'min_v': 'min_v', 'max_v': 'max_v', 'nubins': 'nubins', 'nvbins': 'nvbins', 'sep_units': '"""arcmin"""', 'verbose': '(1)'}), "(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, min_v=min_v, max_v=max_v, nubins=nubins,\n nvbins=nvbins, sep_units='arcmin', verbose=1)\n", (102254, 102422), False, 'import treecorr\n'), ((102554, 102605), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.logr', 'ddd.logr'], {}), '(ddd2.logr, ddd.logr)\n', (102584, 102605), True, 'import numpy as np\n'), ((102610, 102655), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.u', 'ddd.u'], {}), '(ddd2.u, ddd.u)\n', (102640, 102655), True, 'import numpy as np\n'), ((102660, 102705), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.v', 'ddd.v'], {}), '(ddd2.v, ddd.v)\n', (102690, 102705), True, 'import numpy as np\n'), ((102710, 102765), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.meand1', 'ddd.meand1'], {}), '(ddd2.meand1, ddd.meand1)\n', (102740, 102765), True, 'import numpy as np\n'), ((102770, 102831), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.meanlogd1', 'ddd.meanlogd1'], {}), '(ddd2.meanlogd1, ddd.meanlogd1)\n', (102800, 102831), True, 'import numpy as np\n'), ((102836, 102891), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.meand2', 'ddd.meand2'], {}), '(ddd2.meand2, ddd.meand2)\n', (102866, 102891), True, 'import numpy as np\n'), ((102896, 102957), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.meanlogd2', 'ddd.meanlogd2'], {}), '(ddd2.meanlogd2, ddd.meanlogd2)\n', (102926, 102957), True, 'import numpy as np\n'), ((102962, 103017), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.meand3', 'ddd.meand3'], {}), '(ddd2.meand3, ddd.meand3)\n', (102992, 103017), True, 'import numpy as np\n'), ((103022, 103083), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.meanlogd3', 'ddd.meanlogd3'], {}), '(ddd2.meanlogd3, ddd.meanlogd3)\n', (103052, 103083), True, 'import numpy as np\n'), ((103088, 103141), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.meanu', 'ddd.meanu'], {}), '(ddd2.meanu, ddd.meanu)\n', (103118, 103141), True, 'import numpy as np\n'), ((103146, 103199), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.meanv', 'ddd.meanv'], {}), '(ddd2.meanv, ddd.meanv)\n', (103176, 103199), True, 'import numpy as np\n'), ((103204, 103255), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.ntri', 'ddd.ntri'], {}), '(ddd2.ntri, ddd.ntri)\n', (103234, 103255), True, 'import numpy as np\n'), ((103260, 103315), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['(ddd2.tot / ddd.tot)', '(1.0)'], {}), '(ddd2.tot / ddd.tot, 1.0)\n', (103290, 103315), True, 'import numpy as np\n'), ((103506, 103557), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.logr', 'ddd.logr'], {}), '(ddd2.logr, ddd.logr)\n', (103536, 103557), True, 'import numpy as np\n'), ((103562, 103607), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.u', 'ddd.u'], {}), '(ddd2.u, ddd.u)\n', (103592, 103607), True, 'import numpy as np\n'), ((103612, 103657), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.v', 'ddd.v'], {}), '(ddd2.v, ddd.v)\n', (103642, 103657), True, 'import numpy as np\n'), ((103662, 103717), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.meand1', 'ddd.meand1'], {}), '(ddd2.meand1, ddd.meand1)\n', (103692, 103717), True, 'import numpy as np\n'), ((103722, 103783), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.meanlogd1', 'ddd.meanlogd1'], {}), '(ddd2.meanlogd1, ddd.meanlogd1)\n', (103752, 103783), True, 'import numpy as np\n'), ((103788, 103843), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.meand2', 'ddd.meand2'], {}), '(ddd2.meand2, ddd.meand2)\n', (103818, 103843), True, 'import numpy as np\n'), ((103848, 103909), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.meanlogd2', 'ddd.meanlogd2'], {}), '(ddd2.meanlogd2, ddd.meanlogd2)\n', (103878, 103909), True, 'import numpy as np\n'), ((103914, 103969), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.meand3', 'ddd.meand3'], {}), '(ddd2.meand3, ddd.meand3)\n', (103944, 103969), True, 'import numpy as np\n'), ((103974, 104035), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.meanlogd3', 'ddd.meanlogd3'], {}), '(ddd2.meanlogd3, ddd.meanlogd3)\n', (104004, 104035), True, 'import numpy as np\n'), ((104040, 104093), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.meanu', 'ddd.meanu'], {}), '(ddd2.meanu, ddd.meanu)\n', (104070, 104093), True, 'import numpy as np\n'), ((104098, 104151), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.meanv', 'ddd.meanv'], {}), '(ddd2.meanv, ddd.meanv)\n', (104128, 104151), True, 'import numpy as np\n'), ((104156, 104207), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.ntri', 'ddd.ntri'], {}), '(ddd2.ntri, ddd.ntri)\n', (104186, 104207), True, 'import numpy as np\n'), ((104212, 104267), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['(ddd2.tot / ddd.tot)', '(1.0)'], {}), '(ddd2.tot / ddd.tot, 1.0)\n', (104242, 104267), True, 'import numpy as np\n'), ((107808, 107847), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['zeta2', 'zeta'], {}), '(zeta2, zeta)\n', (107834, 107847), True, 'import numpy as np\n'), ((108132, 108312), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'min_v': 'min_v', 'max_v': 'max_v', 'nubins': 'nubins', 'nvbins': 'nvbins', 'sep_units': '"""arcmin"""'}), "(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, min_v=min_v, max_v=max_v, nubins=nubins,\n nvbins=nvbins, sep_units='arcmin')\n", (108155, 108312), False, 'import treecorr\n'), ((108698, 108737), 'os.path.join', 'os.path.join', (['"""output"""', '"""nnn_out3.fits"""'], {}), "('output', 'nnn_out3.fits')\n", (108710, 108737), False, 'import os\n'), ((110107, 110173), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['zeta', 'true_zeta'], {'rtol': '(0.1 * tol_factor)'}), '(zeta, true_zeta, rtol=0.1 * tol_factor)\n', (110133, 110173), True, 'import numpy as np\n'), ((110295, 110334), 'os.path.join', 'os.path.join', (['"""output"""', '"""nnn_out3.fits"""'], {}), "('output', 'nnn_out3.fits')\n", (110307, 110334), False, 'import os\n'), ((110388, 110415), 'fitsio.read', 'fitsio.read', (['out_file_name3'], {}), '(out_file_name3)\n', (110399, 110415), False, 'import fitsio\n'), ((111725, 111762), 'fitsio.read_header', 'fitsio.read_header', (['out_file_name3', '(1)'], {}), '(out_file_name3, 1)\n', (111743, 111762), False, 'import fitsio\n'), ((111767, 111827), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["(header['tot'] / ddd.tot)", '(1.0)'], {}), "(header['tot'] / ddd.tot, 1.0)\n", (111797, 111827), True, 'import numpy as np\n'), ((111860, 111911), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.logr', 'ddd.logr'], {}), '(ddd2.logr, ddd.logr)\n', (111890, 111911), True, 'import numpy as np\n'), ((111916, 111961), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.u', 'ddd.u'], {}), '(ddd2.u, ddd.u)\n', (111946, 111961), True, 'import numpy as np\n'), ((111966, 112011), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.v', 'ddd.v'], {}), '(ddd2.v, ddd.v)\n', (111996, 112011), True, 'import numpy as np\n'), ((112016, 112071), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.meand1', 'ddd.meand1'], {}), '(ddd2.meand1, ddd.meand1)\n', (112046, 112071), True, 'import numpy as np\n'), ((112076, 112137), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.meanlogd1', 'ddd.meanlogd1'], {}), '(ddd2.meanlogd1, ddd.meanlogd1)\n', (112106, 112137), True, 'import numpy as np\n'), ((112142, 112197), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.meand2', 'ddd.meand2'], {}), '(ddd2.meand2, ddd.meand2)\n', (112172, 112197), True, 'import numpy as np\n'), ((112202, 112263), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.meanlogd2', 'ddd.meanlogd2'], {}), '(ddd2.meanlogd2, ddd.meanlogd2)\n', (112232, 112263), True, 'import numpy as np\n'), ((112268, 112323), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.meand3', 'ddd.meand3'], {}), '(ddd2.meand3, ddd.meand3)\n', (112298, 112323), True, 'import numpy as np\n'), ((112328, 112389), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.meanlogd3', 'ddd.meanlogd3'], {}), '(ddd2.meanlogd3, ddd.meanlogd3)\n', (112358, 112389), True, 'import numpy as np\n'), ((112394, 112447), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.meanu', 'ddd.meanu'], {}), '(ddd2.meanu, ddd.meanu)\n', (112424, 112447), True, 'import numpy as np\n'), ((112452, 112505), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.meanv', 'ddd.meanv'], {}), '(ddd2.meanv, ddd.meanv)\n', (112482, 112505), True, 'import numpy as np\n'), ((112510, 112561), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd2.ntri', 'ddd.ntri'], {}), '(ddd2.ntri, ddd.ntri)\n', (112540, 112561), True, 'import numpy as np\n'), ((112566, 112621), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['(ddd2.tot / ddd.tot)', '(1.0)'], {}), '(ddd2.tot / ddd.tot, 1.0)\n', (112596, 112621), True, 'import numpy as np\n'), ((112791, 112850), 'treecorr.config.read_config', 'treecorr.config.read_config', (['"""configs/nnn_compensated.yaml"""'], {}), "('configs/nnn_compensated.yaml')\n", (112818, 112850), False, 'import treecorr\n'), ((112881, 112903), 'treecorr.corr3', 'treecorr.corr3', (['config'], {}), '(config)\n', (112895, 112903), False, 'import treecorr\n'), ((112924, 112970), 'os.path.join', 'os.path.join', (['"""output"""', '"""nnn_compensated.fits"""'], {}), "('output', 'nnn_compensated.fits')\n", (112936, 112970), False, 'import os\n'), ((112989, 113015), 'fitsio.read', 'fitsio.read', (['corr3_outfile'], {}), '(corr3_outfile)\n', (113000, 113015), False, 'import fitsio\n'), ((114658, 114694), 'fitsio.read_header', 'fitsio.read_header', (['corr3_outfile', '(1)'], {}), '(corr3_outfile, 1)\n', (114676, 114694), False, 'import fitsio\n'), ((114699, 114759), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["(header['tot'] / ddd.tot)", '(1.0)'], {}), "(header['tot'] / ddd.tot, 1.0)\n", (114729, 114759), True, 'import numpy as np\n'), ((116369, 116399), 'numpy.random.RandomState', 'np.random.RandomState', (['(8675309)'], {}), '(8675309)\n', (116390, 116399), True, 'import numpy as np\n'), ((116523, 116553), 'numpy.sqrt', 'np.sqrt', (['(x * x + y * y + z * z)'], {}), '(x * x + y * y + z * z)\n', (116530, 116553), True, 'import numpy as np\n'), ((116818, 116888), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'ra': 'ra', 'dec': 'dec', 'r': 'r', 'ra_units': '"""deg"""', 'dec_units': '"""deg"""'}), "(ra=ra, dec=dec, r=r, ra_units='deg', dec_units='deg')\n", (116834, 116888), False, 'import treecorr\n'), ((116899, 117070), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'min_v': 'min_v', 'max_v': 'max_v', 'nubins': 'nubins', 'nvbins': 'nvbins', 'verbose': '(1)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, min_v=min_v, max_v=max_v, nubins=nubins,\n nvbins=nvbins, verbose=1)\n', (116922, 117070), False, 'import treecorr\n'), ((117359, 117395), 'numpy.sqrt', 'np.sqrt', (['(rx * rx + ry * ry + rz * rz)'], {}), '(rx * rx + ry * ry + rz * rz)\n', (117366, 117395), True, 'import numpy as np\n'), ((117522, 117595), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'ra': 'rra', 'dec': 'rdec', 'r': 'rr', 'ra_units': '"""deg"""', 'dec_units': '"""deg"""'}), "(ra=rra, dec=rdec, r=rr, ra_units='deg', dec_units='deg')\n", (117538, 117595), False, 'import treecorr\n'), ((117606, 117777), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'min_v': 'min_v', 'max_v': 'max_v', 'nubins': 'nubins', 'nvbins': 'nvbins', 'verbose': '(1)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, min_v=min_v, max_v=max_v, nubins=nubins,\n nvbins=nvbins, verbose=1)\n', (117629, 117777), False, 'import treecorr\n'), ((118611, 118677), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['zeta', 'true_zeta'], {'rtol': '(0.1 * tol_factor)'}), '(zeta, true_zeta, rtol=0.1 * tol_factor)\n', (118637, 118677), True, 'import numpy as np\n'), ((118999, 119049), 'treecorr.config.read_config', 'treecorr.config.read_config', (['"""configs/nnn_3d.yaml"""'], {}), "('configs/nnn_3d.yaml')\n", (119026, 119049), False, 'import treecorr\n'), ((119080, 119102), 'treecorr.corr3', 'treecorr.corr3', (['config'], {}), '(config)\n', (119094, 119102), False, 'import treecorr\n'), ((119575, 119606), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'x': 'x', 'y': 'y', 'z': 'z'}), '(x=x, y=y, z=z)\n', (119591, 119606), False, 'import treecorr\n'), ((119618, 119652), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'x': 'rx', 'y': 'ry', 'z': 'rz'}), '(x=rx, y=ry, z=rz)\n', (119634, 119652), False, 'import treecorr\n'), ((119743, 119809), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['zeta', 'true_zeta'], {'rtol': '(0.1 * tol_factor)'}), '(zeta, true_zeta, rtol=0.1 * tol_factor)\n', (119769, 119809), True, 'import numpy as np\n'), ((120172, 120202), 'numpy.random.RandomState', 'np.random.RandomState', (['(8675309)'], {}), '(8675309)\n', (120193, 120202), True, 'import numpy as np\n'), ((120700, 120885), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'min_v': 'min_v', 'max_v': 'max_v', 'nubins': 'nubins', 'nvbins': 'nvbins', 'bin_slop': '(0.1)', 'verbose': '(1)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, min_v=min_v, max_v=max_v, nubins=nubins,\n nvbins=nvbins, bin_slop=0.1, verbose=1)\n', (120723, 120885), False, 'import treecorr\n'), ((121120, 121305), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'min_v': 'min_v', 'max_v': 'max_v', 'nubins': 'nubins', 'nvbins': 'nvbins', 'bin_slop': '(0.1)', 'verbose': '(1)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, min_v=min_v, max_v=max_v, nubins=nubins,\n nvbins=nvbins, bin_slop=0.1, verbose=1)\n', (121143, 121305), False, 'import treecorr\n'), ((121754, 121811), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd.ntri', 'dddx.ntri'], {'rtol': '(0.1)'}), '(ddd.ntri, dddx.ntri, rtol=0.1)\n', (121780, 121811), True, 'import numpy as np\n'), ((121816, 121861), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ddd.tot', 'dddx.tot'], {}), '(ddd.tot, dddx.tot)\n', (121842, 121861), True, 'import numpy as np\n'), ((121873, 122058), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'min_v': 'min_v', 'max_v': 'max_v', 'nubins': 'nubins', 'nvbins': 'nvbins', 'bin_slop': '(0.1)', 'verbose': '(1)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, min_v=min_v, max_v=max_v, nubins=nubins,\n nvbins=nvbins, bin_slop=0.1, verbose=1)\n', (121896, 122058), False, 'import treecorr\n'), ((122192, 122377), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'min_v': 'min_v', 'max_v': 'max_v', 'nubins': 'nubins', 'nvbins': 'nvbins', 'bin_slop': '(0.1)', 'verbose': '(1)'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, min_v=min_v, max_v=max_v, nubins=nubins,\n nvbins=nvbins, bin_slop=0.1, verbose=1)\n', (122215, 122377), False, 'import treecorr\n'), ((122605, 122662), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['rrr.ntri', 'rrrx.ntri'], {'rtol': '(0.1)'}), '(rrr.ntri, rrrx.ntri, rtol=0.1)\n', (122631, 122662), True, 'import numpy as np\n'), ((122667, 122712), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['rrr.tot', 'rrrx.tot'], {}), '(rrr.tot, rrrx.tot)\n', (122693, 122712), True, 'import numpy as np\n'), ((122929, 122978), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['zeta', 'zetax'], {'rtol': '(0.1)'}), '(zeta, zetax, rtol=0.1)\n', (122955, 122978), True, 'import numpy as np\n'), ((123432, 123479), 'os.path.join', 'os.path.join', (['"""data"""', '"""nnn_list_data_files.txt"""'], {}), "('data', 'nnn_list_data_files.txt')\n", (123444, 123479), False, 'import os\n'), ((123614, 123661), 'os.path.join', 'os.path.join', (['"""data"""', '"""nnn_list_rand_files.txt"""'], {}), "('data', 'nnn_list_rand_files.txt')\n", (123626, 123661), False, 'import os\n'), ((123803, 123845), 'os.path.join', 'os.path.join', (['"""data"""', '"""nnn_list_datax.dat"""'], {}), "('data', 'nnn_list_datax.dat')\n", (123815, 123845), False, 'import os\n'), ((123900, 123942), 'os.path.join', 'os.path.join', (['"""data"""', '"""nnn_list_randx.dat"""'], {}), "('data', 'nnn_list_randx.dat')\n", (123912, 123942), False, 'import os\n'), ((123993, 124046), 'treecorr.config.read_config', 'treecorr.config.read_config', (['"""configs/nnn_list1.yaml"""'], {}), "('configs/nnn_list1.yaml')\n", (124020, 124046), False, 'import treecorr\n'), ((124106, 124128), 'treecorr.corr3', 'treecorr.corr3', (['config'], {}), '(config)\n', (124120, 124128), False, 'import treecorr\n'), ((124520, 124573), 'treecorr.config.read_config', 'treecorr.config.read_config', (['"""configs/nnn_list2.json"""'], {}), "('configs/nnn_list2.json')\n", (124547, 124573), False, 'import treecorr\n'), ((124633, 124655), 'treecorr.corr3', 'treecorr.corr3', (['config'], {}), '(config)\n', (124647, 124655), False, 'import treecorr\n'), ((125046, 125101), 'treecorr.config.read_config', 'treecorr.config.read_config', (['"""configs/nnn_list3.params"""'], {}), "('configs/nnn_list3.params')\n", (125073, 125101), False, 'import treecorr\n'), ((125161, 125183), 'treecorr.corr3', 'treecorr.corr3', (['config'], {}), '(config)\n', (125175, 125183), False, 'import treecorr\n'), ((125574, 125649), 'treecorr.config.read_config', 'treecorr.config.read_config', (['"""configs/nnn_list4.config"""'], {'file_type': '"""params"""'}), "('configs/nnn_list4.config', file_type='params')\n", (125601, 125649), False, 'import treecorr\n'), ((125709, 125731), 'treecorr.corr3', 'treecorr.corr3', (['config'], {}), '(config)\n', (125723, 125731), False, 'import treecorr\n'), ((1075, 1161), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['(nnn.ubin_size * nnn.nubins)', '(nnn.max_u - nnn.min_u)'], {}), '(nnn.ubin_size * nnn.nubins, nnn.max_u - nnn.\n min_u)\n', (1105, 1161), True, 'import numpy as np\n'), ((1163, 1249), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['(nnn.vbin_size * nnn.nvbins)', '(nnn.max_v - nnn.min_v)'], {}), '(nnn.vbin_size * nnn.nvbins, nnn.max_v - nnn.\n min_v)\n', (1193, 1249), True, 'import numpy as np\n'), ((1288, 1343), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['nnn.logr1d.shape', '(nnn.nbins,)'], {}), '(nnn.logr1d.shape, (nnn.nbins,))\n', (1311, 1343), True, 'import numpy as np\n'), ((1546, 1631), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['nnn.logr.shape', '(nnn.nbins, nnn.nubins, 2 * nnn.nvbins)'], {}), '(nnn.logr.shape, (nnn.nbins, nnn.nubins, 2 * nnn.nvbins)\n )\n', (1569, 1631), True, 'import numpy as np\n'), ((1634, 1695), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.logr[:, 0, 0]', 'nnn.logr1d'], {}), '(nnn.logr[:, 0, 0], nnn.logr1d)\n', (1664, 1695), True, 'import numpy as np\n'), ((1702, 1765), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.logr[:, -1, -1]', 'nnn.logr1d'], {}), '(nnn.logr[:, -1, -1], nnn.logr1d)\n', (1732, 1765), True, 'import numpy as np\n'), ((1845, 1898), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['nnn.u1d.shape', '(nnn.nubins,)'], {}), '(nnn.u1d.shape, (nnn.nubins,))\n', (1868, 1898), True, 'import numpy as np\n'), ((1908, 1983), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.u1d[0]', '(nnn.min_u + 0.5 * nnn.ubin_size)'], {}), '(nnn.u1d[0], nnn.min_u + 0.5 * nnn.ubin_size)\n', (1938, 1983), True, 'import numpy as np\n'), ((1990, 2066), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.u1d[-1]', '(nnn.max_u - 0.5 * nnn.ubin_size)'], {}), '(nnn.u1d[-1], nnn.max_u - 0.5 * nnn.ubin_size)\n', (2020, 2066), True, 'import numpy as np\n'), ((2073, 2150), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['nnn.u.shape', '(nnn.nbins, nnn.nubins, 2 * nnn.nvbins)'], {}), '(nnn.u.shape, (nnn.nbins, nnn.nubins, 2 * nnn.nvbins))\n', (2096, 2150), True, 'import numpy as np\n'), ((2158, 2213), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.u[0, :, 0]', 'nnn.u1d'], {}), '(nnn.u[0, :, 0], nnn.u1d)\n', (2188, 2213), True, 'import numpy as np\n'), ((2220, 2277), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.u[-1, :, -1]', 'nnn.u1d'], {}), '(nnn.u[-1, :, -1], nnn.u1d)\n', (2250, 2277), True, 'import numpy as np\n'), ((2315, 2372), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['nnn.v1d.shape', '(2 * nnn.nvbins,)'], {}), '(nnn.v1d.shape, (2 * nnn.nvbins,))\n', (2338, 2372), True, 'import numpy as np\n'), ((2380, 2456), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.v1d[0]', '(-nnn.max_v + 0.5 * nnn.vbin_size)'], {}), '(nnn.v1d[0], -nnn.max_v + 0.5 * nnn.vbin_size)\n', (2410, 2456), True, 'import numpy as np\n'), ((2463, 2539), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.v1d[-1]', '(nnn.max_v - 0.5 * nnn.vbin_size)'], {}), '(nnn.v1d[-1], nnn.max_v - 0.5 * nnn.vbin_size)\n', (2493, 2539), True, 'import numpy as np\n'), ((2546, 2635), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.v1d[nnn.nvbins]', '(nnn.min_v + 0.5 * nnn.vbin_size)'], {}), '(nnn.v1d[nnn.nvbins], nnn.min_v + 0.5 * nnn.\n vbin_size)\n', (2576, 2635), True, 'import numpy as np\n'), ((2637, 2730), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.v1d[nnn.nvbins - 1]', '(-nnn.min_v - 0.5 * nnn.vbin_size)'], {}), '(nnn.v1d[nnn.nvbins - 1], -nnn.min_v - 0.5 *\n nnn.vbin_size)\n', (2667, 2730), True, 'import numpy as np\n'), ((2731, 2808), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['nnn.v.shape', '(nnn.nbins, nnn.nubins, 2 * nnn.nvbins)'], {}), '(nnn.v.shape, (nnn.nbins, nnn.nubins, 2 * nnn.nvbins))\n', (2754, 2808), True, 'import numpy as np\n'), ((2816, 2871), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.v[0, 0, :]', 'nnn.v1d'], {}), '(nnn.v[0, 0, :], nnn.v1d)\n', (2846, 2871), True, 'import numpy as np\n'), ((2878, 2935), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['nnn.v[-1, -1, :]', 'nnn.v1d'], {}), '(nnn.v[-1, -1, :], nnn.v1d)\n', (2908, 2935), True, 'import numpy as np\n'), ((15614, 15649), 'math.log', 'math.log', (['(nnn.max_sep / nnn.min_sep)'], {}), '(nnn.max_sep / nnn.min_sep)\n', (15622, 15649), False, 'import math\n'), ((16544, 16579), 'math.log', 'math.log', (['(nnn.max_sep / nnn.min_sep)'], {}), '(nnn.max_sep / nnn.min_sep)\n', (16552, 16579), False, 'import math\n'), ((17408, 17443), 'math.log', 'math.log', (['(nnn.max_sep / nnn.min_sep)'], {}), '(nnn.max_sep / nnn.min_sep)\n', (17416, 17443), False, 'import math\n'), ((18266, 18301), 'math.log', 'math.log', (['(nnn.max_sep / nnn.min_sep)'], {}), '(nnn.max_sep / nnn.min_sep)\n', (18274, 18301), False, 'import math\n'), ((29011, 29051), 'os.path.join', 'os.path.join', (['"""output"""', '"""nnn_direct.out"""'], {}), "('output', 'nnn_direct.out')\n", (29023, 29051), False, 'import os\n'), ((31123, 31163), 'os.path.join', 'os.path.join', (['"""output"""', '"""nnn_direct.out"""'], {}), "('output', 'nnn_direct.out')\n", (31135, 31163), False, 'import os\n'), ((32132, 32172), 'os.path.join', 'os.path.join', (['"""output"""', '"""nnn_direct.out"""'], {}), "('output', 'nnn_direct.out')\n", (32144, 32172), False, 'import os\n'), ((35513, 35561), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['d.ntri', 'true_ntri'], {}), '(d.ntri, true_ntri)\n', (35542, 35561), True, 'import numpy as np\n'), ((35934, 35982), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['d.ntri', 'true_ntri'], {}), '(d.ntri, true_ntri)\n', (35963, 35982), True, 'import numpy as np\n'), ((36079, 36103), 'test_helper.assert_raises', 'assert_raises', (['TypeError'], {}), '(TypeError)\n', (36092, 36103), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((36113, 36135), 'treecorr.corr3', 'treecorr.corr3', (['config'], {}), '(config)\n', (36127, 36135), False, 'import treecorr\n'), ((38897, 38921), 'test_helper.assert_raises', 'assert_raises', (['TypeError'], {}), '(TypeError)\n', (38910, 38921), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((39191, 39216), 'test_helper.assert_raises', 'assert_raises', (['ValueError'], {}), '(ValueError)\n', (39204, 39216), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((39484, 39509), 'test_helper.assert_raises', 'assert_raises', (['ValueError'], {}), '(ValueError)\n', (39497, 39509), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((39777, 39802), 'test_helper.assert_raises', 'assert_raises', (['ValueError'], {}), '(ValueError)\n', (39790, 39802), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((40072, 40097), 'test_helper.assert_raises', 'assert_raises', (['ValueError'], {}), '(ValueError)\n', (40085, 40097), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((40367, 40392), 'test_helper.assert_raises', 'assert_raises', (['ValueError'], {}), '(ValueError)\n', (40380, 40392), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((40660, 40685), 'test_helper.assert_raises', 'assert_raises', (['ValueError'], {}), '(ValueError)\n', (40673, 40685), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((40958, 40983), 'test_helper.assert_raises', 'assert_raises', (['ValueError'], {}), '(ValueError)\n', (40971, 40983), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((41257, 41282), 'test_helper.assert_raises', 'assert_raises', (['ValueError'], {}), '(ValueError)\n', (41270, 41282), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((41554, 41579), 'test_helper.assert_raises', 'assert_raises', (['ValueError'], {}), '(ValueError)\n', (41567, 41579), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((41737, 41749), 'test_helper.CaptureLog', 'CaptureLog', ([], {}), '()\n', (41747, 41749), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((41773, 41951), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'logger': 'cl.logger'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, logger=cl.logger)\n', (41796, 41951), False, 'import treecorr\n'), ((42224, 42236), 'test_helper.CaptureLog', 'CaptureLog', ([], {}), '()\n', (42234, 42236), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((42260, 42438), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'nubins': 'nubins', 'min_v': 'min_v', 'max_v': 'max_v', 'nvbins': 'nvbins', 'logger': 'cl.logger'}), '(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, nubins=nubins, min_v=min_v, max_v=max_v,\n nvbins=nvbins, logger=cl.logger)\n', (42283, 42438), False, 'import treecorr\n'), ((50189, 50214), 'test_helper.assert_raises', 'assert_raises', (['ValueError'], {}), '(ValueError)\n', (50202, 50214), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((50539, 50587), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', '(2 * d1.ntri)'], {}), '(d2.ntri, 2 * d1.ntri)\n', (50565, 50587), True, 'import numpy as np\n'), ((50594, 50642), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', '(2 * d1.ntri)'], {}), '(d2.ntri, 2 * d1.ntri)\n', (50620, 50642), True, 'import numpy as np\n'), ((50649, 50697), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', '(2 * d1.ntri)'], {}), '(d2.ntri, 2 * d1.ntri)\n', (50675, 50697), True, 'import numpy as np\n'), ((50704, 50752), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', '(2 * d1.ntri)'], {}), '(d2.ntri, 2 * d1.ntri)\n', (50730, 50752), True, 'import numpy as np\n'), ((50759, 50807), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', '(2 * d1.ntri)'], {}), '(d2.ntri, 2 * d1.ntri)\n', (50785, 50807), True, 'import numpy as np\n'), ((50814, 50862), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', '(2 * d1.ntri)'], {}), '(d2.ntri, 2 * d1.ntri)\n', (50840, 50862), True, 'import numpy as np\n'), ((50869, 50921), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meand1', '(2 * d1.meand1)'], {}), '(d2.meand1, 2 * d1.meand1)\n', (50895, 50921), True, 'import numpy as np\n'), ((50928, 50980), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meand2', '(2 * d1.meand2)'], {}), '(d2.meand2, 2 * d1.meand2)\n', (50954, 50980), True, 'import numpy as np\n'), ((50987, 51039), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meand3', '(2 * d1.meand3)'], {}), '(d2.meand3, 2 * d1.meand3)\n', (51013, 51039), True, 'import numpy as np\n'), ((51046, 51104), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meanlogd1', '(2 * d1.meanlogd1)'], {}), '(d2.meanlogd1, 2 * d1.meanlogd1)\n', (51072, 51104), True, 'import numpy as np\n'), ((51111, 51169), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meanlogd2', '(2 * d1.meanlogd2)'], {}), '(d2.meanlogd2, 2 * d1.meanlogd2)\n', (51137, 51169), True, 'import numpy as np\n'), ((51176, 51234), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meanlogd3', '(2 * d1.meanlogd3)'], {}), '(d2.meanlogd3, 2 * d1.meanlogd3)\n', (51202, 51234), True, 'import numpy as np\n'), ((51241, 51291), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meanu', '(2 * d1.meanu)'], {}), '(d2.meanu, 2 * d1.meanu)\n', (51267, 51291), True, 'import numpy as np\n'), ((51298, 51348), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meanv', '(2 * d1.meanv)'], {}), '(d2.meanv, 2 * d1.meanv)\n', (51324, 51348), True, 'import numpy as np\n'), ((51537, 51581), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', 'd1.ntri'], {}), '(d2.ntri, d1.ntri)\n', (51563, 51581), True, 'import numpy as np\n'), ((51590, 51634), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', 'd1.ntri'], {}), '(d2.ntri, d1.ntri)\n', (51616, 51634), True, 'import numpy as np\n'), ((51643, 51687), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', 'd1.ntri'], {}), '(d2.ntri, d1.ntri)\n', (51669, 51687), True, 'import numpy as np\n'), ((51696, 51740), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', 'd1.ntri'], {}), '(d2.ntri, d1.ntri)\n', (51722, 51740), True, 'import numpy as np\n'), ((51749, 51793), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', 'd1.ntri'], {}), '(d2.ntri, d1.ntri)\n', (51775, 51793), True, 'import numpy as np\n'), ((51802, 51846), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', 'd1.ntri'], {}), '(d2.ntri, d1.ntri)\n', (51828, 51846), True, 'import numpy as np\n'), ((51855, 51903), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meand1', 'd1.meand1'], {}), '(d2.meand1, d1.meand1)\n', (51881, 51903), True, 'import numpy as np\n'), ((51912, 51960), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meand2', 'd1.meand2'], {}), '(d2.meand2, d1.meand2)\n', (51938, 51960), True, 'import numpy as np\n'), ((51969, 52017), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meand3', 'd1.meand3'], {}), '(d2.meand3, d1.meand3)\n', (51995, 52017), True, 'import numpy as np\n'), ((52026, 52080), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meanlogd1', 'd1.meanlogd1'], {}), '(d2.meanlogd1, d1.meanlogd1)\n', (52052, 52080), True, 'import numpy as np\n'), ((52089, 52143), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meanlogd2', 'd1.meanlogd2'], {}), '(d2.meanlogd2, d1.meanlogd2)\n', (52115, 52143), True, 'import numpy as np\n'), ((52152, 52206), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meanlogd3', 'd1.meanlogd3'], {}), '(d2.meanlogd3, d1.meanlogd3)\n', (52178, 52206), True, 'import numpy as np\n'), ((52215, 52261), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meanu', 'd1.meanu'], {}), '(d2.meanu, d1.meanu)\n', (52241, 52261), True, 'import numpy as np\n'), ((52270, 52316), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meanv', 'd1.meanv'], {}), '(d2.meanv, d1.meanv)\n', (52296, 52316), True, 'import numpy as np\n'), ((52327, 52351), 'test_helper.assert_raises', 'assert_raises', (['TypeError'], {}), '(TypeError)\n', (52340, 52351), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((52416, 52440), 'test_helper.assert_raises', 'assert_raises', (['TypeError'], {}), '(TypeError)\n', (52429, 52440), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((52759, 52784), 'test_helper.assert_raises', 'assert_raises', (['ValueError'], {}), '(ValueError)\n', (52772, 52784), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((53364, 53408), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', 'd1.ntri'], {}), '(d2.ntri, d1.ntri)\n', (53390, 53408), True, 'import numpy as np\n'), ((53417, 53461), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', 'd1.ntri'], {}), '(d2.ntri, d1.ntri)\n', (53443, 53461), True, 'import numpy as np\n'), ((53470, 53514), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', 'd1.ntri'], {}), '(d2.ntri, d1.ntri)\n', (53496, 53514), True, 'import numpy as np\n'), ((53523, 53567), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', 'd1.ntri'], {}), '(d2.ntri, d1.ntri)\n', (53549, 53567), True, 'import numpy as np\n'), ((53576, 53620), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', 'd1.ntri'], {}), '(d2.ntri, d1.ntri)\n', (53602, 53620), True, 'import numpy as np\n'), ((53629, 53673), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', 'd1.ntri'], {}), '(d2.ntri, d1.ntri)\n', (53655, 53673), True, 'import numpy as np\n'), ((53682, 53730), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meand1', 'd1.meand1'], {}), '(d2.meand1, d1.meand1)\n', (53708, 53730), True, 'import numpy as np\n'), ((53739, 53787), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meand2', 'd1.meand2'], {}), '(d2.meand2, d1.meand2)\n', (53765, 53787), True, 'import numpy as np\n'), ((53796, 53844), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meand3', 'd1.meand3'], {}), '(d2.meand3, d1.meand3)\n', (53822, 53844), True, 'import numpy as np\n'), ((53853, 53907), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meanlogd1', 'd1.meanlogd1'], {}), '(d2.meanlogd1, d1.meanlogd1)\n', (53879, 53907), True, 'import numpy as np\n'), ((53916, 53970), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meanlogd2', 'd1.meanlogd2'], {}), '(d2.meanlogd2, d1.meanlogd2)\n', (53942, 53970), True, 'import numpy as np\n'), ((53979, 54033), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meanlogd3', 'd1.meanlogd3'], {}), '(d2.meanlogd3, d1.meanlogd3)\n', (54005, 54033), True, 'import numpy as np\n'), ((54042, 54088), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meanu', 'd1.meanu'], {}), '(d2.meanu, d1.meanu)\n', (54068, 54088), True, 'import numpy as np\n'), ((54097, 54143), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meanv', 'd1.meanv'], {}), '(d2.meanv, d1.meanv)\n', (54123, 54143), True, 'import numpy as np\n'), ((54642, 54686), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', 'd1.ntri'], {}), '(d2.ntri, d1.ntri)\n', (54668, 54686), True, 'import numpy as np\n'), ((54695, 54739), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', 'd1.ntri'], {}), '(d2.ntri, d1.ntri)\n', (54721, 54739), True, 'import numpy as np\n'), ((54748, 54792), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', 'd1.ntri'], {}), '(d2.ntri, d1.ntri)\n', (54774, 54792), True, 'import numpy as np\n'), ((54801, 54845), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', 'd1.ntri'], {}), '(d2.ntri, d1.ntri)\n', (54827, 54845), True, 'import numpy as np\n'), ((54854, 54898), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', 'd1.ntri'], {}), '(d2.ntri, d1.ntri)\n', (54880, 54898), True, 'import numpy as np\n'), ((54907, 54951), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', 'd1.ntri'], {}), '(d2.ntri, d1.ntri)\n', (54933, 54951), True, 'import numpy as np\n'), ((54960, 55008), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meand1', 'd1.meand1'], {}), '(d2.meand1, d1.meand1)\n', (54986, 55008), True, 'import numpy as np\n'), ((55017, 55065), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meand2', 'd1.meand2'], {}), '(d2.meand2, d1.meand2)\n', (55043, 55065), True, 'import numpy as np\n'), ((55074, 55122), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meand3', 'd1.meand3'], {}), '(d2.meand3, d1.meand3)\n', (55100, 55122), True, 'import numpy as np\n'), ((55131, 55185), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meanlogd1', 'd1.meanlogd1'], {}), '(d2.meanlogd1, d1.meanlogd1)\n', (55157, 55185), True, 'import numpy as np\n'), ((55194, 55248), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meanlogd2', 'd1.meanlogd2'], {}), '(d2.meanlogd2, d1.meanlogd2)\n', (55220, 55248), True, 'import numpy as np\n'), ((55257, 55311), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meanlogd3', 'd1.meanlogd3'], {}), '(d2.meanlogd3, d1.meanlogd3)\n', (55283, 55311), True, 'import numpy as np\n'), ((55320, 55366), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meanu', 'd1.meanu'], {}), '(d2.meanu, d1.meanu)\n', (55346, 55366), True, 'import numpy as np\n'), ((55375, 55421), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meanv', 'd1.meanv'], {}), '(d2.meanv, d1.meanv)\n', (55401, 55421), True, 'import numpy as np\n'), ((56059, 56103), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', 'd1.ntri'], {}), '(d2.ntri, d1.ntri)\n', (56085, 56103), True, 'import numpy as np\n'), ((56112, 56156), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', 'd1.ntri'], {}), '(d2.ntri, d1.ntri)\n', (56138, 56156), True, 'import numpy as np\n'), ((56165, 56209), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', 'd1.ntri'], {}), '(d2.ntri, d1.ntri)\n', (56191, 56209), True, 'import numpy as np\n'), ((56218, 56262), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', 'd1.ntri'], {}), '(d2.ntri, d1.ntri)\n', (56244, 56262), True, 'import numpy as np\n'), ((56271, 56315), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', 'd1.ntri'], {}), '(d2.ntri, d1.ntri)\n', (56297, 56315), True, 'import numpy as np\n'), ((56324, 56368), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.ntri', 'd1.ntri'], {}), '(d2.ntri, d1.ntri)\n', (56350, 56368), True, 'import numpy as np\n'), ((56377, 56425), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meand1', 'd1.meand1'], {}), '(d2.meand1, d1.meand1)\n', (56403, 56425), True, 'import numpy as np\n'), ((56434, 56482), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meand2', 'd1.meand2'], {}), '(d2.meand2, d1.meand2)\n', (56460, 56482), True, 'import numpy as np\n'), ((56491, 56539), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meand3', 'd1.meand3'], {}), '(d2.meand3, d1.meand3)\n', (56517, 56539), True, 'import numpy as np\n'), ((56548, 56602), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meanlogd1', 'd1.meanlogd1'], {}), '(d2.meanlogd1, d1.meanlogd1)\n', (56574, 56602), True, 'import numpy as np\n'), ((56611, 56665), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meanlogd2', 'd1.meanlogd2'], {}), '(d2.meanlogd2, d1.meanlogd2)\n', (56637, 56665), True, 'import numpy as np\n'), ((56674, 56728), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meanlogd3', 'd1.meanlogd3'], {}), '(d2.meanlogd3, d1.meanlogd3)\n', (56700, 56728), True, 'import numpy as np\n'), ((56737, 56783), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meanu', 'd1.meanu'], {}), '(d2.meanu, d1.meanu)\n', (56763, 56783), True, 'import numpy as np\n'), ((56792, 56838), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['d2.meanv', 'd1.meanv'], {}), '(d2.meanv, d1.meanv)\n', (56818, 56838), True, 'import numpy as np\n'), ((68137, 68162), 'numpy.log', 'np.log', (['(max_sep / min_sep)'], {}), '(max_sep / min_sep)\n', (68143, 68162), True, 'import numpy as np\n'), ((68743, 68801), 'coord.CelestialCoord', 'coord.CelestialCoord', (['(r * coord.radians)', '(d * coord.radians)'], {}), '(r * coord.radians, d * coord.radians)\n', (68763, 68801), False, 'import coord\n'), ((96871, 96889), 'numpy.log', 'np.log', (['ddd.meand1'], {}), '(ddd.meand1)\n', (96877, 96889), True, 'import numpy as np\n'), ((96949, 96967), 'numpy.log', 'np.log', (['ddd.meand2'], {}), '(ddd.meand2)\n', (96955, 96967), True, 'import numpy as np\n'), ((97027, 97045), 'numpy.log', 'np.log', (['ddd.meand3'], {}), '(ddd.meand3)\n', (97033, 97045), True, 'import numpy as np\n'), ((97216, 97233), 'numpy.abs', 'np.abs', (['ddd.meanv'], {}), '(ddd.meanv)\n', (97222, 97233), True, 'import numpy as np\n'), ((97379, 97396), 'numpy.log', 'np.log', (['ddd.meanu'], {}), '(ddd.meanu)\n', (97385, 97396), True, 'import numpy as np\n'), ((98995, 99031), 'os.path.join', 'os.path.join', (['"""data"""', '"""nnn_data.dat"""'], {}), "('data', 'nnn_data.dat')\n", (99007, 99031), False, 'import os\n'), ((99047, 99083), 'os.path.join', 'os.path.join', (['"""data"""', '"""nnn_rand.dat"""'], {}), "('data', 'nnn_rand.dat')\n", (99059, 99083), False, 'import os\n'), ((99231, 99264), 'os.path.join', 'os.path.join', (['"""output"""', '"""nnn.out"""'], {}), "('output', 'nnn.out')\n", (99243, 99264), False, 'import os\n'), ((104630, 104669), 'os.path.join', 'os.path.join', (['"""output"""', '"""nnn_out3.hdf5"""'], {}), "('output', 'nnn_out3.hdf5')\n", (104642, 104669), False, 'import os\n'), ((106217, 106408), 'treecorr.NNNCorrelation', 'treecorr.NNNCorrelation', ([], {'min_sep': 'min_sep', 'max_sep': 'max_sep', 'nbins': 'nbins', 'min_u': 'min_u', 'max_u': 'max_u', 'min_v': 'min_v', 'max_v': 'max_v', 'nubins': 'nubins', 'nvbins': 'nvbins', 'sep_units': '"""arcmin"""', 'verbose': '(1)'}), "(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, min_v=min_v, max_v=max_v, nubins=nubins,\n nvbins=nvbins, sep_units='arcmin', verbose=1)\n", (106240, 106408), False, 'import treecorr\n'), ((106560, 106611), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd3.logr', 'ddd.logr'], {}), '(ddd3.logr, ddd.logr)\n', (106590, 106611), True, 'import numpy as np\n'), ((106620, 106665), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd3.u', 'ddd.u'], {}), '(ddd3.u, ddd.u)\n', (106650, 106665), True, 'import numpy as np\n'), ((106674, 106719), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd3.v', 'ddd.v'], {}), '(ddd3.v, ddd.v)\n', (106704, 106719), True, 'import numpy as np\n'), ((106728, 106783), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd3.meand1', 'ddd.meand1'], {}), '(ddd3.meand1, ddd.meand1)\n', (106758, 106783), True, 'import numpy as np\n'), ((106792, 106853), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd3.meanlogd1', 'ddd.meanlogd1'], {}), '(ddd3.meanlogd1, ddd.meanlogd1)\n', (106822, 106853), True, 'import numpy as np\n'), ((106862, 106917), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd3.meand2', 'ddd.meand2'], {}), '(ddd3.meand2, ddd.meand2)\n', (106892, 106917), True, 'import numpy as np\n'), ((106926, 106987), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd3.meanlogd2', 'ddd.meanlogd2'], {}), '(ddd3.meanlogd2, ddd.meanlogd2)\n', (106956, 106987), True, 'import numpy as np\n'), ((106996, 107051), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd3.meand3', 'ddd.meand3'], {}), '(ddd3.meand3, ddd.meand3)\n', (107026, 107051), True, 'import numpy as np\n'), ((107060, 107121), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd3.meanlogd3', 'ddd.meanlogd3'], {}), '(ddd3.meanlogd3, ddd.meanlogd3)\n', (107090, 107121), True, 'import numpy as np\n'), ((107130, 107183), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd3.meanu', 'ddd.meanu'], {}), '(ddd3.meanu, ddd.meanu)\n', (107160, 107183), True, 'import numpy as np\n'), ((107192, 107245), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd3.meanv', 'ddd.meanv'], {}), '(ddd3.meanv, ddd.meanv)\n', (107222, 107245), True, 'import numpy as np\n'), ((107254, 107305), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['ddd3.ntri', 'ddd.ntri'], {}), '(ddd3.ntri, ddd.ntri)\n', (107284, 107305), True, 'import numpy as np\n'), ((107314, 107369), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['(ddd3.tot / ddd.tot)', '(1.0)'], {}), '(ddd3.tot / ddd.tot, 1.0)\n', (107344, 107369), True, 'import numpy as np\n'), ((107904, 107928), 'test_helper.assert_raises', 'assert_raises', (['TypeError'], {}), '(TypeError)\n', (107917, 107928), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((107982, 108006), 'test_helper.assert_raises', 'assert_raises', (['TypeError'], {}), '(TypeError)\n', (107995, 108006), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((108056, 108080), 'test_helper.assert_raises', 'assert_raises', (['TypeError'], {}), '(TypeError)\n', (108069, 108080), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((108433, 108458), 'test_helper.assert_raises', 'assert_raises', (['ValueError'], {}), '(ValueError)\n', (108446, 108458), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((108517, 108542), 'test_helper.assert_raises', 'assert_raises', (['ValueError'], {}), '(ValueError)\n', (108530, 108542), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((108601, 108626), 'test_helper.assert_raises', 'assert_raises', (['ValueError'], {}), '(ValueError)\n', (108614, 108626), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((108746, 108770), 'test_helper.assert_raises', 'assert_raises', (['TypeError'], {}), '(TypeError)\n', (108759, 108770), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((108831, 108855), 'test_helper.assert_raises', 'assert_raises', (['TypeError'], {}), '(TypeError)\n', (108844, 108855), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((108916, 108940), 'test_helper.assert_raises', 'assert_raises', (['TypeError'], {}), '(TypeError)\n', (108929, 108940), False, 'from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer\n'), ((116554, 116570), 'numpy.arcsin', 'np.arcsin', (['(z / r)'], {}), '(z / r)\n', (116563, 116570), True, 'import numpy as np\n'), ((116612, 116628), 'numpy.arctan2', 'np.arctan2', (['y', 'x'], {}), '(y, x)\n', (116622, 116628), True, 'import numpy as np\n'), ((117397, 117415), 'numpy.arcsin', 'np.arcsin', (['(rz / rr)'], {}), '(rz / rr)\n', (117406, 117415), True, 'import numpy as np\n'), ((117458, 117476), 'numpy.arctan2', 'np.arctan2', (['ry', 'rx'], {}), '(ry, rx)\n', (117468, 117476), True, 'import numpy as np\n'), ((118891, 118930), 'os.path.join', 'os.path.join', (['"""data"""', '"""nnn_3d_data.dat"""'], {}), "('data', 'nnn_3d_data.dat')\n", (118903, 118930), False, 'import os\n'), ((118946, 118985), 'os.path.join', 'os.path.join', (['"""data"""', '"""nnn_3d_rand.dat"""'], {}), "('data', 'nnn_3d_rand.dat')\n", (118958, 118985), False, 'import os\n'), ((119136, 119172), 'os.path.join', 'os.path.join', (['"""output"""', '"""nnn_3d.out"""'], {}), "('output', 'nnn_3d.out')\n", (119148, 119172), False, 'import os\n'), ((120443, 120481), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'x': 'x[:, k]', 'y': 'y[:, k]'}), '(x=x[:, k], y=y[:, k])\n', (120459, 120481), False, 'import treecorr\n'), ((120626, 120666), 'treecorr.Catalog', 'treecorr.Catalog', ([], {'x': 'rx[:, k]', 'y': 'ry[:, k]'}), '(x=rx[:, k], y=ry[:, k])\n', (120642, 120666), False, 'import treecorr\n'), ((123136, 123183), 'os.path.join', 'os.path.join', (['"""data"""', "('nnn_list_data%d.dat' % k)"], {}), "('data', 'nnn_list_data%d.dat' % k)\n", (123148, 123183), False, 'import os\n'), ((123281, 123328), 'os.path.join', 'os.path.join', (['"""data"""', "('nnn_list_rand%d.dat' % k)"], {}), "('data', 'nnn_list_rand%d.dat' % k)\n", (123293, 123328), False, 'import os\n'), ((124162, 124201), 'os.path.join', 'os.path.join', (['"""output"""', '"""nnn_list1.out"""'], {}), "('output', 'nnn_list1.out')\n", (124174, 124201), False, 'import os\n'), ((124689, 124728), 'os.path.join', 'os.path.join', (['"""output"""', '"""nnn_list2.out"""'], {}), "('output', 'nnn_list2.out')\n", (124701, 124728), False, 'import os\n'), ((125217, 125256), 'os.path.join', 'os.path.join', (['"""output"""', '"""nnn_list3.out"""'], {}), "('output', 'nnn_list3.out')\n", (125229, 125256), False, 'import os\n'), ((125765, 125804), 'os.path.join', 'os.path.join', (['"""output"""', '"""nnn_list4.out"""'], {}), "('output', 'nnn_list4.out')\n", (125777, 125804), False, 'import os\n'), ((1032, 1067), 'math.log', 'math.log', (['(nnn.max_sep / nnn.min_sep)'], {}), '(nnn.max_sep / nnn.min_sep)\n', (1040, 1067), False, 'import math\n'), ((3056, 3084), 'numpy.ceil', 'np.ceil', (['(1.0 / nnn.ubin_size)'], {}), '(1.0 / nnn.ubin_size)\n', (3063, 3084), True, 'import numpy as np\n'), ((3173, 3201), 'numpy.ceil', 'np.ceil', (['(1.0 / nnn.vbin_size)'], {}), '(1.0 / nnn.vbin_size)\n', (3180, 3201), True, 'import numpy as np\n'), ((15759, 15770), 'math.log', 'math.log', (['(5)'], {}), '(5)\n', (15767, 15770), False, 'import math\n'), ((15840, 15852), 'math.log', 'math.log', (['(20)'], {}), '(20)\n', (15848, 15852), False, 'import math\n'), ((16627, 16638), 'math.log', 'math.log', (['(5)'], {}), '(5)\n', (16635, 16638), False, 'import math\n'), ((16708, 16720), 'math.log', 'math.log', (['(20)'], {}), '(20)\n', (16716, 16720), False, 'import math\n'), ((17491, 17502), 'math.log', 'math.log', (['(5)'], {}), '(5)\n', (17499, 17502), False, 'import math\n'), ((17572, 17584), 'math.log', 'math.log', (['(20)'], {}), '(20)\n', (17580, 17584), False, 'import math\n'), ((18349, 18360), 'math.log', 'math.log', (['(5)'], {}), '(5)\n', (18357, 18360), False, 'import math\n'), ((18430, 18442), 'math.log', 'math.log', (['(20)'], {}), '(20)\n', (18438, 18442), False, 'import math\n'), ((96077, 96095), 'numpy.log', 'np.log', (['ddd.meand1'], {}), '(ddd.meand1)\n', (96083, 96095), True, 'import numpy as np\n'), ((96152, 96170), 'numpy.log', 'np.log', (['ddd.meand2'], {}), '(ddd.meand2)\n', (96158, 96170), True, 'import numpy as np\n'), ((96227, 96245), 'numpy.log', 'np.log', (['ddd.meand3'], {}), '(ddd.meand3)\n', (96233, 96245), True, 'import numpy as np\n'), ((96366, 96409), 'numpy.abs', 'np.abs', (['(ddd.meand3 / ddd.meand2 - ddd.meanu)'], {}), '(ddd.meand3 / ddd.meand2 - ddd.meanu)\n', (96372, 96409), True, 'import numpy as np\n'), ((96444, 96501), 'numpy.abs', 'np.abs', (['((ddd.meand3 / ddd.meand2 - ddd.meanu) / ddd.meanu)'], {}), '((ddd.meand3 / ddd.meand2 - ddd.meanu) / ddd.meanu)\n', (96450, 96501), True, 'import numpy as np\n'), ((97488, 97519), 'numpy.log', 'np.log', (['(ddd.meand1 - ddd.meand2)'], {}), '(ddd.meand1 - ddd.meand2)\n', (97494, 97519), True, 'import numpy as np\n'), ((97574, 97591), 'numpy.abs', 'np.abs', (['ddd.meanv'], {}), '(ddd.meanv)\n', (97580, 97591), True, 'import numpy as np\n'), ((98410, 98465), 'numpy.exp', 'np.exp', (['(-(d1 ** 2 + d2 ** 2 + d3 ** 2) / (6.0 * s ** 2))'], {}), '(-(d1 ** 2 + d2 ** 2 + d3 ** 2) / (6.0 * s ** 2))\n', (98416, 98465), True, 'import numpy as np\n'), ((98672, 98710), 'numpy.abs', 'np.abs', (['((zeta - true_zeta) / true_zeta)'], {}), '((zeta - true_zeta) / true_zeta)\n', (98678, 98710), True, 'import numpy as np\n'), ((98818, 98830), 'numpy.abs', 'np.abs', (['zeta'], {}), '(zeta)\n', (98824, 98830), True, 'import numpy as np\n'), ((98840, 98857), 'numpy.abs', 'np.abs', (['true_zeta'], {}), '(true_zeta)\n', (98846, 98857), True, 'import numpy as np\n'), ((104721, 104751), 'h5py.File', 'h5py.File', (['out_file_name3', '"""r"""'], {}), "(out_file_name3, 'r')\n", (104730, 104751), False, 'import h5py\n'), ((106144, 106203), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["(attrs['tot'] / ddd.tot)", '(1.0)'], {}), "(attrs['tot'] / ddd.tot, 1.0)\n", (106174, 106203), True, 'import numpy as np\n'), ((109588, 109621), 'numpy.exp', 'np.exp', (['(-d1 ** 2 / (4.0 * s ** 2))'], {}), '(-d1 ** 2 / (4.0 * s ** 2))\n', (109594, 109621), True, 'import numpy as np\n'), ((109657, 109690), 'numpy.exp', 'np.exp', (['(-d2 ** 2 / (4.0 * s ** 2))'], {}), '(-d2 ** 2 / (4.0 * s ** 2))\n', (109663, 109690), True, 'import numpy as np\n'), ((109726, 109759), 'numpy.exp', 'np.exp', (['(-d3 ** 2 / (4.0 * s ** 2))'], {}), '(-d3 ** 2 / (4.0 * s ** 2))\n', (109732, 109759), True, 'import numpy as np\n'), ((110064, 110102), 'numpy.abs', 'np.abs', (['((zeta - true_zeta) / true_zeta)'], {}), '((zeta - true_zeta) / true_zeta)\n', (110070, 110102), True, 'import numpy as np\n'), ((110210, 110222), 'numpy.abs', 'np.abs', (['zeta'], {}), '(zeta)\n', (110216, 110222), True, 'import numpy as np\n'), ((110232, 110249), 'numpy.abs', 'np.abs', (['true_zeta'], {}), '(true_zeta)\n', (110238, 110249), True, 'import numpy as np\n'), ((118261, 118316), 'numpy.exp', 'np.exp', (['(-(d1 ** 2 + d2 ** 2 + d3 ** 2) / (6.0 * s ** 2))'], {}), '(-(d1 ** 2 + d2 ** 2 + d3 ** 2) / (6.0 * s ** 2))\n', (118267, 118316), True, 'import numpy as np\n'), ((118568, 118606), 'numpy.abs', 'np.abs', (['((zeta - true_zeta) / true_zeta)'], {}), '((zeta - true_zeta) / true_zeta)\n', (118574, 118606), True, 'import numpy as np\n'), ((118714, 118726), 'numpy.abs', 'np.abs', (['zeta'], {}), '(zeta)\n', (118720, 118726), True, 'import numpy as np\n'), ((118736, 118753), 'numpy.abs', 'np.abs', (['true_zeta'], {}), '(true_zeta)\n', (118742, 118753), True, 'import numpy as np\n'), ((119846, 119858), 'numpy.abs', 'np.abs', (['zeta'], {}), '(zeta)\n', (119852, 119858), True, 'import numpy as np\n'), ((119868, 119885), 'numpy.abs', 'np.abs', (['true_zeta'], {}), '(true_zeta)\n', (119874, 119885), True, 'import numpy as np\n'), ((1399, 1420), 'math.log', 'math.log', (['nnn.min_sep'], {}), '(nnn.min_sep)\n', (1407, 1420), False, 'import math\n'), ((1496, 1517), 'math.log', 'math.log', (['nnn.max_sep'], {}), '(nnn.max_sep)\n', (1504, 1517), False, 'import math\n'), ((25212, 25260), 'numpy.sqrt', 'np.sqrt', (['((x[i] - x[j]) ** 2 + (y[i] - y[j]) ** 2)'], {}), '((x[i] - x[j]) ** 2 + (y[i] - y[j]) ** 2)\n', (25219, 25260), True, 'import numpy as np\n'), ((25275, 25323), 'numpy.sqrt', 'np.sqrt', (['((x[i] - x[k]) ** 2 + (y[i] - y[k]) ** 2)'], {}), '((x[i] - x[k]) ** 2 + (y[i] - y[k]) ** 2)\n', (25282, 25323), True, 'import numpy as np\n'), ((25338, 25386), 'numpy.sqrt', 'np.sqrt', (['((x[j] - x[k]) ** 2 + (y[j] - y[k]) ** 2)'], {}), '((x[j] - x[k]) ** 2 + (y[j] - y[k]) ** 2)\n', (25345, 25386), True, 'import numpy as np\n'), ((30737, 30753), 'numpy.sqrt', 'np.sqrt', (['varzeta'], {}), '(varzeta)\n', (30744, 30753), True, 'import numpy as np\n'), ((33249, 33265), 'numpy.sqrt', 'np.sqrt', (['varzeta'], {}), '(varzeta)\n', (33256, 33265), True, 'import numpy as np\n'), ((45368, 45420), 'numpy.sqrt', 'np.sqrt', (['((x1[i] - x2[j]) ** 2 + (y1[i] - y2[j]) ** 2)'], {}), '((x1[i] - x2[j]) ** 2 + (y1[i] - y2[j]) ** 2)\n', (45375, 45420), True, 'import numpy as np\n'), ((45435, 45487), 'numpy.sqrt', 'np.sqrt', (['((x1[i] - x3[k]) ** 2 + (y1[i] - y3[k]) ** 2)'], {}), '((x1[i] - x3[k]) ** 2 + (y1[i] - y3[k]) ** 2)\n', (45442, 45487), True, 'import numpy as np\n'), ((45502, 45554), 'numpy.sqrt', 'np.sqrt', (['((x2[j] - x3[k]) ** 2 + (y2[j] - y3[k]) ** 2)'], {}), '((x2[j] - x3[k]) ** 2 + (y2[j] - y3[k]) ** 2)\n', (45509, 45554), True, 'import numpy as np\n'), ((58162, 58214), 'numpy.sqrt', 'np.sqrt', (['((x1[i] - x2[j]) ** 2 + (y1[i] - y2[j]) ** 2)'], {}), '((x1[i] - x2[j]) ** 2 + (y1[i] - y2[j]) ** 2)\n', (58169, 58214), True, 'import numpy as np\n'), ((58229, 58281), 'numpy.sqrt', 'np.sqrt', (['((x1[i] - x2[k]) ** 2 + (y1[i] - y2[k]) ** 2)'], {}), '((x1[i] - x2[k]) ** 2 + (y1[i] - y2[k]) ** 2)\n', (58236, 58281), True, 'import numpy as np\n'), ((58296, 58348), 'numpy.sqrt', 'np.sqrt', (['((x2[j] - x2[k]) ** 2 + (y2[j] - y2[k]) ** 2)'], {}), '((x2[j] - x2[k]) ** 2 + (y2[j] - y2[k]) ** 2)\n', (58303, 58348), True, 'import numpy as np\n'), ((64695, 64764), 'numpy.sqrt', 'np.sqrt', (['((x[i] - x[j]) ** 2 + (y[i] - y[j]) ** 2 + (z[i] - z[j]) ** 2)'], {}), '((x[i] - x[j]) ** 2 + (y[i] - y[j]) ** 2 + (z[i] - z[j]) ** 2)\n', (64702, 64764), True, 'import numpy as np\n'), ((64775, 64844), 'numpy.sqrt', 'np.sqrt', (['((x[j] - x[k]) ** 2 + (y[j] - y[k]) ** 2 + (z[j] - z[k]) ** 2)'], {}), '((x[j] - x[k]) ** 2 + (y[j] - y[k]) ** 2 + (z[j] - z[k]) ** 2)\n', (64782, 64844), True, 'import numpy as np\n'), ((64855, 64924), 'numpy.sqrt', 'np.sqrt', (['((x[k] - x[i]) ** 2 + (y[k] - y[i]) ** 2 + (z[k] - z[i]) ** 2)'], {}), '((x[k] - x[i]) ** 2 + (y[k] - y[i]) ** 2 + (z[k] - z[i]) ** 2)\n', (64862, 64924), True, 'import numpy as np\n'), ((73649, 73701), 'numpy.sqrt', 'np.sqrt', (['((x1[i] - x2[j]) ** 2 + (y1[i] - y2[j]) ** 2)'], {}), '((x1[i] - x2[j]) ** 2 + (y1[i] - y2[j]) ** 2)\n', (73656, 73701), True, 'import numpy as np\n'), ((73716, 73768), 'numpy.sqrt', 'np.sqrt', (['((x1[i] - x3[k]) ** 2 + (y1[i] - y3[k]) ** 2)'], {}), '((x1[i] - x3[k]) ** 2 + (y1[i] - y3[k]) ** 2)\n', (73723, 73768), True, 'import numpy as np\n'), ((73783, 73835), 'numpy.sqrt', 'np.sqrt', (['((x2[j] - x3[k]) ** 2 + (y2[j] - y3[k]) ** 2)'], {}), '((x2[j] - x3[k]) ** 2 + (y2[j] - y3[k]) ** 2)\n', (73790, 73835), True, 'import numpy as np\n'), ((80533, 80602), 'numpy.sqrt', 'np.sqrt', (['((x[i] - x[j]) ** 2 + (y[i] - y[j]) ** 2 + (z[i] - z[j]) ** 2)'], {}), '((x[i] - x[j]) ** 2 + (y[i] - y[j]) ** 2 + (z[i] - z[j]) ** 2)\n', (80540, 80602), True, 'import numpy as np\n'), ((80613, 80682), 'numpy.sqrt', 'np.sqrt', (['((x[i] - x[k]) ** 2 + (y[i] - y[k]) ** 2 + (z[i] - z[k]) ** 2)'], {}), '((x[i] - x[k]) ** 2 + (y[i] - y[k]) ** 2 + (z[i] - z[k]) ** 2)\n', (80620, 80682), True, 'import numpy as np\n'), ((80693, 80762), 'numpy.sqrt', 'np.sqrt', (['((x[j] - x[k]) ** 2 + (y[j] - y[k]) ** 2 + (z[j] - z[k]) ** 2)'], {}), '((x[j] - x[k]) ** 2 + (y[j] - y[k]) ** 2 + (z[j] - z[k]) ** 2)\n', (80700, 80762), True, 'import numpy as np\n'), ((87477, 87552), 'numpy.sqrt', 'np.sqrt', (['((x2[j] - x3[k]) ** 2 + (y2[j] - y3[k]) ** 2 + (z2[j] - z3[k]) ** 2)'], {}), '((x2[j] - x3[k]) ** 2 + (y2[j] - y3[k]) ** 2 + (z2[j] - z3[k]) ** 2)\n', (87484, 87552), True, 'import numpy as np\n'), ((87563, 87638), 'numpy.sqrt', 'np.sqrt', (['((x1[i] - x3[k]) ** 2 + (y1[i] - y3[k]) ** 2 + (z1[i] - z3[k]) ** 2)'], {}), '((x1[i] - x3[k]) ** 2 + (y1[i] - y3[k]) ** 2 + (z1[i] - z3[k]) ** 2)\n', (87570, 87638), True, 'import numpy as np\n'), ((87649, 87724), 'numpy.sqrt', 'np.sqrt', (['((x1[i] - x2[j]) ** 2 + (y1[i] - y2[j]) ** 2 + (z1[i] - z2[j]) ** 2)'], {}), '((x1[i] - x2[j]) ** 2 + (y1[i] - y2[j]) ** 2 + (z1[i] - z2[j]) ** 2)\n', (87656, 87724), True, 'import numpy as np\n'), ((99783, 99799), 'numpy.exp', 'np.exp', (['ddd.logr'], {}), '(ddd.logr)\n', (99789, 99799), True, 'import numpy as np\n'), ((100910, 100926), 'numpy.exp', 'np.exp', (['ddd.logr'], {}), '(ddd.logr)\n', (100916, 100926), True, 'import numpy as np\n'), ((101790, 101806), 'numpy.sqrt', 'np.sqrt', (['varzeta'], {}), '(varzeta)\n', (101797, 101806), True, 'import numpy as np\n'), ((110466, 110482), 'numpy.exp', 'np.exp', (['ddd.logr'], {}), '(ddd.logr)\n', (110472, 110482), True, 'import numpy as np\n'), ((111346, 111362), 'numpy.sqrt', 'np.sqrt', (['varzeta'], {}), '(varzeta)\n', (111353, 111362), True, 'import numpy as np\n'), ((113271, 113287), 'numpy.exp', 'np.exp', (['ddd.logr'], {}), '(ddd.logr)\n', (113277, 113287), True, 'import numpy as np\n'), ((114247, 114263), 'numpy.sqrt', 'np.sqrt', (['varzeta'], {}), '(varzeta)\n', (114254, 114263), True, 'import numpy as np\n'), ((117985, 118001), 'numpy.exp', 'np.exp', (['ddd.logr'], {}), '(ddd.logr)\n', (117991, 118001), True, 'import numpy as np\n'), ((26863, 26896), 'numpy.floor', 'np.floor', (['((u - min_u) / ubin_size)'], {}), '((u - min_u) / ubin_size)\n', (26871, 26896), True, 'import numpy as np\n'), ((47367, 47400), 'numpy.floor', 'np.floor', (['((u - min_u) / ubin_size)'], {}), '((u - min_u) / ubin_size)\n', (47375, 47400), True, 'import numpy as np\n'), ((60161, 60194), 'numpy.floor', 'np.floor', (['((u - min_u) / ubin_size)'], {}), '((u - min_u) / ubin_size)\n', (60169, 60194), True, 'import numpy as np\n'), ((75686, 75719), 'numpy.floor', 'np.floor', (['((u - min_u) / ubin_size)'], {}), '((u - min_u) / ubin_size)\n', (75694, 75719), True, 'import numpy as np\n'), ((82343, 82376), 'numpy.floor', 'np.floor', (['((u - min_u) / ubin_size)'], {}), '((u - min_u) / ubin_size)\n', (82351, 82376), True, 'import numpy as np\n'), ((89659, 89692), 'numpy.floor', 'np.floor', (['((u - min_u) / ubin_size)'], {}), '((u - min_u) / ubin_size)\n', (89667, 89692), True, 'import numpy as np\n'), ((96683, 96700), 'numpy.abs', 'np.abs', (['ddd.meanv'], {}), '(ddd.meanv)\n', (96689, 96700), True, 'import numpy as np\n'), ((25643, 25685), 'test_helper.is_ccw', 'is_ccw', (['x[i]', 'y[i]', 'x[j]', 'y[j]', 'x[k]', 'y[k]'], {}), '(x[i], y[i], x[j], y[j], x[k], y[k])\n', (25649, 25685), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((26124, 26166), 'test_helper.is_ccw', 'is_ccw', (['x[i]', 'y[i]', 'x[k]', 'y[k]', 'x[j]', 'y[j]'], {}), '(x[i], y[i], x[k], y[k], x[j], y[j])\n', (26130, 26166), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((27048, 27082), 'numpy.floor', 'np.floor', (['((v - -max_v) / vbin_size)'], {}), '((v - -max_v) / vbin_size)\n', (27056, 27082), True, 'import numpy as np\n'), ((45811, 45859), 'test_helper.is_ccw', 'is_ccw', (['x1[i]', 'y1[i]', 'x2[j]', 'y2[j]', 'x3[k]', 'y3[k]'], {}), '(x1[i], y1[i], x2[j], y2[j], x3[k], y3[k])\n', (45817, 45859), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((46460, 46508), 'test_helper.is_ccw', 'is_ccw', (['x1[i]', 'y1[i]', 'x3[k]', 'y3[k]', 'x2[j]', 'y2[j]'], {}), '(x1[i], y1[i], x3[k], y3[k], x2[j], y2[j])\n', (46466, 46508), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((47552, 47586), 'numpy.floor', 'np.floor', (['((v - -max_v) / vbin_size)'], {}), '((v - -max_v) / vbin_size)\n', (47560, 47586), True, 'import numpy as np\n'), ((58605, 58653), 'test_helper.is_ccw', 'is_ccw', (['x1[i]', 'y1[i]', 'x2[j]', 'y2[j]', 'x2[k]', 'y2[k]'], {}), '(x1[i], y1[i], x2[j], y2[j], x2[k], y2[k])\n', (58611, 58653), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((59254, 59302), 'test_helper.is_ccw', 'is_ccw', (['x1[i]', 'y1[i]', 'x2[k]', 'y2[k]', 'x2[j]', 'y2[j]'], {}), '(x1[i], y1[i], x2[k], y2[k], x2[j], y2[j])\n', (59260, 59302), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((60346, 60380), 'numpy.floor', 'np.floor', (['((v - -max_v) / vbin_size)'], {}), '((v - -max_v) / vbin_size)\n', (60354, 60380), True, 'import numpy as np\n'), ((66100, 66122), 'numpy.floor', 'np.floor', (['(u / bin_size)'], {}), '(u / bin_size)\n', (66108, 66122), True, 'import numpy as np\n'), ((66204, 66232), 'numpy.floor', 'np.floor', (['((v + 1) / bin_size)'], {}), '((v + 1) / bin_size)\n', (66212, 66232), True, 'import numpy as np\n'), ((70286, 70309), 'numpy.floor', 'np.floor', (['(u / ubin_size)'], {}), '(u / ubin_size)\n', (70294, 70309), True, 'import numpy as np\n'), ((70391, 70420), 'numpy.floor', 'np.floor', (['((v + 1) / vbin_size)'], {}), '((v + 1) / vbin_size)\n', (70399, 70420), True, 'import numpy as np\n'), ((74092, 74140), 'test_helper.is_ccw', 'is_ccw', (['x1[i]', 'y1[i]', 'x2[j]', 'y2[j]', 'x3[k]', 'y3[k]'], {}), '(x1[i], y1[i], x2[j], y2[j], x3[k], y3[k])\n', (74098, 74140), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((74741, 74789), 'test_helper.is_ccw', 'is_ccw', (['x1[i]', 'y1[i]', 'x3[k]', 'y3[k]', 'x2[j]', 'y2[j]'], {}), '(x1[i], y1[i], x3[k], y3[k], x2[j], y2[j])\n', (74747, 74789), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((75871, 75905), 'numpy.floor', 'np.floor', (['((v - -max_v) / vbin_size)'], {}), '((v - -max_v) / vbin_size)\n', (75879, 75905), True, 'import numpy as np\n'), ((81015, 81078), 'test_helper.is_ccw_3d', 'is_ccw_3d', (['x[i]', 'y[i]', 'z[i]', 'x[j]', 'y[j]', 'z[j]', 'x[k]', 'y[k]', 'z[k]'], {}), '(x[i], y[i], z[i], x[j], y[j], z[j], x[k], y[k], z[k])\n', (81024, 81078), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((81550, 81613), 'test_helper.is_ccw_3d', 'is_ccw_3d', (['x[i]', 'y[i]', 'z[i]', 'x[k]', 'y[k]', 'z[k]', 'x[j]', 'y[j]', 'z[j]'], {}), '(x[i], y[i], z[i], x[k], y[k], z[k], x[j], y[j], z[j])\n', (81559, 81613), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((82528, 82562), 'numpy.floor', 'np.floor', (['((v - -max_v) / vbin_size)'], {}), '((v - -max_v) / vbin_size)\n', (82536, 82562), True, 'import numpy as np\n'), ((87977, 88049), 'test_helper.is_ccw_3d', 'is_ccw_3d', (['x1[i]', 'y1[i]', 'z1[i]', 'x2[j]', 'y2[j]', 'z2[j]', 'x3[k]', 'y3[k]', 'z3[k]'], {}), '(x1[i], y1[i], z1[i], x2[j], y2[j], z2[j], x3[k], y3[k], z3[k])\n', (87986, 88049), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((88689, 88761), 'test_helper.is_ccw_3d', 'is_ccw_3d', (['x1[i]', 'y1[i]', 'z1[i]', 'x3[k]', 'y3[k]', 'z3[k]', 'x2[j]', 'y2[j]', 'z2[j]'], {}), '(x1[i], y1[i], z1[i], x3[k], y3[k], z3[k], x2[j], y2[j], z2[j])\n', (88698, 88761), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((89844, 89878), 'numpy.floor', 'np.floor', (['((v - -max_v) / vbin_size)'], {}), '((v - -max_v) / vbin_size)\n', (89852, 89878), True, 'import numpy as np\n'), ((96793, 96810), 'numpy.abs', 'np.abs', (['ddd.meanv'], {}), '(ddd.meanv)\n', (96799, 96810), True, 'import numpy as np\n'), ((104846, 104862), 'numpy.exp', 'np.exp', (['ddd.logr'], {}), '(ddd.logr)\n', (104852, 104862), True, 'import numpy as np\n'), ((105899, 105915), 'numpy.sqrt', 'np.sqrt', (['varzeta'], {}), '(varzeta)\n', (105906, 105915), True, 'import numpy as np\n'), ((25800, 25842), 'test_helper.is_ccw', 'is_ccw', (['x[j]', 'y[j]', 'x[i]', 'y[i]', 'x[k]', 'y[k]'], {}), '(x[j], y[j], x[i], y[i], x[k], y[k])\n', (25806, 25842), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((25947, 25989), 'test_helper.is_ccw', 'is_ccw', (['x[j]', 'y[j]', 'x[k]', 'y[k]', 'x[i]', 'y[i]'], {}), '(x[j], y[j], x[k], y[k], x[i], y[i])\n', (25953, 25989), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((26281, 26323), 'test_helper.is_ccw', 'is_ccw', (['x[k]', 'y[k]', 'x[i]', 'y[i]', 'x[j]', 'y[j]'], {}), '(x[k], y[k], x[i], y[i], x[j], y[j])\n', (26287, 26323), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((26428, 26470), 'test_helper.is_ccw', 'is_ccw', (['x[k]', 'y[k]', 'x[j]', 'y[j]', 'x[i]', 'y[i]'], {}), '(x[k], y[k], x[j], y[j], x[i], y[i])\n', (26434, 26470), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((26953, 26986), 'numpy.floor', 'np.floor', (['((v - min_v) / vbin_size)'], {}), '((v - min_v) / vbin_size)\n', (26961, 26986), True, 'import numpy as np\n'), ((46024, 46072), 'test_helper.is_ccw', 'is_ccw', (['x2[j]', 'y2[j]', 'x1[i]', 'y1[i]', 'x3[k]', 'y3[k]'], {}), '(x2[j], y2[j], x1[i], y1[i], x3[k], y3[k])\n', (46030, 46072), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((46227, 46275), 'test_helper.is_ccw', 'is_ccw', (['x2[j]', 'y2[j]', 'x3[k]', 'y3[k]', 'x1[i]', 'y1[i]'], {}), '(x2[j], y2[j], x3[k], y3[k], x1[i], y1[i])\n', (46233, 46275), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((46673, 46721), 'test_helper.is_ccw', 'is_ccw', (['x3[k]', 'y3[k]', 'x1[i]', 'y1[i]', 'x2[j]', 'y2[j]'], {}), '(x3[k], y3[k], x1[i], y1[i], x2[j], y2[j])\n', (46679, 46721), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((46876, 46924), 'test_helper.is_ccw', 'is_ccw', (['x3[k]', 'y3[k]', 'x2[j]', 'y2[j]', 'x1[i]', 'y1[i]'], {}), '(x3[k], y3[k], x2[j], y2[j], x1[i], y1[i])\n', (46882, 46924), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((47457, 47490), 'numpy.floor', 'np.floor', (['((v - min_v) / vbin_size)'], {}), '((v - min_v) / vbin_size)\n', (47465, 47490), True, 'import numpy as np\n'), ((58818, 58866), 'test_helper.is_ccw', 'is_ccw', (['x2[j]', 'y2[j]', 'x1[i]', 'y1[i]', 'x2[k]', 'y2[k]'], {}), '(x2[j], y2[j], x1[i], y1[i], x2[k], y2[k])\n', (58824, 58866), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((59021, 59069), 'test_helper.is_ccw', 'is_ccw', (['x2[j]', 'y2[j]', 'x2[k]', 'y2[k]', 'x1[i]', 'y1[i]'], {}), '(x2[j], y2[j], x2[k], y2[k], x1[i], y1[i])\n', (59027, 59069), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((59467, 59515), 'test_helper.is_ccw', 'is_ccw', (['x2[k]', 'y2[k]', 'x1[i]', 'y1[i]', 'x2[j]', 'y2[j]'], {}), '(x2[k], y2[k], x1[i], y1[i], x2[j], y2[j])\n', (59473, 59515), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((59670, 59718), 'test_helper.is_ccw', 'is_ccw', (['x2[k]', 'y2[k]', 'x2[j]', 'y2[j]', 'x1[i]', 'y1[i]'], {}), '(x2[k], y2[k], x2[j], y2[j], x1[i], y1[i])\n', (59676, 59718), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((60251, 60284), 'numpy.floor', 'np.floor', (['((v - min_v) / vbin_size)'], {}), '((v - min_v) / vbin_size)\n', (60259, 60284), True, 'import numpy as np\n'), ((74305, 74353), 'test_helper.is_ccw', 'is_ccw', (['x2[j]', 'y2[j]', 'x1[i]', 'y1[i]', 'x3[k]', 'y3[k]'], {}), '(x2[j], y2[j], x1[i], y1[i], x3[k], y3[k])\n', (74311, 74353), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((74508, 74556), 'test_helper.is_ccw', 'is_ccw', (['x2[j]', 'y2[j]', 'x3[k]', 'y3[k]', 'x1[i]', 'y1[i]'], {}), '(x2[j], y2[j], x3[k], y3[k], x1[i], y1[i])\n', (74514, 74556), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((74954, 75002), 'test_helper.is_ccw', 'is_ccw', (['x3[k]', 'y3[k]', 'x1[i]', 'y1[i]', 'x2[j]', 'y2[j]'], {}), '(x3[k], y3[k], x1[i], y1[i], x2[j], y2[j])\n', (74960, 75002), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((75157, 75205), 'test_helper.is_ccw', 'is_ccw', (['x3[k]', 'y3[k]', 'x2[j]', 'y2[j]', 'x1[i]', 'y1[i]'], {}), '(x3[k], y3[k], x2[j], y2[j], x1[i], y1[i])\n', (75163, 75205), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((75776, 75809), 'numpy.floor', 'np.floor', (['((v - min_v) / vbin_size)'], {}), '((v - min_v) / vbin_size)\n', (75784, 75809), True, 'import numpy as np\n'), ((81190, 81253), 'test_helper.is_ccw_3d', 'is_ccw_3d', (['x[j]', 'y[j]', 'z[j]', 'x[i]', 'y[i]', 'z[i]', 'x[k]', 'y[k]', 'z[k]'], {}), '(x[j], y[j], z[j], x[i], y[i], z[i], x[k], y[k], z[k])\n', (81199, 81253), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((81355, 81418), 'test_helper.is_ccw_3d', 'is_ccw_3d', (['x[j]', 'y[j]', 'z[j]', 'x[k]', 'y[k]', 'z[k]', 'x[i]', 'y[i]', 'z[i]'], {}), '(x[j], y[j], z[j], x[k], y[k], z[k], x[i], y[i], z[i])\n', (81364, 81418), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((81725, 81788), 'test_helper.is_ccw_3d', 'is_ccw_3d', (['x[k]', 'y[k]', 'z[k]', 'x[i]', 'y[i]', 'z[i]', 'x[j]', 'y[j]', 'z[j]'], {}), '(x[k], y[k], z[k], x[i], y[i], z[i], x[j], y[j], z[j])\n', (81734, 81788), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((81890, 81953), 'test_helper.is_ccw_3d', 'is_ccw_3d', (['x[k]', 'y[k]', 'z[k]', 'x[j]', 'y[j]', 'z[j]', 'x[i]', 'y[i]', 'z[i]'], {}), '(x[k], y[k], z[k], x[j], y[j], z[j], x[i], y[i], z[i])\n', (81899, 81953), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((82433, 82466), 'numpy.floor', 'np.floor', (['((v - min_v) / vbin_size)'], {}), '((v - min_v) / vbin_size)\n', (82441, 82466), True, 'import numpy as np\n'), ((88211, 88283), 'test_helper.is_ccw_3d', 'is_ccw_3d', (['x2[j]', 'y2[j]', 'z2[j]', 'x1[i]', 'y1[i]', 'z1[i]', 'x3[k]', 'y3[k]', 'z3[k]'], {}), '(x2[j], y2[j], z2[j], x1[i], y1[i], z1[i], x3[k], y3[k], z3[k])\n', (88220, 88283), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((88435, 88507), 'test_helper.is_ccw_3d', 'is_ccw_3d', (['x2[j]', 'y2[j]', 'z2[j]', 'x3[k]', 'y3[k]', 'z3[k]', 'x1[i]', 'y1[i]', 'z1[i]'], {}), '(x2[j], y2[j], z2[j], x3[k], y3[k], z3[k], x1[i], y1[i], z1[i])\n', (88444, 88507), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((88923, 88995), 'test_helper.is_ccw_3d', 'is_ccw_3d', (['x3[k]', 'y3[k]', 'z3[k]', 'x1[i]', 'y1[i]', 'z1[i]', 'x2[j]', 'y2[j]', 'z2[j]'], {}), '(x3[k], y3[k], z3[k], x1[i], y1[i], z1[i], x2[j], y2[j], z2[j])\n', (88932, 88995), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((89147, 89219), 'test_helper.is_ccw_3d', 'is_ccw_3d', (['x3[k]', 'y3[k]', 'z3[k]', 'x2[j]', 'y2[j]', 'z2[j]', 'x1[i]', 'y1[i]', 'z1[i]'], {}), '(x3[k], y3[k], z3[k], x2[j], y2[j], z2[j], x1[i], y1[i], z1[i])\n', (89156, 89219), False, 'from test_helper import is_ccw, is_ccw_3d\n'), ((89749, 89782), 'numpy.floor', 'np.floor', (['((v - min_v) / vbin_size)'], {}), '((v - min_v) / vbin_size)\n', (89757, 89782), True, 'import numpy as np\n'), ((118209, 118219), 'numpy.sqrt', 'np.sqrt', (['(3)'], {}), '(3)\n', (118216, 118219), True, 'import numpy as np\n'), ((26801, 26810), 'numpy.log', 'np.log', (['r'], {}), '(r)\n', (26807, 26810), True, 'import numpy as np\n'), ((47305, 47314), 'numpy.log', 'np.log', (['r'], {}), '(r)\n', (47311, 47314), True, 'import numpy as np\n'), ((60099, 60108), 'numpy.log', 'np.log', (['r'], {}), '(r)\n', (60105, 60108), True, 'import numpy as np\n'), ((65001, 65025), 'numpy.log', 'np.log', (['(d2 / rad_min_sep)'], {}), '(d2 / rad_min_sep)\n', (65007, 65025), True, 'import numpy as np\n'), ((69191, 69211), 'numpy.log', 'np.log', (['(d2 / min_sep)'], {}), '(d2 / min_sep)\n', (69197, 69211), True, 'import numpy as np\n'), ((75624, 75633), 'numpy.log', 'np.log', (['r'], {}), '(r)\n', (75630, 75633), True, 'import numpy as np\n'), ((82281, 82290), 'numpy.log', 'np.log', (['r'], {}), '(r)\n', (82287, 82290), True, 'import numpy as np\n'), ((89597, 89606), 'numpy.log', 'np.log', (['r'], {}), '(r)\n', (89603, 89606), True, 'import numpy as np\n')]
import numpy as np import matplotlib.pyplot as plt evenR = np.array([1.212,3.368]) oddR = np.array([2.381]) S = evenR.size+oddR.size prop = np.zeros(S) tunn = np.zeros(S) i=0 j=1 a=0.469 def rad(x): return np.sqrt((1.1*np.pi)**2-x**2) print (S) print (prop) print (tunn) while i< evenR.size: prop[2*i] = evenR[i]/a tunn[2*i] = rad(evenR[i])/a i=i+1 print (i) print("odd") while j-1 < oddR.size: prop[j] = oddR[j-1]/a tunn[j] = rad(oddR[j-1])/a j=j+2 print (j) print (prop) print (tunn) Bcoeff = np.array([0.6318,0.6171,0.4823]) #def Bfn(k,K): # return k+1.2*K l = 0 #while l < S: # Bcoeff[l] = Bfn(prop[l],tunn[l]) # l=l+1 print (Bcoeff) z = 0 def ef1(B,K,k,a): return lambda x: 2*B*np.exp((a+x)*K)*np.cos(a*k) def ef2(B,k): return lambda x: 2*B*np.cos(k*x) def ef3(B,K,k,a): return lambda x: 2*B*np.exp((a-x)*K)*np.cos(a*k) def of1(B,K,k,a): return lambda x: -2*B*np.exp((a+x)*K)*np.sin(a*k) def of2(B,k): return lambda x: 2*B*np.sin(k*x) def of3(B,K,k,a): return lambda x: 2*B*np.exp((a-x)*K)*np.sin(a*k) r1 = np.arange(-5,-a,0.001) r2 = np.arange(-a,a,0.001) r3 = np.arange(a,5,0.001) color = ["r","b","g"] while z <S: # plt.figure if z%2 == 1: plt1 = of1(Bcoeff[z],tunn[z],prop[z],a) plt2 = of2(Bcoeff[z],prop[z]) plt3 = of3(Bcoeff[z],tunn[z],prop[z],a) plt.plot(r1,plt1(r1),color[z],r2,plt2(r2),color[z],r3,plt3(r3),color[z]) # plt.plot(r2,plt2(r2)) # plt.plot(r3,plt3(r3)) else: plt1 = ef1(Bcoeff[z],tunn[z],prop[z],a) plt2 = ef2(Bcoeff[z],prop[z]) plt3 = ef3(Bcoeff[z],tunn[z],prop[z],a) plt.plot(r1,plt1(r1),color[z],r2,plt2(r2),color[z],r3,plt3(r3),color[z]) # plt.plot(r2,plt2(r2)) # plt.plot(r3,plt3(r3)) z = z+1 plt.show()
[ "numpy.sqrt", "numpy.exp", "numpy.array", "numpy.zeros", "numpy.cos", "numpy.sin", "numpy.arange", "matplotlib.pyplot.show" ]
[((60, 84), 'numpy.array', 'np.array', (['[1.212, 3.368]'], {}), '([1.212, 3.368])\n', (68, 84), True, 'import numpy as np\n'), ((91, 108), 'numpy.array', 'np.array', (['[2.381]'], {}), '([2.381])\n', (99, 108), True, 'import numpy as np\n'), ((141, 152), 'numpy.zeros', 'np.zeros', (['S'], {}), '(S)\n', (149, 152), True, 'import numpy as np\n'), ((160, 171), 'numpy.zeros', 'np.zeros', (['S'], {}), '(S)\n', (168, 171), True, 'import numpy as np\n'), ((512, 546), 'numpy.array', 'np.array', (['[0.6318, 0.6171, 0.4823]'], {}), '([0.6318, 0.6171, 0.4823])\n', (520, 546), True, 'import numpy as np\n'), ((1057, 1081), 'numpy.arange', 'np.arange', (['(-5)', '(-a)', '(0.001)'], {}), '(-5, -a, 0.001)\n', (1066, 1081), True, 'import numpy as np\n'), ((1085, 1108), 'numpy.arange', 'np.arange', (['(-a)', 'a', '(0.001)'], {}), '(-a, a, 0.001)\n', (1094, 1108), True, 'import numpy as np\n'), ((1112, 1134), 'numpy.arange', 'np.arange', (['a', '(5)', '(0.001)'], {}), '(a, 5, 0.001)\n', (1121, 1134), True, 'import numpy as np\n'), ((1695, 1705), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1703, 1705), True, 'import matplotlib.pyplot as plt\n'), ((209, 245), 'numpy.sqrt', 'np.sqrt', (['((1.1 * np.pi) ** 2 - x ** 2)'], {}), '((1.1 * np.pi) ** 2 - x ** 2)\n', (216, 245), True, 'import numpy as np\n'), ((723, 736), 'numpy.cos', 'np.cos', (['(a * k)'], {}), '(a * k)\n', (729, 736), True, 'import numpy as np\n'), ((773, 786), 'numpy.cos', 'np.cos', (['(k * x)'], {}), '(k * x)\n', (779, 786), True, 'import numpy as np\n'), ((844, 857), 'numpy.cos', 'np.cos', (['(a * k)'], {}), '(a * k)\n', (850, 857), True, 'import numpy as np\n'), ((916, 929), 'numpy.sin', 'np.sin', (['(a * k)'], {}), '(a * k)\n', (922, 929), True, 'import numpy as np\n'), ((966, 979), 'numpy.sin', 'np.sin', (['(k * x)'], {}), '(k * x)\n', (972, 979), True, 'import numpy as np\n'), ((1037, 1050), 'numpy.sin', 'np.sin', (['(a * k)'], {}), '(a * k)\n', (1043, 1050), True, 'import numpy as np\n'), ((707, 726), 'numpy.exp', 'np.exp', (['((a + x) * K)'], {}), '((a + x) * K)\n', (713, 726), True, 'import numpy as np\n'), ((828, 847), 'numpy.exp', 'np.exp', (['((a - x) * K)'], {}), '((a - x) * K)\n', (834, 847), True, 'import numpy as np\n'), ((900, 919), 'numpy.exp', 'np.exp', (['((a + x) * K)'], {}), '((a + x) * K)\n', (906, 919), True, 'import numpy as np\n'), ((1021, 1040), 'numpy.exp', 'np.exp', (['((a - x) * K)'], {}), '((a - x) * K)\n', (1027, 1040), True, 'import numpy as np\n')]
#!/usr/bin/env python3 from contextlib import contextmanager import pandas as pd import numpy as np import random import torch import time import os import argparse from scipy import sparse from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.impute import SimpleImputer from sklearn.preprocessing import OneHotEncoder @contextmanager def timeit(name: str) -> None: before = time.time() try: yield finally: duration = time.time() - before print("%s: %.3f sec." % (name, duration)) parser = argparse.ArgumentParser(description='Linear Regression') parser.add_argument('csv_file', metavar='csv-file', type=str, nargs=1) parser.add_argument('target', metavar='target-column', type=str, nargs=1) parser.add_argument('exclude', metavar='excluded-columns', type=str, nargs='*') parser.add_argument('-testratio', metavar='ratio', type=float, default=0.5, nargs=None) parser.add_argument('-epochs', metavar='epochs', type=int, default=1, nargs=None) parser.add_argument('-batchsize', metavar='batch size', type=int, default=256, nargs=None) parser.add_argument('-lr', metavar='learning rate', type=float, default=0.001, nargs=None) parser.add_argument('-decay', metavar='weight decay', type=float, default=0.0, nargs=None) parser.add_argument('-momentum', metavar='gradient momentum', type=float, default=0.1, nargs=None) parser.add_argument('-sep', metavar='separator', type=str, default=",", nargs=None) args = parser.parse_args() target_col = args.target[0] with timeit("CSV parsing"): excluded = set(args.exclude) df = pd.read_csv(args.csv_file[0], sep=args.sep[0], header=0, na_values=["", " ", "NA", "-"]) numerical = [ col for col, t in df.dtypes.iteritems() if t in (np.int64, np.float64) and t not in excluded ] categorical = [ col for col, t in df.dtypes.iteritems() if t == np.object and t not in excluded ] numerical.remove(target_col) df[categorical] = df[categorical].astype(str) # required for one-hot with timeit("set split"): train_set, test_set = train_test_split(df, shuffle=True, test_size=args.testratio) with timeit("training+running imputer"): X_num = train_set[numerical].values # already makes a copy imputer = SimpleImputer(copy=False) X_num = imputer.fit_transform(X_num) with timeit("training+running scaler"): scaler = StandardScaler(copy=False) X_num = scaler.fit_transform(X_num) # with timeit("hash encoding"): # X_cat = df[categorical] # hash = HashingEncoder(n_components=32).fit(X_cat) # X_cat = hash.transform(X_cat) if len(categorical) > 0: with timeit("one-hot encoding"): X_cat = train_set[categorical].values #cat_imputer = SimpleImputer(copy=False, strategy='most_frequent') #X_cat = cat_imputer.fit_transform(X_cat) one_hot = OneHotEncoder(sparse=True, handle_unknown='ignore') X_cat = one_hot.fit_transform(X_cat) dim = X_cat.shape[1] + X_num.shape[1] else: dim = X_num.shape[1] print("dimensions:", dim) y_true = train_set[args.target[0]].values.astype(np.float32) y_scale = y_true.std() y_true /= y_scale regressor = torch.nn.Linear(dim, 1) torch.nn.init.kaiming_normal_(regressor.weight, nonlinearity='linear') optimizer = torch.optim.SGD( regressor.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=args.decay ) with timeit("training"): indices = list(range(len(X_num))) n_sections = 1 + len(X_num) // args.batchsize for epoch in range(args.epochs): print("epoch", epoch) random.shuffle(indices) for idx in np.array_split(indices, n_sections): y_batch = torch.Tensor(y_true[idx]) num = torch.Tensor(X_num[idx, :]) if len(categorical) > 0: cat = torch.Tensor(X_cat[idx, :].todense()) batch = torch.cat([num, cat], dim=1) else: batch = num optimizer.zero_grad() y_pred = regressor(batch).squeeze(1) loss = (y_batch - y_pred).pow(2).sum() loss.backward() optimizer.step() regressor.eval() with timeit("running imputer on testing data"): X_num = test_set[numerical].values X_num = imputer.transform(X_num) with timeit("running scaler on testing data"): X_num = scaler.transform(X_num) if len(categorical) > 0: with timeit("running one-hot on testing data"): X_cat = test_set[categorical].values X_cat = one_hot.transform(X_cat) with timeit("predicting"): batch_size = 4096 y = [] for i in range(0, len(X_num), batch_size): end = min(len(X_num), i+batch_size) num = torch.Tensor(X_num[i:end, :]) if len(categorical) > 0: cat = torch.Tensor(X_cat[i:end, :].todense()) batch = torch.cat([num, cat], dim=1) else: batch = num y += regressor(batch).squeeze(1).tolist() y = np.array(y) * y_scale y_true = test_set[args.target[0]].values.astype(np.float32) mae = np.abs(y_true - y).mean() print("MAE", mae) ref = np.abs(y_true - y_true.mean()).mean() print("Baseline", ref) outdir = "outdir" # with timeit("writing"): # batch_size = 1024 # for j, i in enumerate(range(0, len(X_num), batch_size)): # d = X_cat[i:i+batch_size, :].todense() # X = np.concatenate([X_num[i:i+batch_size], d], axis=1) # print("X dim", X.shape[1]) # pd.DataFrame(X).to_csv("%s/output%i.csv" % (outdir, j), index=False) with timeit("reading again"): n = 0 for filename in os.listdir(outdir): df = pd.read_csv(os.path.join(outdir, filename)) n += len(df) print("number of rows:", n)
[ "numpy.abs", "os.listdir", "random.shuffle", "pandas.read_csv", "argparse.ArgumentParser", "sklearn.model_selection.train_test_split", "sklearn.preprocessing.OneHotEncoder", "torch.nn.init.kaiming_normal_", "torch.Tensor", "os.path.join", "sklearn.preprocessing.StandardScaler", "numpy.array_sp...
[((591, 647), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Linear Regression"""'}), "(description='Linear Regression')\n", (614, 647), False, 'import argparse\n'), ((3218, 3241), 'torch.nn.Linear', 'torch.nn.Linear', (['dim', '(1)'], {}), '(dim, 1)\n', (3233, 3241), False, 'import torch\n'), ((3242, 3312), 'torch.nn.init.kaiming_normal_', 'torch.nn.init.kaiming_normal_', (['regressor.weight'], {'nonlinearity': '"""linear"""'}), "(regressor.weight, nonlinearity='linear')\n", (3271, 3312), False, 'import torch\n'), ((443, 454), 'time.time', 'time.time', ([], {}), '()\n', (452, 454), False, 'import time\n'), ((1626, 1718), 'pandas.read_csv', 'pd.read_csv', (['args.csv_file[0]'], {'sep': 'args.sep[0]', 'header': '(0)', 'na_values': "['', ' ', 'NA', '-']"}), "(args.csv_file[0], sep=args.sep[0], header=0, na_values=['', ' ',\n 'NA', '-'])\n", (1637, 1718), True, 'import pandas as pd\n'), ((2130, 2190), 'sklearn.model_selection.train_test_split', 'train_test_split', (['df'], {'shuffle': '(True)', 'test_size': 'args.testratio'}), '(df, shuffle=True, test_size=args.testratio)\n', (2146, 2190), False, 'from sklearn.model_selection import train_test_split\n'), ((2311, 2336), 'sklearn.impute.SimpleImputer', 'SimpleImputer', ([], {'copy': '(False)'}), '(copy=False)\n', (2324, 2336), False, 'from sklearn.impute import SimpleImputer\n'), ((2432, 2458), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {'copy': '(False)'}), '(copy=False)\n', (2446, 2458), False, 'from sklearn.preprocessing import StandardScaler\n'), ((5654, 5672), 'os.listdir', 'os.listdir', (['outdir'], {}), '(outdir)\n', (5664, 5672), False, 'import os\n'), ((2906, 2957), 'sklearn.preprocessing.OneHotEncoder', 'OneHotEncoder', ([], {'sparse': '(True)', 'handle_unknown': '"""ignore"""'}), "(sparse=True, handle_unknown='ignore')\n", (2919, 2957), False, 'from sklearn.preprocessing import OneHotEncoder\n'), ((3621, 3644), 'random.shuffle', 'random.shuffle', (['indices'], {}), '(indices)\n', (3635, 3644), False, 'import random\n'), ((3664, 3699), 'numpy.array_split', 'np.array_split', (['indices', 'n_sections'], {}), '(indices, n_sections)\n', (3678, 3699), True, 'import numpy as np\n'), ((4743, 4772), 'torch.Tensor', 'torch.Tensor', (['X_num[i:end, :]'], {}), '(X_num[i:end, :])\n', (4755, 4772), False, 'import torch\n'), ((5010, 5021), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (5018, 5021), True, 'import numpy as np\n'), ((510, 521), 'time.time', 'time.time', ([], {}), '()\n', (519, 521), False, 'import time\n'), ((3723, 3748), 'torch.Tensor', 'torch.Tensor', (['y_true[idx]'], {}), '(y_true[idx])\n', (3735, 3748), False, 'import torch\n'), ((3767, 3794), 'torch.Tensor', 'torch.Tensor', (['X_num[idx, :]'], {}), '(X_num[idx, :])\n', (3779, 3794), False, 'import torch\n'), ((4884, 4912), 'torch.cat', 'torch.cat', (['[num, cat]'], {'dim': '(1)'}), '([num, cat], dim=1)\n', (4893, 4912), False, 'import torch\n'), ((5106, 5124), 'numpy.abs', 'np.abs', (['(y_true - y)'], {}), '(y_true - y)\n', (5112, 5124), True, 'import numpy as np\n'), ((5699, 5729), 'os.path.join', 'os.path.join', (['outdir', 'filename'], {}), '(outdir, filename)\n', (5711, 5729), False, 'import os\n'), ((3916, 3944), 'torch.cat', 'torch.cat', (['[num, cat]'], {'dim': '(1)'}), '([num, cat], dim=1)\n', (3925, 3944), False, 'import torch\n')]
# -*- coding: utf-8 -*- ################################################################# # File : imgfileutils.py # Version : 1.4.5 # Author : czsrh # Date : 10.12.2020 # Institution : Carl Zeiss Microscopy GmbH # Location : https://github.com/zeiss-microscopy/OAD/blob/master/jupyter_notebooks/Read_CZI_and_OMETIFF_and_Napari/modules/imgfileutils.py # Copyright (c) 2020 Carl Zeiss AG, Germany. All Rights Reserved. ################################################################# import czifile as zis from apeer_ometiff_library import omexmlClass import os from pathlib import Path from matplotlib import pyplot as plt, cm, use from mpl_toolkits.axes_grid1 import make_axes_locatable import xmltodict import numpy as np from collections import Counter from lxml import etree as ET import time import re import sys from aicsimageio import AICSImage, imread, imread_dask from aicsimageio.writers import ome_tiff_writer from aicspylibczi import CziFile import dask.array as da import pandas as pd import tifffile import pydash try: import javabridge as jv import bioformats except (ImportError, ModuleNotFoundError) as error: # Output expected ImportErrors. print(error.__class__.__name__ + ": " + error.msg) print('Python-BioFormats cannot be used') try: import napari except ModuleNotFoundError as error: print(error.__class__.__name__ + ": " + error.msg) from PyQt5.QtWidgets import ( QHBoxLayout, QVBoxLayout, QFileSystemModel, QFileDialog, QTreeView, QDialogButtonBox, QWidget, QTableWidget, QTableWidgetItem, QAbstractItemView ) from PyQt5.QtCore import Qt, QDir, QSortFilterProxyModel from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtGui import QFont def get_imgtype(imagefile): """Returns the type of the image based on the file extension - no magic :param imagefile: filename of the image :type imagefile: str :return: string specifying the image type :rtype: str """ imgtype = None if imagefile.lower().endswith('.ome.tiff') or imagefile.lower().endswith('.ome.tif'): # it is on OME-TIFF based on the file extension ... :-) imgtype = 'ometiff' elif imagefile.lower().endswith('.tiff') or imagefile.lower().endswith('.tif'): # it is on OME-TIFF based on the file extension ... :-) imgtype = 'tiff' elif imagefile.lower().endswith('.czi'): # it is on CZI based on the file extension ... :-) imgtype = 'czi' elif imagefile.lower().endswith('.png'): # it is on CZI based on the file extension ... :-) imgtype = 'png' elif imagefile.lower().endswith('.jpg') or imagefile.lower().endswith('.jpeg'): # it is on OME-TIFF based on the file extension ... :-) imgtype = 'jpg' return imgtype def create_metadata_dict(): """A Python dictionary will be created to hold the relevant metadata. :return: dictionary with keys for the relevant metadata :rtype: dict """ metadata = {'Directory': None, 'Filename': None, 'Extension': None, 'ImageType': None, 'AcqDate': None, 'TotalSeries': None, 'SizeX': None, 'SizeY': None, 'SizeZ': 1, 'SizeC': 1, 'SizeT': 1, 'SizeS': 1, 'SizeB': 1, 'SizeM': 1, 'Sizes BF': None, 'DimOrder BF': None, 'DimOrder BF Array': None, 'Axes_czifile': None, 'Shape_czifile': None, 'czi_isRGB': None, 'czi_isMosaic': None, 'ObjNA': [], 'ObjMag': [], 'ObjID': [], 'ObjName': [], 'ObjImmersion': [], 'TubelensMag': [], 'ObjNominalMag': [], 'XScale': None, 'YScale': None, 'ZScale': None, 'XScaleUnit': None, 'YScaleUnit': None, 'ZScaleUnit': None, 'DetectorModel': [], 'DetectorName': [], 'DetectorID': [], 'DetectorType': [], 'InstrumentID': [], 'Channels': [], 'ChannelNames': [], 'ChannelColors': [], 'ImageIDs': [], 'NumPy.dtype': None } return metadata def get_metadata(imagefile, omeseries=0, round_values=False): """Returns a dictionary with metadata depending on the image type. Only CZI and OME-TIFF are currently supported. :param imagefile: filename of the image :type imagefile: str :param omeseries: series of OME-TIFF file, , defaults to 0 :type omeseries: int, optional :param round_values: option to round some values, defaults to TrueFalse :type round_values: bool, optional :return: metadata - dict with the metainformation :rtype: dict :return: additional_mdczi - dict with additional the metainformation for CZI only :rtype: dict """ # get the image type imgtype = get_imgtype(imagefile) print('Detected Image Type (based on extension): ', imgtype) md = {} additional_md = {} if imgtype == 'ometiff': # parse the OME-XML and return the metadata dictionary and additional info md = get_metadata_ometiff(imagefile, series=omeseries) elif imgtype == 'czi': # parse the CZI metadata return the metadata dictionary and additional info md = get_metadata_czi(imagefile, dim2none=False) additional_md = get_additional_metadata_czi(imagefile) # TODO - Remove this when issue is fixed if round_values: # temporary workaround for slider / floating point issue in Napari viewer # https://forum.image.sc/t/problem-with-dimension-slider-when-adding-array-as-new-layer-for-ome-tiff/39092/2?u=sebi06 md['XScale'] = np.round(md['XScale'], 3) md['YScale'] = np.round(md['YScale'], 3) md['ZScale'] = np.round(md['ZScale'], 3) else: # no metadate will be returned print('Scales will not be rounded.') return md, additional_md def get_metadata_ometiff(filename, series=0): """Returns a dictionary with OME-TIFF metadata. :param filename: filename of the OME-TIFF image :type filename: str :param series: Image Series, defaults to 0 :type series: int, optional :return: dictionary with the relevant OME-TIFF metainformation :rtype: dict """ with tifffile.TiffFile(filename) as tif: try: # get OME-XML metadata as string the old way omexml_string = tif[0].image_description.decode('utf-8') except TypeError as e: print(e) omexml_string = tif.ome_metadata # get the OME-XML using the apeer-ometiff-library omemd = omexmlClass.OMEXML(omexml_string) # create dictionary for metadata and get OME-XML data metadata = create_metadata_dict() # get directory and filename etc. metadata['Directory'] = os.path.dirname(filename) metadata['Filename'] = os.path.basename(filename) metadata['Extension'] = 'ome.tiff' metadata['ImageType'] = 'ometiff' metadata['AcqDate'] = omemd.image(series).AcquisitionDate metadata['Name'] = omemd.image(series).Name # get image dimensions TZCXY metadata['SizeT'] = omemd.image(series).Pixels.SizeT metadata['SizeZ'] = omemd.image(series).Pixels.SizeZ metadata['SizeC'] = omemd.image(series).Pixels.SizeC metadata['SizeX'] = omemd.image(series).Pixels.SizeX metadata['SizeY'] = omemd.image(series).Pixels.SizeY # get number of image series metadata['TotalSeries'] = omemd.get_image_count() metadata['Sizes BF'] = [metadata['TotalSeries'], metadata['SizeT'], metadata['SizeZ'], metadata['SizeC'], metadata['SizeY'], metadata['SizeX']] # get dimension order metadata['DimOrder BF'] = omemd.image(series).Pixels.DimensionOrder # reverse the order to reflect later the array shape metadata['DimOrder BF Array'] = metadata['DimOrder BF'][::-1] # get the scaling metadata['XScale'] = omemd.image(series).Pixels.PhysicalSizeX metadata['XScale'] = np.round(metadata['XScale'], 3) # metadata['XScaleUnit'] = omemd.image(series).Pixels.PhysicalSizeXUnit metadata['YScale'] = omemd.image(series).Pixels.PhysicalSizeY metadata['YScale'] = np.round(metadata['YScale'], 3) # metadata['YScaleUnit'] = omemd.image(series).Pixels.PhysicalSizeYUnit metadata['ZScale'] = omemd.image(series).Pixels.PhysicalSizeZ metadata['ZScale'] = np.round(metadata['ZScale'], 3) # metadata['ZScaleUnit'] = omemd.image(series).Pixels.PhysicalSizeZUnit # get all image IDs for i in range(omemd.get_image_count()): metadata['ImageIDs'].append(i) # get information about the instrument and objective try: metadata['InstrumentID'] = omemd.instrument(series).get_ID() except (KeyError, AttributeError) as e: print('Key not found:', e) metadata['InstrumentID'] = None try: metadata['DetectorModel'] = omemd.instrument(series).Detector.get_Model() metadata['DetectorID'] = omemd.instrument(series).Detector.get_ID() metadata['DetectorModel'] = omemd.instrument(series).Detector.get_Type() except (KeyError, AttributeError) as e: print('Key not found:', e) metadata['DetectorModel'] = None metadata['DetectorID'] = None metadata['DetectorModel'] = None try: metadata['ObjNA'] = omemd.instrument(series).Objective.get_LensNA() metadata['ObjID'] = omemd.instrument(series).Objective.get_ID() metadata['ObjMag'] = omemd.instrument(series).Objective.get_NominalMagnification() except (KeyError, AttributeError) as e: print('Key not found:', e) metadata['ObjNA'] = None metadata['ObjID'] = None metadata['ObjMag'] = None # get channel names for c in range(metadata['SizeC']): metadata['Channels'].append(omemd.image(series).Pixels.Channel(c).Name) # add axes and shape information using aicsimageio package ometiff_aics = AICSImage(filename) metadata['Axes_aics'] = ometiff_aics.dims metadata['Shape_aics'] = ometiff_aics.shape metadata['SizeX_aics'] = ometiff_aics.size_x metadata['SizeY_aics'] = ometiff_aics.size_y metadata['SizeC_aics'] = ometiff_aics.size_c metadata['SizeZ_aics'] = ometiff_aics.size_t metadata['SizeT_aics'] = ometiff_aics.size_t metadata['SizeS_aics'] = ometiff_aics.size_s # close AICSImage object ometiff_aics.close() # check for None inside Scaling to avoid issues later one ... metadata = checkmdscale_none(metadata, tocheck=['XScale', 'YScale', 'ZScale'], replace=[1.0, 1.0, 1.0]) return metadata def checkmdscale_none(md, tocheck=['ZScale'], replace=[1.0]): """Check scaling entries for None to avoid issues later on :param md: original metadata :type md: dict :param tocheck: list with entries to check for None, defaults to ['ZScale'] :type tocheck: list, optional :param replace: list with values replacing the None, defaults to [1.0] :type replace: list, optional :return: modified metadata where None entries where replaces by :rtype: [type] """ for tc, rv in zip(tocheck, replace): if md[tc] is None: md[tc] = rv return md def get_metadata_czi(filename, dim2none=False, forceDim=False, forceDimname='SizeC', forceDimvalue=2, convert_scunit=True): """ Returns a dictionary with CZI metadata. Information CZI Dimension Characters: - '0': 'Sample', # e.g. RGBA - 'X': 'Width', - 'Y': 'Height', - 'C': 'Channel', - 'Z': 'Slice', # depth - 'T': 'Time', - 'R': 'Rotation', - 'S': 'Scene', # contiguous regions of interest in a mosaic image - 'I': 'Illumination', # direction - 'B': 'Block', # acquisition - 'M': 'Mosaic', # index of tile for compositing a scene - 'H': 'Phase', # e.g. Airy detector fibers - 'V': 'View', # e.g. for SPIM :param filename: filename of the CZI image :type filename: str :param dim2none: option to set non-existing dimension to None, defaults to False :type dim2none: bool, optional :param forceDim: option to force to not read certain dimensions, defaults to False :type forceDim: bool, optional :param forceDimname: name of the dimension not to read, defaults to SizeC :type forceDimname: str, optional :param forceDimvalue: index of the dimension not to read, defaults to 2 :type forceDimvalue: int, optional :param convert_scunit: convert scale unit string from 'µm' to 'micron', defaults to False :type convert_scunit: bool, optional :return: metadata - dictionary with the relevant CZI metainformation :rtype: dict """ # get CZI object czi = zis.CziFile(filename) # parse the XML into a dictionary metadatadict_czi = czi.metadata(raw=False) # initialize metadata dictionary metadata = create_metadata_dict() # get directory and filename etc. metadata['Directory'] = os.path.dirname(filename) metadata['Filename'] = os.path.basename(filename) metadata['Extension'] = 'czi' metadata['ImageType'] = 'czi' # add axes and shape information using czifile package metadata['Axes_czifile'] = czi.axes metadata['Shape_czifile'] = czi.shape # add axes and shape information using aicsimageio package czi_aics = AICSImage(filename) metadata['Axes_aics'] = czi_aics.dims try: metadata['Shape_aics'] = czi_aics.shape metadata['SizeX_aics'] = czi_aics.size_x metadata['SizeY_aics'] = czi_aics.size_y metadata['SizeC_aics'] = czi_aics.size_c metadata['SizeZ_aics'] = czi_aics.size_t metadata['SizeT_aics'] = czi_aics.size_t metadata['SizeS_aics'] = czi_aics.size_s except KeyError as e: metadata['Shape_aics'] = None metadata['SizeX_aics'] = None metadata['SizeY_aics'] = None metadata['SizeC_aics'] = None metadata['SizeZ_aics'] = None metadata['SizeT_aics'] = None metadata['SizeS_aics'] = None # get additional data by using pylibczi directly # Get the shape of the data, the coordinate pairs are (start index, size) aics_czi = CziFile(filename) metadata['dims_aicspylibczi'] = aics_czi.dims_shape()[0] metadata['dimorder_aicspylibczi'] = aics_czi.dims metadata['size_aicspylibczi'] = aics_czi.size metadata['czi_isMosaic'] = aics_czi.is_mosaic() # determine pixel type for CZI array metadata['NumPy.dtype'] = czi.dtype # check if the CZI image is an RGB image depending # on the last dimension entry of axes if czi.shape[-1] == 3: metadata['czi_isRGB'] = True try: metadata['PixelType'] = metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['PixelType'] except KeyError as e: print('Key not found:', e) metadata['PixelType'] = None try: metadata['SizeX'] = np.int(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeX']) except KeyError as e: metadata['SizeX'] = None try: metadata['SizeY'] = np.int(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeY']) except KeyError as e: metadata['SizeY'] = None try: metadata['SizeZ'] = np.int(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeZ']) except Exception as e: # print('Exception:', e) if dim2none: metadata['SizeZ'] = None if not dim2none: metadata['SizeZ'] = 1 # for special cases do not read the SizeC from the metadata if forceDim and forceDimname == 'SizeC': metadata[forceDimname] = forceDimvalue if not forceDim: try: metadata['SizeC'] = np.int(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeC']) except Exception as e: # print('Exception:', e) if dim2none: metadata['SizeC'] = None if not dim2none: metadata['SizeC'] = 1 # create empty lists for channel related information channels = [] channels_names = [] channels_colors = [] # in case of only one channel if metadata['SizeC'] == 1: # get name for dye try: channels.append(metadatadict_czi['ImageDocument']['Metadata']['DisplaySetting'] ['Channels']['Channel']['ShortName']) except KeyError as e: print('Exception:', e) try: channels.append(metadatadict_czi['ImageDocument']['Metadata']['DisplaySetting'] ['Channels']['Channel']['DyeName']) except KeyError as e: print('Exception:', e) channels.append('Dye-CH1') # get channel name try: channels_names.append(metadatadict_czi['ImageDocument']['Metadata']['DisplaySetting'] ['Channels']['Channel']['Name']) except KeyError as e: print('Exception:', e) channels_names.append['CH1'] # get channel color try: channels_colors.append(metadatadict_czi['ImageDocument']['Metadata']['DisplaySetting'] ['Channels']['Channel']['Color']) except KeyError as e: print('Exception:', e) channels_colors.append('#80808000') # in case of two or more channels if metadata['SizeC'] > 1: # loop over all channels for ch in range(metadata['SizeC']): # get name for dyes try: channels.append(metadatadict_czi['ImageDocument']['Metadata']['DisplaySetting'] ['Channels']['Channel'][ch]['ShortName']) except KeyError as e: print('Exception:', e) try: channels.append(metadatadict_czi['ImageDocument']['Metadata']['DisplaySetting'] ['Channels']['Channel'][ch]['DyeName']) except KeyError as e: print('Exception:', e) channels.append('Dye-CH' + str(ch)) # get channel names try: channels_names.append(metadatadict_czi['ImageDocument']['Metadata']['DisplaySetting'] ['Channels']['Channel'][ch]['Name']) except KeyError as e: print('Exception:', e) channels_names.append('CH' + str(ch)) # get channel colors try: channels_colors.append(metadatadict_czi['ImageDocument']['Metadata']['DisplaySetting'] ['Channels']['Channel'][ch]['Color']) except KeyError as e: print('Exception:', e) # use grayscale instead channels_colors.append('80808000') # write channels information (as lists) into metadata dictionary metadata['Channels'] = channels metadata['ChannelNames'] = channels_names metadata['ChannelColors'] = channels_colors try: metadata['SizeT'] = np.int(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeT']) except Exception as e: # print('Exception:', e) if dim2none: metadata['SizeT'] = None if not dim2none: metadata['SizeT'] = 1 try: metadata['SizeM'] = np.int(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeM']) except Exception as e: # print('Exception:', e) if dim2none: metadata['SizeM'] = None if not dim2none: metadata['SizeM'] = 1 try: metadata['SizeB'] = np.int(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeB']) except Exception as e: # print('Exception:', e) if dim2none: metadata['SizeB'] = None if not dim2none: metadata['SizeB'] = 1 try: metadata['SizeS'] = np.int(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeS']) except Exception as e: # print('Exception:', e) if dim2none: metadata['SizeS'] = None if not dim2none: metadata['SizeS'] = 1 try: metadata['SizeH'] = np.int(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeH']) except Exception as e: # print('Exception:', e) if dim2none: metadata['SizeH'] = None if not dim2none: metadata['SizeH'] = 1 try: metadata['SizeI'] = np.int(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeI']) except Exception as e: # print('Exception:', e) if dim2none: metadata['SizeI'] = None if not dim2none: metadata['SizeI'] = 1 try: metadata['SizeV'] = np.int(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeV']) except Exception as e: # print('Exception:', e) if dim2none: metadata['SizeV'] = None if not dim2none: metadata['SizeV'] = 1 # get the scaling information try: # metadata['Scaling'] = metadatadict_czi['ImageDocument']['Metadata']['Scaling'] metadata['XScale'] = float(metadatadict_czi['ImageDocument']['Metadata']['Scaling']['Items']['Distance'][0]['Value']) * 1000000 metadata['YScale'] = float(metadatadict_czi['ImageDocument']['Metadata']['Scaling']['Items']['Distance'][1]['Value']) * 1000000 metadata['XScale'] = np.round(metadata['XScale'], 3) metadata['YScale'] = np.round(metadata['YScale'], 3) try: metadata['XScaleUnit'] = metadatadict_czi['ImageDocument']['Metadata']['Scaling']['Items']['Distance'][0]['DefaultUnitFormat'] metadata['YScaleUnit'] = metadatadict_czi['ImageDocument']['Metadata']['Scaling']['Items']['Distance'][1]['DefaultUnitFormat'] except KeyError as e: print('Key not found:', e) metadata['XScaleUnit'] = None metadata['YScaleUnit'] = None try: metadata['ZScale'] = float(metadatadict_czi['ImageDocument']['Metadata']['Scaling']['Items']['Distance'][2]['Value']) * 1000000 metadata['ZScale'] = np.round(metadata['ZScale'], 3) # additional check for faulty z-scaling if metadata['ZScale'] == 0.0: metadata['ZScale'] = 1.0 try: metadata['ZScaleUnit'] = metadatadict_czi['ImageDocument']['Metadata']['Scaling']['Items']['Distance'][2]['DefaultUnitFormat'] except KeyError as e: print('Key not found:', e) metadata['ZScaleUnit'] = metadata['XScaleUnit'] except Exception as e: # print('Exception:', e) if dim2none: metadata['ZScale'] = None metadata['ZScaleUnit'] = None if not dim2none: # set to isotropic scaling if it was single plane only metadata['ZScale'] = metadata['XScale'] metadata['ZScaleUnit'] = metadata['XScaleUnit'] except Exception as e: print('Exception:', e) print('Scaling Data could not be found.') # try to get software version try: metadata['SW-Name'] = metadatadict_czi['ImageDocument']['Metadata']['Information']['Application']['Name'] metadata['SW-Version'] = metadatadict_czi['ImageDocument']['Metadata']['Information']['Application']['Version'] except (KeyError, TypeError) as e: print(e) metadata['SW-Name'] = None metadata['SW-Version'] = None try: metadata['AcqDate'] = metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['AcquisitionDateAndTime'] except (KeyError, TypeError) as e: print(e) metadata['AcqDate'] = None # get objective data try: if isinstance(metadatadict_czi['ImageDocument']['Metadata']['Information']['Instrument']['Objectives']['Objective'], list): num_obj = len(metadatadict_czi['ImageDocument']['Metadata']['Information']['Instrument']['Objectives']['Objective']) else: num_obj = 1 except (KeyError, TypeError) as e: print(e) num_obj = 1 # if there is only one objective found if num_obj == 1: try: metadata['ObjName'].append(metadatadict_czi['ImageDocument']['Metadata']['Information'] ['Instrument']['Objectives']['Objective']['Name']) except (KeyError, TypeError) as e: print(e) metadata['ObjName'].append(None) try: metadata['ObjImmersion'] = metadatadict_czi['ImageDocument']['Metadata']['Information']['Instrument']['Objectives']['Objective']['Immersion'] except (KeyError, TypeError) as e: print(e) metadata['ObjImmersion'] = None try: metadata['ObjNA'] = np.float(metadatadict_czi['ImageDocument']['Metadata']['Information'] ['Instrument']['Objectives']['Objective']['LensNA']) except (KeyError, TypeError) as e: print(e) metadata['ObjNA'] = None try: metadata['ObjID'] = metadatadict_czi['ImageDocument']['Metadata']['Information']['Instrument']['Objectives']['Objective']['Id'] except (KeyError, TypeError) as e: print(e) metadata['ObjID'] = None try: metadata['TubelensMag'] = np.float(metadatadict_czi['ImageDocument']['Metadata']['Information'] ['Instrument']['TubeLenses']['TubeLens']['Magnification']) except (KeyError, TypeError) as e: print(e, 'Using Default Value = 1.0 for Tublens Magnification.') metadata['TubelensMag'] = 1.0 try: metadata['ObjNominalMag'] = np.float(metadatadict_czi['ImageDocument']['Metadata']['Information'] ['Instrument']['Objectives']['Objective']['NominalMagnification']) except (KeyError, TypeError) as e: print(e, 'Using Default Value = 1.0 for Nominal Magnification.') metadata['ObjNominalMag'] = 1.0 try: if metadata['TubelensMag'] is not None: metadata['ObjMag'] = metadata['ObjNominalMag'] * metadata['TubelensMag'] if metadata['TubelensMag'] is None: print('No TublensMag found. Use 1 instead') metadata['ObjMag'] = metadata['ObjNominalMag'] * 1.0 except (KeyError, TypeError) as e: print(e) metadata['ObjMag'] = None if num_obj > 1: for o in range(num_obj): try: metadata['ObjName'].append(metadatadict_czi['ImageDocument']['Metadata']['Information'] ['Instrument']['Objectives']['Objective'][o]['Name']) except KeyError as e: print('Key not found:', e) metadata['ObjName'].append(None) try: metadata['ObjImmersion'].append(metadatadict_czi['ImageDocument']['Metadata']['Information'] ['Instrument']['Objectives']['Objective'][o]['Immersion']) except KeyError as e: print('Key not found:', e) metadata['ObjImmersion'].append(None) try: metadata['ObjNA'].append(np.float(metadatadict_czi['ImageDocument']['Metadata']['Information'] ['Instrument']['Objectives']['Objective'][o]['LensNA'])) except KeyError as e: print('Key not found:', e) metadata['ObjNA'].append(None) try: metadata['ObjID'].append(metadatadict_czi['ImageDocument']['Metadata']['Information'] ['Instrument']['Objectives']['Objective'][o]['Id']) except KeyError as e: print('Key not found:', e) metadata['ObjID'].append(None) try: metadata['TubelensMag'].append(np.float(metadatadict_czi['ImageDocument']['Metadata']['Information'] ['Instrument']['TubeLenses']['TubeLens'][o]['Magnification'])) except KeyError as e: print('Key not found:', e, 'Using Default Value = 1.0 for Tublens Magnification.') metadata['TubelensMag'].append(1.0) try: metadata['ObjNominalMag'].append(np.float(metadatadict_czi['ImageDocument']['Metadata']['Information'] ['Instrument']['Objectives']['Objective'][o]['NominalMagnification'])) except KeyError as e: print('Key not found:', e, 'Using Default Value = 1.0 for Nominal Magnification.') metadata['ObjNominalMag'].append(1.0) try: if metadata['TubelensMag'] is not None: metadata['ObjMag'].append(metadata['ObjNominalMag'][o] * metadata['TubelensMag'][o]) if metadata['TubelensMag'] is None: print('No TublensMag found. Use 1 instead') metadata['ObjMag'].append(metadata['ObjNominalMag'][o] * 1.0) except KeyError as e: print('Key not found:', e) metadata['ObjMag'].append(None) # get detector information # check if there are any detector entries inside the dictionary if pydash.objects.has(metadatadict_czi, ['ImageDocument', 'Metadata', 'Information', 'Instrument', 'Detectors']): if isinstance(metadatadict_czi['ImageDocument']['Metadata']['Information']['Instrument']['Detectors']['Detector'], list): num_detectors = len(metadatadict_czi['ImageDocument']['Metadata']['Information']['Instrument']['Detectors']['Detector']) else: num_detectors = 1 # if there is only one detector found if num_detectors == 1: # check for detector ID try: metadata['DetectorID'].append(metadatadict_czi['ImageDocument']['Metadata']['Information'] ['Instrument']['Detectors']['Detector']['Id']) except KeyError as e: metadata['DetectorID'].append(None) # check for detector Name try: metadata['DetectorName'].append(metadatadict_czi['ImageDocument']['Metadata']['Information'] ['Instrument']['Detectors']['Detector']['Name']) except KeyError as e: metadata['DetectorName'].append(None) # check for detector model try: metadata['DetectorModel'].append(metadatadict_czi['ImageDocument']['Metadata']['Information'] ['Instrument']['Detectors']['Detector']['Manufacturer']['Model']) except KeyError as e: metadata['DetectorModel'].append(None) # check for detector type try: metadata['DetectorType'].append(metadatadict_czi['ImageDocument']['Metadata']['Information'] ['Instrument']['Detectors']['Detector']['Type']) except KeyError as e: metadata['DetectorType'].append(None) if num_detectors > 1: for d in range(num_detectors): # check for detector ID try: metadata['DetectorID'].append(metadatadict_czi['ImageDocument']['Metadata']['Information'] ['Instrument']['Detectors']['Detector'][d]['Id']) except KeyError as e: metadata['DetectorID'].append(None) # check for detector Name try: metadata['DetectorName'].append(metadatadict_czi['ImageDocument']['Metadata']['Information'] ['Instrument']['Detectors']['Detector'][d]['Name']) except KeyError as e: metadata['DetectorName'].append(None) # check for detector model try: metadata['DetectorModel'].append(metadatadict_czi['ImageDocument']['Metadata']['Information'] ['Instrument']['Detectors']['Detector'][d]['Manufacturer']['Model']) except KeyError as e: metadata['DetectorModel'].append(None) # check for detector type try: metadata['DetectorType'].append(metadatadict_czi['ImageDocument']['Metadata']['Information'] ['Instrument']['Detectors']['Detector'][d]['Type']) except KeyError as e: metadata['DetectorType'].append(None) # check for well information metadata['Well_ArrayNames'] = [] metadata['Well_Indices'] = [] metadata['Well_PositionNames'] = [] metadata['Well_ColId'] = [] metadata['Well_RowId'] = [] metadata['WellCounter'] = None metadata['SceneStageCenterX'] = [] metadata['SceneStageCenterY'] = [] try: print('Trying to extract Scene and Well information if existing ...') # extract well information from the dictionary allscenes = metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['Dimensions']['S']['Scenes']['Scene'] # loop over all detected scenes for s in range(metadata['SizeS']): if metadata['SizeS'] == 1: well = allscenes try: metadata['Well_ArrayNames'].append(allscenes['ArrayName']) except KeyError as e: # print('Key not found in Metadata Dictionary:', e) try: metadata['Well_ArrayNames'].append(well['Name']) except KeyError as e: print('Key not found in Metadata Dictionary:', e, 'Using A1 instead') metadata['Well_ArrayNames'].append('A1') try: metadata['Well_Indices'].append(allscenes['Index']) except KeyError as e: print('Key not found in Metadata Dictionary:', e) metadata['Well_Indices'].append(1) try: metadata['Well_PositionNames'].append(allscenes['Name']) except KeyError as e: print('Key not found in Metadata Dictionary:', e) metadata['Well_PositionNames'].append('P1') try: metadata['Well_ColId'].append(np.int(allscenes['Shape']['ColumnIndex'])) except KeyError as e: print('Key not found in Metadata Dictionary:', e) metadata['Well_ColId'].append(0) try: metadata['Well_RowId'].append(np.int(allscenes['Shape']['RowIndex'])) except KeyError as e: print('Key not found in Metadata Dictionary:', e) metadata['Well_RowId'].append(0) try: # count the content of the list, e.g. how many time a certain well was detected metadata['WellCounter'] = Counter(metadata['Well_ArrayNames']) except KeyError as e: print('Key not found in Metadata Dictionary:', e) metadata['WellCounter'].append(Counter({'A1': 1})) try: # get the SceneCenter Position sx = allscenes['CenterPosition'].split(',')[0] sy = allscenes['CenterPosition'].split(',')[1] metadata['SceneStageCenterX'].append(np.double(sx)) metadata['SceneStageCenterY'].append(np.double(sy)) except KeyError as e: metadata['SceneStageCenterX'].append(0.0) metadata['SceneStageCenterY'].append(0.0) if metadata['SizeS'] > 1: try: well = allscenes[s] metadata['Well_ArrayNames'].append(well['ArrayName']) except KeyError as e: # print('Key not found in Metadata Dictionary:', e) try: metadata['Well_ArrayNames'].append(well['Name']) except KeyError as e: print('Key not found in Metadata Dictionary:', e, 'Using A1 instead') metadata['Well_ArrayNames'].append('A1') # get the well information try: metadata['Well_Indices'].append(well['Index']) except KeyError as e: # print('Key not found in Metadata Dictionary:', e) metadata['Well_Indices'].append(None) try: metadata['Well_PositionNames'].append(well['Name']) except KeyError as e: # print('Key not found in Metadata Dictionary:', e) metadata['Well_PositionNames'].append(None) try: metadata['Well_ColId'].append(np.int(well['Shape']['ColumnIndex'])) except KeyError as e: print('Key not found in Metadata Dictionary:', e) metadata['Well_ColId'].append(None) try: metadata['Well_RowId'].append(np.int(well['Shape']['RowIndex'])) except KeyError as e: print('Key not found in Metadata Dictionary:', e) metadata['Well_RowId'].append(None) # count the content of the list, e.g. how many time a certain well was detected metadata['WellCounter'] = Counter(metadata['Well_ArrayNames']) # try: if isinstance(allscenes, list): try: # get the SceneCenter Position sx = allscenes[s]['CenterPosition'].split(',')[0] sy = allscenes[s]['CenterPosition'].split(',')[1] metadata['SceneStageCenterX'].append(np.double(sx)) metadata['SceneStageCenterY'].append(np.double(sy)) except KeyError as e: print('Key not found in Metadata Dictionary:', e) metadata['SceneCenterX'].append(0.0) metadata['SceneCenterY'].append(0.0) if not isinstance(allscenes, list): metadata['SceneStageCenterX'].append(0.0) metadata['SceneStageCenterY'].append(0.0) # count the number of different wells metadata['NumWells'] = len(metadata['WellCounter'].keys()) except (KeyError, TypeError) as e: print('No valid Scene or Well information found:', e) # close CZI file czi.close() # close AICSImage object czi_aics.close() # convert scale unit tom avoid encoding problems if convert_scunit: if metadata['XScaleUnit'] == 'µm': metadata['XScaleUnit'] = 'micron' if metadata['YScaleUnit'] == 'µm': metadata['YScaleUnit'] = 'micron' if metadata['ZScaleUnit'] == 'µm': metadata['ZScaleUnit'] = 'micron' # imwrite(filename, data, description='micron \xB5'.encode('latin-1'))) return metadata def get_additional_metadata_czi(filename): """ Returns a dictionary with additional CZI metadata. :param filename: filename of the CZI image :type filename: str :return: additional_czimd - dictionary with additional CZI metainformation :rtype: dict """ # get CZI object and read array czi = zis.CziFile(filename) # parse the XML into a dictionary metadatadict_czi = xmltodict.parse(czi.metadata()) additional_czimd = {} try: additional_czimd['Experiment'] = metadatadict_czi['ImageDocument']['Metadata']['Experiment'] except KeyError as e: print('Key not found:', e) additional_czimd['Experiment'] = None try: additional_czimd['HardwareSetting'] = metadatadict_czi['ImageDocument']['Metadata']['HardwareSetting'] except KeyError as e: print('Key not found:', e) additional_czimd['HardwareSetting'] = None try: additional_czimd['CustomAttributes'] = metadatadict_czi['ImageDocument']['Metadata']['CustomAttributes'] except KeyError as e: print('Key not found:', e) additional_czimd['CustomAttributes'] = None try: additional_czimd['DisplaySetting'] = metadatadict_czi['ImageDocument']['Metadata']['DisplaySetting'] except KeyError as e: print('Key not found:', e) additional_czimd['DisplaySetting'] = None try: additional_czimd['Layers'] = metadatadict_czi['ImageDocument']['Metadata']['Layers'] except KeyError as e: print('Key not found:', e) additional_czimd['Layers'] = None # close CZI file czi.close() return additional_czimd def md2dataframe(metadata, paramcol='Parameter', keycol='Value'): """Convert the metadata dictionary to a Pandas DataFrame. :param metadata: MeteData dictionary :type metadata: dict :param paramcol: Name of Columns for the MetaData Parameters, defaults to 'Parameter' :type paramcol: str, optional :param keycol: Name of Columns for the MetaData Values, defaults to 'Value' :type keycol: str, optional :return: Pandas DataFrame containing all the metadata :rtype: Pandas.DataFrame """ mdframe = pd.DataFrame(columns=[paramcol, keycol]) for k in metadata.keys(): d = {'Parameter': k, 'Value': metadata[k]} df = pd.DataFrame([d], index=[0]) mdframe = pd.concat([mdframe, df], ignore_index=True) return mdframe def get_dimorder(dimstring): """Get the order of dimensions from dimension string :param dimstring: string containing the dimensions :type dimstring: str :return: dims_dict - dictionary with the dimensions and its positions :rtype: dict :return: dimindex_list - list with indices of dimensions :rtype: list :return: numvalid_dims - number of valid dimensions :rtype: integer """ dimindex_list = [] dims = ['R', 'I', 'M', 'H', 'V', 'B', 'S', 'T', 'C', 'Z', 'Y', 'X', '0'] dims_dict = {} # loop over all dimensions and find the index for d in dims: dims_dict[d] = dimstring.find(d) dimindex_list.append(dimstring.find(d)) # check if a dimension really exists numvalid_dims = sum(i > 0 for i in dimindex_list) return dims_dict, dimindex_list, numvalid_dims def get_array_czi(filename, replace_value=False, remove_HDim=True, return_addmd=False, forceDim=False, forceDimname='SizeC', forceDimvalue=2): """Get the pixel data of the CZI file as multidimensional NumPy.Array :param filename: filename of the CZI file :type filename: str :param replacevalue: replace arrays entries with a specific value with NaN, defaults to False :type replacevalue: bool, optional :param remove_HDim: remove the H-Dimension (Airy Scan Detectors), defaults to True :type remove_HDim: bool, optional :param return_addmd: read the additional metadata, defaults to False :type return_addmd: bool, optional :param forceDim: force a specfic dimension to have a specif value, defaults to False :type forceDim: bool, optional :param forceDimname: name of the dimension, defaults to 'SizeC' :type forceDimname: str, optional :param forceDimvalue: value of the dimension, defaults to 2 :type forceDimvalue: int, optional :return: cziarray - dictionary with the dimensions and its positions :rtype: NumPy.Array :return: metadata - dictionary with CZI metadata :rtype: dict :return: additional_metadata_czi - dictionary with additional CZI metadata :rtype: dict """ metadata = get_metadata_czi(filename, forceDim=forceDim, forceDimname=forceDimname, forceDimvalue=forceDimvalue) # get additional metainformation additional_metadata_czi = get_additional_metadata_czi(filename) # get CZI object and read array czi = zis.CziFile(filename) cziarray = czi.asarray() # check for H dimension and remove if remove_HDim and metadata['Axes_czifile'][0] == 'H': # metadata['Axes'] = metadata['Axes_czifile'][1:] metadata['Axes_czifile'] = metadata['Axes_czifile'].replace('H', '') cziarray = np.squeeze(cziarray, axis=0) # get additional information about dimension order etc. dim_dict, dim_list, numvalid_dims = get_dimorder(metadata['Axes_czifile']) metadata['DimOrder CZI'] = dim_dict if cziarray.shape[-1] == 3: pass else: # remove the last dimension from the end cziarray = np.squeeze(cziarray, axis=len(metadata['Axes_czifile']) - 1) metadata['Axes_czifile'] = metadata['Axes_czifile'].replace('0', '') if replace_value: cziarray = replace_value(cziarray, value=0) # close czi file czi.close() return cziarray, metadata, additional_metadata_czi def replace_value(data, value=0): """Replace specifc values in array with NaN :param data: Array where values should be replaced :type data: NumPy.Array :param value: value inside array to be replaced with NaN, defaults to 0 :type value: int, optional :return: array with new values :rtype: NumPy.Array """ data = data.astype('float') data[data == value] = np.nan return data def get_scalefactor(metadata): """Add scaling factors to the metadata dictionary :param metadata: dictionary with CZI or OME-TIFF metadata :type metadata: dict :return: dictionary with additional keys for scling factors :rtype: dict """ # set default scale factor to 1.0 scalefactors = {'xy': 1.0, 'zx': 1.0 } try: # get the factor between XY scaling scalefactors['xy'] = np.round(metadata['XScale'] / metadata['YScale'], 3) # get the scalefactor between XZ scaling scalefactors['zx'] = np.round(metadata['ZScale'] / metadata['YScale'], 3) except KeyError as e: print('Key not found: ', e, 'Using defaults = 1.0') return scalefactors def calc_scaling(data, corr_min=1.0, offset_min=0, corr_max=0.85, offset_max=0): """[summary] :param data: Calculate min / max scaling :type data: Numpy.Array :param corr_min: correction factor for minvalue, defaults to 1.0 :type corr_min: float, optional :param offset_min: offset for min value, defaults to 0 :type offset_min: int, optional :param corr_max: correction factor for max value, defaults to 0.85 :type corr_max: float, optional :param offset_max: offset for max value, defaults to 0 :type offset_max: int, optional :return: list with [minvalue, maxvalue] :rtype: list """ # get min-max values for initial scaling minvalue = np.round((data.min() + offset_min) * corr_min) maxvalue = np.round((data.max() + offset_max) * corr_max) print('Scaling: ', minvalue, maxvalue) return [minvalue, maxvalue] def show_napari(array, metadata, blending='additive', gamma=0.85, add_mdtable=True, rename_sliders=False, use_BFdims=False): """Show the multidimensional array using the Napari viewer :param array: multidimensional NumPy.Array containing the pixeldata :type array: NumPy.Array :param metadata: dictionary with CZI or OME-TIFF metadata :type metadata: dict :param blending: NapariViewer option for blending, defaults to 'additive' :type blending: str, optional :param gamma: NapariViewer value for Gamma, defaults to 0.85 :type gamma: float, optional :param rename_sliders: name slider with correct labels output, defaults to False :type verbose: bool, optional :param use_BFdims: if True use the 5D dimension string from BioFormats or apeer-ometiff library and if False use 6D dimension string from AICSImageIO. Only use when the image is read via apeer-ometiff-library etc., defaults to False :type verbose: bool, optional """ # create list for the napari layers napari_layers = [] with napari.gui_qt(): # create scalefcator with all ones scalefactors = [1.0] * len(array.shape) # extra check for czi to avoid user mistakes if metadata['ImageType'] == 'czi': use_BFdims = False if use_BFdims: # use the dimension string from BioFormats 5D dimpos = get_dimpositions(metadata['DimOrder BF Array']) if not use_BFdims: # use the dimension string from AICSImageIO 6D (default) dimpos = get_dimpositions(metadata['Axes_aics']) # get the scalefactors from the metadata scalef = get_scalefactor(metadata) # modify the tuple for the scales for napari scalefactors[dimpos['Z']] = scalef['zx'] # remove C dimension from scalefactor scalefactors_ch = scalefactors.copy() del scalefactors_ch[dimpos['C']] # initialize the napari viewer print('Initializing Napari Viewer ...') # create a viewer and add some images viewer = napari.Viewer() # add widget for metadata if add_mdtable: # create widget for the metadata mdbrowser = TableWidget() viewer.window.add_dock_widget(mdbrowser, name='mdbrowser', area='right') # add the metadata and adapt the table display mdbrowser.update_metadata(metadata) mdbrowser.update_style() if metadata['SizeC'] > 1: # add all channels as layers for ch in range(metadata['SizeC']): try: # get the channel name chname = metadata['Channels'][ch] except KeyError as e: print(e) # or use CH1 etc. as string for the name chname = 'CH' + str(ch + 1) # cut out channel # use dask if array is a dask.array if isinstance(array, da.Array): print('Extract Channel as Dask.Array') channel = array.compute().take(ch, axis=dimpos['C']) #new_dimstring = metadata['Axes_aics'].replace('C', '') else: # use normal numpy if not print('Extract Channel as NumPy.Array') channel = array.take(ch, axis=dimpos['C']) if use_BFdims: new_dimstring = metadata['DimOrder BF Array'].replace('C', '') if not use_BFdims: new_dimstring = metadata['Axes_aics'].replace('C', '') # actually show the image array print('Adding Channel : ', chname) print('Shape Channel : ', ch, channel.shape) print('Scaling Factors : ', scalefactors_ch) # get min-max values for initial scaling clim = calc_scaling(channel, corr_min=1.0, offset_min=0, corr_max=0.85, offset_max=0) # add channel to napari viewer new_layer = viewer.add_image(channel, name=chname, scale=scalefactors_ch, contrast_limits=clim, blending=blending, gamma=gamma) napari_layers.append(new_layer) if metadata['SizeC'] == 1: # just add one channel as a layer try: # get the channel name chname = metadata['Channels'][0] except KeyError: # or use CH1 etc. as string for the name chname = 'CH' + str(ch + 1) # actually show the image array print('Adding Channel: ', chname) print('Scaling Factors: ', scalefactors) # use dask if array is a dask.array if isinstance(array, da.Array): print('Extract Channel using Dask.Array') array = array.compute() # get min-max values for initial scaling clim = calc_scaling(array) # add layer to Napari viewer new_layer = viewer.add_image(array, name=chname, scale=scalefactors, contrast_limits=clim, blending=blending, gamma=gamma) napari_layers.append(new_layer) if rename_sliders: print('Renaming the Sliders based on the Dimension String ....') if metadata['SizeC'] == 1: # get the position of dimension entries after removing C dimension dimpos_viewer = get_dimpositions(metadata['Axes_aics']) # get the label of the sliders sliders = viewer.dims.axis_labels # update the labels with the correct dimension strings slidernames = ['B', 'S', 'T', 'Z', 'C'] if metadata['SizeC'] > 1: new_dimstring = metadata['Axes_aics'].replace('C', '') # get the position of dimension entries after removing C dimension dimpos_viewer = get_dimpositions(new_dimstring) # get the label of the sliders sliders = viewer.dims.axis_labels # update the labels with the correct dimension strings slidernames = ['B', 'S', 'T', 'Z'] for s in slidernames: if dimpos_viewer[s] >= 0: sliders[dimpos_viewer[s]] = s # apply the new labels to the viewer viewer.dims.axis_labels = sliders return napari_layers def check_for_previewimage(czi): """Check if the CZI contains an image from a prescan camera :param czi: CZI imagefile object :type metadata: CziFile object :return: has_attimage - Boolean if CZI image contains prescan image :rtype: bool """ att = [] # loop over the attachments for attachment in czi.attachments(): entry = attachment.attachment_entry print(entry.name) att.append(entry.name) has_attimage = False # check for the entry "SlidePreview" if 'SlidePreview' in att: has_attimage = True return has_attimage def writexml_czi(filename, xmlsuffix='_CZI_MetaData.xml'): """Write XML imformation of CZI to disk :param filename: CZI image filename :type filename: str :param xmlsuffix: suffix for the XML file that will be created, defaults to '_CZI_MetaData.xml' :type xmlsuffix: str, optional :return: filename of the XML file :rtype: str """ # open czi file and get the metadata czi = zis.CziFile(filename) mdczi = czi.metadata() czi.close() # change file name xmlfile = filename.replace('.czi', xmlsuffix) # get tree from string tree = ET.ElementTree(ET.fromstring(mdczi)) # write XML file to same folder tree.write(xmlfile, encoding='utf-8', method='xml') return xmlfile def writexml_ometiff(filename, xmlsuffix='_OMETIFF_MetaData.xml'): """Write XML imformation of OME-TIFF to disk :param filename: OME-TIFF image filename :type filename: str :param xmlsuffix: suffix for the XML file that will be created, defaults to '_OMETIFF_MetaData.xml' :type xmlsuffix: str, optional :return: filename of the XML file :rtype: str """ if filename.lower().endswith('.ome.tiff'): ext = '.ome.tiff' if filename.lower().endswith('.ome.tif'): ext = '.ome.tif' with tifffile.TiffFile(filename) as tif: omexml_string = tif.ome_metadata # get tree from string tree = ET.ElementTree(ET.fromstring(omexml_string.encode('utf-8'))) # change file name xmlfile = filename.replace(ext, xmlsuffix) tree.write(xmlfile, encoding='utf-8', method='xml', pretty_print=True) print('Created OME-XML file for testdata: ', filename) return xmlfile def getImageSeriesIDforWell(welllist, wellID): """ Returns all ImageSeries (for OME-TIFF) indicies for a specific wellID :param welllist: list containing all wellIDs as stringe, e.g. '[B4, B4, B4, B4, B5, B5, B5, B5]' :type welllist: list :param wellID: string specifying the well, eg.g. 'B4' :type wellID: str :return: imageseriesindices - list containing all ImageSeries indices, which correspond the the well :rtype: list """ imageseries_indices = [i for i, x in enumerate(welllist) if x == wellID] return imageseries_indices def addzeros(number): """Convert a number into a string and add leading zeros. Typically used to construct filenames with equal lengths. :param number: the number :type number: int :return: zerostring - string with leading zeros :rtype: str """ if number < 10: zerostring = '0000' + str(number) if number >= 10 and number < 100: zerostring = '000' + str(number) if number >= 100 and number < 1000: zerostring = '00' + str(number) if number >= 1000 and number < 10000: zerostring = '0' + str(number) return zerostring def write_ometiff(filepath, img, scalex=0.1, scaley=0.1, scalez=1.0, dimorder='TZCYX', pixeltype=np.uint16, swapxyaxes=True, series=1): """ONLY FOR INTERNAL TESTING - DO NOT USE! This function will write an OME-TIFF file to disk. The out 6D array has the following dimension order: [T, Z, C, Y, X] if swapxyaxes = True [T, Z, C, X, Y] if swapxyaxes = False """ # Dimension STZCXY if swapxyaxes: # swap xy to write the OME-Stack with the correct shape SizeT = img.shape[0] SizeZ = img.shape[1] SizeC = img.shape[2] SizeX = img.shape[4] SizeY = img.shape[3] if not swapxyaxes: SizeT = img.shape[0] SizeZ = img.shape[1] SizeC = img.shape[2] SizeX = img.shape[3] SizeY = img.shape[4] # Getting metadata info omexml = bioformats.omexml.OMEXML() omexml.image(series - 1).Name = filepath for s in range(series): p = omexml.image(s).Pixels p.ID = str(s) p.SizeX = SizeX p.SizeY = SizeY p.SizeC = SizeC p.SizeT = SizeT p.SizeZ = SizeZ p.PhysicalSizeX = np.float(scalex) p.PhysicalSizeY = np.float(scaley) p.PhysicalSizeZ = np.float(scalez) if pixeltype == np.uint8: p.PixelType = 'uint8' if pixeltype == np.uint16: p.PixelType = 'uint16' p.channel_count = SizeC p.plane_count = SizeZ * SizeT * SizeC p = writeOMETIFFplanes(p, SizeT=SizeT, SizeZ=SizeZ, SizeC=SizeC, order=dimorder) for c in range(SizeC): # if pixeltype == 'unit8': if pixeltype == np.uint8: p.Channel(c).SamplesPerPixel = 1 if pixeltype == np.uint16: p.Channel(c).SamplesPerPixel = 2 omexml.structured_annotations.add_original_metadata(bioformats.omexml.OM_SAMPLES_PER_PIXEL, str(SizeC)) # Converting to omexml xml = omexml.to_xml(encoding='utf-8') # write file and save OME-XML as description tifffile.imwrite(filepath, img, metadata={'axes': dimorder}, description=xml) return filepath def writeOMETIFFplanes(pixel, SizeT=1, SizeZ=1, SizeC=1, order='TZCXY', verbose=False): """ONLY FOR INTERNAL TESTING - DO NOT USE! """ if order == 'TZCYX' or order == 'TZCXY': pixel.DimensionOrder = bioformats.omexml.DO_XYCZT counter = 0 for t in range(SizeT): for z in range(SizeZ): for c in range(SizeC): if verbose: print('Write PlaneTable: ', t, z, c), sys.stdout.flush() pixel.Plane(counter).TheT = t pixel.Plane(counter).TheZ = z pixel.Plane(counter).TheC = c counter = counter + 1 return pixel def write_ometiff_aicsimageio(savepath, imgarray, metadata, reader='aicsimageio', overwrite=False): """Write an OME-TIFF file from an image array based on the metadata. :param filepath: savepath of the OME-TIFF stack :type filepath: str :param imgarray: multi-dimensional image array :type imgarray: NumPy.Array :param metadata: metadata dictionary with the required information to create an correct OME-TIFF file :type metadata: dict :param reader: string (aicsimagio or czifile) specifying the used reader, defaults to aicsimageio :type metadata: str :param overwrite: option to overwrite an existing OME-TIFF, defaults to False :type overwrite: bool, optional """ # define scaling from metadata or use defualt scaling try: pixels_physical_size = [metadata['XScale'], metadata['YScale'], metadata['ZScale']] except KeyError as e: print('Key not found:', e) print('Use default scaling XYZ=1.0') pixels_physical_size = [1.0, 1.0, 1.0] # define channel names list from metadata try: channel_names = [] for ch in metadata['Channels']: channel_names.append(ch) except KeyError as e: print('Key not found:', e) channel_names = None # get the dimensions and their position inside the dimension string if reader == 'aicsimageio': dims_dict, dimindex_list, numvalid_dims = get_dimorder(metadata['Axes_aics']) # if the array has more than 5 dimensions then remove the S dimension # because it is not supported by OME-TIFF if len(imgarray.shape) > 5: try: imgarray = np.squeeze(imgarray, axis=dims_dict['S']) except Exception: print('Could not remover S Dimension from string.)') # remove the S character from the dimension string new_dimorder = metadata['Axes_aics'].replace('S', '') if reader == 'czifile': new_dimorder = metadata['Axes'] dims_dict, dimindex_list, numvalid_dims = get_dimorder(metadata['Axes']) """ '0': 'Sample', # e.g. RGBA 'X': 'Width', 'Y': 'Height', 'C': 'Channel', 'Z': 'Slice', # depth 'T': 'Time', 'R': 'Rotation', 'S': 'Scene', # contiguous regions of interest in a mosaic image 'I': 'Illumination', # direction 'B': 'Block', # acquisition 'M': 'Mosaic', # index of tile for compositing a scene 'H': 'Phase', # e.g. Airy detector fibers 'V': 'View', # e.g. for SPIM """ to_remove = [] # list of unspupported dims for writing an OME-TIFF dims = ['R', 'I', 'M', 'H', 'V', 'B', 'S', '0'] for dim in dims: if dims_dict[dim] >= 0: # remove the CZI DIMENSION character from the dimension string new_dimorder = new_dimorder.replace(dim, '') # add dimension index to the list of axis to be removed to_remove.append(dims_dict[dim]) print('Remove Dimension:', dim) # create tuple with dimensions to be removed dims2remove = tuple(to_remove) # remove dimensions from array imgarray = np.squeeze(imgarray, axis=dims2remove) # write the array as an OME-TIFF incl. the metadata try: with ome_tiff_writer.OmeTiffWriter(savepath, overwrite_file=overwrite) as writer: writer.save(imgarray, channel_names=channel_names, ome_xml=None, image_name=os.path.basename((savepath)), pixels_physical_size=pixels_physical_size, channel_colors=None, dimension_order=new_dimorder) writer.close() except Exception as error: print(error.__class__.__name__ + ": " + error.msg) print('Could not write OME-TIFF') savepath = None return savepath def correct_omeheader(omefile, old=("2012-03", "2013-06", r"ome/2016-06"), new=("2016-06", "2016-06", r"OME/2016-06") ): """This function is actually a workaround for AICSImageIO<=3.1.4 that correct some incorrect namespaces inside the OME-XML header :param omefile: OME-TIFF image file :type omefile: string :param old: strings that should be corrected, defaults to ("2012-03", "2013-06", r"ome/2016-06") :type old: tuple, optional :param new: replacement for the strings to be corrected, defaults to ("2016-06", "2016-06", r"OME/2016-06") :type new: tuple, optional """ # create the tif object from the filename tif = tifffile.TiffFile(omefile) # get the pixel array and the OME-XML string array = tif.asarray() omexml_string = tif.ome_metadata # search for the strings to be replaced and do it for ostr, nstr in zip(old, new): print('Replace: ', ostr, 'with', nstr) omexml_string = omexml_string.replace(ostr, nstr) # save the file with the new, correct strings tifffile.imsave(omefile, array, photometric='minisblack', description=omexml_string) # close tif object tif.close() print('Updated OME Header.') def get_fname_woext(filepath): """Get the complete path of a file without the extension It alos will works for extensions like c:\myfile.abc.xyz The output will be: c:\myfile :param filepath: complete fiepath :type filepath: str :return: complete filepath without extension :rtype: str """ # create empty string real_extension = '' # get all part of the file extension sufs = Path(filepath).suffixes for s in sufs: real_extension = real_extension + s # remover real extension from filepath filepath_woext = filepath.replace(real_extension, '') return filepath_woext def convert_to_ometiff(imagefilepath, bftoolsdir='/Users/bftools', czi_include_attachments=False, czi_autostitch=True, verbose=True): """Convert image file using bfconvert tool into a OME-TIFF from with a python script. :param imagefilepath: path to imagefile :type imagefilepath: str :param bftoolsdir: bftools directory containing the bfconvert, defaults to '/Users/bftools' :type bftoolsdir: str, optional :param czi_include_attachments: option convert a CZI attachment (if CZI), defaults to False :type czi_include_attachments: bool, optional :param czi_autostitch: option stich a CZI, defaults to True :type czi_autostitch: bool, optional :param verbose: show additional output, defaults to True :type verbose: bool, optional :return: fileparh of created OME-TIFF file :rtype: str """ # check if path exits if not os.path.exists(bftoolsdir): print('No bftools dirctory found. Nothing will be converted') file_ometiff = None if os.path.exists(bftoolsdir): # set working dir os.chdir(bftoolsdir) # get the imagefile path without extension imagefilepath_woext = get_fname_woext(imagefilepath) # create imagefile path for OME-TIFF file_ometiff = imagefilepath_woext + '.ome.tiff' # create cmdstring for CZI files- mind the spaces !!! if imagefilepath.lower().endswith('.czi'): # configure the CZI options if czi_include_attachments: czi_att = 'true' if not czi_include_attachments: czi_att = 'false' if czi_autostitch: czi_stitch = 'true' if not czi_autostitch: czi_stitch = 'false' # create cmdstring - mind the spaces !!! cmdstring = 'bfconvert -no-upgrade -option zeissczi.attachments ' + czi_att + ' -option zeissczi.autostitch ' + \ czi_stitch + ' "' + imagefilepath + '" "' + file_ometiff + '"' else: # create cmdstring for non-CZIs- mind the spaces !!! cmdstring = 'bfconvert -no-upgrade' + ' "' + imagefilepath + '" "' + file_ometiff + '"' if verbose: print('Original ImageFile : ', imagefilepath_woext) print('ImageFile OME.TIFF : ', file_ometiff) print('Use CMD : ', cmdstring) # run the bfconvert tool with the specified parameters os.system(cmdstring) print('Done.') return file_ometiff def get_dimpositions(dimstring, tocheck=['B', 'S', 'T', 'Z', 'C']): """Simple function to get the indices of the dimension identifiers in a string :param dimstring: dimension string :type dimstring: str :param tocheck: list of entries to check, defaults to ['B', 'S', 'T', 'Z', 'C'] :type tocheck: list, optional :return: dictionary with positions of dimensions inside string :rtype: dict """ dimpos = {} for p in tocheck: dimpos[p] = dimstring.find(p) return dimpos def norm_columns(df, colname='Time [s]', mode='min'): """Normalize a specif column inside a Pandas dataframe :param df: DataFrame :type df: pf.DataFrame :param colname: Name of the coumn to be normalized, defaults to 'Time [s]' :type colname: str, optional :param mode: Mode of Normalization, defaults to 'min' :type mode: str, optional :return: Dataframe with normalized column :rtype: pd.DataFrame """ # normalize columns according to min or max value if mode == 'min': min_value = df[colname].min() df[colname] = df[colname] - min_value if mode == 'max': max_value = df[colname].max() df[colname] = df[colname] - max_value return df def update5dstack(image5d, image2d, dimstring5d='TCZYX', t=0, z=0, c=0): # remove XY dimstring5d = dimstring5d.replace('X', '').replace('Y', '') if dimstring5d == 'TZC': image5d[t, z, c, :, :] = image2d if dimstring5d == 'TCZ': image5d[t, c, z, :, :] = image2d if dimstring5d == 'ZTC': image5d[z, t, c, :, :] = image2d if dimstring5d == 'ZCT': image5d[z, c, t, :, :] = image2d if dimstring5d == 'CTZ': image5d[c, t, z, :, :] = image2d if dimstring5d == 'CZT': image5d[c, z, t, :, :] = image2d return image5d def getdims_pylibczi(czi): # Get the shape of the data, the coordinate pairs are (start index, size) # [{'X': (0, 1900), 'Y': (0, 1300), 'Z': (0, 60), 'C': (0, 4), 'S': (0, 40), 'B': (0, 1)}] # dimensions = czi.dims_shape() dimsizes = {} for d in range(len(czi.dims)): # print(d) dimsizes['Size' + czi.dims[d]] = czi.size[d] return dimsizes def calc_normvar(img2d): """Determine normalized focus value for a 2D image - based on algorithm F - 11 "Normalized Variance" - Taken from: Sun et al., 2004. MICROSCOPY RESEARCH AND TECHNIQUE 65, 139–149. - Maximum value is best-focused, decreasing as defocus increases :param img2d: 2D image :type img2d: NumPy.Array :return: normalized focus value for the 2D image :rtype: float """ mean = np.mean(img2d) height = img2d.shape[0] width = img2d.shape[1] # subtract the mean and sum up the whole array fi = (img2d - mean)**2 b = np.sum(fi) # calculate the normalized variance value normvar = b / (height * width * mean) return normvar class TableWidget(QWidget): def __init__(self): super(QWidget, self).__init__() self.layout = QHBoxLayout(self) self.mdtable = QTableWidget() self.layout.addWidget(self.mdtable) self.mdtable.setShowGrid(True) self.mdtable.setHorizontalHeaderLabels(['Parameter', 'Value']) header = self.mdtable.horizontalHeader() header.setDefaultAlignment(Qt.AlignLeft) def update_metadata(self, metadata): row_count = len(metadata) col_count = 2 self.mdtable.setColumnCount(col_count) self.mdtable.setRowCount(row_count) row = 0 for key, value in metadata.items(): newkey = QTableWidgetItem(key) self.mdtable.setItem(row, 0, newkey) newvalue = QTableWidgetItem(str(value)) self.mdtable.setItem(row, 1, newvalue) row += 1 # fit columns to content self.mdtable.resizeColumnsToContents() def update_style(self): # define font fnt = QFont() fnt.setPointSize(11) fnt.setBold(True) fnt.setFamily('Arial') # update both header items item1 = QtWidgets.QTableWidgetItem('Parameter') item1.setForeground(QtGui.QColor(25, 25, 25)) item1.setFont(fnt) self.mdtable.setHorizontalHeaderItem(0, item1) item2 = QtWidgets.QTableWidgetItem('Value') item2.setForeground(QtGui.QColor(25, 25, 25)) item2.setFont(fnt) self.mdtable.setHorizontalHeaderItem(1, item2)
[ "pydash.objects.has", "PyQt5.QtGui.QColor", "bioformats.omexml.OMEXML", "lxml.etree.fromstring", "aicspylibczi.CziFile", "tifffile.TiffFile", "os.path.exists", "aicsimageio.AICSImage", "numpy.mean", "PyQt5.QtWidgets.QTableWidget", "pathlib.Path", "napari.gui_qt", "tifffile.imsave", "pandas...
[((7062, 7095), 'apeer_ometiff_library.omexmlClass.OMEXML', 'omexmlClass.OMEXML', (['omexml_string'], {}), '(omexml_string)\n', (7080, 7095), False, 'from apeer_ometiff_library import omexmlClass\n'), ((7260, 7285), 'os.path.dirname', 'os.path.dirname', (['filename'], {}), '(filename)\n', (7275, 7285), False, 'import os\n'), ((7313, 7339), 'os.path.basename', 'os.path.basename', (['filename'], {}), '(filename)\n', (7329, 7339), False, 'import os\n'), ((8559, 8590), 'numpy.round', 'np.round', (["metadata['XScale']", '(3)'], {}), "(metadata['XScale'], 3)\n", (8567, 8590), True, 'import numpy as np\n'), ((8758, 8789), 'numpy.round', 'np.round', (["metadata['YScale']", '(3)'], {}), "(metadata['YScale'], 3)\n", (8766, 8789), True, 'import numpy as np\n'), ((8957, 8988), 'numpy.round', 'np.round', (["metadata['ZScale']", '(3)'], {}), "(metadata['ZScale'], 3)\n", (8965, 8988), True, 'import numpy as np\n'), ((10532, 10551), 'aicsimageio.AICSImage', 'AICSImage', (['filename'], {}), '(filename)\n', (10541, 10551), False, 'from aicsimageio import AICSImage, imread, imread_dask\n'), ((13439, 13460), 'czifile.CziFile', 'zis.CziFile', (['filename'], {}), '(filename)\n', (13450, 13460), True, 'import czifile as zis\n'), ((13690, 13715), 'os.path.dirname', 'os.path.dirname', (['filename'], {}), '(filename)\n', (13705, 13715), False, 'import os\n'), ((13743, 13769), 'os.path.basename', 'os.path.basename', (['filename'], {}), '(filename)\n', (13759, 13769), False, 'import os\n'), ((14059, 14078), 'aicsimageio.AICSImage', 'AICSImage', (['filename'], {}), '(filename)\n', (14068, 14078), False, 'from aicsimageio import AICSImage, imread, imread_dask\n'), ((14911, 14928), 'aicspylibczi.CziFile', 'CziFile', (['filename'], {}), '(filename)\n', (14918, 14928), False, 'from aicspylibczi import CziFile\n'), ((30653, 30766), 'pydash.objects.has', 'pydash.objects.has', (['metadatadict_czi', "['ImageDocument', 'Metadata', 'Information', 'Instrument', 'Detectors']"], {}), "(metadatadict_czi, ['ImageDocument', 'Metadata',\n 'Information', 'Instrument', 'Detectors'])\n", (30671, 30766), False, 'import pydash\n'), ((41210, 41231), 'czifile.CziFile', 'zis.CziFile', (['filename'], {}), '(filename)\n', (41221, 41231), True, 'import czifile as zis\n'), ((43084, 43124), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': '[paramcol, keycol]'}), '(columns=[paramcol, keycol])\n', (43096, 43124), True, 'import pandas as pd\n'), ((45924, 45945), 'czifile.CziFile', 'zis.CziFile', (['filename'], {}), '(filename)\n', (45935, 45945), True, 'import czifile as zis\n'), ((57298, 57319), 'czifile.CziFile', 'zis.CziFile', (['filename'], {}), '(filename)\n', (57309, 57319), True, 'import czifile as zis\n'), ((60732, 60758), 'bioformats.omexml.OMEXML', 'bioformats.omexml.OMEXML', ([], {}), '()\n', (60756, 60758), False, 'import bioformats\n'), ((61928, 62005), 'tifffile.imwrite', 'tifffile.imwrite', (['filepath', 'img'], {'metadata': "{'axes': dimorder}", 'description': 'xml'}), "(filepath, img, metadata={'axes': dimorder}, description=xml)\n", (61944, 62005), False, 'import tifffile\n'), ((67643, 67669), 'tifffile.TiffFile', 'tifffile.TiffFile', (['omefile'], {}), '(omefile)\n', (67660, 67669), False, 'import tifffile\n'), ((68035, 68124), 'tifffile.imsave', 'tifffile.imsave', (['omefile', 'array'], {'photometric': '"""minisblack"""', 'description': 'omexml_string'}), "(omefile, array, photometric='minisblack', description=\n omexml_string)\n", (68050, 68124), False, 'import tifffile\n'), ((69990, 70016), 'os.path.exists', 'os.path.exists', (['bftoolsdir'], {}), '(bftoolsdir)\n', (70004, 70016), False, 'import os\n'), ((74244, 74258), 'numpy.mean', 'np.mean', (['img2d'], {}), '(img2d)\n', (74251, 74258), True, 'import numpy as np\n'), ((74401, 74411), 'numpy.sum', 'np.sum', (['fi'], {}), '(fi)\n', (74407, 74411), True, 'import numpy as np\n'), ((6117, 6142), 'numpy.round', 'np.round', (["md['XScale']", '(3)'], {}), "(md['XScale'], 3)\n", (6125, 6142), True, 'import numpy as np\n'), ((6166, 6191), 'numpy.round', 'np.round', (["md['YScale']", '(3)'], {}), "(md['YScale'], 3)\n", (6174, 6191), True, 'import numpy as np\n'), ((6215, 6240), 'numpy.round', 'np.round', (["md['ZScale']", '(3)'], {}), "(md['ZScale'], 3)\n", (6223, 6240), True, 'import numpy as np\n'), ((6723, 6750), 'tifffile.TiffFile', 'tifffile.TiffFile', (['filename'], {}), '(filename)\n', (6740, 6750), False, 'import tifffile\n'), ((15650, 15741), 'numpy.int', 'np.int', (["metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeX']"], {}), "(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image'\n ]['SizeX'])\n", (15656, 15741), True, 'import numpy as np\n'), ((15833, 15924), 'numpy.int', 'np.int', (["metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeY']"], {}), "(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image'\n ]['SizeY'])\n", (15839, 15924), True, 'import numpy as np\n'), ((16017, 16108), 'numpy.int', 'np.int', (["metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeZ']"], {}), "(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image'\n ]['SizeZ'])\n", (16023, 16108), True, 'import numpy as np\n'), ((19987, 20078), 'numpy.int', 'np.int', (["metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeT']"], {}), "(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image'\n ]['SizeT'])\n", (19993, 20078), True, 'import numpy as np\n'), ((20289, 20380), 'numpy.int', 'np.int', (["metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeM']"], {}), "(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image'\n ]['SizeM'])\n", (20295, 20380), True, 'import numpy as np\n'), ((20591, 20682), 'numpy.int', 'np.int', (["metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeB']"], {}), "(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image'\n ]['SizeB'])\n", (20597, 20682), True, 'import numpy as np\n'), ((20893, 20984), 'numpy.int', 'np.int', (["metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeS']"], {}), "(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image'\n ]['SizeS'])\n", (20899, 20984), True, 'import numpy as np\n'), ((21195, 21286), 'numpy.int', 'np.int', (["metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeH']"], {}), "(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image'\n ]['SizeH'])\n", (21201, 21286), True, 'import numpy as np\n'), ((21497, 21588), 'numpy.int', 'np.int', (["metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeI']"], {}), "(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image'\n ]['SizeI'])\n", (21503, 21588), True, 'import numpy as np\n'), ((21799, 21890), 'numpy.int', 'np.int', (["metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeV']"], {}), "(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image'\n ]['SizeV'])\n", (21805, 21890), True, 'import numpy as np\n'), ((22497, 22528), 'numpy.round', 'np.round', (["metadata['XScale']", '(3)'], {}), "(metadata['XScale'], 3)\n", (22505, 22528), True, 'import numpy as np\n'), ((22558, 22589), 'numpy.round', 'np.round', (["metadata['YScale']", '(3)'], {}), "(metadata['YScale'], 3)\n", (22566, 22589), True, 'import numpy as np\n'), ((43220, 43248), 'pandas.DataFrame', 'pd.DataFrame', (['[d]'], {'index': '[0]'}), '([d], index=[0])\n', (43232, 43248), True, 'import pandas as pd\n'), ((43267, 43310), 'pandas.concat', 'pd.concat', (['[mdframe, df]'], {'ignore_index': '(True)'}), '([mdframe, df], ignore_index=True)\n', (43276, 43310), True, 'import pandas as pd\n'), ((46228, 46256), 'numpy.squeeze', 'np.squeeze', (['cziarray'], {'axis': '(0)'}), '(cziarray, axis=0)\n', (46238, 46256), True, 'import numpy as np\n'), ((47762, 47814), 'numpy.round', 'np.round', (["(metadata['XScale'] / metadata['YScale'])", '(3)'], {}), "(metadata['XScale'] / metadata['YScale'], 3)\n", (47770, 47814), True, 'import numpy as np\n'), ((47893, 47945), 'numpy.round', 'np.round', (["(metadata['ZScale'] / metadata['YScale'])", '(3)'], {}), "(metadata['ZScale'] / metadata['YScale'], 3)\n", (47901, 47945), True, 'import numpy as np\n'), ((50148, 50163), 'napari.gui_qt', 'napari.gui_qt', ([], {}), '()\n', (50161, 50163), False, 'import napari\n'), ((51175, 51190), 'napari.Viewer', 'napari.Viewer', ([], {}), '()\n', (51188, 51190), False, 'import napari\n'), ((57491, 57511), 'lxml.etree.fromstring', 'ET.fromstring', (['mdczi'], {}), '(mdczi)\n', (57504, 57511), True, 'from lxml import etree as ET\n'), ((58170, 58197), 'tifffile.TiffFile', 'tifffile.TiffFile', (['filename'], {}), '(filename)\n', (58187, 58197), False, 'import tifffile\n'), ((61036, 61052), 'numpy.float', 'np.float', (['scalex'], {}), '(scalex)\n', (61044, 61052), True, 'import numpy as np\n'), ((61079, 61095), 'numpy.float', 'np.float', (['scaley'], {}), '(scaley)\n', (61087, 61095), True, 'import numpy as np\n'), ((61122, 61138), 'numpy.float', 'np.float', (['scalez'], {}), '(scalez)\n', (61130, 61138), True, 'import numpy as np\n'), ((66154, 66192), 'numpy.squeeze', 'np.squeeze', (['imgarray'], {'axis': 'dims2remove'}), '(imgarray, axis=dims2remove)\n', (66164, 66192), True, 'import numpy as np\n'), ((68662, 68676), 'pathlib.Path', 'Path', (['filepath'], {}), '(filepath)\n', (68666, 68676), False, 'from pathlib import Path\n'), ((69856, 69882), 'os.path.exists', 'os.path.exists', (['bftoolsdir'], {}), '(bftoolsdir)\n', (69870, 69882), False, 'import os\n'), ((70053, 70073), 'os.chdir', 'os.chdir', (['bftoolsdir'], {}), '(bftoolsdir)\n', (70061, 70073), False, 'import os\n'), ((71432, 71452), 'os.system', 'os.system', (['cmdstring'], {}), '(cmdstring)\n', (71441, 71452), False, 'import os\n'), ((74638, 74655), 'PyQt5.QtWidgets.QHBoxLayout', 'QHBoxLayout', (['self'], {}), '(self)\n', (74649, 74655), False, 'from PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout, QFileSystemModel, QFileDialog, QTreeView, QDialogButtonBox, QWidget, QTableWidget, QTableWidgetItem, QAbstractItemView\n'), ((74679, 74693), 'PyQt5.QtWidgets.QTableWidget', 'QTableWidget', ([], {}), '()\n', (74691, 74693), False, 'from PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout, QFileSystemModel, QFileDialog, QTreeView, QDialogButtonBox, QWidget, QTableWidget, QTableWidgetItem, QAbstractItemView\n'), ((75561, 75568), 'PyQt5.QtGui.QFont', 'QFont', ([], {}), '()\n', (75566, 75568), False, 'from PyQt5.QtGui import QFont\n'), ((75707, 75746), 'PyQt5.QtWidgets.QTableWidgetItem', 'QtWidgets.QTableWidgetItem', (['"""Parameter"""'], {}), "('Parameter')\n", (75733, 75746), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((75900, 75935), 'PyQt5.QtWidgets.QTableWidgetItem', 'QtWidgets.QTableWidgetItem', (['"""Value"""'], {}), "('Value')\n", (75926, 75935), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((16506, 16597), 'numpy.int', 'np.int', (["metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeC']"], {}), "(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image'\n ]['SizeC'])\n", (16512, 16597), True, 'import numpy as np\n'), ((23220, 23251), 'numpy.round', 'np.round', (["metadata['ZScale']", '(3)'], {}), "(metadata['ZScale'], 3)\n", (23228, 23251), True, 'import numpy as np\n'), ((25940, 26066), 'numpy.float', 'np.float', (["metadatadict_czi['ImageDocument']['Metadata']['Information']['Instrument'][\n 'Objectives']['Objective']['LensNA']"], {}), "(metadatadict_czi['ImageDocument']['Metadata']['Information'][\n 'Instrument']['Objectives']['Objective']['LensNA'])\n", (25948, 26066), True, 'import numpy as np\n'), ((26512, 26644), 'numpy.float', 'np.float', (["metadatadict_czi['ImageDocument']['Metadata']['Information']['Instrument'][\n 'TubeLenses']['TubeLens']['Magnification']"], {}), "(metadatadict_czi['ImageDocument']['Metadata']['Information'][\n 'Instrument']['TubeLenses']['TubeLens']['Magnification'])\n", (26520, 26644), True, 'import numpy as np\n'), ((26904, 27044), 'numpy.float', 'np.float', (["metadatadict_czi['ImageDocument']['Metadata']['Information']['Instrument'][\n 'Objectives']['Objective']['NominalMagnification']"], {}), "(metadatadict_czi['ImageDocument']['Metadata']['Information'][\n 'Instrument']['Objectives']['Objective']['NominalMagnification'])\n", (26912, 27044), True, 'import numpy as np\n'), ((66272, 66337), 'aicsimageio.writers.ome_tiff_writer.OmeTiffWriter', 'ome_tiff_writer.OmeTiffWriter', (['savepath'], {'overwrite_file': 'overwrite'}), '(savepath, overwrite_file=overwrite)\n', (66301, 66337), False, 'from aicsimageio.writers import ome_tiff_writer\n'), ((75219, 75240), 'PyQt5.QtWidgets.QTableWidgetItem', 'QTableWidgetItem', (['key'], {}), '(key)\n', (75235, 75240), False, 'from PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout, QFileSystemModel, QFileDialog, QTreeView, QDialogButtonBox, QWidget, QTableWidget, QTableWidgetItem, QAbstractItemView\n'), ((75775, 75799), 'PyQt5.QtGui.QColor', 'QtGui.QColor', (['(25)', '(25)', '(25)'], {}), '(25, 25, 25)\n', (75787, 75799), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((75964, 75988), 'PyQt5.QtGui.QColor', 'QtGui.QColor', (['(25)', '(25)', '(25)'], {}), '(25, 25, 25)\n', (75976, 75988), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((39221, 39257), 'collections.Counter', 'Counter', (["metadata['Well_ArrayNames']"], {}), "(metadata['Well_ArrayNames'])\n", (39228, 39257), False, 'from collections import Counter\n'), ((64565, 64606), 'numpy.squeeze', 'np.squeeze', (['imgarray'], {'axis': "dims_dict['S']"}), "(imgarray, axis=dims_dict['S'])\n", (64575, 64606), True, 'import numpy as np\n'), ((28512, 28641), 'numpy.float', 'np.float', (["metadatadict_czi['ImageDocument']['Metadata']['Information']['Instrument'][\n 'Objectives']['Objective'][o]['LensNA']"], {}), "(metadatadict_czi['ImageDocument']['Metadata']['Information'][\n 'Instrument']['Objectives']['Objective'][o]['LensNA'])\n", (28520, 28641), True, 'import numpy as np\n'), ((29215, 29350), 'numpy.float', 'np.float', (["metadatadict_czi['ImageDocument']['Metadata']['Information']['Instrument'][\n 'TubeLenses']['TubeLens'][o]['Magnification']"], {}), "(metadatadict_czi['ImageDocument']['Metadata']['Information'][\n 'Instrument']['TubeLenses']['TubeLens'][o]['Magnification'])\n", (29223, 29350), True, 'import numpy as np\n'), ((29656, 29799), 'numpy.float', 'np.float', (["metadatadict_czi['ImageDocument']['Metadata']['Information']['Instrument'][\n 'Objectives']['Objective'][o]['NominalMagnification']"], {}), "(metadatadict_czi['ImageDocument']['Metadata']['Information'][\n 'Instrument']['Objectives']['Objective'][o]['NominalMagnification'])\n", (29664, 29799), True, 'import numpy as np\n'), ((36658, 36694), 'collections.Counter', 'Counter', (["metadata['Well_ArrayNames']"], {}), "(metadata['Well_ArrayNames'])\n", (36665, 36694), False, 'from collections import Counter\n'), ((66509, 66535), 'os.path.basename', 'os.path.basename', (['savepath'], {}), '(savepath)\n', (66525, 66535), False, 'import os\n'), ((36013, 36054), 'numpy.int', 'np.int', (["allscenes['Shape']['ColumnIndex']"], {}), "(allscenes['Shape']['ColumnIndex'])\n", (36019, 36054), True, 'import numpy as np\n'), ((36289, 36327), 'numpy.int', 'np.int', (["allscenes['Shape']['RowIndex']"], {}), "(allscenes['Shape']['RowIndex'])\n", (36295, 36327), True, 'import numpy as np\n'), ((37138, 37151), 'numpy.double', 'np.double', (['sx'], {}), '(sx)\n', (37147, 37151), True, 'import numpy as np\n'), ((37210, 37223), 'numpy.double', 'np.double', (['sy'], {}), '(sy)\n', (37219, 37223), True, 'import numpy as np\n'), ((38609, 38645), 'numpy.int', 'np.int', (["well['Shape']['ColumnIndex']"], {}), "(well['Shape']['ColumnIndex'])\n", (38615, 38645), True, 'import numpy as np\n'), ((38883, 38916), 'numpy.int', 'np.int', (["well['Shape']['RowIndex']"], {}), "(well['Shape']['RowIndex'])\n", (38889, 38916), True, 'import numpy as np\n'), ((62521, 62539), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (62537, 62539), False, 'import sys\n'), ((36854, 36872), 'collections.Counter', 'Counter', (["{'A1': 1}"], {}), "({'A1': 1})\n", (36861, 36872), False, 'from collections import Counter\n'), ((39619, 39632), 'numpy.double', 'np.double', (['sx'], {}), '(sx)\n', (39628, 39632), True, 'import numpy as np\n'), ((39695, 39708), 'numpy.double', 'np.double', (['sy'], {}), '(sy)\n', (39704, 39708), True, 'import numpy as np\n')]
from ipdb import set_trace as st import os import time import random import numpy as np from loguru import logger import torch def set_seed(seed): random.seed(seed) np.random.seed(seed) os.environ["PYTHONHASHSEED"] = str(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) # type: ignore torch.backends.cudnn.deterministic = True # type: ignore torch.backends.cudnn.benchmark = True # type: ignore def get_save_dir_exp(config): _dir = os.path.dirname(os.path.abspath(__file__)) exp_name = _dir.split('/')[-1] dir_save_exp = f'{config["path"]["dir_save"]}{exp_name}' dir_save_ignore_exp = f'{config["path"]["dir_save_ignore"]}{exp_name}' return dir_save_exp, dir_save_ignore_exp, exp_name def mixup_data(x, y, alpha=1.0, use_cuda=True): '''Returns mixed inputs, pairs of targets, and lambda''' if alpha > 0: lam = np.random.beta(alpha, alpha) else: lam = 1 batch_size = x.size()[0] if use_cuda: index = torch.randperm(batch_size).cuda() else: index = torch.randperm(batch_size) mixed_x = lam * x + (1 - lam) * x[index, :] y_a, y_b = y, y[index] return mixed_x, y_a, y_b, lam def get_debug_idx(trn_tp, trn_idxs, val_idxs, config): n_classes = config['model']['params']['n_classes'] trn_tp_trn = trn_tp.iloc[trn_idxs].copy() trn_tp_val = trn_tp.iloc[val_idxs].copy() trn_tp_trn['idx_'] = trn_idxs trn_tp_val['idx_'] = val_idxs trn_idxs_debug = [] val_idxs_debug = [] for idx in range(n_classes): bools = trn_tp_trn.species_id == idx trn_idxs_debug.append(trn_tp_trn[bools]['idx_'].values[0]) bools = trn_tp_val.species_id == idx val_idxs_debug.append(trn_tp_val[bools]['idx_'].values[0]) return trn_idxs_debug, val_idxs_debug def set_debug_config(config): if config['globals']['debug']: logger.info(':: debug mode ::') config['globals']['num_epochs'] = 2 config['split']['n_fold'] = 2 config['loader']['train']['batch_size'] = 1 config['loader']['valid']['batch_size'] = 1 return config else: return config def sec2time(sec): hour = int(sec//3600) minute = int((sec - 3600*hour)//60) second = int(sec - 3600*hour - 60*minute) hour = str(hour).zfill(2) minute = str(minute).zfill(2) second = str(second).zfill(2) str_time = f'{hour}:{minute}:{second}' return str_time def LWLRAP(preds, labels): ''' https://github.com/yuki-a4/rfcx-species-audio-detection/blob/main/yuki/notebook/ex_059_resnest_changeLoss_lr_0.15_aug0.3_seed239.ipynb ''' # st() # device device = torch.device("cuda" if torch.cuda.is_available() else "cpu") preds, labels = preds.to(device), labels.to(device) # Ranks of the predictions ranked_classes = torch.argsort(preds, dim=-1, descending=True) # i, j corresponds to rank of prediction in row i class_ranks = torch.zeros_like(ranked_classes) for i in range(ranked_classes.size(0)): for j in range(ranked_classes.size(1)): class_ranks[i, ranked_classes[i][j]] = j + 1 # Mask out to only use the ranks of relevant GT labels ground_truth_ranks = class_ranks * labels + (1e6) * (1 - labels) # All the GT ranks are in front now sorted_ground_truth_ranks, _ = torch.sort(ground_truth_ranks, dim=-1, descending=False) # Number of GT labels per instance # num_labels = labels.sum(-1) pos_matrix = torch.tensor( np.array([i+1 for i in range(labels.size(-1))])).unsqueeze(0) pos_matrix = pos_matrix.to(device) sorted_ground_truth_ranks = sorted_ground_truth_ranks.to(device) score_matrix = pos_matrix / sorted_ground_truth_ranks score_mask_matrix, _ = torch.sort(labels, dim=-1, descending=True) scores = score_matrix * score_mask_matrix score = scores.sum() / labels.sum() return score.item()
[ "torch.sort", "torch.manual_seed", "numpy.random.beta", "torch.randperm", "loguru.logger.info", "random.seed", "torch.zeros_like", "torch.argsort", "torch.cuda.is_available", "numpy.random.seed", "os.path.abspath", "torch.cuda.manual_seed" ]
[((153, 170), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (164, 170), False, 'import random\n'), ((175, 195), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (189, 195), True, 'import numpy as np\n'), ((245, 268), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (262, 268), False, 'import torch\n'), ((273, 301), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['seed'], {}), '(seed)\n', (295, 301), False, 'import torch\n'), ((2863, 2908), 'torch.argsort', 'torch.argsort', (['preds'], {'dim': '(-1)', 'descending': '(True)'}), '(preds, dim=-1, descending=True)\n', (2876, 2908), False, 'import torch\n'), ((2981, 3013), 'torch.zeros_like', 'torch.zeros_like', (['ranked_classes'], {}), '(ranked_classes)\n', (2997, 3013), False, 'import torch\n'), ((3366, 3422), 'torch.sort', 'torch.sort', (['ground_truth_ranks'], {'dim': '(-1)', 'descending': '(False)'}), '(ground_truth_ranks, dim=-1, descending=False)\n', (3376, 3422), False, 'import torch\n'), ((3840, 3883), 'torch.sort', 'torch.sort', (['labels'], {'dim': '(-1)', 'descending': '(True)'}), '(labels, dim=-1, descending=True)\n', (3850, 3883), False, 'import torch\n'), ((497, 522), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (512, 522), False, 'import os\n'), ((893, 921), 'numpy.random.beta', 'np.random.beta', (['alpha', 'alpha'], {}), '(alpha, alpha)\n', (907, 921), True, 'import numpy as np\n'), ((1070, 1096), 'torch.randperm', 'torch.randperm', (['batch_size'], {}), '(batch_size)\n', (1084, 1096), False, 'import torch\n'), ((1904, 1935), 'loguru.logger.info', 'logger.info', (['""":: debug mode ::"""'], {}), "(':: debug mode ::')\n", (1915, 1935), False, 'from loguru import logger\n'), ((2716, 2741), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2739, 2741), False, 'import torch\n'), ((1010, 1036), 'torch.randperm', 'torch.randperm', (['batch_size'], {}), '(batch_size)\n', (1024, 1036), False, 'import torch\n')]
#!/usr/bin/env python from sense2vec import Sense2Vec from sense2vec.util import split_key from pathlib import Path import plac from wasabi import msg import numpy def _get_shape(file_): """Return a tuple with (number of entries, vector dimensions). Handle both word2vec/FastText format, which has a header with this, or GloVe's format, which doesn't.""" first_line = next(file_).split() if len(first_line) == 2: return tuple(int(size) for size in first_line), file_ count = 1 for line in file_: count += 1 file_.seek(0) shape = (count, len(first_line) - 1) return shape, file_ @plac.annotations( in_file=("Vectors file (text-based)", "positional", None, str), vocab_file=("Vocabulary file", "positional", None, str), out_dir=("Path to output directory", "positional", None, str), ) def main(in_file, vocab_file, out_dir): """ Step 5: Export a sense2vec component Expects a vectors.txt and a vocab file trained with GloVe and exports a component that can be loaded with Sense2vec.from_disk. """ input_path = Path(in_file) vocab_path = Path(vocab_file) output_path = Path(out_dir) if not input_path.exists(): msg.fail("Can't find input file", in_file, exits=1) if input_path.suffix == ".bin": msg.fail("Need text-based vectors file, not binary", in_file, exits=1) if not vocab_path.exists(): msg.fail("Can't find vocab file", vocab_file, exits=1) if not output_path.exists(): output_path.mkdir(parents=True) msg.good(f"Created output directory {out_dir}") with input_path.open("r", encoding="utf8") as f: (n_vectors, vector_size), f = _get_shape(f) vectors_data = f.readlines() with vocab_path.open("r", encoding="utf8") as f: vocab_data = f.readlines() data = [] all_senses = set() for item in vectors_data: item = item.rstrip().rsplit(" ", vector_size) key = item[0] try: _, sense = split_key(key) except ValueError: continue vec = item[1:] if len(vec) != vector_size: msg.fail(f"Wrong vector size: {len(vec)} (expected {vector_size})", exits=1) all_senses.add(sense) data.append((key, numpy.asarray(vec, dtype=numpy.float32))) s2v = Sense2Vec(shape=(len(data), vector_size), senses=all_senses) for key, vector in data: s2v.add(key, vector) for item in vocab_data: item = item.rstrip() if item.endswith(" word"): # for fastText vocabs item = item[:-5] try: key, freq = item.rsplit(" ", 1) except ValueError: continue s2v.set_freq(key, int(freq)) msg.good("Created the sense2vec model") msg.info(f"{len(data)} vectors, {len(all_senses)} total senses") s2v.to_disk(output_path) msg.good("Saved model to directory", out_dir) if __name__ == "__main__": plac.call(main)
[ "plac.annotations", "pathlib.Path", "wasabi.msg.good", "numpy.asarray", "plac.call", "sense2vec.util.split_key", "wasabi.msg.fail" ]
[((639, 848), 'plac.annotations', 'plac.annotations', ([], {'in_file': "('Vectors file (text-based)', 'positional', None, str)", 'vocab_file': "('Vocabulary file', 'positional', None, str)", 'out_dir': "('Path to output directory', 'positional', None, str)"}), "(in_file=('Vectors file (text-based)', 'positional', None,\n str), vocab_file=('Vocabulary file', 'positional', None, str), out_dir=\n ('Path to output directory', 'positional', None, str))\n", (655, 848), False, 'import plac\n'), ((1105, 1118), 'pathlib.Path', 'Path', (['in_file'], {}), '(in_file)\n', (1109, 1118), False, 'from pathlib import Path\n'), ((1136, 1152), 'pathlib.Path', 'Path', (['vocab_file'], {}), '(vocab_file)\n', (1140, 1152), False, 'from pathlib import Path\n'), ((1171, 1184), 'pathlib.Path', 'Path', (['out_dir'], {}), '(out_dir)\n', (1175, 1184), False, 'from pathlib import Path\n'), ((2753, 2792), 'wasabi.msg.good', 'msg.good', (['"""Created the sense2vec model"""'], {}), "('Created the sense2vec model')\n", (2761, 2792), False, 'from wasabi import msg\n'), ((2895, 2940), 'wasabi.msg.good', 'msg.good', (['"""Saved model to directory"""', 'out_dir'], {}), "('Saved model to directory', out_dir)\n", (2903, 2940), False, 'from wasabi import msg\n'), ((2974, 2989), 'plac.call', 'plac.call', (['main'], {}), '(main)\n', (2983, 2989), False, 'import plac\n'), ((1225, 1276), 'wasabi.msg.fail', 'msg.fail', (['"""Can\'t find input file"""', 'in_file'], {'exits': '(1)'}), '("Can\'t find input file", in_file, exits=1)\n', (1233, 1276), False, 'from wasabi import msg\n'), ((1321, 1391), 'wasabi.msg.fail', 'msg.fail', (['"""Need text-based vectors file, not binary"""', 'in_file'], {'exits': '(1)'}), "('Need text-based vectors file, not binary', in_file, exits=1)\n", (1329, 1391), False, 'from wasabi import msg\n'), ((1432, 1486), 'wasabi.msg.fail', 'msg.fail', (['"""Can\'t find vocab file"""', 'vocab_file'], {'exits': '(1)'}), '("Can\'t find vocab file", vocab_file, exits=1)\n', (1440, 1486), False, 'from wasabi import msg\n'), ((1568, 1615), 'wasabi.msg.good', 'msg.good', (['f"""Created output directory {out_dir}"""'], {}), "(f'Created output directory {out_dir}')\n", (1576, 1615), False, 'from wasabi import msg\n'), ((2025, 2039), 'sense2vec.util.split_key', 'split_key', (['key'], {}), '(key)\n', (2034, 2039), False, 'from sense2vec.util import split_key\n'), ((2292, 2331), 'numpy.asarray', 'numpy.asarray', (['vec'], {'dtype': 'numpy.float32'}), '(vec, dtype=numpy.float32)\n', (2305, 2331), False, 'import numpy\n')]
""" <NAME> - November 2020 This program creates stellar mass-selected group catalogs for ECO/RESOLVE-G3 using the new algorithm, described in the readme markdown. The outline of this code is: (1) Read in observational data from RESOLVE-B and ECO (the latter includes RESOLVE-A). (2) Prepare arrays of input parameters and for storing results. (3) Perform FoF only for giants in ECO, using an adaptive linking strategy. (a) Get the adaptive links for every ECO galaxy. (b) Fit those adaptive links for use in RESOLVE-B. (c) Perform giant-only FoF for ECO (d) Perform giant-only FoF for RESOLVE-B, by interpolating the fit to obtain separations for RESOLVE-B. (4) From giant-only groups, fit model for individual giant projected radii and peculiar velocites, to use for association. (5) Associate dwarf galaxies to giant-only FoF groups for ECO and RESOLVE-B (note different selection floors for dwarfs). (6) Based on giant+dwarf groups, calibrate boundaries (as function of giant+dwarf integrated stellar mass) for iterative combination (7) Iterative combination on remaining ungrouped dwarf galaxies (8) halo mass assignment (9) Finalize arrays + output """ import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import interp1d from scipy.optimize import curve_fit from center_binned_stats import center_binned_stats import foftools as fof import iterativecombination as ic import virtools as vz from smoothedbootstrap import smoothedbootstrap as sbs import sys from scipy.interpolate import UnivariateSpline import virtools as vz from lss_dens import lss_dens_by_galaxy #def giantmodel(x, a, b, c, d): # return a*np.log(np.abs(b)*x+c)+d def giantmodel(x, a, b): return np.abs(a)*np.log(np.abs(b)*x+1) def exp(x, a, b, c): return np.abs(a)*np.exp(1*np.abs(b)*(x) + c) #return a*np.exp(b*(x**2) + c*(x) + d)+np.abs(e) def sepmodel(x, a, b, c, d, e): #return np.abs(a)*np.exp(-1*np.abs(b)*x + c)+d #return a*(x**3)+b*(x**2)+c*x return a*(x**4)+b*(x**3)+c*(x**2)+(d*x)+e def sigmarange(x): q84, q16 = np.percentile(x, [84 ,16]) return (q84-q16)/2. if __name__=='__main__': #################################### # Step 1: Read in obs data #################################### ecodata = pd.read_csv("ECOdata_022521.csv") resolvedata = pd.read_csv("RESOLVEdata_022521.csv") resolvebdata = resolvedata[resolvedata.f_b==1] #################################### # Step 2: Prepare arrays #################################### ecosz = len(ecodata) econame = np.array(ecodata.name) ecoresname = np.array(ecodata.resname) ecoradeg = np.array(ecodata.radeg) ecodedeg = np.array(ecodata.dedeg) ecocz = np.array(ecodata.cz) ecologmstar = np.array(ecodata.logmstar) ecologmgas = np.array(ecodata.logmgas) ecourcolor = np.array(ecodata.modelu_rcorr) ecog3grp = np.full(ecosz, -99.) # id number of g3 group ecog3grpn = np.full(ecosz, -99.) # multiplicity of g3 group ecog3grpradeg = np.full(ecosz,-99.) # ra of group center ecog3grpdedeg = np.full(ecosz,-99.) # dec of group center ecog3grpcz = np.full(ecosz,-99.) # cz of group center ecog3logmh = np.full(ecosz,-99.) # abundance-matched halo mass ecog3intmstar = np.full(ecosz,-99.) # group-integrated stellar mass resbana_g3grp = np.full(ecosz,-99.) # for RESOLVE-B analogue dataset resbsz = int(len(resolvebdata)) resbname = np.array(resolvebdata.name) resbradeg = np.array(resolvebdata.radeg) resbdedeg = np.array(resolvebdata.dedeg) resbcz = np.array(resolvebdata.cz) resblogmstar = np.array(resolvebdata.logmstar) resblogmgas = np.array(resolvebdata.logmgas) resburcolor = np.array(resolvebdata.modelu_rcorr) resbg3grp = np.full(resbsz, -99.) resbg3grpn = np.full(resbsz, -99.) resbg3grpradeg = np.full(resbsz, -99.) resbg3grpdedeg = np.full(resbsz, -99.) resbg3grpcz = np.full(resbsz, -99.) resbg3logmh = np.full(resbsz, -99.) resbg3intmstar = np.full(resbsz, -99.) #################################### # Step 3: Giant-Only FOF #################################### ecogiantsel = (ecologmstar>=9.5) & (ecocz>2530.) & (ecocz<8000.) # (a) compute sep values for eco giants ecovolume = 192351.36 # Mpc^3 with h=1 ** meansep0 = (ecovolume/len(ecologmstar[ecogiantsel]))**(1/3.) # (b) make an interpolation function use this for RESOLVE-B # (c) perform giant-only FoF on ECO blos = 1.1 bperp = 0.07 # from Duarte & Mamon 2014 ecogiantfofid = fof.fast_fof(ecoradeg[ecogiantsel], ecodedeg[ecogiantsel], ecocz[ecogiantsel], bperp, blos, meansep0) # meansep0 if fixed LL ecog3grp[ecogiantsel] = ecogiantfofid resbana_g3grp[ecogiantsel] = ecogiantfofid # RESOLVE-B analogue dataset # (d) perform giant-only FoF on RESOLVE-B resbgiantsel = (resblogmstar>=9.5) & (resbcz>4250) & (resbcz<7300) resbgiantfofid = fof.fast_fof(resbradeg[resbgiantsel], resbdedeg[resbgiantsel], resbcz[resbgiantsel], bperp, blos, meansep0) resbg3grp[resbgiantsel] = resbgiantfofid # (e) check the FOF results plt.figure() binv = np.arange(0.5,3000.5,3) plt.hist(fof.multiplicity_function(ecog3grp[ecog3grp!=-99.], return_by_galaxy=False), bins=binv, histtype='step', linewidth=3, label='ECO Giant-Only FoF Groups') plt.hist(fof.multiplicity_function(resbg3grp[resbg3grp!=-99.], return_by_galaxy=False), bins=binv, histtype='step', linewidth=1.5, hatch='\\', label='RESOLVE-B Giant-Only FoF Groups') plt.xlabel("Number of Giant Galaxies per Group") plt.ylabel("Number of Giant-Only FoF Groups") plt.yscale('log') plt.legend(loc='best') plt.xlim(0,80) plt.show() ########################################## # Step 4: Compute Association Boundaries ########################################## ecogiantgrpra, ecogiantgrpdec, ecogiantgrpcz = fof.group_skycoords(ecoradeg[ecogiantsel], ecodedeg[ecogiantsel], ecocz[ecogiantsel], ecogiantfofid) relvel = np.abs(ecogiantgrpcz - ecocz[ecogiantsel]) relprojdist = (ecogiantgrpcz + ecocz[ecogiantsel])/100. * ic.angular_separation(ecogiantgrpra, ecogiantgrpdec, ecoradeg[ecogiantsel], ecodedeg[ecogiantsel])/2.0 ecogiantgrpn = fof.multiplicity_function(ecogiantfofid, return_by_galaxy=True) uniqecogiantgrpn, uniqindex = np.unique(ecogiantgrpn, return_index=True) keepcalsel = np.where(uniqecogiantgrpn>1) median_relprojdist = np.array([np.median(relprojdist[np.where(ecogiantgrpn==sz)]) for sz in uniqecogiantgrpn[keepcalsel]]) median_relvel = np.array([np.median(relvel[np.where(ecogiantgrpn==sz)]) for sz in uniqecogiantgrpn[keepcalsel]]) rproj_median_error = np.std(np.array([sbs(relprojdist[np.where(ecogiantgrpn==sz)], 10000, np.median, kwargs=dict({'axis':1 })) for sz in uniqecogiantgrpn[keepcalsel]]), axis=1) dvproj_median_error = np.std(np.array([sbs(relvel[np.where(ecogiantgrpn==sz)], 10000, np.median, kwargs=dict({'axis':1})) for sz in uniqecogiantgrpn[keepcalsel]]), axis=1) #rprojslope, rprojint = np.polyfit(uniqecogiantgrpn[keepcalsel], median_relprojdist, deg=1, w=1/rproj_median_error) #dvprojslope, dvprojint = np.polyfit(uniqecogiantgrpn[keepcalsel], median_relvel, deg=1, w=1/dvproj_median_error) poptrproj, jk = curve_fit(giantmodel, uniqecogiantgrpn[keepcalsel], median_relprojdist, sigma=rproj_median_error)#, p0=[0.1, -2, 3, -0.1]) poptdvproj,jk = curve_fit(giantmodel, uniqecogiantgrpn[keepcalsel], median_relvel, sigma=dvproj_median_error)#, p0=[160,6.5,45,-600]) rproj_boundary = lambda N: 3*giantmodel(N, *poptrproj) #3*(rprojslope*N+rprojint) vproj_boundary = lambda N: 4.5*giantmodel(N, *poptdvproj) #4.5*(dvprojslope*N+dvprojint) assert ((rproj_boundary(1)>0) and (vproj_boundary(1)>0)), "Cannot extrapolate Rproj_fit or dv_proj_fit to N=1" # get virial radii from abundance matching to giant-only groups gihaloid, gilogmh, gir280, gihalovdisp = ic.HAMwrapper(ecoradeg[ecogiantsel], ecodedeg[ecogiantsel], ecocz[ecogiantsel], ecologmstar[ecogiantsel], ecog3grp[ecogiantsel],\ ecovolume, inputfilename=None, outputfilename=None) gilogmh = np.log10(10**gilogmh)# no longer need 7/29: /fof.getmhoffset(280,337,1,1,6)) gihalorvir = (3*(10**gilogmh) / (4*np.pi*337*0.3*2.77e11) )**(1/3.) gihalon = fof.multiplicity_function(np.sort(ecog3grp[ecogiantsel]), return_by_galaxy=False) plt.figure() plt.plot(gihalon, gihalorvir, 'k.') plt.show() plt.figure() sel = (ecogiantgrpn>1) plt.scatter(gihalon, gihalovdisp, marker='D', color='purple', label=r'ECO HAM Velocity Dispersion') plt.plot(ecogiantgrpn[sel], relvel[sel], 'r.', alpha=0.2, label='ECO Giant Galaxies') plt.errorbar(uniqecogiantgrpn[keepcalsel], median_relvel, fmt='k^', label=r'$\Delta v_{\rm proj}$ (Median of $\Delta v_{\rm proj,\, gal}$)',yerr=dvproj_median_error) tx = np.linspace(1,max(ecogiantgrpn),1000) plt.plot(tx, giantmodel(tx, *poptdvproj), label=r'$1\Delta v_{\rm proj}^{\rm fit}$') plt.plot(tx, 4.5*giantmodel(tx, *poptdvproj), 'g', label=r'$4.5\Delta v_{\rm proj}^{\rm fit}$', linestyle='-.') plt.xlabel("Number of Giant Members") plt.ylabel("Relative Velocity to Group Center [km/s]") plt.legend(loc='best') plt.show() plt.clf() plt.scatter(gihalon, gihalorvir, marker='D', color='purple', label=r'ECO Group Virial Radii') plt.plot(ecogiantgrpn[sel], relprojdist[sel], 'r.', alpha=0.2, label='ECO Giant Galaxies') plt.errorbar(uniqecogiantgrpn[keepcalsel], median_relprojdist, fmt='k^', label=r'$R_{\rm proj}$ (Median of $R_{\rm proj,\, gal}$)',yerr=rproj_median_error) plt.plot(tx, giantmodel(tx, *poptrproj), label=r'$1R_{\rm proj}^{\rm fit}$') plt.plot(tx, 3*giantmodel(tx, *poptrproj), 'g', label=r'$3R_{\rm proj}^{\rm fit}$', linestyle='-.') plt.xlabel("Number of Giant Members in Galaxy's Group") plt.ylabel("Projected Distance from Giant to Group Center [Mpc/h]") plt.legend(loc='best') #plt.xlim(0,20) #plt.ylim(0,2.5) #plt.xticks(np.arange(0,22,2)) plt.show() #################################### # Step 5: Association of Dwarfs #################################### ecodwarfsel = (ecologmstar<9.5) & (ecologmstar>=8.9) & (ecocz>2530) & (ecocz<8000) resbdwarfsel = (resblogmstar<9.5) & (resblogmstar>=8.7) & (resbcz>4250) & (resbcz<7300) resbana_dwarfsel = (ecologmstar<9.5) & (ecologmstar>=8.7) & (ecocz>2530) & (ecocz<8000) resbgiantgrpra, resbgiantgrpdec, resbgiantgrpcz = fof.group_skycoords(resbradeg[resbgiantsel], resbdedeg[resbgiantsel], resbcz[resbgiantsel], resbgiantfofid) resbgiantgrpn = fof.multiplicity_function(resbgiantfofid, return_by_galaxy=True) ecodwarfassocid, junk = fof.fast_faint_assoc(ecoradeg[ecodwarfsel],ecodedeg[ecodwarfsel],ecocz[ecodwarfsel],ecogiantgrpra,ecogiantgrpdec,ecogiantgrpcz,ecogiantfofid,\ rproj_boundary(ecogiantgrpn),vproj_boundary(ecogiantgrpn)) resbdwarfassocid, junk = fof.fast_faint_assoc(resbradeg[resbdwarfsel],resbdedeg[resbdwarfsel],resbcz[resbdwarfsel],resbgiantgrpra,resbgiantgrpdec,resbgiantgrpcz,resbgiantfofid,\ rproj_boundary(resbgiantgrpn),vproj_boundary(resbgiantgrpn)) resbana_dwarfassocid, jk = fof.fast_faint_assoc(ecoradeg[resbana_dwarfsel], ecodedeg[resbana_dwarfsel], ecocz[resbana_dwarfsel], ecogiantgrpra, ecogiantgrpdec, ecogiantgrpcz, ecogiantfofid,\ rproj_boundary(ecogiantgrpn), vproj_boundary(ecogiantgrpn)) ecog3grp[ecodwarfsel] = ecodwarfassocid resbg3grp[resbdwarfsel] = resbdwarfassocid resbana_g3grp[resbana_dwarfsel] = resbana_dwarfassocid ############################################### # Step 6: Calibration for Iter. Combination ############################################### ecogdgrpn = fof.multiplicity_function(ecog3grp, return_by_galaxy=True) #ecogdsel = np.logical_not((ecogdgrpn==1) & (ecologmstar<9.5) & (ecog3grp>0)) # select galaxies that AREN'T ungrouped dwarfs ecogdsel = np.logical_and(np.logical_not(np.logical_or(ecog3grp==-99., ((ecogdgrpn==1) & (ecologmstar<9.5) & (ecologmstar>=8.9)))), (ecogdgrpn>1)) ecogdgrpra, ecogdgrpdec, ecogdgrpcz = fof.group_skycoords(ecoradeg[ecogdsel], ecodedeg[ecogdsel], ecocz[ecogdsel], ecog3grp[ecogdsel]) ecogdrelvel = np.abs(ecogdgrpcz - ecocz[ecogdsel]) ecogdrelprojdist = (ecogdgrpcz + ecocz[ecogdsel])/100. * ic.angular_separation(ecogdgrpra, ecogdgrpdec, ecoradeg[ecogdsel], ecodedeg[ecogdsel])/2.0 ecogdn = ecogdgrpn[ecogdsel] ecogdtotalmass = ic.get_int_mass(ecologmstar[ecogdsel], ecog3grp[ecogdsel]) massbins=np.arange(9.75,14,0.15) binsel = np.where(np.logical_and(ecogdn>1, ecogdtotalmass<14)) gdmedianrproj, massbincenters, massbinedges, jk = center_binned_stats(ecogdtotalmass[binsel], ecogdrelprojdist[binsel], np.median, bins=massbins) #gdmedianrproj_err = np.std(np.array([sbs(ecogdrelprojdist[binsel][np.where(np.logical_and(ecogdtotalmass[binsel]>massbinedges[i-1], ecogdtotalmass[binsel]<=massbinedges[i]))],\ # 10000, np.median) for i in range(1,len(massbinedges))]), axis=1) gdmedianrelvel, jk, jk, jk = center_binned_stats(ecogdtotalmass[binsel], ecogdrelvel[binsel], np.median, bins=massbins) #gdmedianrelvel_err = np.std(np.array([sbs(ecogdrelvel[binsel][np.where(np.logical_and(ecogdtotalmass[binsel]>massbinedges[i-1], ecogdtotalmass[binsel]<=massbinedges[i]))],\ # 10000, np.median) for i in range(1,len(massbinedges))]), axis=1) gdmedianrproj_err, jk, jk, jk = center_binned_stats(ecogdtotalmass[binsel], ecogdrelprojdist[binsel], sigmarange, bins=massbins) gdmedianrelvel, jk, jk, jk = center_binned_stats(ecogdtotalmass[binsel], ecogdrelvel[binsel], np.median, bins=massbins) gdmedianrelvel_err, jk, jk, jk = center_binned_stats(ecogdtotalmass[binsel], ecogdrelvel[binsel], sigmarange, bins=massbins) nansel = np.isnan(gdmedianrproj) if 0: #guess=None #guess=[-1,0.01,0.05,-6,0.01] guess=[-1,0.01,0.05] else: guess= [-1,0.01,0.05]#None#[1e-5, 0.4, 0.2, 1] poptr, pcovr = curve_fit(exp, massbincenters[~nansel], gdmedianrproj[~nansel], p0=guess, maxfev=5000, sigma=gdmedianrproj_err[~nansel])#30**massbincenters[~nansel]) poptv, pcovv = curve_fit(exp, massbincenters[~nansel], gdmedianrelvel[~nansel], p0=[3e-5,4e-1,5e-03], maxfev=5000)#, sigma=gdmedianrelvel_err[~nansel]) print(poptr, poptv) tx = np.linspace(7,15,100) plt.figure() plt.axhline(0) plt.plot(ecogdtotalmass[binsel], ecogdrelprojdist[binsel], 'k.', alpha=0.2, label='ECO Galaxies in N>1 Giant+Dwarf Groups') #plt.plot(massbincenters, gdmedianrproj, 'r^', label='Median') plt.errorbar(massbincenters, gdmedianrproj, yerr=gdmedianrproj_err, fmt='r^', label='Median') plt.plot(tx, exp(tx,*poptr), label='Fit to Medians') plt.plot(tx, 3*exp(tx,*poptr), label='3 times Fit to Medians') plt.xlabel(r"Integrated Stellar Mass of Giant + Dwarf Members") plt.ylabel("Projected Distance from Galaxy to Group Center [Mpc/h]") plt.legend(loc='best') plt.xlim(9.5,13.2) plt.ylim(0,3) #plt.yscale('log') plt.show() plt.figure() plt.plot(ecogdtotalmass[binsel], ecogdrelvel[binsel], 'k.', alpha=0.2, label='Mock Galaxies in N=2 Giant+Dwarf Groups') #plt.plot(massbincenters, gdmedianrelvel, 'r^',label='Medians') plt.errorbar(massbincenters, gdmedianrelvel, yerr=gdmedianrelvel_err, fmt='r^', label='Median') plt.plot(tx, exp(tx, *poptv), label='Fit to Medians') plt.plot(tx, 4.5*exp(tx, *poptv), label='4.5 times Fit to Medians') plt.ylabel("Relative Velocity between Galaxy and Group Center") plt.xlabel(r"Integrated Stellar Mass of Giant + Dwarf Members") plt.xlim(9.5,13) plt.ylim(0,2000) plt.legend(loc='best') plt.show() rproj_for_iteration = lambda M: 3*exp(M, *poptr) vproj_for_iteration = lambda M: 4.5*exp(M, *poptv) # --------------- now need to do this calibration for the RESOLVE-B analogue dataset, down to 8.7 stellar mass) -------------$ resbana_gdgrpn = fof.multiplicity_function(resbana_g3grp, return_by_galaxy=True) #resbana_gdsel = np.logical_not((resbana_gdgrpn==1) & (ecologmstar>-19.4) & (resbana_g3grp!=-99.) & (resbana_g3grp>0)) # select galaxies that AREN'T ungrouped dwarfs resbana_gdsel = np.logical_and(np.logical_not(np.logical_or(resbana_g3grp==-99., ((resbana_gdgrpn==1) & (ecologmstar<9.5) & (ecologmstar>=8.7)))), (resbana_gdgrpn>2)) resbana_gdgrpra, resbana_gdgrpdec, resbana_gdgrpcz = fof.group_skycoords(ecoradeg[resbana_gdsel], ecodedeg[resbana_gdsel], ecocz[resbana_gdsel], resbana_g3grp[resbana_gdsel]) resbana_gdrelvel = np.abs(resbana_gdgrpcz - ecocz[resbana_gdsel]) resbana_gdrelprojdist = (resbana_gdgrpcz + ecocz[resbana_gdsel])/100. * ic.angular_separation(resbana_gdgrpra, resbana_gdgrpdec, ecoradeg[resbana_gdsel], ecodedeg[resbana_gdsel])/2.0 resbana_gdn = resbana_gdgrpn[resbana_gdsel] resbana_gdtotalmass = ic.get_int_mass(ecologmstar[resbana_gdsel], resbana_g3grp[resbana_gdsel]) massbins2=np.arange(9.75,14,0.15) binsel2 = np.where(np.logical_and(resbana_gdn>1, resbana_gdtotalmass>-24)) gdmedianrproj, massbincenters, massbinedges, jk = center_binned_stats(resbana_gdtotalmass[binsel2], resbana_gdrelprojdist[binsel2], np.median, bins=massbins2) gdmedianrproj_err, jk, jk, jk = center_binned_stats(resbana_gdtotalmass[binsel2], resbana_gdrelprojdist[binsel2], sigmarange, bins=massbins2) gdmedianrelvel, jk, jk, jk = center_binned_stats(resbana_gdtotalmass[binsel2], resbana_gdrelvel[binsel2], np.median, bins=massbins2) gdmedianrelvel_err, jk, jk, jk = center_binned_stats(resbana_gdtotalmass[binsel2], resbana_gdrelvel[binsel2], sigmarange, bins=massbins2) nansel = np.isnan(gdmedianrproj) poptr_resbana, jk = curve_fit(exp, massbincenters[~nansel], gdmedianrproj[~nansel], p0=poptr, sigma=gdmedianrproj_err[~nansel])#10**massbincenters[~nansel]) poptv_resbana, jk = curve_fit(exp, massbincenters[~nansel], gdmedianrelvel[~nansel], p0=poptv, sigma=gdmedianrelvel_err[~nansel])#[3e-5,4e-1,5e-03,1]) tx = np.linspace(7,15) plt.figure() plt.plot(resbana_gdtotalmass[binsel2], resbana_gdrelprojdist[binsel2], 'k.', alpha=0.2, label='Mock Galaxies in N>1 Giant+Dwarf Groups') plt.errorbar(massbincenters, gdmedianrproj, gdmedianrproj_err, fmt='r^', label='Median') plt.plot(tx, exp(tx,*poptr_resbana), label='Fit to Medians') plt.plot(tx, 3*exp(tx,*poptr_resbana), label='3 times Fit to Medians') plt.xlabel(r"Integrated Stellar Mass of Giant + Dwarf Members") plt.ylabel("Projected Distance from Galaxy to Group Center [Mpc/h]") plt.legend(loc='best') plt.xlim(9.5,13) plt.ylim(0,3) plt.show() plt.figure() plt.plot(resbana_gdtotalmass[binsel2], resbana_gdrelvel[binsel2], 'k.', alpha=0.2, label='Mock Galaxies in N=2 Giant+Dwarf Groups') plt.errorbar(massbincenters, gdmedianrelvel, yerr=gdmedianrelvel_err, fmt='r^',label='Medians') plt.plot(tx, exp(tx, *poptv_resbana), label='Fit to Medians') plt.plot(tx, 4.5*exp(tx, *poptv_resbana), label='4.5 times Fit to Medians') plt.ylabel("Relative Velocity between Galaxy and Group Center") plt.xlabel(r"Integrated Stellar Mass of Giant + Dwarf Members") plt.xlim(9.5,13) plt.ylim(0,2000) plt.legend(loc='best') plt.show() rproj_for_iteration_resbana = lambda M: 3*exp(M, *poptr_resbana) vproj_for_iteration_resbana = lambda M: 4.5*exp(M, *poptv_resbana) ########################################################### # Step 7: Iterative Combination of Dwarf Galaxies ########################################################### assert (ecog3grp[(ecologmstar>9.5) & (ecocz<8000) & (ecocz>2530)]!=-99.).all(), "Not all giants are grouped." ecogrpnafterassoc = fof.multiplicity_function(ecog3grp, return_by_galaxy=True) resbgrpnafterassoc = fof.multiplicity_function(resbg3grp, return_by_galaxy=True) resbana_grpnafterassoc = fof.multiplicity_function(resbana_g3grp, return_by_galaxy=True) eco_ungroupeddwarf_sel = (ecologmstar<9.5) & (ecologmstar>=8.9) & (ecocz<8000) & (ecocz>2530) & (ecogrpnafterassoc==1) ecoitassocid = ic.iterative_combination(ecoradeg[eco_ungroupeddwarf_sel], ecodedeg[eco_ungroupeddwarf_sel], ecocz[eco_ungroupeddwarf_sel], ecologmstar[eco_ungroupeddwarf_sel],\ rproj_for_iteration, vproj_for_iteration, starting_id=np.max(ecog3grp)+1, centermethod='arithmetic') resb_ungroupeddwarf_sel = (resblogmstar<9.5) & (resblogmstar>=8.7) & (resbcz<7300) & (resbcz>4250) & (resbgrpnafterassoc==1) resbitassocid = ic.iterative_combination(resbradeg[resb_ungroupeddwarf_sel], resbdedeg[resb_ungroupeddwarf_sel], resbcz[resb_ungroupeddwarf_sel], resblogmstar[resb_ungroupeddwarf_sel],\ rproj_for_iteration, vproj_for_iteration, starting_id=np.max(resbg3grp)+1, centermethod='arithmetic') resbana_ungroupeddwarf_sel = (ecologmstar<9.5) & (ecologmstar>=8.7) & (ecocz<8000) & (ecocz>2530) & (resbana_grpnafterassoc==1) resbana_itassocid = ic.iterative_combination(ecoradeg[resbana_ungroupeddwarf_sel], ecodedeg[resbana_ungroupeddwarf_sel], ecocz[resbana_ungroupeddwarf_sel], ecologmstar[resbana_ungroupeddwarf_sel],\ rproj_for_iteration_resbana, vproj_for_iteration_resbana, starting_id=np.max(resbana_g3grp)+1, centermethod='arithmetic') ecog3grp[eco_ungroupeddwarf_sel] = ecoitassocid resbg3grp[resb_ungroupeddwarf_sel] = resbitassocid resbana_g3grp[resbana_ungroupeddwarf_sel] = resbana_itassocid #plt.figure() #plt.hist(fof.multiplicity_function(ecoitassocid, return_by_galaxy=False), log=True) #plt.hist(fof.multiplicity_function(resbitassocid, return_by_galaxy=False), log=True, histtype='step') #plt.show() plt.figure() binv = np.arange(0.5,1200.5,3) plt.hist(fof.multiplicity_function(ecog3grp[ecog3grp!=-99.], return_by_galaxy=False), bins=binv, log=True, label='ECO Groups', histtype='step', linewidth=3) plt.hist(fof.multiplicity_function(resbg3grp[resbg3grp!=-99.], return_by_galaxy=False), bins=binv, log=True, label='RESOLVE-B Groups', histtype='step', hatch='\\') plt.xlabel("Number of Giant + Dwarf Group Members") plt.ylabel("Number of Groups") plt.legend(loc='best') plt.xlim(0,100) plt.show() ############################################################ # Step 8: Halo Abundance Matching ########################################################### # --- for RESOLVE-B analogue ----# resbana_hamsel = (resbana_g3grp!=-99.) resbana_haloid, resbana_halomass, jk, jk = ic.HAMwrapper(ecoradeg[resbana_hamsel], ecodedeg[resbana_hamsel], ecocz[resbana_hamsel], ecologmstar[resbana_hamsel], resbana_g3grp[resbana_hamsel],\ ecovolume, inputfilename=None, outputfilename=None) resbana_halomass = np.log10(10**resbana_halomass)# no longer needed as of 7/29: /fof.getmhoffset(280,337,1,1,6)) junk, uniqindex = np.unique(resbana_g3grp[resbana_hamsel], return_index=True) resbana_intmass = ic.get_int_mass(ecologmstar[resbana_hamsel], resbana_g3grp[resbana_hamsel])[uniqindex] sortind = np.argsort(resbana_intmass) sortedmass = resbana_intmass[sortind] resbcubicspline = interp1d(sortedmass, resbana_halomass[sortind], fill_value='extrapolate') resbintmass = ic.get_int_mass(resblogmstar[resbg3grp!=-99.], resbg3grp[resbg3grp!=-99.]) resbg3logmh[resbg3grp!=-99.] = resbcubicspline(resbintmass)-np.log10(0.7) # ---- for ECO ----- # ecohamsel = (ecog3grp!=-99.) haloid, halomass, junk, junk = ic.HAMwrapper(ecoradeg[ecohamsel], ecodedeg[ecohamsel], ecocz[ecohamsel], ecologmstar[ecohamsel], ecog3grp[ecohamsel],\ ecovolume, inputfilename=None, outputfilename=None) junk, uniqindex = np.unique(ecog3grp[ecohamsel], return_index=True) halomass = halomass-np.log10(0.7) for i,idv in enumerate(haloid): sel = np.where(ecog3grp==idv) ecog3logmh[sel] = halomass[i] # m337b # calculate Rvir in arcsec ecog3rvir = (3*(10**ecog3logmh) / (4*np.pi*337*0.3*1.36e11) )**(1/3.) resbg3rvir = (3*(10**resbg3logmh ) / (4*np.pi*337*0.3*1.36e11))**(1/3.) ecointmass = ic.get_int_mass(ecologmstar[ecohamsel], ecog3grp[ecohamsel]) plt.figure() plt.plot(ecointmass, ecog3logmh[ecog3grp!=-99.], '.', color='palegreen', alpha=0.6, label='ECO', markersize=11) plt.plot(resbintmass, resbg3logmh[resbg3grp!=-99.], 'k.', alpha=1, label='RESOLVE-B', markersize=3) plt.plot plt.xlabel("group-integrated log stellar mass") plt.ylabel(r"group halo mass (log$M_\odot$)") plt.legend(loc='best') plt.show() ######################################## # (9) Output arrays ######################################## # ---- first get the quantities for ECO ---- # #eco_in_gf = np.where(ecog3grp!=-99.) ecog3grpn = fof.multiplicity_function(ecog3grp, return_by_galaxy=True) ecog3grpngi = np.zeros(len(ecog3grpn)) ecog3grpndw = np.zeros(len(ecog3grpn)) for uid in np.unique(ecog3grp): grpsel = np.where(ecog3grp==uid) gisel = np.where(np.logical_and((ecog3grp==uid),(ecologmstar>=9.5))) dwsel = np.where(np.logical_and((ecog3grp==uid), (ecologmstar<9.5))) if len(gisel[0])>0.: ecog3grpngi[grpsel] = len(gisel[0]) if len(dwsel[0])>0.: ecog3grpndw[grpsel] = len(dwsel[0]) ecog3grpradeg, ecog3grpdedeg, ecog3grpcz = fof.group_skycoords(ecoradeg, ecodedeg, ecocz, ecog3grp) ecog3rproj = fof.get_grprproj_e17(ecoradeg, ecodedeg, ecocz, ecog3grp, h=0.7) / (ecog3grpcz/70.) * 206265 # in arcsec ecog3fc = fof.get_central_flag(ecologmstar, ecog3grp) ecog3router = fof.get_outermost_galradius(ecoradeg, ecodedeg, ecocz, ecog3grp) # in arcsec ecog3router[(ecog3grpngi+ecog3grpndw)==1] = 0. junk, ecog3vdisp = fof.get_rproj_czdisp(ecoradeg, ecodedeg, ecocz, ecog3grp) ecog3rvir = ecog3rvir*206265/(ecog3grpcz/70.) ecog3grpgas = ic.get_int_mass(ecologmgas, ecog3grp) ecog3grpstars = ic.get_int_mass(ecologmstar, ecog3grp) ecog3ADtest = vz.AD_test(ecocz, ecog3grp) ecog3tcross = vz.group_crossing_time(ecoradeg, ecodedeg, ecocz, ecog3grp) ecog3colorgap = vz.group_color_gap(ecog3grp, ecologmstar, ecourcolor) ecog3dsprob = vz.fast_DS_test(ecoradeg,ecodedeg,ecocz,ecog3grp,niter=2500) ecog3nndens, ecog3edgeflag, ecog3nndens2d, ecog3edgeflag2d, ecog3edgescale2d = lss_dens_by_galaxy(ecog3grp,\ ecoradeg, ecodedeg, ecocz, ecog3logmh, Nnn=3, rarange=(130.05,237.45), decrange=(-1,50), czrange=(2530,7470)) outofsample = (ecog3grp==-99.) ecog3grpn[outofsample]=-99. ecog3grpngi[outofsample]=-99. ecog3grpndw[outofsample]=-99. ecog3grpradeg[outofsample]=-99. ecog3grpdedeg[outofsample]=-99. ecog3grpcz[outofsample]=-99. ecog3logmh[outofsample]=-99. ecog3rvir[outofsample]=-99. ecog3rproj[outofsample]=-99. ecog3fc[outofsample]=-99. ecog3router[outofsample]=-99. ecog3vdisp[outofsample]=-99. ecog3grpgas[outofsample]=-99. ecog3grpstars[outofsample]=-99. ecog3ADtest[outofsample]=-99. ecog3tcross[outofsample]=-99. ecog3colorgap[outofsample]=-99. ecog3dsprob[outofsample]=-99. ecog3nndens[outofsample]=-99. ecog3edgeflag[outofsample]=-99. ecog3nndens2d[outofsample]=-99. ecog3edgeflag2d[outofsample]=-99. ecog3edgescale2d[outofsample]=-99. insample = ecog3grpn!=-99. ecodata['g3grp_s'] = ecog3grp ecodata['g3grpradeg_s'] = ecog3grpradeg ecodata['g3grpdedeg_s'] = ecog3grpdedeg ecodata['g3grpcz_s'] = ecog3grpcz ecodata['g3grpndw_s'] = ecog3grpndw ecodata['g3grpngi_s'] = ecog3grpngi ecodata['g3logmh_s'] = ecog3logmh ecodata['g3r337_s'] = ecog3rvir ecodata['g3rproj_s'] = ecog3rproj ecodata['g3router_s'] = ecog3router ecodata['g3fc_s'] = ecog3fc ecodata['g3vdisp_s'] = ecog3vdisp ecodata['g3grplogG_s'] = ecog3grpgas ecodata['g3grplogS_s'] = ecog3grpstars ecodata['g3grpadAlpha_s'] = ecog3ADtest ecodata['g3grptcross_s'] = ecog3tcross ecodata['g3grpcolorgap_s'] = ecog3colorgap ecodata['g3grpcolorgap_s'] = ecog3colorgap ecodata['g3grpdsProb_s'] = ecog3dsprob ecodata['g3grpnndens_s'] = ecog3nndens ecodata['g3grpedgeflag_s'] = ecog3edgeflag ecodata['g3grpnndens2d_s'] = ecog3nndens2d ecodata['g3grpedgeflag2d_s'] = ecog3edgeflag2d ecodata['g3grpedgescale2d_s'] = ecog3edgescale2d ecodata.to_csv("ECOdata_G3catalog_stellar.csv", index=False) # ------ now do RESOLVE sz = len(resolvedata) resolvename = np.array(resolvedata.name) resolveg3grp = np.full(sz, -99.) resolveg3grpngi = np.full(sz, -99.) resolveg3grpndw = np.full(sz, -99.) resolveg3grpradeg = np.full(sz, -99.) resolveg3grpdedeg = np.full(sz, -99.) resolveg3grpcz = np.full(sz, -99.) resolveg3intmstar = np.full(sz, -99.) resolveg3logmh = np.full(sz, -99.) resolveg3rvir = np.full(sz, -99.) resolveg3rproj = np.full(sz,-99.) resolveg3fc = np.full(sz,-99.) resolveg3router = np.full(sz,-99.) resolveg3vdisp = np.full(sz,-99.) resolveg3grpgas = np.full(sz, -99.) resolveg3grpstars = np.full(sz, -99.) resolveg3ADtest = np.full(sz, -99.) resolveg3tcross = np.full(sz, -99.) resolveg3colorgap = np.full(sz, -99.) resolveg3dsprob = np.full(sz,-99.) resolveg3nndens = np.full(sz, -99.) resolveg3edgeflag = np.full(sz, -99.) resolveg3nndens2d = np.full(sz, -99.) resolveg3edgeflag2d = np.full(sz, -99.) resolveg3edgescale2d = np.full(sz, -99.) resbg3grpngi = np.full(len(resbg3grp), 0) resbg3grpndw = np.full(len(resbg3grp), 0) for uid in np.unique(resbg3grp): grpsel = np.where(resbg3grp==uid) gisel = np.where(np.logical_and((resbg3grp==uid),(resblogmstar>=9.5))) dwsel = np.where(np.logical_and((resbg3grp==uid), (resblogmstar<9.5))) if len(gisel[0])>0.: resbg3grpngi[grpsel] = len(gisel[0]) if len(dwsel[0])>0.: resbg3grpndw[grpsel] = len(dwsel[0]) resbg3grpradeg, resbg3grpdedeg, resbg3grpcz = fof.group_skycoords(resbradeg, resbdedeg, resbcz, resbg3grp) resbg3intmstar = ic.get_int_mass(resblogmstar, resbg3grp) resbg3rproj = fof.get_grprproj_e17(resbradeg, resbdedeg, resbcz, resbg3grp, h=0.7) / (resbg3grpcz/70.) * 206265 # in arcsec resbg3fc = fof.get_central_flag(resblogmstar, resbg3grp) resbg3router = fof.get_outermost_galradius(resbradeg, resbdedeg, resbcz, resbg3grp) # in arcsec resbg3router[(resbg3grpngi+resbg3grpndw)==1] = 0. junk, resbg3vdisp = fof.get_rproj_czdisp(resbradeg, resbdedeg, resbcz, resbg3grp) resbg3rvir = resbg3rvir*206265/(resbg3grpcz/70.) resbg3grpgas = ic.get_int_mass(resblogmgas, resbg3grp) resbg3grpstars = ic.get_int_mass(resblogmstar, resbg3grp) resbg3ADtest = vz.AD_test(resbcz, resbg3grp) resbg3tcross = vz.group_crossing_time(resbradeg, resbdedeg, resbcz, resbg3grp) resbg3colorgap = vz.group_color_gap(resbg3grp, resblogmstar, resburcolor) resbg3dsprob = vz.fast_DS_test(resbradeg,resbdedeg,resbcz,resbg3grp,niter=2500) RESB_RADEG_REMAPPED = np.copy(resbradeg) REMAPSEL = np.where(resbradeg>18*15.) RESB_RADEG_REMAPPED[REMAPSEL] = resbradeg[REMAPSEL]-360. resbg3nndens, resbg3edgeflag, resbg3nndens2d, resbg3edgeflag2d, resbg3edgescale2d = lss_dens_by_galaxy(resbg3grp,\ RESB_RADEG_REMAPPED, resbdedeg, resbcz, resbg3logmh, Nnn=3, rarange=(-2*15.,3*15.), decrange=(-1.25,1.25),\ czrange=(4250,7250)) # must use remapped RESOLVE-B RA because of 0/360 wraparound outofsample = (resbg3grp==-99.) resbg3grpngi[outofsample]=-99. resbg3grpndw[outofsample]=-99. resbg3grpradeg[outofsample]=-99. resbg3grpdedeg[outofsample]=-99. resbg3grpcz[outofsample]=-99. resbg3intmstar[outofsample]=-99. resbg3logmh[outofsample]=-99. resbg3rvir[outofsample]=-99. resbg3rproj[outofsample]=-99. resbg3router[outofsample]=-99. resbg3fc[outofsample]=-99. resbg3vdisp[outofsample]=-99. resbg3grpgas[outofsample]=-99. resbg3grpstars[outofsample]=-99. resbg3ADtest[outofsample]=-99. resbg3tcross[outofsample]=-99. resbg3colorgap[outofsample]=-99. resbg3dsprob[outofsample]=-99. resbg3nndens[outofsample]=-99. resbg3edgeflag[outofsample]=-99. resbg3nndens2d[outofsample]=-99. resbg3edgeflag2d[outofsample]=-99. resbg3edgescale2d[outofsample]=-99. for i,nm in enumerate(resolvename): if nm.startswith('rs'): sel_in_eco = np.where(ecoresname==nm) resolveg3grp[i] = ecog3grp[sel_in_eco] resolveg3grpngi[i] = ecog3grpngi[sel_in_eco] resolveg3grpndw[i] = ecog3grpndw[sel_in_eco] resolveg3grpradeg[i] = ecog3grpradeg[sel_in_eco] resolveg3grpdedeg[i] = ecog3grpdedeg[sel_in_eco] resolveg3grpcz[i] = ecog3grpcz[sel_in_eco] resolveg3intmstar[i] = ecog3intmstar[sel_in_eco] resolveg3logmh[i] = ecog3logmh[sel_in_eco] resolveg3rvir[i] = ecog3rvir[sel_in_eco] resolveg3rproj[i] = ecog3rproj[sel_in_eco] resolveg3fc[i] = ecog3fc[sel_in_eco] resolveg3router[i]=ecog3router[sel_in_eco] resolveg3vdisp[i]=ecog3vdisp[sel_in_eco] resolveg3grpstars[i] = ecog3grpstars[sel_in_eco] resolveg3grpgas[i] = ecog3grpgas[sel_in_eco] resolveg3ADtest[i] = ecog3ADtest[sel_in_eco] resolveg3tcross[i] = ecog3tcross[sel_in_eco] resolveg3colorgap[i] = ecog3colorgap[sel_in_eco] resolveg3dsprob[i] = ecog3dsprob[sel_in_eco] resolveg3nndens[i] = ecog3nndens[sel_in_eco] resolveg3edgeflag[i] = ecog3edgeflag[sel_in_eco] resolveg3nndens2d[i] = ecog3nndens2d[sel_in_eco] resolveg3edgeflag2d[i] = ecog3edgeflag2d[sel_in_eco] resolveg3edgescale2d[i] = ecog3edgescale2d[sel_in_eco] elif nm.startswith('rf'): sel_in_resb = np.where(resbname==nm) resolveg3grp[i] = resbg3grp[sel_in_resb] resolveg3grpngi[i] = resbg3grpngi[sel_in_resb] resolveg3grpndw[i] = resbg3grpndw[sel_in_resb] resolveg3grpradeg[i] = resbg3grpradeg[sel_in_resb] resolveg3grpdedeg[i] = resbg3grpdedeg[sel_in_resb] resolveg3grpcz[i] = resbg3grpcz[sel_in_resb] resolveg3intmstar[i] = resbg3intmstar[sel_in_resb] resolveg3logmh[i] = resbg3logmh[sel_in_resb] resolveg3rvir[i] = resbg3rvir[sel_in_resb] resolveg3rproj[i] = resbg3rproj[sel_in_resb] resolveg3fc[i] = resbg3fc[sel_in_resb] resolveg3router[i] = resbg3router[sel_in_resb] resolveg3vdisp[i] = resbg3vdisp[sel_in_resb] resolveg3grpgas[i] = resbg3grpgas[sel_in_resb] resolveg3grpstars[i] = resbg3grpstars[sel_in_resb] resolveg3ADtest[i] = resbg3ADtest[sel_in_resb] resolveg3tcross[i] = resbg3tcross[sel_in_resb] resolveg3colorgap[i] = resbg3colorgap[sel_in_resb] resolveg3dsprob[i] = resbg3dsprob[sel_in_resb] resolveg3nndens[i] = resbg3nndens[sel_in_resb] resolveg3edgeflag[i] = resbg3edgeflag[sel_in_resb] resolveg3nndens2d[i] = resbg3nndens2d[sel_in_resb] resolveg3edgeflag2d[i] = resbg3edgeflag2d[sel_in_resb] resolveg3edgescale2d[i] = resbg3edgescale2d[sel_in_resb] else: assert False, nm+" not in RESOLVE" resolvedata['g3grp_s'] = resolveg3grp resolvedata['g3grpngi_s'] = resolveg3grpngi resolvedata['g3grpndw_s'] = resolveg3grpndw resolvedata['g3grpradeg_s'] = resolveg3grpradeg resolvedata['g3grpdedeg_s'] = resolveg3grpdedeg resolvedata['g3grpcz_s'] = resolveg3grpcz resolvedata['g3logmh_s'] = resolveg3logmh resolvedata['g3r337_s'] = resolveg3rvir resolvedata['g3rproj_s'] = resolveg3rproj resolvedata['g3router_s'] = resolveg3router resolvedata['g3fc_s'] = resolveg3fc resolvedata['g3vdisp_s'] = resolveg3vdisp resolvedata['g3grplogG_s'] = resolveg3grpgas resolvedata['g3grplogS_s'] = resolveg3grpstars resolvedata['g3grpadAlpha_s'] = resolveg3ADtest resolvedata['g3grptcross_s'] = resolveg3tcross resolvedata['g3grpcolorgap_s'] = resolveg3colorgap resolvedata['g3grpdsProb_s'] = resolveg3dsprob resolvedata['g3grpnndens_s'] = resolveg3nndens resolvedata['g3grpedgeflag_s'] = resolveg3edgeflag resolvedata['g3grpnndens2d_s'] = resolveg3nndens2d resolvedata['g3grpedgeflag2d_s'] = resolveg3edgeflag2d resolvedata['g3grpedgescale2d_s'] = resolveg3edgescale2d resolvedata.to_csv("RESOLVEdata_G3catalog_stellar.csv", index=False)
[ "numpy.log10", "pandas.read_csv", "matplotlib.pyplot.ylabel", "scipy.interpolate.interp1d", "numpy.argsort", "numpy.array", "numpy.percentile", "matplotlib.pyplot.errorbar", "foftools.fast_fof", "numpy.arange", "virtools.group_color_gap", "numpy.where", "matplotlib.pyplot.xlabel", "matplot...
[((2094, 2120), 'numpy.percentile', 'np.percentile', (['x', '[84, 16]'], {}), '(x, [84, 16])\n', (2107, 2120), True, 'import numpy as np\n'), ((2298, 2331), 'pandas.read_csv', 'pd.read_csv', (['"""ECOdata_022521.csv"""'], {}), "('ECOdata_022521.csv')\n", (2309, 2331), True, 'import pandas as pd\n'), ((2350, 2387), 'pandas.read_csv', 'pd.read_csv', (['"""RESOLVEdata_022521.csv"""'], {}), "('RESOLVEdata_022521.csv')\n", (2361, 2387), True, 'import pandas as pd\n'), ((2590, 2612), 'numpy.array', 'np.array', (['ecodata.name'], {}), '(ecodata.name)\n', (2598, 2612), True, 'import numpy as np\n'), ((2630, 2655), 'numpy.array', 'np.array', (['ecodata.resname'], {}), '(ecodata.resname)\n', (2638, 2655), True, 'import numpy as np\n'), ((2671, 2694), 'numpy.array', 'np.array', (['ecodata.radeg'], {}), '(ecodata.radeg)\n', (2679, 2694), True, 'import numpy as np\n'), ((2710, 2733), 'numpy.array', 'np.array', (['ecodata.dedeg'], {}), '(ecodata.dedeg)\n', (2718, 2733), True, 'import numpy as np\n'), ((2746, 2766), 'numpy.array', 'np.array', (['ecodata.cz'], {}), '(ecodata.cz)\n', (2754, 2766), True, 'import numpy as np\n'), ((2785, 2811), 'numpy.array', 'np.array', (['ecodata.logmstar'], {}), '(ecodata.logmstar)\n', (2793, 2811), True, 'import numpy as np\n'), ((2829, 2854), 'numpy.array', 'np.array', (['ecodata.logmgas'], {}), '(ecodata.logmgas)\n', (2837, 2854), True, 'import numpy as np\n'), ((2872, 2902), 'numpy.array', 'np.array', (['ecodata.modelu_rcorr'], {}), '(ecodata.modelu_rcorr)\n', (2880, 2902), True, 'import numpy as np\n'), ((2918, 2939), 'numpy.full', 'np.full', (['ecosz', '(-99.0)'], {}), '(ecosz, -99.0)\n', (2925, 2939), True, 'import numpy as np\n'), ((2979, 3000), 'numpy.full', 'np.full', (['ecosz', '(-99.0)'], {}), '(ecosz, -99.0)\n', (2986, 3000), True, 'import numpy as np\n'), ((3047, 3068), 'numpy.full', 'np.full', (['ecosz', '(-99.0)'], {}), '(ecosz, -99.0)\n', (3054, 3068), True, 'import numpy as np\n'), ((3108, 3129), 'numpy.full', 'np.full', (['ecosz', '(-99.0)'], {}), '(ecosz, -99.0)\n', (3115, 3129), True, 'import numpy as np\n'), ((3167, 3188), 'numpy.full', 'np.full', (['ecosz', '(-99.0)'], {}), '(ecosz, -99.0)\n', (3174, 3188), True, 'import numpy as np\n'), ((3225, 3246), 'numpy.full', 'np.full', (['ecosz', '(-99.0)'], {}), '(ecosz, -99.0)\n', (3232, 3246), True, 'import numpy as np\n'), ((3295, 3316), 'numpy.full', 'np.full', (['ecosz', '(-99.0)'], {}), '(ecosz, -99.0)\n', (3302, 3316), True, 'import numpy as np\n'), ((3368, 3389), 'numpy.full', 'np.full', (['ecosz', '(-99.0)'], {}), '(ecosz, -99.0)\n', (3375, 3389), True, 'import numpy as np\n'), ((3473, 3500), 'numpy.array', 'np.array', (['resolvebdata.name'], {}), '(resolvebdata.name)\n', (3481, 3500), True, 'import numpy as np\n'), ((3517, 3545), 'numpy.array', 'np.array', (['resolvebdata.radeg'], {}), '(resolvebdata.radeg)\n', (3525, 3545), True, 'import numpy as np\n'), ((3562, 3590), 'numpy.array', 'np.array', (['resolvebdata.dedeg'], {}), '(resolvebdata.dedeg)\n', (3570, 3590), True, 'import numpy as np\n'), ((3604, 3629), 'numpy.array', 'np.array', (['resolvebdata.cz'], {}), '(resolvebdata.cz)\n', (3612, 3629), True, 'import numpy as np\n'), ((3649, 3680), 'numpy.array', 'np.array', (['resolvebdata.logmstar'], {}), '(resolvebdata.logmstar)\n', (3657, 3680), True, 'import numpy as np\n'), ((3699, 3729), 'numpy.array', 'np.array', (['resolvebdata.logmgas'], {}), '(resolvebdata.logmgas)\n', (3707, 3729), True, 'import numpy as np\n'), ((3748, 3783), 'numpy.array', 'np.array', (['resolvebdata.modelu_rcorr'], {}), '(resolvebdata.modelu_rcorr)\n', (3756, 3783), True, 'import numpy as np\n'), ((3800, 3822), 'numpy.full', 'np.full', (['resbsz', '(-99.0)'], {}), '(resbsz, -99.0)\n', (3807, 3822), True, 'import numpy as np\n'), ((3839, 3861), 'numpy.full', 'np.full', (['resbsz', '(-99.0)'], {}), '(resbsz, -99.0)\n', (3846, 3861), True, 'import numpy as np\n'), ((3882, 3904), 'numpy.full', 'np.full', (['resbsz', '(-99.0)'], {}), '(resbsz, -99.0)\n', (3889, 3904), True, 'import numpy as np\n'), ((3925, 3947), 'numpy.full', 'np.full', (['resbsz', '(-99.0)'], {}), '(resbsz, -99.0)\n', (3932, 3947), True, 'import numpy as np\n'), ((3965, 3987), 'numpy.full', 'np.full', (['resbsz', '(-99.0)'], {}), '(resbsz, -99.0)\n', (3972, 3987), True, 'import numpy as np\n'), ((4005, 4027), 'numpy.full', 'np.full', (['resbsz', '(-99.0)'], {}), '(resbsz, -99.0)\n', (4012, 4027), True, 'import numpy as np\n'), ((4048, 4070), 'numpy.full', 'np.full', (['resbsz', '(-99.0)'], {}), '(resbsz, -99.0)\n', (4055, 4070), True, 'import numpy as np\n'), ((4591, 4697), 'foftools.fast_fof', 'fof.fast_fof', (['ecoradeg[ecogiantsel]', 'ecodedeg[ecogiantsel]', 'ecocz[ecogiantsel]', 'bperp', 'blos', 'meansep0'], {}), '(ecoradeg[ecogiantsel], ecodedeg[ecogiantsel], ecocz[\n ecogiantsel], bperp, blos, meansep0)\n', (4603, 4697), True, 'import foftools as fof\n'), ((4972, 5084), 'foftools.fast_fof', 'fof.fast_fof', (['resbradeg[resbgiantsel]', 'resbdedeg[resbgiantsel]', 'resbcz[resbgiantsel]', 'bperp', 'blos', 'meansep0'], {}), '(resbradeg[resbgiantsel], resbdedeg[resbgiantsel], resbcz[\n resbgiantsel], bperp, blos, meansep0)\n', (4984, 5084), True, 'import foftools as fof\n'), ((5162, 5174), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (5172, 5174), True, 'import matplotlib.pyplot as plt\n'), ((5186, 5211), 'numpy.arange', 'np.arange', (['(0.5)', '(3000.5)', '(3)'], {}), '(0.5, 3000.5, 3)\n', (5195, 5211), True, 'import numpy as np\n'), ((5568, 5616), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Number of Giant Galaxies per Group"""'], {}), "('Number of Giant Galaxies per Group')\n", (5578, 5616), True, 'import matplotlib.pyplot as plt\n'), ((5621, 5666), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Number of Giant-Only FoF Groups"""'], {}), "('Number of Giant-Only FoF Groups')\n", (5631, 5666), True, 'import matplotlib.pyplot as plt\n'), ((5671, 5688), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (5681, 5688), True, 'import matplotlib.pyplot as plt\n'), ((5693, 5715), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""'}), "(loc='best')\n", (5703, 5715), True, 'import matplotlib.pyplot as plt\n'), ((5720, 5735), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(80)'], {}), '(0, 80)\n', (5728, 5735), True, 'import matplotlib.pyplot as plt\n'), ((5739, 5749), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5747, 5749), True, 'import matplotlib.pyplot as plt\n'), ((5941, 6046), 'foftools.group_skycoords', 'fof.group_skycoords', (['ecoradeg[ecogiantsel]', 'ecodedeg[ecogiantsel]', 'ecocz[ecogiantsel]', 'ecogiantfofid'], {}), '(ecoradeg[ecogiantsel], ecodedeg[ecogiantsel], ecocz[\n ecogiantsel], ecogiantfofid)\n', (5960, 6046), True, 'import foftools as fof\n'), ((6055, 6097), 'numpy.abs', 'np.abs', (['(ecogiantgrpcz - ecocz[ecogiantsel])'], {}), '(ecogiantgrpcz - ecocz[ecogiantsel])\n', (6061, 6097), True, 'import numpy as np\n'), ((6282, 6345), 'foftools.multiplicity_function', 'fof.multiplicity_function', (['ecogiantfofid'], {'return_by_galaxy': '(True)'}), '(ecogiantfofid, return_by_galaxy=True)\n', (6307, 6345), True, 'import foftools as fof\n'), ((6380, 6422), 'numpy.unique', 'np.unique', (['ecogiantgrpn'], {'return_index': '(True)'}), '(ecogiantgrpn, return_index=True)\n', (6389, 6422), True, 'import numpy as np\n'), ((6440, 6470), 'numpy.where', 'np.where', (['(uniqecogiantgrpn > 1)'], {}), '(uniqecogiantgrpn > 1)\n', (6448, 6470), True, 'import numpy as np\n'), ((7331, 7432), 'scipy.optimize.curve_fit', 'curve_fit', (['giantmodel', 'uniqecogiantgrpn[keepcalsel]', 'median_relprojdist'], {'sigma': 'rproj_median_error'}), '(giantmodel, uniqecogiantgrpn[keepcalsel], median_relprojdist,\n sigma=rproj_median_error)\n', (7340, 7432), False, 'from scipy.optimize import curve_fit\n'), ((7474, 7572), 'scipy.optimize.curve_fit', 'curve_fit', (['giantmodel', 'uniqecogiantgrpn[keepcalsel]', 'median_relvel'], {'sigma': 'dvproj_median_error'}), '(giantmodel, uniqecogiantgrpn[keepcalsel], median_relvel, sigma=\n dvproj_median_error)\n', (7483, 7572), False, 'from scipy.optimize import curve_fit\n'), ((8000, 8189), 'iterativecombination.HAMwrapper', 'ic.HAMwrapper', (['ecoradeg[ecogiantsel]', 'ecodedeg[ecogiantsel]', 'ecocz[ecogiantsel]', 'ecologmstar[ecogiantsel]', 'ecog3grp[ecogiantsel]', 'ecovolume'], {'inputfilename': 'None', 'outputfilename': 'None'}), '(ecoradeg[ecogiantsel], ecodedeg[ecogiantsel], ecocz[\n ecogiantsel], ecologmstar[ecogiantsel], ecog3grp[ecogiantsel],\n ecovolume, inputfilename=None, outputfilename=None)\n', (8013, 8189), True, 'import iterativecombination as ic\n'), ((8260, 8283), 'numpy.log10', 'np.log10', (['(10 ** gilogmh)'], {}), '(10 ** gilogmh)\n', (8268, 8283), True, 'import numpy as np\n'), ((8509, 8521), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (8519, 8521), True, 'import matplotlib.pyplot as plt\n'), ((8526, 8561), 'matplotlib.pyplot.plot', 'plt.plot', (['gihalon', 'gihalorvir', '"""k."""'], {}), "(gihalon, gihalorvir, 'k.')\n", (8534, 8561), True, 'import matplotlib.pyplot as plt\n'), ((8566, 8576), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (8574, 8576), True, 'import matplotlib.pyplot as plt\n'), ((8582, 8594), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (8592, 8594), True, 'import matplotlib.pyplot as plt\n'), ((8626, 8729), 'matplotlib.pyplot.scatter', 'plt.scatter', (['gihalon', 'gihalovdisp'], {'marker': '"""D"""', 'color': '"""purple"""', 'label': '"""ECO HAM Velocity Dispersion"""'}), "(gihalon, gihalovdisp, marker='D', color='purple', label=\n 'ECO HAM Velocity Dispersion')\n", (8637, 8729), True, 'import matplotlib.pyplot as plt\n'), ((8730, 8820), 'matplotlib.pyplot.plot', 'plt.plot', (['ecogiantgrpn[sel]', 'relvel[sel]', '"""r."""'], {'alpha': '(0.2)', 'label': '"""ECO Giant Galaxies"""'}), "(ecogiantgrpn[sel], relvel[sel], 'r.', alpha=0.2, label=\n 'ECO Giant Galaxies')\n", (8738, 8820), True, 'import matplotlib.pyplot as plt\n'), ((8820, 8999), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (['uniqecogiantgrpn[keepcalsel]', 'median_relvel'], {'fmt': '"""k^"""', 'label': '"""$\\\\Delta v_{\\\\rm proj}$ (Median of $\\\\Delta v_{\\\\rm proj,\\\\, gal}$)"""', 'yerr': 'dvproj_median_error'}), "(uniqecogiantgrpn[keepcalsel], median_relvel, fmt='k^', label=\n '$\\\\Delta v_{\\\\rm proj}$ (Median of $\\\\Delta v_{\\\\rm proj,\\\\, gal}$)',\n yerr=dvproj_median_error)\n", (8832, 8999), True, 'import matplotlib.pyplot as plt\n'), ((9243, 9280), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Number of Giant Members"""'], {}), "('Number of Giant Members')\n", (9253, 9280), True, 'import matplotlib.pyplot as plt\n'), ((9285, 9339), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Relative Velocity to Group Center [km/s]"""'], {}), "('Relative Velocity to Group Center [km/s]')\n", (9295, 9339), True, 'import matplotlib.pyplot as plt\n'), ((9344, 9366), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""'}), "(loc='best')\n", (9354, 9366), True, 'import matplotlib.pyplot as plt\n'), ((9371, 9381), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (9379, 9381), True, 'import matplotlib.pyplot as plt\n'), ((9387, 9396), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (9394, 9396), True, 'import matplotlib.pyplot as plt\n'), ((9401, 9498), 'matplotlib.pyplot.scatter', 'plt.scatter', (['gihalon', 'gihalorvir'], {'marker': '"""D"""', 'color': '"""purple"""', 'label': '"""ECO Group Virial Radii"""'}), "(gihalon, gihalorvir, marker='D', color='purple', label=\n 'ECO Group Virial Radii')\n", (9412, 9498), True, 'import matplotlib.pyplot as plt\n'), ((9499, 9594), 'matplotlib.pyplot.plot', 'plt.plot', (['ecogiantgrpn[sel]', 'relprojdist[sel]', '"""r."""'], {'alpha': '(0.2)', 'label': '"""ECO Giant Galaxies"""'}), "(ecogiantgrpn[sel], relprojdist[sel], 'r.', alpha=0.2, label=\n 'ECO Giant Galaxies')\n", (9507, 9594), True, 'import matplotlib.pyplot as plt\n'), ((9594, 9761), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (['uniqecogiantgrpn[keepcalsel]', 'median_relprojdist'], {'fmt': '"""k^"""', 'label': '"""$R_{\\\\rm proj}$ (Median of $R_{\\\\rm proj,\\\\, gal}$)"""', 'yerr': 'rproj_median_error'}), "(uniqecogiantgrpn[keepcalsel], median_relprojdist, fmt='k^',\n label='$R_{\\\\rm proj}$ (Median of $R_{\\\\rm proj,\\\\, gal}$)', yerr=\n rproj_median_error)\n", (9606, 9761), True, 'import matplotlib.pyplot as plt\n'), ((9939, 9994), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Number of Giant Members in Galaxy\'s Group"""'], {}), '("Number of Giant Members in Galaxy\'s Group")\n', (9949, 9994), True, 'import matplotlib.pyplot as plt\n'), ((9999, 10066), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Projected Distance from Giant to Group Center [Mpc/h]"""'], {}), "('Projected Distance from Giant to Group Center [Mpc/h]')\n", (10009, 10066), True, 'import matplotlib.pyplot as plt\n'), ((10071, 10093), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""'}), "(loc='best')\n", (10081, 10093), True, 'import matplotlib.pyplot as plt\n'), ((10174, 10184), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (10182, 10184), True, 'import matplotlib.pyplot as plt\n'), ((10630, 10741), 'foftools.group_skycoords', 'fof.group_skycoords', (['resbradeg[resbgiantsel]', 'resbdedeg[resbgiantsel]', 'resbcz[resbgiantsel]', 'resbgiantfofid'], {}), '(resbradeg[resbgiantsel], resbdedeg[resbgiantsel],\n resbcz[resbgiantsel], resbgiantfofid)\n', (10649, 10741), True, 'import foftools as fof\n'), ((10758, 10822), 'foftools.multiplicity_function', 'fof.multiplicity_function', (['resbgiantfofid'], {'return_by_galaxy': '(True)'}), '(resbgiantfofid, return_by_galaxy=True)\n', (10783, 10822), True, 'import foftools as fof\n'), ((11963, 12021), 'foftools.multiplicity_function', 'fof.multiplicity_function', (['ecog3grp'], {'return_by_galaxy': '(True)'}), '(ecog3grp, return_by_galaxy=True)\n', (11988, 12021), True, 'import foftools as fof\n'), ((12344, 12444), 'foftools.group_skycoords', 'fof.group_skycoords', (['ecoradeg[ecogdsel]', 'ecodedeg[ecogdsel]', 'ecocz[ecogdsel]', 'ecog3grp[ecogdsel]'], {}), '(ecoradeg[ecogdsel], ecodedeg[ecogdsel], ecocz[ecogdsel],\n ecog3grp[ecogdsel])\n', (12363, 12444), True, 'import foftools as fof\n'), ((12459, 12495), 'numpy.abs', 'np.abs', (['(ecogdgrpcz - ecocz[ecogdsel])'], {}), '(ecogdgrpcz - ecocz[ecogdsel])\n', (12465, 12495), True, 'import numpy as np\n'), ((12702, 12760), 'iterativecombination.get_int_mass', 'ic.get_int_mass', (['ecologmstar[ecogdsel]', 'ecog3grp[ecogdsel]'], {}), '(ecologmstar[ecogdsel], ecog3grp[ecogdsel])\n', (12717, 12760), True, 'import iterativecombination as ic\n'), ((12775, 12800), 'numpy.arange', 'np.arange', (['(9.75)', '(14)', '(0.15)'], {}), '(9.75, 14, 0.15)\n', (12784, 12800), True, 'import numpy as np\n'), ((12920, 13020), 'center_binned_stats.center_binned_stats', 'center_binned_stats', (['ecogdtotalmass[binsel]', 'ecogdrelprojdist[binsel]', 'np.median'], {'bins': 'massbins'}), '(ecogdtotalmass[binsel], ecogdrelprojdist[binsel], np.\n median, bins=massbins)\n', (12939, 13020), False, 'from center_binned_stats import center_binned_stats\n'), ((13328, 13422), 'center_binned_stats.center_binned_stats', 'center_binned_stats', (['ecogdtotalmass[binsel]', 'ecogdrelvel[binsel]', 'np.median'], {'bins': 'massbins'}), '(ecogdtotalmass[binsel], ecogdrelvel[binsel], np.median,\n bins=massbins)\n', (13347, 13422), False, 'from center_binned_stats import center_binned_stats\n'), ((13730, 13830), 'center_binned_stats.center_binned_stats', 'center_binned_stats', (['ecogdtotalmass[binsel]', 'ecogdrelprojdist[binsel]', 'sigmarange'], {'bins': 'massbins'}), '(ecogdtotalmass[binsel], ecogdrelprojdist[binsel],\n sigmarange, bins=massbins)\n', (13749, 13830), False, 'from center_binned_stats import center_binned_stats\n'), ((13860, 13954), 'center_binned_stats.center_binned_stats', 'center_binned_stats', (['ecogdtotalmass[binsel]', 'ecogdrelvel[binsel]', 'np.median'], {'bins': 'massbins'}), '(ecogdtotalmass[binsel], ecogdrelvel[binsel], np.median,\n bins=massbins)\n', (13879, 13954), False, 'from center_binned_stats import center_binned_stats\n'), ((13988, 14083), 'center_binned_stats.center_binned_stats', 'center_binned_stats', (['ecogdtotalmass[binsel]', 'ecogdrelvel[binsel]', 'sigmarange'], {'bins': 'massbins'}), '(ecogdtotalmass[binsel], ecogdrelvel[binsel], sigmarange,\n bins=massbins)\n', (14007, 14083), False, 'from center_binned_stats import center_binned_stats\n'), ((14093, 14116), 'numpy.isnan', 'np.isnan', (['gdmedianrproj'], {}), '(gdmedianrproj)\n', (14101, 14116), True, 'import numpy as np\n'), ((14298, 14422), 'scipy.optimize.curve_fit', 'curve_fit', (['exp', 'massbincenters[~nansel]', 'gdmedianrproj[~nansel]'], {'p0': 'guess', 'maxfev': '(5000)', 'sigma': 'gdmedianrproj_err[~nansel]'}), '(exp, massbincenters[~nansel], gdmedianrproj[~nansel], p0=guess,\n maxfev=5000, sigma=gdmedianrproj_err[~nansel])\n', (14307, 14422), False, 'from scipy.optimize import curve_fit\n'), ((14467, 14572), 'scipy.optimize.curve_fit', 'curve_fit', (['exp', 'massbincenters[~nansel]', 'gdmedianrelvel[~nansel]'], {'p0': '[3e-05, 0.4, 0.005]', 'maxfev': '(5000)'}), '(exp, massbincenters[~nansel], gdmedianrelvel[~nansel], p0=[3e-05,\n 0.4, 0.005], maxfev=5000)\n', (14476, 14572), False, 'from scipy.optimize import curve_fit\n'), ((14638, 14661), 'numpy.linspace', 'np.linspace', (['(7)', '(15)', '(100)'], {}), '(7, 15, 100)\n', (14649, 14661), True, 'import numpy as np\n'), ((14664, 14676), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (14674, 14676), True, 'import matplotlib.pyplot as plt\n'), ((14681, 14695), 'matplotlib.pyplot.axhline', 'plt.axhline', (['(0)'], {}), '(0)\n', (14692, 14695), True, 'import matplotlib.pyplot as plt\n'), ((14700, 14827), 'matplotlib.pyplot.plot', 'plt.plot', (['ecogdtotalmass[binsel]', 'ecogdrelprojdist[binsel]', '"""k."""'], {'alpha': '(0.2)', 'label': '"""ECO Galaxies in N>1 Giant+Dwarf Groups"""'}), "(ecogdtotalmass[binsel], ecogdrelprojdist[binsel], 'k.', alpha=0.2,\n label='ECO Galaxies in N>1 Giant+Dwarf Groups')\n", (14708, 14827), True, 'import matplotlib.pyplot as plt\n'), ((14895, 14993), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (['massbincenters', 'gdmedianrproj'], {'yerr': 'gdmedianrproj_err', 'fmt': '"""r^"""', 'label': '"""Median"""'}), "(massbincenters, gdmedianrproj, yerr=gdmedianrproj_err, fmt=\n 'r^', label='Median')\n", (14907, 14993), True, 'import matplotlib.pyplot as plt\n'), ((15117, 15179), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Integrated Stellar Mass of Giant + Dwarf Members"""'], {}), "('Integrated Stellar Mass of Giant + Dwarf Members')\n", (15127, 15179), True, 'import matplotlib.pyplot as plt\n'), ((15185, 15253), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Projected Distance from Galaxy to Group Center [Mpc/h]"""'], {}), "('Projected Distance from Galaxy to Group Center [Mpc/h]')\n", (15195, 15253), True, 'import matplotlib.pyplot as plt\n'), ((15258, 15280), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""'}), "(loc='best')\n", (15268, 15280), True, 'import matplotlib.pyplot as plt\n'), ((15285, 15304), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(9.5)', '(13.2)'], {}), '(9.5, 13.2)\n', (15293, 15304), True, 'import matplotlib.pyplot as plt\n'), ((15308, 15322), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(3)'], {}), '(0, 3)\n', (15316, 15322), True, 'import matplotlib.pyplot as plt\n'), ((15349, 15359), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (15357, 15359), True, 'import matplotlib.pyplot as plt\n'), ((15365, 15377), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (15375, 15377), True, 'import matplotlib.pyplot as plt\n'), ((15382, 15505), 'matplotlib.pyplot.plot', 'plt.plot', (['ecogdtotalmass[binsel]', 'ecogdrelvel[binsel]', '"""k."""'], {'alpha': '(0.2)', 'label': '"""Mock Galaxies in N=2 Giant+Dwarf Groups"""'}), "(ecogdtotalmass[binsel], ecogdrelvel[binsel], 'k.', alpha=0.2,\n label='Mock Galaxies in N=2 Giant+Dwarf Groups')\n", (15390, 15505), True, 'import matplotlib.pyplot as plt\n'), ((15574, 15674), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (['massbincenters', 'gdmedianrelvel'], {'yerr': 'gdmedianrelvel_err', 'fmt': '"""r^"""', 'label': '"""Median"""'}), "(massbincenters, gdmedianrelvel, yerr=gdmedianrelvel_err, fmt=\n 'r^', label='Median')\n", (15586, 15674), True, 'import matplotlib.pyplot as plt\n'), ((15804, 15867), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Relative Velocity between Galaxy and Group Center"""'], {}), "('Relative Velocity between Galaxy and Group Center')\n", (15814, 15867), True, 'import matplotlib.pyplot as plt\n'), ((15872, 15934), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Integrated Stellar Mass of Giant + Dwarf Members"""'], {}), "('Integrated Stellar Mass of Giant + Dwarf Members')\n", (15882, 15934), True, 'import matplotlib.pyplot as plt\n'), ((15940, 15957), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(9.5)', '(13)'], {}), '(9.5, 13)\n', (15948, 15957), True, 'import matplotlib.pyplot as plt\n'), ((15961, 15978), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(2000)'], {}), '(0, 2000)\n', (15969, 15978), True, 'import matplotlib.pyplot as plt\n'), ((15982, 16004), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""'}), "(loc='best')\n", (15992, 16004), True, 'import matplotlib.pyplot as plt\n'), ((16009, 16019), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (16017, 16019), True, 'import matplotlib.pyplot as plt\n'), ((16282, 16345), 'foftools.multiplicity_function', 'fof.multiplicity_function', (['resbana_g3grp'], {'return_by_galaxy': '(True)'}), '(resbana_g3grp, return_by_galaxy=True)\n', (16307, 16345), True, 'import foftools as fof\n'), ((16744, 16870), 'foftools.group_skycoords', 'fof.group_skycoords', (['ecoradeg[resbana_gdsel]', 'ecodedeg[resbana_gdsel]', 'ecocz[resbana_gdsel]', 'resbana_g3grp[resbana_gdsel]'], {}), '(ecoradeg[resbana_gdsel], ecodedeg[resbana_gdsel], ecocz\n [resbana_gdsel], resbana_g3grp[resbana_gdsel])\n', (16763, 16870), True, 'import foftools as fof\n'), ((16889, 16935), 'numpy.abs', 'np.abs', (['(resbana_gdgrpcz - ecocz[resbana_gdsel])'], {}), '(resbana_gdgrpcz - ecocz[resbana_gdsel])\n', (16895, 16935), True, 'import numpy as np\n'), ((17198, 17271), 'iterativecombination.get_int_mass', 'ic.get_int_mass', (['ecologmstar[resbana_gdsel]', 'resbana_g3grp[resbana_gdsel]'], {}), '(ecologmstar[resbana_gdsel], resbana_g3grp[resbana_gdsel])\n', (17213, 17271), True, 'import iterativecombination as ic\n'), ((17287, 17312), 'numpy.arange', 'np.arange', (['(9.75)', '(14)', '(0.15)'], {}), '(9.75, 14, 0.15)\n', (17296, 17312), True, 'import numpy as np\n'), ((17444, 17557), 'center_binned_stats.center_binned_stats', 'center_binned_stats', (['resbana_gdtotalmass[binsel2]', 'resbana_gdrelprojdist[binsel2]', 'np.median'], {'bins': 'massbins2'}), '(resbana_gdtotalmass[binsel2], resbana_gdrelprojdist[\n binsel2], np.median, bins=massbins2)\n', (17463, 17557), False, 'from center_binned_stats import center_binned_stats\n'), ((17589, 17703), 'center_binned_stats.center_binned_stats', 'center_binned_stats', (['resbana_gdtotalmass[binsel2]', 'resbana_gdrelprojdist[binsel2]', 'sigmarange'], {'bins': 'massbins2'}), '(resbana_gdtotalmass[binsel2], resbana_gdrelprojdist[\n binsel2], sigmarange, bins=massbins2)\n', (17608, 17703), False, 'from center_binned_stats import center_binned_stats\n'), ((17733, 17840), 'center_binned_stats.center_binned_stats', 'center_binned_stats', (['resbana_gdtotalmass[binsel2]', 'resbana_gdrelvel[binsel2]', 'np.median'], {'bins': 'massbins2'}), '(resbana_gdtotalmass[binsel2], resbana_gdrelvel[binsel2],\n np.median, bins=massbins2)\n', (17752, 17840), False, 'from center_binned_stats import center_binned_stats\n'), ((17874, 17982), 'center_binned_stats.center_binned_stats', 'center_binned_stats', (['resbana_gdtotalmass[binsel2]', 'resbana_gdrelvel[binsel2]', 'sigmarange'], {'bins': 'massbins2'}), '(resbana_gdtotalmass[binsel2], resbana_gdrelvel[binsel2],\n sigmarange, bins=massbins2)\n', (17893, 17982), False, 'from center_binned_stats import center_binned_stats\n'), ((17994, 18017), 'numpy.isnan', 'np.isnan', (['gdmedianrproj'], {}), '(gdmedianrproj)\n', (18002, 18017), True, 'import numpy as np\n'), ((18042, 18153), 'scipy.optimize.curve_fit', 'curve_fit', (['exp', 'massbincenters[~nansel]', 'gdmedianrproj[~nansel]'], {'p0': 'poptr', 'sigma': 'gdmedianrproj_err[~nansel]'}), '(exp, massbincenters[~nansel], gdmedianrproj[~nansel], p0=poptr,\n sigma=gdmedianrproj_err[~nansel])\n', (18051, 18153), False, 'from scipy.optimize import curve_fit\n'), ((18203, 18316), 'scipy.optimize.curve_fit', 'curve_fit', (['exp', 'massbincenters[~nansel]', 'gdmedianrelvel[~nansel]'], {'p0': 'poptv', 'sigma': 'gdmedianrelvel_err[~nansel]'}), '(exp, massbincenters[~nansel], gdmedianrelvel[~nansel], p0=poptv,\n sigma=gdmedianrelvel_err[~nansel])\n', (18212, 18316), False, 'from scipy.optimize import curve_fit\n'), ((18344, 18362), 'numpy.linspace', 'np.linspace', (['(7)', '(15)'], {}), '(7, 15)\n', (18355, 18362), True, 'import numpy as np\n'), ((18366, 18378), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (18376, 18378), True, 'import matplotlib.pyplot as plt\n'), ((18383, 18523), 'matplotlib.pyplot.plot', 'plt.plot', (['resbana_gdtotalmass[binsel2]', 'resbana_gdrelprojdist[binsel2]', '"""k."""'], {'alpha': '(0.2)', 'label': '"""Mock Galaxies in N>1 Giant+Dwarf Groups"""'}), "(resbana_gdtotalmass[binsel2], resbana_gdrelprojdist[binsel2], 'k.',\n alpha=0.2, label='Mock Galaxies in N>1 Giant+Dwarf Groups')\n", (18391, 18523), True, 'import matplotlib.pyplot as plt\n'), ((18524, 18616), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (['massbincenters', 'gdmedianrproj', 'gdmedianrproj_err'], {'fmt': '"""r^"""', 'label': '"""Median"""'}), "(massbincenters, gdmedianrproj, gdmedianrproj_err, fmt='r^',\n label='Median')\n", (18536, 18616), True, 'import matplotlib.pyplot as plt\n'), ((18758, 18820), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Integrated Stellar Mass of Giant + Dwarf Members"""'], {}), "('Integrated Stellar Mass of Giant + Dwarf Members')\n", (18768, 18820), True, 'import matplotlib.pyplot as plt\n'), ((18826, 18894), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Projected Distance from Galaxy to Group Center [Mpc/h]"""'], {}), "('Projected Distance from Galaxy to Group Center [Mpc/h]')\n", (18836, 18894), True, 'import matplotlib.pyplot as plt\n'), ((18899, 18921), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""'}), "(loc='best')\n", (18909, 18921), True, 'import matplotlib.pyplot as plt\n'), ((18926, 18943), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(9.5)', '(13)'], {}), '(9.5, 13)\n', (18934, 18943), True, 'import matplotlib.pyplot as plt\n'), ((18947, 18961), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(3)'], {}), '(0, 3)\n', (18955, 18961), True, 'import matplotlib.pyplot as plt\n'), ((18965, 18975), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (18973, 18975), True, 'import matplotlib.pyplot as plt\n'), ((18981, 18993), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (18991, 18993), True, 'import matplotlib.pyplot as plt\n'), ((18998, 19133), 'matplotlib.pyplot.plot', 'plt.plot', (['resbana_gdtotalmass[binsel2]', 'resbana_gdrelvel[binsel2]', '"""k."""'], {'alpha': '(0.2)', 'label': '"""Mock Galaxies in N=2 Giant+Dwarf Groups"""'}), "(resbana_gdtotalmass[binsel2], resbana_gdrelvel[binsel2], 'k.',\n alpha=0.2, label='Mock Galaxies in N=2 Giant+Dwarf Groups')\n", (19006, 19133), True, 'import matplotlib.pyplot as plt\n'), ((19134, 19235), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (['massbincenters', 'gdmedianrelvel'], {'yerr': 'gdmedianrelvel_err', 'fmt': '"""r^"""', 'label': '"""Medians"""'}), "(massbincenters, gdmedianrelvel, yerr=gdmedianrelvel_err, fmt=\n 'r^', label='Medians')\n", (19146, 19235), True, 'import matplotlib.pyplot as plt\n'), ((19380, 19443), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Relative Velocity between Galaxy and Group Center"""'], {}), "('Relative Velocity between Galaxy and Group Center')\n", (19390, 19443), True, 'import matplotlib.pyplot as plt\n'), ((19448, 19510), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Integrated Stellar Mass of Giant + Dwarf Members"""'], {}), "('Integrated Stellar Mass of Giant + Dwarf Members')\n", (19458, 19510), True, 'import matplotlib.pyplot as plt\n'), ((19516, 19533), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(9.5)', '(13)'], {}), '(9.5, 13)\n', (19524, 19533), True, 'import matplotlib.pyplot as plt\n'), ((19537, 19554), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(2000)'], {}), '(0, 2000)\n', (19545, 19554), True, 'import matplotlib.pyplot as plt\n'), ((19558, 19580), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""'}), "(loc='best')\n", (19568, 19580), True, 'import matplotlib.pyplot as plt\n'), ((19585, 19595), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (19593, 19595), True, 'import matplotlib.pyplot as plt\n'), ((20060, 20118), 'foftools.multiplicity_function', 'fof.multiplicity_function', (['ecog3grp'], {'return_by_galaxy': '(True)'}), '(ecog3grp, return_by_galaxy=True)\n', (20085, 20118), True, 'import foftools as fof\n'), ((20144, 20203), 'foftools.multiplicity_function', 'fof.multiplicity_function', (['resbg3grp'], {'return_by_galaxy': '(True)'}), '(resbg3grp, return_by_galaxy=True)\n', (20169, 20203), True, 'import foftools as fof\n'), ((20233, 20296), 'foftools.multiplicity_function', 'fof.multiplicity_function', (['resbana_g3grp'], {'return_by_galaxy': '(True)'}), '(resbana_g3grp, return_by_galaxy=True)\n', (20258, 20296), True, 'import foftools as fof\n'), ((22127, 22139), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (22137, 22139), True, 'import matplotlib.pyplot as plt\n'), ((22151, 22176), 'numpy.arange', 'np.arange', (['(0.5)', '(1200.5)', '(3)'], {}), '(0.5, 1200.5, 3)\n', (22160, 22176), True, 'import numpy as np\n'), ((22508, 22559), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Number of Giant + Dwarf Group Members"""'], {}), "('Number of Giant + Dwarf Group Members')\n", (22518, 22559), True, 'import matplotlib.pyplot as plt\n'), ((22564, 22594), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Number of Groups"""'], {}), "('Number of Groups')\n", (22574, 22594), True, 'import matplotlib.pyplot as plt\n'), ((22599, 22621), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""'}), "(loc='best')\n", (22609, 22621), True, 'import matplotlib.pyplot as plt\n'), ((22626, 22642), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(100)'], {}), '(0, 100)\n', (22634, 22642), True, 'import matplotlib.pyplot as plt\n'), ((22646, 22656), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (22654, 22656), True, 'import matplotlib.pyplot as plt\n'), ((22954, 23164), 'iterativecombination.HAMwrapper', 'ic.HAMwrapper', (['ecoradeg[resbana_hamsel]', 'ecodedeg[resbana_hamsel]', 'ecocz[resbana_hamsel]', 'ecologmstar[resbana_hamsel]', 'resbana_g3grp[resbana_hamsel]', 'ecovolume'], {'inputfilename': 'None', 'outputfilename': 'None'}), '(ecoradeg[resbana_hamsel], ecodedeg[resbana_hamsel], ecocz[\n resbana_hamsel], ecologmstar[resbana_hamsel], resbana_g3grp[\n resbana_hamsel], ecovolume, inputfilename=None, outputfilename=None)\n', (22967, 23164), True, 'import iterativecombination as ic\n'), ((23243, 23275), 'numpy.log10', 'np.log10', (['(10 ** resbana_halomass)'], {}), '(10 ** resbana_halomass)\n', (23251, 23275), True, 'import numpy as np\n'), ((23359, 23418), 'numpy.unique', 'np.unique', (['resbana_g3grp[resbana_hamsel]'], {'return_index': '(True)'}), '(resbana_g3grp[resbana_hamsel], return_index=True)\n', (23368, 23418), True, 'import numpy as np\n'), ((23542, 23569), 'numpy.argsort', 'np.argsort', (['resbana_intmass'], {}), '(resbana_intmass)\n', (23552, 23569), True, 'import numpy as np\n'), ((23634, 23707), 'scipy.interpolate.interp1d', 'interp1d', (['sortedmass', 'resbana_halomass[sortind]'], {'fill_value': '"""extrapolate"""'}), "(sortedmass, resbana_halomass[sortind], fill_value='extrapolate')\n", (23642, 23707), False, 'from scipy.interpolate import interp1d\n'), ((23727, 23812), 'iterativecombination.get_int_mass', 'ic.get_int_mass', (['resblogmstar[resbg3grp != -99.0]', 'resbg3grp[resbg3grp != -99.0]'], {}), '(resblogmstar[resbg3grp != -99.0], resbg3grp[resbg3grp != -99.0]\n )\n', (23742, 23812), True, 'import iterativecombination as ic\n'), ((23976, 24155), 'iterativecombination.HAMwrapper', 'ic.HAMwrapper', (['ecoradeg[ecohamsel]', 'ecodedeg[ecohamsel]', 'ecocz[ecohamsel]', 'ecologmstar[ecohamsel]', 'ecog3grp[ecohamsel]', 'ecovolume'], {'inputfilename': 'None', 'outputfilename': 'None'}), '(ecoradeg[ecohamsel], ecodedeg[ecohamsel], ecocz[ecohamsel],\n ecologmstar[ecohamsel], ecog3grp[ecohamsel], ecovolume, inputfilename=\n None, outputfilename=None)\n', (23989, 24155), True, 'import iterativecombination as ic\n'), ((24223, 24272), 'numpy.unique', 'np.unique', (['ecog3grp[ecohamsel]'], {'return_index': '(True)'}), '(ecog3grp[ecohamsel], return_index=True)\n', (24232, 24272), True, 'import numpy as np\n'), ((24631, 24691), 'iterativecombination.get_int_mass', 'ic.get_int_mass', (['ecologmstar[ecohamsel]', 'ecog3grp[ecohamsel]'], {}), '(ecologmstar[ecohamsel], ecog3grp[ecohamsel])\n', (24646, 24691), True, 'import iterativecombination as ic\n'), ((24696, 24708), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (24706, 24708), True, 'import matplotlib.pyplot as plt\n'), ((24713, 24831), 'matplotlib.pyplot.plot', 'plt.plot', (['ecointmass', 'ecog3logmh[ecog3grp != -99.0]', '"""."""'], {'color': '"""palegreen"""', 'alpha': '(0.6)', 'label': '"""ECO"""', 'markersize': '(11)'}), "(ecointmass, ecog3logmh[ecog3grp != -99.0], '.', color='palegreen',\n alpha=0.6, label='ECO', markersize=11)\n", (24721, 24831), True, 'import matplotlib.pyplot as plt\n'), ((24829, 24936), 'matplotlib.pyplot.plot', 'plt.plot', (['resbintmass', 'resbg3logmh[resbg3grp != -99.0]', '"""k."""'], {'alpha': '(1)', 'label': '"""RESOLVE-B"""', 'markersize': '(3)'}), "(resbintmass, resbg3logmh[resbg3grp != -99.0], 'k.', alpha=1, label\n ='RESOLVE-B', markersize=3)\n", (24837, 24936), True, 'import matplotlib.pyplot as plt\n'), ((24946, 24993), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""group-integrated log stellar mass"""'], {}), "('group-integrated log stellar mass')\n", (24956, 24993), True, 'import matplotlib.pyplot as plt\n'), ((24998, 25043), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""group halo mass (log$M_\\\\odot$)"""'], {}), "('group halo mass (log$M_\\\\odot$)')\n", (25008, 25043), True, 'import matplotlib.pyplot as plt\n'), ((25048, 25070), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""'}), "(loc='best')\n", (25058, 25070), True, 'import matplotlib.pyplot as plt\n'), ((25075, 25085), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (25083, 25085), True, 'import matplotlib.pyplot as plt\n'), ((25310, 25368), 'foftools.multiplicity_function', 'fof.multiplicity_function', (['ecog3grp'], {'return_by_galaxy': '(True)'}), '(ecog3grp, return_by_galaxy=True)\n', (25335, 25368), True, 'import foftools as fof\n'), ((25470, 25489), 'numpy.unique', 'np.unique', (['ecog3grp'], {}), '(ecog3grp)\n', (25479, 25489), True, 'import numpy as np\n'), ((25888, 25944), 'foftools.group_skycoords', 'fof.group_skycoords', (['ecoradeg', 'ecodedeg', 'ecocz', 'ecog3grp'], {}), '(ecoradeg, ecodedeg, ecocz, ecog3grp)\n', (25907, 25944), True, 'import foftools as fof\n'), ((26081, 26124), 'foftools.get_central_flag', 'fof.get_central_flag', (['ecologmstar', 'ecog3grp'], {}), '(ecologmstar, ecog3grp)\n', (26101, 26124), True, 'import foftools as fof\n'), ((26143, 26207), 'foftools.get_outermost_galradius', 'fof.get_outermost_galradius', (['ecoradeg', 'ecodedeg', 'ecocz', 'ecog3grp'], {}), '(ecoradeg, ecodedeg, ecocz, ecog3grp)\n', (26170, 26207), True, 'import foftools as fof\n'), ((26294, 26351), 'foftools.get_rproj_czdisp', 'fof.get_rproj_czdisp', (['ecoradeg', 'ecodedeg', 'ecocz', 'ecog3grp'], {}), '(ecoradeg, ecodedeg, ecocz, ecog3grp)\n', (26314, 26351), True, 'import foftools as fof\n'), ((26420, 26457), 'iterativecombination.get_int_mass', 'ic.get_int_mass', (['ecologmgas', 'ecog3grp'], {}), '(ecologmgas, ecog3grp)\n', (26435, 26457), True, 'import iterativecombination as ic\n'), ((26478, 26516), 'iterativecombination.get_int_mass', 'ic.get_int_mass', (['ecologmstar', 'ecog3grp'], {}), '(ecologmstar, ecog3grp)\n', (26493, 26516), True, 'import iterativecombination as ic\n'), ((26535, 26562), 'virtools.AD_test', 'vz.AD_test', (['ecocz', 'ecog3grp'], {}), '(ecocz, ecog3grp)\n', (26545, 26562), True, 'import virtools as vz\n'), ((26581, 26640), 'virtools.group_crossing_time', 'vz.group_crossing_time', (['ecoradeg', 'ecodedeg', 'ecocz', 'ecog3grp'], {}), '(ecoradeg, ecodedeg, ecocz, ecog3grp)\n', (26603, 26640), True, 'import virtools as vz\n'), ((26661, 26714), 'virtools.group_color_gap', 'vz.group_color_gap', (['ecog3grp', 'ecologmstar', 'ecourcolor'], {}), '(ecog3grp, ecologmstar, ecourcolor)\n', (26679, 26714), True, 'import virtools as vz\n'), ((26733, 26797), 'virtools.fast_DS_test', 'vz.fast_DS_test', (['ecoradeg', 'ecodedeg', 'ecocz', 'ecog3grp'], {'niter': '(2500)'}), '(ecoradeg, ecodedeg, ecocz, ecog3grp, niter=2500)\n', (26748, 26797), True, 'import virtools as vz\n'), ((26877, 27022), 'lss_dens.lss_dens_by_galaxy', 'lss_dens_by_galaxy', (['ecog3grp', 'ecoradeg', 'ecodedeg', 'ecocz', 'ecog3logmh'], {'Nnn': '(3)', 'rarange': '(130.05, 237.45)', 'decrange': '(-1, 50)', 'czrange': '(2530, 7470)'}), '(ecog3grp, ecoradeg, ecodedeg, ecocz, ecog3logmh, Nnn=3,\n rarange=(130.05, 237.45), decrange=(-1, 50), czrange=(2530, 7470))\n', (26895, 27022), False, 'from lss_dens import lss_dens_by_galaxy\n'), ((29033, 29059), 'numpy.array', 'np.array', (['resolvedata.name'], {}), '(resolvedata.name)\n', (29041, 29059), True, 'import numpy as np\n'), ((29079, 29097), 'numpy.full', 'np.full', (['sz', '(-99.0)'], {}), '(sz, -99.0)\n', (29086, 29097), True, 'import numpy as np\n'), ((29119, 29137), 'numpy.full', 'np.full', (['sz', '(-99.0)'], {}), '(sz, -99.0)\n', (29126, 29137), True, 'import numpy as np\n'), ((29159, 29177), 'numpy.full', 'np.full', (['sz', '(-99.0)'], {}), '(sz, -99.0)\n', (29166, 29177), True, 'import numpy as np\n'), ((29201, 29219), 'numpy.full', 'np.full', (['sz', '(-99.0)'], {}), '(sz, -99.0)\n', (29208, 29219), True, 'import numpy as np\n'), ((29243, 29261), 'numpy.full', 'np.full', (['sz', '(-99.0)'], {}), '(sz, -99.0)\n', (29250, 29261), True, 'import numpy as np\n'), ((29282, 29300), 'numpy.full', 'np.full', (['sz', '(-99.0)'], {}), '(sz, -99.0)\n', (29289, 29300), True, 'import numpy as np\n'), ((29324, 29342), 'numpy.full', 'np.full', (['sz', '(-99.0)'], {}), '(sz, -99.0)\n', (29331, 29342), True, 'import numpy as np\n'), ((29363, 29381), 'numpy.full', 'np.full', (['sz', '(-99.0)'], {}), '(sz, -99.0)\n', (29370, 29381), True, 'import numpy as np\n'), ((29401, 29419), 'numpy.full', 'np.full', (['sz', '(-99.0)'], {}), '(sz, -99.0)\n', (29408, 29419), True, 'import numpy as np\n'), ((29440, 29458), 'numpy.full', 'np.full', (['sz', '(-99.0)'], {}), '(sz, -99.0)\n', (29447, 29458), True, 'import numpy as np\n'), ((29475, 29493), 'numpy.full', 'np.full', (['sz', '(-99.0)'], {}), '(sz, -99.0)\n', (29482, 29493), True, 'import numpy as np\n'), ((29514, 29532), 'numpy.full', 'np.full', (['sz', '(-99.0)'], {}), '(sz, -99.0)\n', (29521, 29532), True, 'import numpy as np\n'), ((29552, 29570), 'numpy.full', 'np.full', (['sz', '(-99.0)'], {}), '(sz, -99.0)\n', (29559, 29570), True, 'import numpy as np\n'), ((29591, 29609), 'numpy.full', 'np.full', (['sz', '(-99.0)'], {}), '(sz, -99.0)\n', (29598, 29609), True, 'import numpy as np\n'), ((29633, 29651), 'numpy.full', 'np.full', (['sz', '(-99.0)'], {}), '(sz, -99.0)\n', (29640, 29651), True, 'import numpy as np\n'), ((29673, 29691), 'numpy.full', 'np.full', (['sz', '(-99.0)'], {}), '(sz, -99.0)\n', (29680, 29691), True, 'import numpy as np\n'), ((29713, 29731), 'numpy.full', 'np.full', (['sz', '(-99.0)'], {}), '(sz, -99.0)\n', (29720, 29731), True, 'import numpy as np\n'), ((29755, 29773), 'numpy.full', 'np.full', (['sz', '(-99.0)'], {}), '(sz, -99.0)\n', (29762, 29773), True, 'import numpy as np\n'), ((29795, 29813), 'numpy.full', 'np.full', (['sz', '(-99.0)'], {}), '(sz, -99.0)\n', (29802, 29813), True, 'import numpy as np\n'), ((29834, 29852), 'numpy.full', 'np.full', (['sz', '(-99.0)'], {}), '(sz, -99.0)\n', (29841, 29852), True, 'import numpy as np\n'), ((29876, 29894), 'numpy.full', 'np.full', (['sz', '(-99.0)'], {}), '(sz, -99.0)\n', (29883, 29894), True, 'import numpy as np\n'), ((29918, 29936), 'numpy.full', 'np.full', (['sz', '(-99.0)'], {}), '(sz, -99.0)\n', (29925, 29936), True, 'import numpy as np\n'), ((29962, 29980), 'numpy.full', 'np.full', (['sz', '(-99.0)'], {}), '(sz, -99.0)\n', (29969, 29980), True, 'import numpy as np\n'), ((30007, 30025), 'numpy.full', 'np.full', (['sz', '(-99.0)'], {}), '(sz, -99.0)\n', (30014, 30025), True, 'import numpy as np\n'), ((30133, 30153), 'numpy.unique', 'np.unique', (['resbg3grp'], {}), '(resbg3grp)\n', (30142, 30153), True, 'import numpy as np\n'), ((30562, 30622), 'foftools.group_skycoords', 'fof.group_skycoords', (['resbradeg', 'resbdedeg', 'resbcz', 'resbg3grp'], {}), '(resbradeg, resbdedeg, resbcz, resbg3grp)\n', (30581, 30622), True, 'import foftools as fof\n'), ((30644, 30684), 'iterativecombination.get_int_mass', 'ic.get_int_mass', (['resblogmstar', 'resbg3grp'], {}), '(resblogmstar, resbg3grp)\n', (30659, 30684), True, 'import iterativecombination as ic\n'), ((30828, 30873), 'foftools.get_central_flag', 'fof.get_central_flag', (['resblogmstar', 'resbg3grp'], {}), '(resblogmstar, resbg3grp)\n', (30848, 30873), True, 'import foftools as fof\n'), ((30893, 30961), 'foftools.get_outermost_galradius', 'fof.get_outermost_galradius', (['resbradeg', 'resbdedeg', 'resbcz', 'resbg3grp'], {}), '(resbradeg, resbdedeg, resbcz, resbg3grp)\n', (30920, 30961), True, 'import foftools as fof\n'), ((31052, 31113), 'foftools.get_rproj_czdisp', 'fof.get_rproj_czdisp', (['resbradeg', 'resbdedeg', 'resbcz', 'resbg3grp'], {}), '(resbradeg, resbdedeg, resbcz, resbg3grp)\n', (31072, 31113), True, 'import foftools as fof\n'), ((31186, 31225), 'iterativecombination.get_int_mass', 'ic.get_int_mass', (['resblogmgas', 'resbg3grp'], {}), '(resblogmgas, resbg3grp)\n', (31201, 31225), True, 'import iterativecombination as ic\n'), ((31247, 31287), 'iterativecombination.get_int_mass', 'ic.get_int_mass', (['resblogmstar', 'resbg3grp'], {}), '(resblogmstar, resbg3grp)\n', (31262, 31287), True, 'import iterativecombination as ic\n'), ((31307, 31336), 'virtools.AD_test', 'vz.AD_test', (['resbcz', 'resbg3grp'], {}), '(resbcz, resbg3grp)\n', (31317, 31336), True, 'import virtools as vz\n'), ((31356, 31419), 'virtools.group_crossing_time', 'vz.group_crossing_time', (['resbradeg', 'resbdedeg', 'resbcz', 'resbg3grp'], {}), '(resbradeg, resbdedeg, resbcz, resbg3grp)\n', (31378, 31419), True, 'import virtools as vz\n'), ((31441, 31497), 'virtools.group_color_gap', 'vz.group_color_gap', (['resbg3grp', 'resblogmstar', 'resburcolor'], {}), '(resbg3grp, resblogmstar, resburcolor)\n', (31459, 31497), True, 'import virtools as vz\n'), ((31517, 31585), 'virtools.fast_DS_test', 'vz.fast_DS_test', (['resbradeg', 'resbdedeg', 'resbcz', 'resbg3grp'], {'niter': '(2500)'}), '(resbradeg, resbdedeg, resbcz, resbg3grp, niter=2500)\n', (31532, 31585), True, 'import virtools as vz\n'), ((31608, 31626), 'numpy.copy', 'np.copy', (['resbradeg'], {}), '(resbradeg)\n', (31615, 31626), True, 'import numpy as np\n'), ((31642, 31673), 'numpy.where', 'np.where', (['(resbradeg > 18 * 15.0)'], {}), '(resbradeg > 18 * 15.0)\n', (31650, 31673), True, 'import numpy as np\n'), ((31819, 31994), 'lss_dens.lss_dens_by_galaxy', 'lss_dens_by_galaxy', (['resbg3grp', 'RESB_RADEG_REMAPPED', 'resbdedeg', 'resbcz', 'resbg3logmh'], {'Nnn': '(3)', 'rarange': '(-2 * 15.0, 3 * 15.0)', 'decrange': '(-1.25, 1.25)', 'czrange': '(4250, 7250)'}), '(resbg3grp, RESB_RADEG_REMAPPED, resbdedeg, resbcz,\n resbg3logmh, Nnn=3, rarange=(-2 * 15.0, 3 * 15.0), decrange=(-1.25, \n 1.25), czrange=(4250, 7250))\n', (31837, 31994), False, 'from lss_dens import lss_dens_by_galaxy\n'), ((1739, 1748), 'numpy.abs', 'np.abs', (['a'], {}), '(a)\n', (1745, 1748), True, 'import numpy as np\n'), ((1804, 1813), 'numpy.abs', 'np.abs', (['a'], {}), '(a)\n', (1810, 1813), True, 'import numpy as np\n'), ((5223, 5301), 'foftools.multiplicity_function', 'fof.multiplicity_function', (['ecog3grp[ecog3grp != -99.0]'], {'return_by_galaxy': '(False)'}), '(ecog3grp[ecog3grp != -99.0], return_by_galaxy=False)\n', (5248, 5301), True, 'import foftools as fof\n'), ((5389, 5474), 'foftools.multiplicity_function', 'fof.multiplicity_function', (['resbg3grp[resbg3grp != -99.0]'], {'return_by_galaxy': '(False)'}), '(resbg3grp[resbg3grp != -99.0], return_by_galaxy=False\n )\n', (5414, 5474), True, 'import foftools as fof\n'), ((8449, 8479), 'numpy.sort', 'np.sort', (['ecog3grp[ecogiantsel]'], {}), '(ecog3grp[ecogiantsel])\n', (8456, 8479), True, 'import numpy as np\n'), ((12821, 12868), 'numpy.logical_and', 'np.logical_and', (['(ecogdn > 1)', '(ecogdtotalmass < 14)'], {}), '(ecogdn > 1, ecogdtotalmass < 14)\n', (12835, 12868), True, 'import numpy as np\n'), ((17334, 17392), 'numpy.logical_and', 'np.logical_and', (['(resbana_gdn > 1)', '(resbana_gdtotalmass > -24)'], {}), '(resbana_gdn > 1, resbana_gdtotalmass > -24)\n', (17348, 17392), True, 'import numpy as np\n'), ((22188, 22266), 'foftools.multiplicity_function', 'fof.multiplicity_function', (['ecog3grp[ecog3grp != -99.0]'], {'return_by_galaxy': '(False)'}), '(ecog3grp[ecog3grp != -99.0], return_by_galaxy=False)\n', (22213, 22266), True, 'import foftools as fof\n'), ((22349, 22434), 'foftools.multiplicity_function', 'fof.multiplicity_function', (['resbg3grp[resbg3grp != -99.0]'], {'return_by_galaxy': '(False)'}), '(resbg3grp[resbg3grp != -99.0], return_by_galaxy=False\n )\n', (22374, 22434), True, 'import foftools as fof\n'), ((23441, 23516), 'iterativecombination.get_int_mass', 'ic.get_int_mass', (['ecologmstar[resbana_hamsel]', 'resbana_g3grp[resbana_hamsel]'], {}), '(ecologmstar[resbana_hamsel], resbana_g3grp[resbana_hamsel])\n', (23456, 23516), True, 'import iterativecombination as ic\n'), ((23866, 23879), 'numpy.log10', 'np.log10', (['(0.7)'], {}), '(0.7)\n', (23874, 23879), True, 'import numpy as np\n'), ((24297, 24310), 'numpy.log10', 'np.log10', (['(0.7)'], {}), '(0.7)\n', (24305, 24310), True, 'import numpy as np\n'), ((24361, 24386), 'numpy.where', 'np.where', (['(ecog3grp == idv)'], {}), '(ecog3grp == idv)\n', (24369, 24386), True, 'import numpy as np\n'), ((25508, 25533), 'numpy.where', 'np.where', (['(ecog3grp == uid)'], {}), '(ecog3grp == uid)\n', (25516, 25533), True, 'import numpy as np\n'), ((30172, 30198), 'numpy.where', 'np.where', (['(resbg3grp == uid)'], {}), '(resbg3grp == uid)\n', (30180, 30198), True, 'import numpy as np\n'), ((6160, 6262), 'iterativecombination.angular_separation', 'ic.angular_separation', (['ecogiantgrpra', 'ecogiantgrpdec', 'ecoradeg[ecogiantsel]', 'ecodedeg[ecogiantsel]'], {}), '(ecogiantgrpra, ecogiantgrpdec, ecoradeg[ecogiantsel],\n ecodedeg[ecogiantsel])\n', (6181, 6262), True, 'import iterativecombination as ic\n'), ((12196, 12296), 'numpy.logical_or', 'np.logical_or', (['(ecog3grp == -99.0)', '((ecogdgrpn == 1) & (ecologmstar < 9.5) & (ecologmstar >= 8.9))'], {}), '(ecog3grp == -99.0, (ecogdgrpn == 1) & (ecologmstar < 9.5) & (\n ecologmstar >= 8.9))\n', (12209, 12296), True, 'import numpy as np\n'), ((12557, 12648), 'iterativecombination.angular_separation', 'ic.angular_separation', (['ecogdgrpra', 'ecogdgrpdec', 'ecoradeg[ecogdsel]', 'ecodedeg[ecogdsel]'], {}), '(ecogdgrpra, ecogdgrpdec, ecoradeg[ecogdsel], ecodedeg\n [ecogdsel])\n', (12578, 12648), True, 'import iterativecombination as ic\n'), ((16566, 16675), 'numpy.logical_or', 'np.logical_or', (['(resbana_g3grp == -99.0)', '((resbana_gdgrpn == 1) & (ecologmstar < 9.5) & (ecologmstar >= 8.7))'], {}), '(resbana_g3grp == -99.0, (resbana_gdgrpn == 1) & (ecologmstar <\n 9.5) & (ecologmstar >= 8.7))\n', (16579, 16675), True, 'import numpy as np\n'), ((17012, 17123), 'iterativecombination.angular_separation', 'ic.angular_separation', (['resbana_gdgrpra', 'resbana_gdgrpdec', 'ecoradeg[resbana_gdsel]', 'ecodedeg[resbana_gdsel]'], {}), '(resbana_gdgrpra, resbana_gdgrpdec, ecoradeg[\n resbana_gdsel], ecodedeg[resbana_gdsel])\n', (17033, 17123), True, 'import iterativecombination as ic\n'), ((25557, 25608), 'numpy.logical_and', 'np.logical_and', (['(ecog3grp == uid)', '(ecologmstar >= 9.5)'], {}), '(ecog3grp == uid, ecologmstar >= 9.5)\n', (25571, 25608), True, 'import numpy as np\n'), ((25634, 25684), 'numpy.logical_and', 'np.logical_and', (['(ecog3grp == uid)', '(ecologmstar < 9.5)'], {}), '(ecog3grp == uid, ecologmstar < 9.5)\n', (25648, 25684), True, 'import numpy as np\n'), ((25962, 26026), 'foftools.get_grprproj_e17', 'fof.get_grprproj_e17', (['ecoradeg', 'ecodedeg', 'ecocz', 'ecog3grp'], {'h': '(0.7)'}), '(ecoradeg, ecodedeg, ecocz, ecog3grp, h=0.7)\n', (25982, 26026), True, 'import foftools as fof\n'), ((30222, 30275), 'numpy.logical_and', 'np.logical_and', (['(resbg3grp == uid)', '(resblogmstar >= 9.5)'], {}), '(resbg3grp == uid, resblogmstar >= 9.5)\n', (30236, 30275), True, 'import numpy as np\n'), ((30301, 30353), 'numpy.logical_and', 'np.logical_and', (['(resbg3grp == uid)', '(resblogmstar < 9.5)'], {}), '(resbg3grp == uid, resblogmstar < 9.5)\n', (30315, 30353), True, 'import numpy as np\n'), ((30703, 30771), 'foftools.get_grprproj_e17', 'fof.get_grprproj_e17', (['resbradeg', 'resbdedeg', 'resbcz', 'resbg3grp'], {'h': '(0.7)'}), '(resbradeg, resbdedeg, resbcz, resbg3grp, h=0.7)\n', (30723, 30771), True, 'import foftools as fof\n'), ((33010, 33036), 'numpy.where', 'np.where', (['(ecoresname == nm)'], {}), '(ecoresname == nm)\n', (33018, 33036), True, 'import numpy as np\n'), ((20699, 20715), 'numpy.max', 'np.max', (['ecog3grp'], {}), '(ecog3grp)\n', (20705, 20715), True, 'import numpy as np\n'), ((21164, 21181), 'numpy.max', 'np.max', (['resbg3grp'], {}), '(resbg3grp)\n', (21170, 21181), True, 'import numpy as np\n'), ((21666, 21687), 'numpy.max', 'np.max', (['resbana_g3grp'], {}), '(resbana_g3grp)\n', (21672, 21687), True, 'import numpy as np\n'), ((34479, 34503), 'numpy.where', 'np.where', (['(resbname == nm)'], {}), '(resbname == nm)\n', (34487, 34503), True, 'import numpy as np\n'), ((1756, 1765), 'numpy.abs', 'np.abs', (['b'], {}), '(b)\n', (1762, 1765), True, 'import numpy as np\n'), ((6527, 6555), 'numpy.where', 'np.where', (['(ecogiantgrpn == sz)'], {}), '(ecogiantgrpn == sz)\n', (6535, 6555), True, 'import numpy as np\n'), ((6644, 6672), 'numpy.where', 'np.where', (['(ecogiantgrpn == sz)'], {}), '(ecogiantgrpn == sz)\n', (6652, 6672), True, 'import numpy as np\n'), ((1823, 1832), 'numpy.abs', 'np.abs', (['b'], {}), '(b)\n', (1829, 1832), True, 'import numpy as np\n'), ((6773, 6801), 'numpy.where', 'np.where', (['(ecogiantgrpn == sz)'], {}), '(ecogiantgrpn == sz)\n', (6781, 6801), True, 'import numpy as np\n'), ((6950, 6978), 'numpy.where', 'np.where', (['(ecogiantgrpn == sz)'], {}), '(ecogiantgrpn == sz)\n', (6958, 6978), True, 'import numpy as np\n')]
from types import MappingProxyType from typing import Any, Union, Mapping, Callable, Optional, Sequence from scanpy import logging as logg from dask import delayed from scipy.ndimage.filters import gaussian_filter as scipy_gf import numpy as np import dask.array as da from skimage.color import rgb2gray from skimage.util.dtype import img_as_float32 from dask_image.ndfilters import gaussian_filter as dask_gf from squidpy._docs import d, inject_docs from squidpy.im._container import ImageContainer from squidpy._constants._constants import Processing from squidpy._constants._pkg_constants import Key __all__ = ["process"] def to_grayscale(img: Union[np.ndarray, da.Array]) -> Union[np.ndarray, da.Array]: if img.shape[-1] != 3: raise ValueError(f"Expected channel dimension to be `3`, found `{img.shape[-1]}`.") if isinstance(img, da.Array): img = da.from_delayed(delayed(img_as_float32)(img), shape=img.shape, dtype=np.float32) coeffs = np.array([0.2125, 0.7154, 0.0721], dtype=img.dtype) return img @ coeffs return rgb2gray(img) @d.dedent @inject_docs(p=Processing) def process( img: ImageContainer, layer: Optional[str] = None, library_id: Optional[Union[str, Sequence[str]]] = None, method: Union[str, Callable[..., np.ndarray]] = "smooth", chunks: Optional[int] = None, lazy: bool = False, layer_added: Optional[str] = None, channel_dim: Optional[str] = None, copy: bool = False, apply_kwargs: Mapping[str, Any] = MappingProxyType({}), **kwargs: Any, ) -> Optional[ImageContainer]: """ Process an image by applying a transformation. Parameters ---------- %(img_container)s %(img_layer)s %(library_id)s If `None`, all Z-dimensions are processed at once, treating the image as a 3D volume. method Processing method to use. Valid options are: - `{p.SMOOTH.s!r}` - :func:`skimage.filters.gaussian`. - `{p.GRAY.s!r}` - :func:`skimage.color.rgb2gray`. %(custom_fn)s %(chunks_lazy)s %(layer_added)s If `None`, use ``'{{layer}}_{{method}}'``. channel_dim Name of the channel dimension of the new image layer. Default is the same as the original, if the processing function does not change the number of channels, and ``'{{channel}}_{{processing}}'`` otherwise. %(copy_cont)s apply_kwargs Keyword arguments for :meth:`squidpy.im.ImageContainer.apply`. kwargs Keyword arguments for ``method``. Returns ------- If ``copy = True``, returns a new container with the processed image in ``'{{layer_added}}'``. Otherwise, modifies the ``img`` with the following key: - :class:`squidpy.im.ImageContainer` ``['{{layer_added}}']`` - the processed image. Raises ------ NotImplementedError If ``method`` has not been implemented. """ layer = img._get_layer(layer) method = Processing(method) if isinstance(method, (str, Processing)) else method # type: ignore[assignment] apply_kwargs = dict(apply_kwargs) apply_kwargs["lazy"] = lazy if channel_dim is None: channel_dim = img[layer].dims[-1] layer_new = Key.img.process(method, layer, layer_added=layer_added) if callable(method): callback = method elif method == Processing.SMOOTH: # type: ignore[comparison-overlap] if library_id is None: expected_ndim = 4 kwargs.setdefault("sigma", [1, 1, 0, 0]) # y, x, z, c else: expected_ndim = 3 kwargs.setdefault("sigma", [1, 1, 0]) # y, x, c sigma = kwargs["sigma"] if isinstance(sigma, int): kwargs["sigma"] = sigma = [sigma, sigma] + [0] * (expected_ndim - 2) if len(sigma) != expected_ndim: raise ValueError(f"Expected `sigma` to be of length `{expected_ndim}`, found `{len(sigma)}`.") if chunks is not None: # dask_image already handles map_overlap chunks_, chunks = chunks, None callback = lambda arr, **kwargs: dask_gf(da.asarray(arr).rechunk(chunks_), **kwargs) # noqa: E731 else: callback = scipy_gf elif method == Processing.GRAY: # type: ignore[comparison-overlap] apply_kwargs["drop_axis"] = 3 callback = to_grayscale else: raise NotImplementedError(f"Method `{method}` is not yet implemented.") # to which library_ids should this function be applied? if library_id is not None: callback = {lid: callback for lid in img._get_library_ids(library_id)} # type: ignore[assignment] start = logg.info(f"Processing image using `{method}` method") res: ImageContainer = img.apply( callback, layer=layer, copy=True, drop=copy, chunks=chunks, fn_kwargs=kwargs, **apply_kwargs ) # if the method changes the number of channels if res[layer].shape[-1] != img[layer].shape[-1]: modifier = "_".join(layer_new.split("_")[1:]) if layer_added is None else layer_added channel_dim = f"{channel_dim}_{modifier}" res._data = res.data.rename({res[layer].dims[-1]: channel_dim}) logg.info("Finish", time=start) if copy: return res.rename(layer, layer_new) img.add_img( img=res[layer], layer=layer_new, copy=False, lazy=lazy, dims=res[layer].dims, library_id=img[layer].coords["z"].values, )
[ "skimage.color.rgb2gray", "dask.delayed", "squidpy._constants._constants.Processing", "types.MappingProxyType", "squidpy._constants._pkg_constants.Key.img.process", "dask.array.asarray", "numpy.array", "scanpy.logging.info", "squidpy._docs.inject_docs" ]
[((1101, 1126), 'squidpy._docs.inject_docs', 'inject_docs', ([], {'p': 'Processing'}), '(p=Processing)\n', (1112, 1126), False, 'from squidpy._docs import d, inject_docs\n'), ((1074, 1087), 'skimage.color.rgb2gray', 'rgb2gray', (['img'], {}), '(img)\n', (1082, 1087), False, 'from skimage.color import rgb2gray\n'), ((1518, 1538), 'types.MappingProxyType', 'MappingProxyType', (['{}'], {}), '({})\n', (1534, 1538), False, 'from types import MappingProxyType\n'), ((3224, 3279), 'squidpy._constants._pkg_constants.Key.img.process', 'Key.img.process', (['method', 'layer'], {'layer_added': 'layer_added'}), '(method, layer, layer_added=layer_added)\n', (3239, 3279), False, 'from squidpy._constants._pkg_constants import Key\n'), ((4664, 4718), 'scanpy.logging.info', 'logg.info', (['f"""Processing image using `{method}` method"""'], {}), "(f'Processing image using `{method}` method')\n", (4673, 4718), True, 'from scanpy import logging as logg\n'), ((5185, 5216), 'scanpy.logging.info', 'logg.info', (['"""Finish"""'], {'time': 'start'}), "('Finish', time=start)\n", (5194, 5216), True, 'from scanpy import logging as logg\n'), ((981, 1032), 'numpy.array', 'np.array', (['[0.2125, 0.7154, 0.0721]'], {'dtype': 'img.dtype'}), '([0.2125, 0.7154, 0.0721], dtype=img.dtype)\n', (989, 1032), True, 'import numpy as np\n'), ((2967, 2985), 'squidpy._constants._constants.Processing', 'Processing', (['method'], {}), '(method)\n', (2977, 2985), False, 'from squidpy._constants._constants import Processing\n'), ((899, 922), 'dask.delayed', 'delayed', (['img_as_float32'], {}), '(img_as_float32)\n', (906, 922), False, 'from dask import delayed\n'), ((4116, 4131), 'dask.array.asarray', 'da.asarray', (['arr'], {}), '(arr)\n', (4126, 4131), True, 'import dask.array as da\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created 2022 @author: <NAME> """ from Levenshtein import distance as levenshtein_distance import pandas as pd import numpy as np from sklearn.model_selection import train_test_split print('Now Executing Trastuzumab Train/Val/Test Splitting...') """ This script serves to split the trastuzumab (her2) data into training, validation, and testing sets. The train and validation sets are selected to be an edit distance of 7 or less from the wild type trastuzumab. The test set is an edit distance of 8 or greater from the wild type Inputs ---------- labeled trastuzumab data from Mason et. al 2021 github repo: https://github.com/dahjan/DMS_opt mHER_H3_AgPos.csv mHER_H3_AgNeg.csv Outputs ------- csv files containing training, validation, and testing sets """ def add_LD_to_df(antigen_ID, data_frame): ''' Function to add Edit Distance (Levenshtein Distance) from wt for each sequence to dataframe Parameters ---------- antigen_ID : str corresponds to the antigen identity. in this case, her2 data_frame : pandas.DataFrame dataframe containing all sequence & label data Returns ------- data_frame : pandas.DataFrame input dataframe with an added column containing the Levenshtein Distance from the wild type for each sequence in the dataframe ''' if antigen_ID == 'her2': wt_str = 'WGGDGFYAMK' LD_arr = [] for i in range(len(data_frame)): LD_arr.append( levenshtein_distance(wt_str, data_frame['AASeq'].iloc[i]) ) data_frame['LD'] = LD_arr return data_frame def class_balance_binary(data_frame): ''' Function to class balance dataset Parameters ---------- data_frame : pandas.DataFrame dataframe containing all sequence & label data Returns ------- data_frame : pandas.DataFrame class balanced dataframe. number of positive examples is equal to the number of negatives ''' positives = data_frame[data_frame['AgClass'] == 1].copy() negatives = data_frame[data_frame['AgClass'] == 0].copy() min_list = min([len(ls) for ls in [positives, negatives]]) positives = positives[: int(np.round(min_list))] negatives = negatives[: int(np.round(min_list))] return positives, negatives her2_path_local = '../data/her2/' pos = pd.read_csv(her2_path_local + 'mHER_H3_AgPos.csv') neg = pd.read_csv(her2_path_local + 'mHER_H3_AgNeg.csv') def combine_df_list_and_shuffle(df_list, keep = False): ''' combines two dataframes, drops duplicates, & shuffles Parameters ---------- data_frame : pandas.DataFrame dataframe containing all sequence & label data keep: bool whether or not to keep duplicates Returns ------- data_frame : pandas.DataFrame combined, shuffled dataframe ''' frames = df_list common_cols = list(set.intersection(*(set(df.columns) for df in frames))) combined_df = pd.concat([df[common_cols] for df in frames], ignore_index=True).drop_duplicates(subset='AASeq', keep=keep) np.random.seed(0) combined_df = combined_df.reindex(np.random.permutation(combined_df.index)) return combined_df all_data_frames = [pos.copy(), neg.copy()] data_frame = combine_df_list_and_shuffle(all_data_frames, keep = False) data_frame = add_LD_to_df('her2', data_frame) selected_LD_split = 7 train_df = data_frame[data_frame['LD'] <= selected_LD_split] test_df_initial = data_frame[data_frame['LD'] > selected_LD_split] #Function to drop duplicates from two dataframes def drop_test_seqs(train_df, test_df, seq_name): ''' Function serves as a check to prevent dataleakage between training & test or training & val sets Parameters ---------- train_df : pandas.DataFrame train dataframe test_df : pandas.DataFrame test dataframe seq_name : str corresponds to the dataframe column name containing sequences. Returns ------- out_df : TYPE train dataframe without test sequences ''' train_df = train_df.copy() train_df['df'] = 'train' test_df_copy = test_df.copy() test_df_copy['df'] = 'test' frames = [train_df.copy(),test_df_copy] common_cols = list(set.intersection(*(set(df.columns) for df in frames))) concat_df = pd.concat([df[common_cols] for df in frames], ignore_index=True) concat_df = concat_df.drop_duplicates(subset=[seq_name],keep=False) out_df = concat_df[concat_df['df'] == 'train'] return out_df train_df = drop_test_seqs(train_df, test_df_initial, 'AASeq') def drop_and_rename_columns(df): df = df.copy() df = df.rename(columns = {'AASeq': 'aaseq', 'AgClass': 'target'}) df = df.drop(columns = ['Unnamed: 0', 'Fraction', 'NucSeq', 'Count', 'df']) return df #Balance test set & save to csv test_df = test_df_initial.copy() test_df['df'] = 'test' #add to df to facilitate using the function below test_df = drop_and_rename_columns(test_df) test_positives = test_df[test_df['target'] == 1] test_negs = test_df[test_df['target'] == 0].sample(n = int(len(test_positives)), random_state = 1) test_df = test_positives.append(test_negs,ignore_index = True) test_df = test_df.reindex(np.random.permutation(test_df.index)) out_path = '../data/her2/' test_df.to_csv(out_path + 'her2_test.csv', index=False) train_df = drop_and_rename_columns(train_df) #Class balance full training data set & shuffle dataframe initial_train_pos = train_df[train_df['target'] == 1] initial_train_neg = train_df[train_df['target'] == 0] initial_train_neg = initial_train_neg[initial_train_neg['LD'] != 3] #drop the single LD 3 seq from df. required for sklearn train test stratifying later in script initial_train_pos = initial_train_pos[initial_train_pos['LD'] != 2] #drop the two LD 2 seq from df. required for sklearn train test stratifying later in script minlen = min([len(initial_train_pos),len(initial_train_neg) ]) initial_train_pos = initial_train_pos.sample(n = minlen, random_state = 1) initial_train_neg = initial_train_neg.sample(n = minlen, random_state = 1) train_df = pd.DataFrame() train_df = initial_train_pos.append(initial_train_neg, ignore_index = True) train_df = train_df.sample(n = int(len(train_df)), random_state = 1) #Batch training & val sets with different quantities of class imbalance using positives as the minority class class_imbalance_qty_list = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 1.0] train_df_master_copy = train_df.copy() for imbal_qty in class_imbalance_qty_list: #artificially increase class imbalance in training set by downsampling positives train_positives = train_df_master_copy[train_df_master_copy['target'] == 1] train_negs = train_df_master_copy[train_df_master_copy['target'] == 0] #new downsampling method using sklearn & edit distance if imbal_qty != 1.0: train_positives, x_discard, y_train, y_discard = train_test_split(train_positives, train_positives['target'], test_size = 1 - imbal_qty, random_state = 1, shuffle = True, stratify = train_positives['LD']) elif imbal_qty == 1.0: train_truncated = train_positives #split val set from training & maintain LD distribution per class train_positives, val_positives, y_train, y_val = train_test_split(train_positives, train_positives['target'], test_size = 1 - 0.8, random_state = 1, shuffle = True, stratify = train_positives['LD']) train_negs, val_negs, y_train, y_val = train_test_split(train_negs, train_negs['target'], test_size = 1 - 0.8, random_state = 1, shuffle = True, stratify = train_negs['LD']) train_df = train_positives.append(train_negs,ignore_index = True) train_df = train_df.reindex(np.random.permutation(train_df.index)) val_df = val_positives.append(val_negs,ignore_index = True) val_df = val_df.reindex(np.random.permutation(val_df.index)) train_df = drop_test_seqs(train_df, val_df, 'aaseq') train_df = train_df.drop(columns = ['df']) train_df = train_df.drop(columns = ['LD']) val_df = val_df.drop(columns = ['LD']) out_str_train = out_path + 'her2_train_imbal_' + str(imbal_qty) + '.csv' out_str_val = out_path + 'her2_val_imbal_' + str(imbal_qty) + '.csv' train_df.to_csv(out_str_train, index=False) val_df.to_csv(out_str_val, index=False)
[ "pandas.read_csv", "sklearn.model_selection.train_test_split", "Levenshtein.distance", "numpy.random.seed", "pandas.DataFrame", "pandas.concat", "numpy.round", "numpy.random.permutation" ]
[((2388, 2438), 'pandas.read_csv', 'pd.read_csv', (["(her2_path_local + 'mHER_H3_AgPos.csv')"], {}), "(her2_path_local + 'mHER_H3_AgPos.csv')\n", (2399, 2438), True, 'import pandas as pd\n'), ((2445, 2495), 'pandas.read_csv', 'pd.read_csv', (["(her2_path_local + 'mHER_H3_AgNeg.csv')"], {}), "(her2_path_local + 'mHER_H3_AgNeg.csv')\n", (2456, 2495), True, 'import pandas as pd\n'), ((6167, 6181), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (6179, 6181), True, 'import pandas as pd\n'), ((3134, 3151), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (3148, 3151), True, 'import numpy as np\n'), ((4370, 4434), 'pandas.concat', 'pd.concat', (['[df[common_cols] for df in frames]'], {'ignore_index': '(True)'}), '([df[common_cols] for df in frames], ignore_index=True)\n', (4379, 4434), True, 'import pandas as pd\n'), ((5280, 5316), 'numpy.random.permutation', 'np.random.permutation', (['test_df.index'], {}), '(test_df.index)\n', (5301, 5316), True, 'import numpy as np\n'), ((7428, 7574), 'sklearn.model_selection.train_test_split', 'train_test_split', (['train_positives', "train_positives['target']"], {'test_size': '(1 - 0.8)', 'random_state': '(1)', 'shuffle': '(True)', 'stratify': "train_positives['LD']"}), "(train_positives, train_positives['target'], test_size=1 - \n 0.8, random_state=1, shuffle=True, stratify=train_positives['LD'])\n", (7444, 7574), False, 'from sklearn.model_selection import train_test_split\n'), ((7688, 7818), 'sklearn.model_selection.train_test_split', 'train_test_split', (['train_negs', "train_negs['target']"], {'test_size': '(1 - 0.8)', 'random_state': '(1)', 'shuffle': '(True)', 'stratify': "train_negs['LD']"}), "(train_negs, train_negs['target'], test_size=1 - 0.8,\n random_state=1, shuffle=True, stratify=train_negs['LD'])\n", (7704, 7818), False, 'from sklearn.model_selection import train_test_split\n'), ((3190, 3230), 'numpy.random.permutation', 'np.random.permutation', (['combined_df.index'], {}), '(combined_df.index)\n', (3211, 3230), True, 'import numpy as np\n'), ((6993, 7144), 'sklearn.model_selection.train_test_split', 'train_test_split', (['train_positives', "train_positives['target']"], {'test_size': '(1 - imbal_qty)', 'random_state': '(1)', 'shuffle': '(True)', 'stratify': "train_positives['LD']"}), "(train_positives, train_positives['target'], test_size=1 -\n imbal_qty, random_state=1, shuffle=True, stratify=train_positives['LD'])\n", (7009, 7144), False, 'from sklearn.model_selection import train_test_split\n'), ((7984, 8021), 'numpy.random.permutation', 'np.random.permutation', (['train_df.index'], {}), '(train_df.index)\n', (8005, 8021), True, 'import numpy as np\n'), ((8116, 8151), 'numpy.random.permutation', 'np.random.permutation', (['val_df.index'], {}), '(val_df.index)\n', (8137, 8151), True, 'import numpy as np\n'), ((1526, 1583), 'Levenshtein.distance', 'levenshtein_distance', (['wt_str', "data_frame['AASeq'].iloc[i]"], {}), "(wt_str, data_frame['AASeq'].iloc[i])\n", (1546, 1583), True, 'from Levenshtein import distance as levenshtein_distance\n'), ((3022, 3086), 'pandas.concat', 'pd.concat', (['[df[common_cols] for df in frames]'], {'ignore_index': '(True)'}), '([df[common_cols] for df in frames], ignore_index=True)\n', (3031, 3086), True, 'import pandas as pd\n'), ((2237, 2255), 'numpy.round', 'np.round', (['min_list'], {}), '(min_list)\n', (2245, 2255), True, 'import numpy as np\n'), ((2291, 2309), 'numpy.round', 'np.round', (['min_list'], {}), '(min_list)\n', (2299, 2309), True, 'import numpy as np\n')]
from .fis import FIS import numpy as np try: import pandas as pd except ImportError: pd = None try: from sklearn.model_selection import GridSearchCV except ImportError: GridSearchCV = None def _get_vars(fis): """Get an encoded version of the parameters of the fuzzy sets in a FIS""" for variable in fis.variables: for value_name, value in variable.values.items(): for par, default in value._get_description().items(): if par != "type": yield "var_" + variable.name + "_" + value_name + "_" + par, default # Same for target for variable in [fis.target]: # For symmetry for value_name, value in variable.values.items(): for par, default in value._get_description().items(): if par != "type": yield "target_" + variable.name + "_" + value_name + "_" + par, default def _set_vars(fis, kwargs): """Return a modified version of the FIS, setting the changes in the parameters described by kwargs""" description = fis._get_description() positions = {variable["name"]: i for i, variable in enumerate(description["variables"])} for code, parameter_value in kwargs.items(): if code.startswith("var_"): _, variable_name, fuzzy_value, parameter = code.split("_") description["variables"][positions[variable_name]]["values"][fuzzy_value][parameter] = parameter_value elif code.startswith("target_"): _, _, fuzzy_value, parameter = code.split("_") description["target"]["values"][fuzzy_value][parameter] = parameter_value elif code in ["defuzzification"]: description[code] = parameter_value else: raise ValueError("Parameter not supported: %s" % code) return FIS._from_description(description) class ParametrizedFIS: """A parametrizable Fuzzy Inference System with a scikit-learn-like interface""" def __init__(self, fis, defuzzification="centroid", **kwargs): self.fis = fis self.defuzzification = defuzzification for parameter, value in _get_vars(fis): setattr(self, parameter, kwargs.get(parameter, value)) def get_params(self, deep=True): """Get the parameters in a sklearn-consistent interface""" return {"fis": self.fis, "defuzzification": self.defuzzification, **{parameter: getattr(self, parameter) for parameter, _ in _get_vars(self.fis)}} def set_params(self, **parameters): """Set the parameters in a sklearn-consistent interface""" for parameter, value in parameters.items(): setattr(self, parameter, value) return self def fit(self, X=None, y=None): """'Fit' the model (freeze the attributes and compile if available)""" self.fis_ = _set_vars(self.fis, {parameter: getattr(self, parameter) for parameter, _ in _get_vars(self.fis)}) self.fis_.defuzzification = self.defuzzification try: self.fis_ = self.fis_.compile() except Exception: pass return self def predict(self, X): """A sklearn-like predict method""" return self.fis_.batch_predict(X) class TrivialSplitter: """Splitter with single split no training data and full test data""" def __init__(self): pass def split(self, X, y=None, groups=None): yield np.asarray([], dtype=int), np.arange(0, len(X)) def get_n_splits(self, X, y=None, groups=None): return 1 class FuzzyGridTune: """An exhaustive FIS tuner""" def __init__(self, fis, params, scoring="neg_root_mean_squared_error", n_jobs=None): """ Args: fis (FIS): The Fuzzy Inference System to tune params (dict of str to list): A mapping from encoded parameters to the list of values to explore. scoring (str): The metric used for scoring. Must be one of sklearn's regression scorings. n_jobs (int): Number of jobs to run in parallel. """ # Grid parameter tuning if GridSearchCV is None: raise ModuleNotFoundError("scikit-learn is required for model tuning") self.fis = fis self.cv = GridSearchCV(ParametrizedFIS(fis), params, scoring=scoring, cv=TrivialSplitter(), refit=False, n_jobs=n_jobs ) def fit(self, X, y=None): """ Args: X (2D array-like): An object suitable for FIS.batch_predict. y (1D array-like): An array with true values. If None, but X is a DataFrame, the values are extracted from there. Returns: """ # Try to extract y if a single dataframe is provided if y is None and pd is not None and isinstance(X, pd.DataFrame): y = X[self.fis.target.name] self.cv.fit(X, y) self.best_params_ = self.cv.best_params_ self.results = self.cv.cv_results_ self.tuned_fis_ = _set_vars(self.fis, self.cv.best_params_)
[ "numpy.asarray" ]
[((3461, 3486), 'numpy.asarray', 'np.asarray', (['[]'], {'dtype': 'int'}), '([], dtype=int)\n', (3471, 3486), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Single VsOne Chip Match Interface For VsMany Interaction Interaction for looking at matches between a single query and database annotation Main development file CommandLine: python -m ibeis.viz.interact.interact_matches --test-show_coverage --show """ from __future__ import absolute_import, division, print_function, unicode_literals import utool as ut import numpy as np import plottool as pt import six from plottool import interact_helpers as ih from ibeis import viz from ibeis.algo.hots import scoring from ibeis.algo.hots import hstypes from ibeis.viz import viz_helpers as vh from ibeis.viz import viz_hough from ibeis.viz import viz_chip from plottool import interact_matches from ibeis.viz.interact.interact_chip import ishow_chip (print, rrr, profile) = ut.inject2(__name__, '[interact_matches]') def testdata_match_interact(**kwargs): """ CommandLine: python -m ibeis.viz.interact.interact_matches --test-testdata_match_interact --show --db PZ_MTEST --qaid 3 Example: >>> # VIZ_DOCTEST >>> from ibeis.viz.interact.interact_matches import * # NOQA >>> import plottool as pt >>> kwargs = {} >>> mx = ut.get_argval('--mx', type_=int, default=None) >>> self = testdata_match_interact(mx=mx, **kwargs) >>> pt.show_if_requested() """ import ibeis qreq_ = ibeis.testdata_qreq_(defaultdb='testdb1', t=['default:Knorm=3']) ibs = qreq_.ibs cm = qreq_.execute()[0] cm.sortself() aid2 = None self = MatchInteraction(ibs, cm, aid2, mode=1, dodraw=False, qreq_=qreq_, **kwargs) self.start() return self # TODO inherit from AbstractInteraction @six.add_metaclass(ut.ReloadingMetaclass) class MatchInteraction(interact_matches.MatchInteraction2): """ Plots a chip result and sets up callbacks for interaction. SeeAlso: plottool.interact_matches.MatchInteraction2 CommandLine: python -m ibeis.viz.interact.interact_matches --test-testdata_match_interact --show --db PZ_MTEST --qaid 3 """ def __init__(self, ibs, cm, aid2=None, fnum=None, qreq_=None, figtitle='Match Interaction', **kwargs): #print('[ibs] MatchInteraction.__init__') self.ibs = ibs self.cm = cm self.qreq_ = qreq_ # Unpack Args if aid2 is None: index = 0 # FIXME: no sortself cm.sortself() self.rank = index else: index = cm.daid2_idx.get(aid2, None) # TODO: rank? self.rank = None if index is not None: self.qaid = self.cm.qaid self.daid = self.cm.daid_list[index] fm = self.cm.fm_list[index] fk = self.cm.fk_list[index] fsv = self.cm.fsv_list[index] if self.cm.fs_list is None: fs_list = self.cm.get_fsv_prod_list() else: fs_list = self.cm.fs_list fs = None if fs_list is None else fs_list[index] H1 = None if self.cm.H_list is None else cm.H_list[index] self.score = None if self.cm.score_list is None else self.cm.score_list[index] else: self.qaid = self.cm.qaid self.daid = aid2 fm = np.empty((0, 2), dtype=hstypes.FM_DTYPE) fk = np.empty(0, dtype=hstypes.FK_DTYPE) fsv = np.empty((0, 2), dtype=hstypes.FS_DTYPE) fs = np.empty(0, dtype=hstypes.FS_DTYPE) H1 = None self.score = None # Read properties self.query_config2_ = (None if self.qreq_ is None else self.qreq_.extern_query_config2) self.data_config2_ = (None if self.qreq_ is None else self.qreq_.extern_data_config2) rchip1 = vh.get_chips(ibs, [self.qaid], config2_=self.query_config2_)[0] rchip2 = vh.get_chips(ibs, [self.daid], config2_=self.data_config2_)[0] kpts1 = ibs.get_annot_kpts([self.qaid], config2_=self.query_config2_)[0] kpts2 = ibs.get_annot_kpts([self.daid], config2_=self.data_config2_)[0] vecs1 = ibs.get_annot_vecs([self.qaid], config2_=self.query_config2_)[0] vecs2 = ibs.get_annot_vecs([self.daid], config2_=self.data_config2_)[0] self.figtitle = figtitle self.kwargs = kwargs self.fnum2 = pt.next_fnum() super(MatchInteraction, self).__init__(rchip1, rchip2, kpts1, kpts2, fm, fs, fsv, vecs1, vecs2, H1, H2=None, fk=fk, fnum=fnum, **kwargs) #def plot(self, fnum, pnum): def chipmatch_view(self, fnum=None, pnum=(1, 1, 1), verbose=None, **kwargs_): """ just visualizes the matches using some type of lines CommandLine: python -m ibeis.viz.interact.interact_matches --test-chipmatch_view --show Example: >>> # DISABLE_DOCTEST >>> from ibeis.viz.interact.interact_matches import * # NOQA >>> self = testdata_match_interact() >>> self.chipmatch_view() >>> pt.show_if_requested() """ if fnum is None: fnum = self.fnum if verbose is None: verbose = ut.VERBOSE ibs = self.ibs aid = self.daid qaid = self.qaid figtitle = self.figtitle # drawing mode draw: with/without lines/feats mode = kwargs_.get('mode', self.mode) draw_ell = mode >= 1 draw_lines = mode == 2 #self.mode = (self.mode + 1) % 3 pt.figure(fnum=fnum, docla=True, doclf=True) show_matches_kw = self.kwargs.copy() show_matches_kw.update( dict(fnum=fnum, pnum=pnum, draw_lines=draw_lines, draw_ell=draw_ell, colorbar_=True, vert=self.vert)) show_matches_kw.update(kwargs_) if self.warp_homog: show_matches_kw['H1'] = self.H1 #show_matches_kw['score'] = self.score show_matches_kw['rawscore'] = self.score show_matches_kw['aid2_raw_rank'] = self.rank tup = viz.viz_matches.show_matches2(ibs, self.qaid, self.daid, self.fm, self.fs, qreq_=self.qreq_, **show_matches_kw) ax, xywh1, xywh2 = tup self.xywh2 = xywh2 pt.set_figtitle(figtitle + ' ' + vh.get_vsstr(qaid, aid)) def sv_view(self, dodraw=True): """ spatial verification view """ #fnum = viz.FNUMS['special'] aid = self.daid fnum = pt.next_fnum() fig = pt.figure(fnum=fnum, docla=True, doclf=True) ih.disconnect_callback(fig, 'button_press_event') viz.viz_sver.show_sver(self.ibs, self.qaid, aid2=aid, fnum=fnum) if dodraw: #self.draw() pt.draw() def show_coverage(self, dodraw=True): """ CommandLine: python -m ibeis.viz.interact.interact_matches --test-show_coverage --show python -m ibeis.viz.interact.interact_matches --test-show_coverage Example: >>> # DISABLE_DOCTEST >>> from ibeis.viz.interact.interact_matches import * # NOQA >>> self = testdata_match_interact(mx=1) >>> self.show_coverage(dodraw=False) >>> pt.show_if_requested() """ masks_list = scoring.get_masks(self.qreq_, self.cm) scoring.show_coverage_mask(self.qreq_, self.cm, masks_list) if dodraw: #self.draw() pt.draw() def show_each_chip(self): viz_chip.show_chip(self.ibs, self.qaid, fnum=pt.next_fnum(), nokpts=True) viz_chip.show_chip(self.ibs, self.daid, fnum=pt.next_fnum(), nokpts=True) pt.draw() #self.draw() def show_each_fgweight_chip(self): viz_chip.show_chip(self.ibs, self.qaid, fnum=pt.next_fnum(), weight_label='fg_weights') viz_chip.show_chip(self.ibs, self.daid, fnum=pt.next_fnum(), weight_label='fg_weights') #self.draw() pt.draw() def show_each_dstncvs_chip(self, dodraw=True): """ CommandLine: python -m ibeis.viz.interact.interact_matches --test-show_each_dstncvs_chip --show Example: >>> # DISABLE_DOCTEST >>> from ibeis.viz.interact.interact_matches import * # NOQA >>> self = testdata_match_interact(mx=1) >>> self.show_each_dstncvs_chip(dodraw=False) >>> pt.show_if_requested() """ dstncvs1, dstncvs2 = scoring.get_kpts_distinctiveness(self.ibs, [self.qaid, self.daid]) print('dstncvs1_stats = ' + ut.get_stats_str(dstncvs1)) print('dstncvs2_stats = ' + ut.get_stats_str(dstncvs2)) weight_label = 'dstncvs' showkw = dict(weight_label=weight_label, ell=False, pts=True) viz_chip.show_chip(self.ibs, self.qaid, weights=dstncvs1, fnum=pt.next_fnum(), **showkw) viz_chip.show_chip(self.ibs, self.daid, weights=dstncvs2, fnum=pt.next_fnum(), **showkw) if dodraw: #self.draw() pt.draw() def show_each_probchip(self): viz_hough.show_probability_chip(self.ibs, self.qaid, fnum=pt.next_fnum()) viz_hough.show_probability_chip(self.ibs, self.daid, fnum=pt.next_fnum()) pt.draw() #self.draw() def dev_reload(self): ih.disconnect_callback(self.fig, 'button_press_event') self.rrr() self.set_callbacks() def dev_embed(self): ut.embed() def toggle_samefig(self): self.same_fig = not self.same_fig if self.mx is not None: self.select_ith_match(self.mx) self.draw() def query_last_feature(self): ibs = self.ibs qaid = self.qaid viz.show_nearest_descriptors(ibs, qaid, self.last_fx, pt.next_fnum(), qreq_=self.qreq_, draw_chip=True) fig3 = pt.gcf() ih.connect_callback(fig3, 'button_press_event', self.on_click) pt.draw() def get_popup_options(self): from ibeis.gui import inspect_gui options = [] ax = pt.gca() # HACK from plottool import plot_helpers as ph viztype = ph.get_plotdat(ax, 'viztype', '') is_match_type = viztype in ['matches', 'multi_match'] if is_match_type: options += inspect_gui.get_aidpair_context_menu_options( self.ibs, self.qaid, self.daid, self.cm, qreq_=self.qreq_, #update_callback=self.show_page, #backend_callback=None, aid_list=aid_list) ) options += [ #('Toggle same_fig', self.toggle_samefig), #('Toggle vert', self.toggle_vert), ('query last feature', self.query_last_feature), ('show each chip', self.show_each_chip), ('show each distinctiveness chip', self.show_each_dstncvs_chip), ('show each foreground weight chip', self.show_each_fgweight_chip), ('show each probchip', self.show_each_probchip), ('show coverage', self.show_coverage), #('show each probchip', self.query_last_feature), ] #options.append(('name_interaction', self.name_interaction)) #if self.H1 is not None: # options.append(('Toggle homog', self.toggle_homog)) if ut.is_developer(): options.append(('dev_reload', self.dev_reload)) options.append(('dev_embed', self.dev_embed)) #options.append(('cancel', lambda: print('cancel'))) options += super(MatchInteraction, self).get_popup_options() return options #self.show_popup_menu(options, event) # Callback def on_click_inside(self, event, ax): from plottool import plot_helpers as ph ibs = self.ibs viztype = ph.get_plotdat(ax, 'viztype', '') is_match_type = viztype in ['matches', 'multi_match'] key = '' if event.key is None else event.key print('key=%r ' % key) ctrl_down = key.find('control') == 0 # Click in match axes if event.button == 3: return super(MatchInteraction, self).on_click_inside(event, ax) if is_match_type and ctrl_down: # Ctrl-Click print('.. control click') return self.sv_view() elif viztype in ['warped', 'unwarped']: print('clicked at patch') ut.print_dict(ph.get_plotdat_dict(ax)) hs_aid = { 'aid1': self.qaid, 'aid2': self.daid, }[vh.get_ibsdat(ax, 'aid', None)] hs_fx = vh.get_ibsdat(ax, 'fx', None) print('hs_fx = %r' % (hs_fx,)) print('hs_aid = %r' % (hs_aid,)) if hs_aid is not None and viztype == 'unwarped': ishow_chip(ibs, hs_aid, fx=hs_fx, fnum=pt.next_fnum()) elif hs_aid is not None and viztype == 'warped': viz.show_keypoint_gradient_orientations(ibs, hs_aid, hs_fx, fnum=pt.next_fnum()) else: return super(MatchInteraction, self).on_click_inside(event, ax) self.draw() if __name__ == '__main__': """ CommandLine: python -m ibeis.viz.interact.interact_matches python -m ibeis.viz.interact.interact_matches --allexamples python -m ibeis.viz.interact.interact_matches --allexamples --noface --nosrc """ import multiprocessing multiprocessing.freeze_support() # for win32 import utool as ut # NOQA ut.doctest_funcs()
[ "utool.get_stats_str", "utool.embed", "plottool.gca", "utool.doctest_funcs", "multiprocessing.freeze_support", "ibeis.algo.hots.scoring.get_kpts_distinctiveness", "ibeis.algo.hots.scoring.get_masks", "plottool.gcf", "plottool.interact_helpers.connect_callback", "plottool.plot_helpers.get_plotdat_d...
[((800, 842), 'utool.inject2', 'ut.inject2', (['__name__', '"""[interact_matches]"""'], {}), "(__name__, '[interact_matches]')\n", (810, 842), True, 'import utool as ut\n'), ((1699, 1739), 'six.add_metaclass', 'six.add_metaclass', (['ut.ReloadingMetaclass'], {}), '(ut.ReloadingMetaclass)\n', (1716, 1739), False, 'import six\n'), ((1388, 1452), 'ibeis.testdata_qreq_', 'ibeis.testdata_qreq_', ([], {'defaultdb': '"""testdb1"""', 't': "['default:Knorm=3']"}), "(defaultdb='testdb1', t=['default:Knorm=3'])\n", (1408, 1452), False, 'import ibeis\n'), ((14075, 14107), 'multiprocessing.freeze_support', 'multiprocessing.freeze_support', ([], {}), '()\n', (14105, 14107), False, 'import multiprocessing\n'), ((14156, 14174), 'utool.doctest_funcs', 'ut.doctest_funcs', ([], {}), '()\n', (14172, 14174), True, 'import utool as ut\n'), ((4465, 4479), 'plottool.next_fnum', 'pt.next_fnum', ([], {}), '()\n', (4477, 4479), True, 'import plottool as pt\n'), ((5774, 5818), 'plottool.figure', 'pt.figure', ([], {'fnum': 'fnum', 'docla': '(True)', 'doclf': '(True)'}), '(fnum=fnum, docla=True, doclf=True)\n', (5783, 5818), True, 'import plottool as pt\n'), ((6304, 6419), 'ibeis.viz.viz_matches.show_matches2', 'viz.viz_matches.show_matches2', (['ibs', 'self.qaid', 'self.daid', 'self.fm', 'self.fs'], {'qreq_': 'self.qreq_'}), '(ibs, self.qaid, self.daid, self.fm, self.fs,\n qreq_=self.qreq_, **show_matches_kw)\n', (6333, 6419), False, 'from ibeis import viz\n'), ((6837, 6851), 'plottool.next_fnum', 'pt.next_fnum', ([], {}), '()\n', (6849, 6851), True, 'import plottool as pt\n'), ((6866, 6910), 'plottool.figure', 'pt.figure', ([], {'fnum': 'fnum', 'docla': '(True)', 'doclf': '(True)'}), '(fnum=fnum, docla=True, doclf=True)\n', (6875, 6910), True, 'import plottool as pt\n'), ((6919, 6968), 'plottool.interact_helpers.disconnect_callback', 'ih.disconnect_callback', (['fig', '"""button_press_event"""'], {}), "(fig, 'button_press_event')\n", (6941, 6968), True, 'from plottool import interact_helpers as ih\n'), ((6977, 7041), 'ibeis.viz.viz_sver.show_sver', 'viz.viz_sver.show_sver', (['self.ibs', 'self.qaid'], {'aid2': 'aid', 'fnum': 'fnum'}), '(self.ibs, self.qaid, aid2=aid, fnum=fnum)\n', (6999, 7041), False, 'from ibeis import viz\n'), ((7649, 7687), 'ibeis.algo.hots.scoring.get_masks', 'scoring.get_masks', (['self.qreq_', 'self.cm'], {}), '(self.qreq_, self.cm)\n', (7666, 7687), False, 'from ibeis.algo.hots import scoring\n'), ((7696, 7755), 'ibeis.algo.hots.scoring.show_coverage_mask', 'scoring.show_coverage_mask', (['self.qreq_', 'self.cm', 'masks_list'], {}), '(self.qreq_, self.cm, masks_list)\n', (7722, 7755), False, 'from ibeis.algo.hots import scoring\n'), ((8025, 8034), 'plottool.draw', 'pt.draw', ([], {}), '()\n', (8032, 8034), True, 'import plottool as pt\n'), ((8371, 8380), 'plottool.draw', 'pt.draw', ([], {}), '()\n', (8378, 8380), True, 'import plottool as pt\n'), ((8878, 8944), 'ibeis.algo.hots.scoring.get_kpts_distinctiveness', 'scoring.get_kpts_distinctiveness', (['self.ibs', '[self.qaid, self.daid]'], {}), '(self.ibs, [self.qaid, self.daid])\n', (8910, 8944), False, 'from ibeis.algo.hots import scoring\n'), ((9822, 9831), 'plottool.draw', 'pt.draw', ([], {}), '()\n', (9829, 9831), True, 'import plottool as pt\n'), ((9888, 9942), 'plottool.interact_helpers.disconnect_callback', 'ih.disconnect_callback', (['self.fig', '"""button_press_event"""'], {}), "(self.fig, 'button_press_event')\n", (9910, 9942), True, 'from plottool import interact_helpers as ih\n'), ((10025, 10035), 'utool.embed', 'ut.embed', ([], {}), '()\n', (10033, 10035), True, 'import utool as ut\n'), ((10460, 10468), 'plottool.gcf', 'pt.gcf', ([], {}), '()\n', (10466, 10468), True, 'import plottool as pt\n'), ((10477, 10539), 'plottool.interact_helpers.connect_callback', 'ih.connect_callback', (['fig3', '"""button_press_event"""', 'self.on_click'], {}), "(fig3, 'button_press_event', self.on_click)\n", (10496, 10539), True, 'from plottool import interact_helpers as ih\n'), ((10548, 10557), 'plottool.draw', 'pt.draw', ([], {}), '()\n', (10555, 10557), True, 'import plottool as pt\n'), ((10669, 10677), 'plottool.gca', 'pt.gca', ([], {}), '()\n', (10675, 10677), True, 'import plottool as pt\n'), ((10753, 10786), 'plottool.plot_helpers.get_plotdat', 'ph.get_plotdat', (['ax', '"""viztype"""', '""""""'], {}), "(ax, 'viztype', '')\n", (10767, 10786), True, 'from plottool import plot_helpers as ph\n'), ((11917, 11934), 'utool.is_developer', 'ut.is_developer', ([], {}), '()\n', (11932, 11934), True, 'import utool as ut\n'), ((12407, 12440), 'plottool.plot_helpers.get_plotdat', 'ph.get_plotdat', (['ax', '"""viztype"""', '""""""'], {}), "(ax, 'viztype', '')\n", (12421, 12440), True, 'from plottool import plot_helpers as ph\n'), ((3348, 3388), 'numpy.empty', 'np.empty', (['(0, 2)'], {'dtype': 'hstypes.FM_DTYPE'}), '((0, 2), dtype=hstypes.FM_DTYPE)\n', (3356, 3388), True, 'import numpy as np\n'), ((3409, 3444), 'numpy.empty', 'np.empty', (['(0)'], {'dtype': 'hstypes.FK_DTYPE'}), '(0, dtype=hstypes.FK_DTYPE)\n', (3417, 3444), True, 'import numpy as np\n'), ((3465, 3505), 'numpy.empty', 'np.empty', (['(0, 2)'], {'dtype': 'hstypes.FS_DTYPE'}), '((0, 2), dtype=hstypes.FS_DTYPE)\n', (3473, 3505), True, 'import numpy as np\n'), ((3526, 3561), 'numpy.empty', 'np.empty', (['(0)'], {'dtype': 'hstypes.FS_DTYPE'}), '(0, dtype=hstypes.FS_DTYPE)\n', (3534, 3561), True, 'import numpy as np\n'), ((3913, 3973), 'ibeis.viz.viz_helpers.get_chips', 'vh.get_chips', (['ibs', '[self.qaid]'], {'config2_': 'self.query_config2_'}), '(ibs, [self.qaid], config2_=self.query_config2_)\n', (3925, 3973), True, 'from ibeis.viz import viz_helpers as vh\n'), ((3994, 4053), 'ibeis.viz.viz_helpers.get_chips', 'vh.get_chips', (['ibs', '[self.daid]'], {'config2_': 'self.data_config2_'}), '(ibs, [self.daid], config2_=self.data_config2_)\n', (4006, 4053), True, 'from ibeis.viz import viz_helpers as vh\n'), ((7098, 7107), 'plottool.draw', 'pt.draw', ([], {}), '()\n', (7105, 7107), True, 'import plottool as pt\n'), ((7812, 7821), 'plottool.draw', 'pt.draw', ([], {}), '()\n', (7819, 7821), True, 'import plottool as pt\n'), ((9605, 9614), 'plottool.draw', 'pt.draw', ([], {}), '()\n', (9612, 9614), True, 'import plottool as pt\n'), ((10358, 10372), 'plottool.next_fnum', 'pt.next_fnum', ([], {}), '()\n', (10370, 10372), True, 'import plottool as pt\n'), ((10899, 11006), 'ibeis.gui.inspect_gui.get_aidpair_context_menu_options', 'inspect_gui.get_aidpair_context_menu_options', (['self.ibs', 'self.qaid', 'self.daid', 'self.cm'], {'qreq_': 'self.qreq_'}), '(self.ibs, self.qaid, self.daid,\n self.cm, qreq_=self.qreq_)\n', (10943, 11006), False, 'from ibeis.gui import inspect_gui\n'), ((6648, 6671), 'ibeis.viz.viz_helpers.get_vsstr', 'vh.get_vsstr', (['qaid', 'aid'], {}), '(qaid, aid)\n', (6660, 6671), True, 'from ibeis.viz import viz_helpers as vh\n'), ((7906, 7920), 'plottool.next_fnum', 'pt.next_fnum', ([], {}), '()\n', (7918, 7920), True, 'import plottool as pt\n'), ((7988, 8002), 'plottool.next_fnum', 'pt.next_fnum', ([], {}), '()\n', (8000, 8002), True, 'import plottool as pt\n'), ((8149, 8163), 'plottool.next_fnum', 'pt.next_fnum', ([], {}), '()\n', (8161, 8163), True, 'import plottool as pt\n'), ((8272, 8286), 'plottool.next_fnum', 'pt.next_fnum', ([], {}), '()\n', (8284, 8286), True, 'import plottool as pt\n'), ((9106, 9132), 'utool.get_stats_str', 'ut.get_stats_str', (['dstncvs1'], {}), '(dstncvs1)\n', (9122, 9132), True, 'import utool as ut\n'), ((9170, 9196), 'utool.get_stats_str', 'ut.get_stats_str', (['dstncvs2'], {}), '(dstncvs2)\n', (9186, 9196), True, 'import utool as ut\n'), ((9399, 9413), 'plottool.next_fnum', 'pt.next_fnum', ([], {}), '()\n', (9411, 9413), True, 'import plottool as pt\n'), ((9523, 9537), 'plottool.next_fnum', 'pt.next_fnum', ([], {}), '()\n', (9535, 9537), True, 'import plottool as pt\n'), ((9716, 9730), 'plottool.next_fnum', 'pt.next_fnum', ([], {}), '()\n', (9728, 9730), True, 'import plottool as pt\n'), ((9798, 9812), 'plottool.next_fnum', 'pt.next_fnum', ([], {}), '()\n', (9810, 9812), True, 'import plottool as pt\n'), ((13202, 13231), 'ibeis.viz.viz_helpers.get_ibsdat', 'vh.get_ibsdat', (['ax', '"""fx"""', 'None'], {}), "(ax, 'fx', None)\n", (13215, 13231), True, 'from ibeis.viz import viz_helpers as vh\n'), ((13018, 13041), 'plottool.plot_helpers.get_plotdat_dict', 'ph.get_plotdat_dict', (['ax'], {}), '(ax)\n', (13037, 13041), True, 'from plottool import plot_helpers as ph\n'), ((13150, 13180), 'ibeis.viz.viz_helpers.get_ibsdat', 'vh.get_ibsdat', (['ax', '"""aid"""', 'None'], {}), "(ax, 'aid', None)\n", (13163, 13180), True, 'from ibeis.viz import viz_helpers as vh\n'), ((13436, 13450), 'plottool.next_fnum', 'pt.next_fnum', ([], {}), '()\n', (13448, 13450), True, 'import plottool as pt\n'), ((13650, 13664), 'plottool.next_fnum', 'pt.next_fnum', ([], {}), '()\n', (13662, 13664), True, 'import plottool as pt\n')]
"""Example systems created in Python """ import numpy as np from pysim.cythonsystem import Sys class VanDerPol(Sys): """Simple example of a class representing a VanDerPol oscillator. """ def __init__(self): self.add_state_scalar("x", "dx") self.add_state_scalar("y", "dy") self.add_input_scalar("a") self.add_input_scalar("b") self.inputs.a = 1.0 self.inputs.b = 1.0 self.states.x = 1.0 self.states.y = 0.0 def do_step(self,dummy): """Perform a timestep by implmenting the VanDerPol equations""" a = self.inputs.a b = self.inputs.b x = self.states.x y = self.states.y self.ders.dx = a*x*(b-y*y)-y self.ders.dy = x class MassSpringDamper(Sys): """Simple class for testing the mass-spring-damper simulations with a cython system""" def __init__(self): """Setup two states (one dimensional vectors for now). Initial conditions are simular to those in the build in c++ system""" self.add_state_scalar("x1", "dx1") self.add_state_scalar("x2", "dx2") self.states.x1 = 1 self.states.x2 = 0 def do_step(self,dummy): """Perform a step using default constants, same as those in the cpp system""" m = 100.0 b = 1.0 k = 50.0 f = 0.0 x1 = self.states.x1 x2 = self.states.x2 self.ders.dx1 = x2 self.ders.dx2 =-k/m*x1-b/m*x2+1/m*f class InOutTestSystem(Sys): """Python representation of the cpp InOutTestSystem Used for testing that the cpp system behaves as the python system with regards to the input output handling """ def __init__(self): self.add_input_scalar("input_scalar") self.add_input_vector("input_vector",3) self.add_input_matrix("input_matrix",3,3) self.add_state_scalar("state_scalar","der_scalar") self.add_state_vector("state_vector","der_vector", 3) self.add_state_matrix("state_matrix","der_matrix", 3, 3) self.add_output_scalar("input_output_scalar") self.add_output_vector("input_output_vector",3) self.add_output_matrix("input_output_matrix",3,3) self.add_output_scalar("state_output_scalar") self.add_output_vector("state_output_vector",3) self.add_output_matrix("state_output_matrix",3,3) self.inputs.input_scalar = 0.0 self.inputs.input_vector = [0.0, 0.0, 0.0] self.inputs.input_matrix = np.zeros((3,3)) self.outputs.input_output_scalar = 0.0 self.outputs.input_output_vector = [0.0, 0.0, 0.0] self.outputs.input_output_matrix = np.zeros((3,3)) self.outputs.state_output_scalar = 0.0 self.outputs.state_output_vector = [0.0, 0.0, 0.0] self.outputs.state_output_matrix = np.zeros((3,3)) self.states.state_scalar = 1.23 self.states.state_vector = np.ones(3)*4.56 self.states.state_matrix = np.ones((3,3))*7.89 self.ders.der_scalar = 0 self.ders.der_vector = np.zeros(3) self.ders.der_matrix = np.zeros((3,3)) def do_step(self,dummy): """During a timestep we set the outputs to their respective inputs""" self.outputs.input_output_scalar = self.inputs.input_scalar self.outputs.input_output_vector = self.inputs.input_vector self.outputs.input_output_matrix = self.inputs.input_matrix self.outputs.state_output_scalar = self.states.state_scalar self.outputs.state_output_vector = self.states.state_vector self.outputs.state_output_matrix = self.states.state_matrix
[ "numpy.zeros", "numpy.ones" ]
[((2545, 2561), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {}), '((3, 3))\n', (2553, 2561), True, 'import numpy as np\n'), ((2711, 2727), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {}), '((3, 3))\n', (2719, 2727), True, 'import numpy as np\n'), ((2876, 2892), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {}), '((3, 3))\n', (2884, 2892), True, 'import numpy as np\n'), ((3103, 3114), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (3111, 3114), True, 'import numpy as np\n'), ((3146, 3162), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {}), '((3, 3))\n', (3154, 3162), True, 'import numpy as np\n'), ((2968, 2978), 'numpy.ones', 'np.ones', (['(3)'], {}), '(3)\n', (2975, 2978), True, 'import numpy as np\n'), ((3019, 3034), 'numpy.ones', 'np.ones', (['(3, 3)'], {}), '((3, 3))\n', (3026, 3034), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- # """*********************************************************************************************""" # FileName [ classifiers.py ] # Synopsis [ 'Naive Bayes' and 'Decision Tree' training, testing, and tunning functions ] # Author [ <NAME> (Andi611) ] # Copyright [ Copyleft(c), NTUEE, NTU, Taiwan ] """*********************************************************************************************""" ############### # IMPORTATION # ############### import numpy as np from sklearn.naive_bayes import GaussianNB from sklearn.naive_bayes import MultinomialNB from sklearn.naive_bayes import ComplementNB from sklearn.naive_bayes import BernoulliNB from sklearn.model_selection import cross_val_score from sklearn import metrics from sklearn import tree ############ # CONSTANT # ############ N_FOLD = 10 DEPTHS = np.arange(1, 64) ALPHAS = np.arange(0.001, 1.0, 0.001) ALPHAS_MUSHROOM = np.arange(0.0001, 1.0, 0.0001) BEST_DISTRIBUTION = 'Multinominal' ############### # NAIVE BAYES # ############### class naive_bayes_runner(object): def __init__(self, MODEL, train_x, train_y, test_x, test_y): #---data---# self.train_x = train_x self.train_y = train_y self.test_x = test_x self.test_y = test_y #---model---# self.cross_validate = False self.MODEL = MODEL if self.MODEL == 'NEWS': self.models = { 'Guassian' : GaussianNB(), 'Multinominal' : MultinomialNB(alpha=0.065), 'Complement' : ComplementNB(alpha=0.136), 'Bernoulli' : BernoulliNB(alpha=0.002) } if self.MODEL == 'MUSHROOM': ALPHAS = ALPHAS_MUSHROOM self.models = { 'Guassian' : GaussianNB(), 'Multinominal' : MultinomialNB(alpha=0.0001), 'Complement' : ComplementNB(alpha=0.0001), 'Bernoulli' : BernoulliNB(alpha=0.0001) } if self.MODEL == 'INCOME': self.cross_validate = True self.models = { 'Guassian' : GaussianNB(), 'Multinominal' : MultinomialNB(alpha=0.959), 'Complement' : ComplementNB(alpha=0.16), 'Bernoulli' : BernoulliNB(alpha=0.001) } def _fit_and_evaluate(self, model): model_fit = model.fit(self.train_x, self.train_y) pred_y = model_fit.predict(self.test_x) acc = metrics.accuracy_score(self.test_y, pred_y) return acc, pred_y def search_alpha(self): try: from tqdm import tqdm except: raise ImportError('Failed to import tqdm, use the following command to install: pip3 install tqdm') for distribution, model in self.models.items(): best_acc = 0.0 best_alpha = 0.001 if distribution != 'Guassian': print('>> [Naive Bayes Runner] Searching for best alpha value, distribution:', distribution) for alpha in tqdm(ALPHAS): model.set_params(alpha=alpha) if self.cross_validate: scores = cross_val_score(model, self.train_x, self.train_y, cv=N_FOLD, scoring='accuracy') acc = scores.mean() else: acc, _ = self._fit_and_evaluate(model) if acc > best_acc: best_acc = acc best_alpha = alpha print('>> [Naive Bayes Runner] '+ distribution + ' - Best Alpha Value:', best_alpha) def run_best_all(self): for distribution, model in self.models.items(): if self.cross_validate: scores = cross_val_score(model, self.train_x, self.train_y, cv=N_FOLD, scoring='accuracy') acc = scores.mean() else: acc, _ = self._fit_and_evaluate(model) print('>> [Naive Bayes Runner] '+ distribution + ' - Accuracy:', acc) def run_best(self): if self.cross_validate: scores = cross_val_score(self.models[BEST_DISTRIBUTION], self.train_x, self.train_y, cv=N_FOLD, scoring='accuracy') acc = scores.mean() model_fit = self.models[BEST_DISTRIBUTION].fit(self.train_x, self.train_y) pred_y = model_fit.predict(self.test_x) else: acc, pred_y = self._fit_and_evaluate(self.models[BEST_DISTRIBUTION]) print('>> [Naive Bayes Runner] '+ BEST_DISTRIBUTION + ' - Accuracy:', acc) return pred_y ################# # DECISION TREE # ################# class decision_tree_runner(object): def __init__(self, MODEL, train_x, train_y, test_x, test_y): #---data---# self.train_x = train_x self.train_y = train_y self.test_x = test_x self.test_y = test_y #---model---# self.cross_validate = False self.MODEL = MODEL if self.MODEL == 'NEWS': self.model = tree.DecisionTreeClassifier(criterion='gini', splitter='random', max_depth=47, random_state=1337) elif self.MODEL == 'MUSHROOM': self.model = tree.DecisionTreeClassifier(criterion='gini', splitter='random', max_depth=7, random_state=1337) elif self.MODEL == 'INCOME': self.cross_validate = True self.model = tree.DecisionTreeClassifier(criterion='entropy', min_impurity_decrease=2e-4, max_depth=15, random_state=1337) def _fit_and_evaluate(self): model_fit = self.model.fit(self.train_x, self.train_y) pred_y = model_fit.predict(self.test_x) acc = metrics.accuracy_score(self.test_y, pred_y) return acc, pred_y def search_max_depth(self): try: from tqdm import tqdm except: raise ImportError('Failed to import tqdm, use the following command to install: $ pip3 install tqdm') best_acc = 0.0 best_depth = 1 print('>> [Naive Bayes Runner] Searching for best max depth value...') for depth in tqdm(DEPTHS): self.model.set_params(max_depth=depth) if self.cross_validate: scores = cross_val_score(self.model, self.train_x, self.train_y, cv=N_FOLD, scoring='accuracy') acc = scores.mean() else: acc, _ = self._fit_and_evaluate() if acc > best_acc: best_acc = acc best_depth = depth print('>> [Decision Tree Runner] - Best Dpeth Value:', best_depth) def visualize(self): try: import graphviz except: raise ImportError('Failed to import graphviz, use the following command to install: $ pip3 install graphviz, and $ sudo apt-get install graphviz') model_fit = self.model.fit(self.train_x, self.train_y) dot_data = tree.export_graphviz(model_fit, out_file=None, filled=True, rounded=True, special_characters=True) graph = graphviz.Source(dot_data) graph.format = 'png' graph.render('../image/TREE_' + self.MODEL) print('>> [Decision Tree Runner] - Tree visualization complete.') def run_best(self): if self.cross_validate: scores = cross_val_score(self.model, self.train_x, self.train_y, cv=N_FOLD, scoring='accuracy') acc = scores.mean() model_fit = self.model.fit(self.train_x, self.train_y) pred_y = model_fit.predict(self.test_x) else: acc, pred_y = self._fit_and_evaluate() print('>> [Decision Tree Runner] - Accuracy:', acc) return pred_y
[ "sklearn.naive_bayes.ComplementNB", "numpy.arange", "tqdm.tqdm", "sklearn.tree.DecisionTreeClassifier", "sklearn.tree.export_graphviz", "sklearn.naive_bayes.MultinomialNB", "sklearn.naive_bayes.BernoulliNB", "sklearn.naive_bayes.GaussianNB", "sklearn.metrics.accuracy_score", "graphviz.Source", "...
[((863, 879), 'numpy.arange', 'np.arange', (['(1)', '(64)'], {}), '(1, 64)\n', (872, 879), True, 'import numpy as np\n'), ((889, 917), 'numpy.arange', 'np.arange', (['(0.001)', '(1.0)', '(0.001)'], {}), '(0.001, 1.0, 0.001)\n', (898, 917), True, 'import numpy as np\n'), ((936, 966), 'numpy.arange', 'np.arange', (['(0.0001)', '(1.0)', '(0.0001)'], {}), '(0.0001, 1.0, 0.0001)\n', (945, 966), True, 'import numpy as np\n'), ((2218, 2261), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', (['self.test_y', 'pred_y'], {}), '(self.test_y, pred_y)\n', (2240, 2261), False, 'from sklearn import metrics\n'), ((5031, 5074), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', (['self.test_y', 'pred_y'], {}), '(self.test_y, pred_y)\n', (5053, 5074), False, 'from sklearn import metrics\n'), ((5399, 5411), 'tqdm.tqdm', 'tqdm', (['DEPTHS'], {}), '(DEPTHS)\n', (5403, 5411), False, 'from tqdm import tqdm\n'), ((6067, 6169), 'sklearn.tree.export_graphviz', 'tree.export_graphviz', (['model_fit'], {'out_file': 'None', 'filled': '(True)', 'rounded': '(True)', 'special_characters': '(True)'}), '(model_fit, out_file=None, filled=True, rounded=True,\n special_characters=True)\n', (6087, 6169), False, 'from sklearn import tree\n'), ((6201, 6226), 'graphviz.Source', 'graphviz.Source', (['dot_data'], {}), '(dot_data)\n', (6216, 6226), False, 'import graphviz\n'), ((3523, 3633), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['self.models[BEST_DISTRIBUTION]', 'self.train_x', 'self.train_y'], {'cv': 'N_FOLD', 'scoring': '"""accuracy"""'}), "(self.models[BEST_DISTRIBUTION], self.train_x, self.train_y,\n cv=N_FOLD, scoring='accuracy')\n", (3538, 3633), False, 'from sklearn.model_selection import cross_val_score\n'), ((4329, 4431), 'sklearn.tree.DecisionTreeClassifier', 'tree.DecisionTreeClassifier', ([], {'criterion': '"""gini"""', 'splitter': '"""random"""', 'max_depth': '(47)', 'random_state': '(1337)'}), "(criterion='gini', splitter='random', max_depth=\n 47, random_state=1337)\n", (4356, 4431), False, 'from sklearn import tree\n'), ((6426, 6517), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['self.model', 'self.train_x', 'self.train_y'], {'cv': 'N_FOLD', 'scoring': '"""accuracy"""'}), "(self.model, self.train_x, self.train_y, cv=N_FOLD, scoring=\n 'accuracy')\n", (6441, 6517), False, 'from sklearn.model_selection import cross_val_score\n'), ((1392, 1404), 'sklearn.naive_bayes.GaussianNB', 'GaussianNB', ([], {}), '()\n', (1402, 1404), False, 'from sklearn.naive_bayes import GaussianNB\n'), ((1433, 1459), 'sklearn.naive_bayes.MultinomialNB', 'MultinomialNB', ([], {'alpha': '(0.065)'}), '(alpha=0.065)\n', (1446, 1459), False, 'from sklearn.naive_bayes import MultinomialNB\n'), ((1483, 1508), 'sklearn.naive_bayes.ComplementNB', 'ComplementNB', ([], {'alpha': '(0.136)'}), '(alpha=0.136)\n', (1495, 1508), False, 'from sklearn.naive_bayes import ComplementNB\n'), ((1532, 1556), 'sklearn.naive_bayes.BernoulliNB', 'BernoulliNB', ([], {'alpha': '(0.002)'}), '(alpha=0.002)\n', (1543, 1556), False, 'from sklearn.naive_bayes import BernoulliNB\n'), ((1650, 1662), 'sklearn.naive_bayes.GaussianNB', 'GaussianNB', ([], {}), '()\n', (1660, 1662), False, 'from sklearn.naive_bayes import GaussianNB\n'), ((1691, 1718), 'sklearn.naive_bayes.MultinomialNB', 'MultinomialNB', ([], {'alpha': '(0.0001)'}), '(alpha=0.0001)\n', (1704, 1718), False, 'from sklearn.naive_bayes import MultinomialNB\n'), ((1742, 1768), 'sklearn.naive_bayes.ComplementNB', 'ComplementNB', ([], {'alpha': '(0.0001)'}), '(alpha=0.0001)\n', (1754, 1768), False, 'from sklearn.naive_bayes import ComplementNB\n'), ((1792, 1817), 'sklearn.naive_bayes.BernoulliNB', 'BernoulliNB', ([], {'alpha': '(0.0001)'}), '(alpha=0.0001)\n', (1803, 1817), False, 'from sklearn.naive_bayes import BernoulliNB\n'), ((1911, 1923), 'sklearn.naive_bayes.GaussianNB', 'GaussianNB', ([], {}), '()\n', (1921, 1923), False, 'from sklearn.naive_bayes import GaussianNB\n'), ((1952, 1978), 'sklearn.naive_bayes.MultinomialNB', 'MultinomialNB', ([], {'alpha': '(0.959)'}), '(alpha=0.959)\n', (1965, 1978), False, 'from sklearn.naive_bayes import MultinomialNB\n'), ((2002, 2026), 'sklearn.naive_bayes.ComplementNB', 'ComplementNB', ([], {'alpha': '(0.16)'}), '(alpha=0.16)\n', (2014, 2026), False, 'from sklearn.naive_bayes import ComplementNB\n'), ((2050, 2074), 'sklearn.naive_bayes.BernoulliNB', 'BernoulliNB', ([], {'alpha': '(0.001)'}), '(alpha=0.001)\n', (2061, 2074), False, 'from sklearn.naive_bayes import BernoulliNB\n'), ((2695, 2707), 'tqdm.tqdm', 'tqdm', (['ALPHAS'], {}), '(ALPHAS)\n', (2699, 2707), False, 'from tqdm import tqdm\n'), ((3230, 3316), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['model', 'self.train_x', 'self.train_y'], {'cv': 'N_FOLD', 'scoring': '"""accuracy"""'}), "(model, self.train_x, self.train_y, cv=N_FOLD, scoring=\n 'accuracy')\n", (3245, 3316), False, 'from sklearn.model_selection import cross_val_score\n'), ((4520, 4621), 'sklearn.tree.DecisionTreeClassifier', 'tree.DecisionTreeClassifier', ([], {'criterion': '"""gini"""', 'splitter': '"""random"""', 'max_depth': '(7)', 'random_state': '(1337)'}), "(criterion='gini', splitter='random', max_depth=\n 7, random_state=1337)\n", (4547, 4621), False, 'from sklearn import tree\n'), ((5496, 5587), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['self.model', 'self.train_x', 'self.train_y'], {'cv': 'N_FOLD', 'scoring': '"""accuracy"""'}), "(self.model, self.train_x, self.train_y, cv=N_FOLD, scoring=\n 'accuracy')\n", (5511, 5587), False, 'from sklearn.model_selection import cross_val_score\n'), ((4738, 4854), 'sklearn.tree.DecisionTreeClassifier', 'tree.DecisionTreeClassifier', ([], {'criterion': '"""entropy"""', 'min_impurity_decrease': '(0.0002)', 'max_depth': '(15)', 'random_state': '(1337)'}), "(criterion='entropy', min_impurity_decrease=\n 0.0002, max_depth=15, random_state=1337)\n", (4765, 4854), False, 'from sklearn import tree\n'), ((2789, 2875), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['model', 'self.train_x', 'self.train_y'], {'cv': 'N_FOLD', 'scoring': '"""accuracy"""'}), "(model, self.train_x, self.train_y, cv=N_FOLD, scoring=\n 'accuracy')\n", (2804, 2875), False, 'from sklearn.model_selection import cross_val_score\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 21 19:43:50 2022 Illustrating a basic transient magnetic diffusion problem, See Jackson Section 5.18 @author: zettergm """ import numpy as np import scipy.sparse.linalg import scipy.sparse from scipy.special import erf import matplotlib.pyplot as plt from numpy import pi,sqrt,abs from difftools import matrix_kernel # Material parameters mu=4*pi*1e-7 sigma=1e6 D=1/mu/sigma # equivalent diffusion coefficient a=1 H0=1 nu=1/mu/sigma/a**2 # Size of grid lz=250 Nmax=200 z=np.linspace(-5*a,5*a,lz) dz=z[1]-z[0] dt = 5*dz**2/D/2 # explicit stabilty limit will results in really slow time stepping; use 5 times larger. # This could definitely benefit for sparse storage and a banded/tridiagonal solver #A=np.exp(-(x**2/2)) Hx=np.zeros(lz) indmin=np.argmin(abs(z+a)) indmax=np.argmin(abs(z-a)) Hx[indmin:indmax]=1 # Matrix defining finite-difference equation for laplacian operator, one-time setup for this problem Msparse=matrix_kernel(lz,dt,dz,D) rhs=np.zeros( (lz,1) ) # time iterations for n in range(0,Nmax): # set up time-dependent part of the problem and solve for i in range(1,lz-1): rhs[i]=Hx[i] rhssparse=scipy.sparse.csr_matrix(np.reshape(rhs,[lz,1])) Hx=scipy.sparse.linalg.spsolve(Msparse,rhssparse,use_umfpack=True) # umfpack is overkill for this but will presumably work # Solution from Jackson eqn. 5.176 HxJ=H0/2*( erf((1+abs(z)/a)/2/sqrt((n+1)*dt*nu)) + erf((1-abs(z)/a)/2/sqrt((n+1)*dt*nu)) ) # plot results of each time step and pause briefly plt.figure(1,dpi=150) plt.clf() plt.plot(z,HxJ,'o') plt.plot(z,Hx) plt.xlabel("$x$") plt.ylabel("$H_x(z)$") plt.title( "$t$ = %6.4f s" % ( (n+1)*dt) ) plt.ylim((0,H0)) plt.xlim((-2*a,2*a)) plt.legend( ("Jackson 5.176","Numerical BTCS") ) plt.show() plt.pause(0.01)
[ "numpy.abs", "numpy.reshape", "numpy.sqrt", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.clf", "matplotlib.pyplot.plot", "difftools.matrix_kernel", "numpy.linspace", "matplotlib.pyplot.figure", "numpy.zeros", "matplotlib.pyplot.pause", "matplotlib.pyplot.title",...
[((549, 579), 'numpy.linspace', 'np.linspace', (['(-5 * a)', '(5 * a)', 'lz'], {}), '(-5 * a, 5 * a, lz)\n', (560, 579), True, 'import numpy as np\n'), ((808, 820), 'numpy.zeros', 'np.zeros', (['lz'], {}), '(lz)\n', (816, 820), True, 'import numpy as np\n'), ((1005, 1033), 'difftools.matrix_kernel', 'matrix_kernel', (['lz', 'dt', 'dz', 'D'], {}), '(lz, dt, dz, D)\n', (1018, 1033), False, 'from difftools import matrix_kernel\n'), ((1035, 1052), 'numpy.zeros', 'np.zeros', (['(lz, 1)'], {}), '((lz, 1))\n', (1043, 1052), True, 'import numpy as np\n'), ((838, 848), 'numpy.abs', 'abs', (['(z + a)'], {}), '(z + a)\n', (841, 848), False, 'from numpy import pi, sqrt, abs\n'), ((865, 875), 'numpy.abs', 'abs', (['(z - a)'], {}), '(z - a)\n', (868, 875), False, 'from numpy import pi, sqrt, abs\n'), ((1590, 1612), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {'dpi': '(150)'}), '(1, dpi=150)\n', (1600, 1612), True, 'import matplotlib.pyplot as plt\n'), ((1616, 1625), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (1623, 1625), True, 'import matplotlib.pyplot as plt\n'), ((1630, 1651), 'matplotlib.pyplot.plot', 'plt.plot', (['z', 'HxJ', '"""o"""'], {}), "(z, HxJ, 'o')\n", (1638, 1651), True, 'import matplotlib.pyplot as plt\n'), ((1654, 1669), 'matplotlib.pyplot.plot', 'plt.plot', (['z', 'Hx'], {}), '(z, Hx)\n', (1662, 1669), True, 'import matplotlib.pyplot as plt\n'), ((1673, 1690), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$x$"""'], {}), "('$x$')\n", (1683, 1690), True, 'import matplotlib.pyplot as plt\n'), ((1695, 1717), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$H_x(z)$"""'], {}), "('$H_x(z)$')\n", (1705, 1717), True, 'import matplotlib.pyplot as plt\n'), ((1722, 1765), 'matplotlib.pyplot.title', 'plt.title', (["('$t$ = %6.4f s' % ((n + 1) * dt))"], {}), "('$t$ = %6.4f s' % ((n + 1) * dt))\n", (1731, 1765), True, 'import matplotlib.pyplot as plt\n'), ((1769, 1786), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0, H0)'], {}), '((0, H0))\n', (1777, 1786), True, 'import matplotlib.pyplot as plt\n'), ((1790, 1815), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(-2 * a, 2 * a)'], {}), '((-2 * a, 2 * a))\n', (1798, 1815), True, 'import matplotlib.pyplot as plt\n'), ((1815, 1862), 'matplotlib.pyplot.legend', 'plt.legend', (["('Jackson 5.176', 'Numerical BTCS')"], {}), "(('Jackson 5.176', 'Numerical BTCS'))\n", (1825, 1862), True, 'import matplotlib.pyplot as plt\n'), ((1868, 1878), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1876, 1878), True, 'import matplotlib.pyplot as plt\n'), ((1883, 1898), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.01)'], {}), '(0.01)\n', (1892, 1898), True, 'import matplotlib.pyplot as plt\n'), ((1242, 1266), 'numpy.reshape', 'np.reshape', (['rhs', '[lz, 1]'], {}), '(rhs, [lz, 1])\n', (1252, 1266), True, 'import numpy as np\n'), ((1469, 1492), 'numpy.sqrt', 'sqrt', (['((n + 1) * dt * nu)'], {}), '((n + 1) * dt * nu)\n', (1473, 1492), False, 'from numpy import pi, sqrt, abs\n'), ((1509, 1532), 'numpy.sqrt', 'sqrt', (['((n + 1) * dt * nu)'], {}), '((n + 1) * dt * nu)\n', (1513, 1532), False, 'from numpy import pi, sqrt, abs\n'), ((1457, 1463), 'numpy.abs', 'abs', (['z'], {}), '(z)\n', (1460, 1463), False, 'from numpy import pi, sqrt, abs\n'), ((1497, 1503), 'numpy.abs', 'abs', (['z'], {}), '(z)\n', (1500, 1503), False, 'from numpy import pi, sqrt, abs\n')]
# -*- coding: utf-8 -*- # # Copyright 2018-2020 Data61, CSIRO # # 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. """ Mappers to provide input data for the graph models in layers. """ __all__ = ["ClusterNodeGenerator", "ClusterNodeSequence"] import random import copy import numpy as np import networkx as nx from tensorflow.keras.utils import Sequence from scipy import sparse from ..core.graph import StellarGraph from ..core.utils import is_real_iterable class ClusterNodeGenerator: """ A data generator for use with ClusterGCN models on homogeneous graphs, [1]. The supplied graph G should be a StellarGraph object that is ready for machine learning. Currently the model requires node features to be available for all nodes in the graph. Use the :meth:`flow` method supplying the nodes and (optionally) targets to get an object that can be used as a Keras data generator. This generator will supply the features array and the adjacency matrix to a mini-batch Keras graph ML model. [1] `<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, 2019 <https://arxiv.org/abs/1905.07953>`_. For more information, please see the ClusterGCN demo: `<https://github.com/stellargraph/stellargraph/blob/master/demos/>`_ Args: G (StellarGraph): a machine-learning StellarGraph-type graph clusters (int or list): If int then it indicates the number of clusters (default is 1 that is the given graph). If clusters is greater than 1, then nodes are uniformly at random assigned to a cluster. If list, then it should be a list of lists of node IDs such that each list corresponds to a cluster of nodes in G. The clusters should be non-overlapping. q (float): The number of clusters to combine for each mini-batch. The default is 1. lam (float): The mixture coefficient for adjacency matrix normalisation. name (str): an optional name of the generator """ def __init__(self, G, clusters=1, q=1, lam=0.1, name=None): if not isinstance(G, StellarGraph): raise TypeError("Graph must be a StellarGraph or StellarDiGraph object.") self.graph = G self.name = name self.q = q # The number of clusters to sample per mini-batch self.lam = lam self.clusters = clusters if isinstance(clusters, list): self.k = len(clusters) elif isinstance(clusters, int): if clusters <= 0: raise ValueError( "{}: clusters must be greater than 0.".format(type(self).__name__) ) self.k = clusters else: raise TypeError( "{}: clusters must be either int or list type.".format( type(self).__name__ ) ) # Some error checking on the given parameter values if not isinstance(lam, float): raise TypeError("{}: lam must be a float type.".format(type(self).__name__)) if lam < 0 or lam > 1: raise ValueError( "{}: lam must be in the range [0, 1].".format(type(self).__name__) ) if not isinstance(q, int): raise TypeError("{}: q must be integer type.".format(type(self).__name__)) if q <= 0: raise ValueError( "{}: q must be greater than 0.".format(type(self).__name__) ) if self.k % q != 0: raise ValueError( "{}: the number of clusters must be exactly divisible by q.".format( type(self).__name__ ) ) # Check if the graph has features G.check_graph_for_ml() self.node_list = list(G.nodes()) # Check that there is only a single node type if len(G.node_types) > 1: raise ValueError( "{}: node generator requires graph with single node type; " "a graph with multiple node types is passed. Stopping.".format( type(self).__name__ ) ) if isinstance(clusters, int): # We are not given graph clusters. # We are going to split the graph into self.k random clusters all_nodes = list(G.nodes()) random.shuffle(all_nodes) cluster_size = len(all_nodes) // self.k self.clusters = [ all_nodes[i : i + cluster_size] for i in range(0, len(all_nodes), cluster_size) ] if len(self.clusters) > self.k: # for the case that the number of nodes is not exactly divisible by k, we combine # the last cluster with the second last one self.clusters[-2].extend(self.clusters[-1]) del self.clusters[-1] print(f"Number of clusters {self.k}") for i, c in enumerate(self.clusters): print(f"{i} cluster has size {len(c)}") # Get the features for the nodes self.features = G.node_features(self.node_list) def flow(self, node_ids, targets=None, name=None): """ Creates a generator/sequence object for training, evaluation, or prediction with the supplied node ids and numeric targets. Args: node_ids (iterable): an iterable of node ids for the nodes of interest (e.g., training, validation, or test set nodes) targets (2d array, optional): a 2D array of numeric node targets with shape `(len(node_ids), target_size)` name (str, optional): An optional name for the returned generator object. Returns: A ClusterNodeSequence object to use with ClusterGCN in Keras methods :meth:`fit_generator`, :meth:`evaluate_generator`, and :meth:`predict_generator` """ if targets is not None: # Check targets is an iterable if not is_real_iterable(targets): raise TypeError( "{}: Targets must be an iterable or None".format( type(self).__name__ ) ) # Check targets correct shape if len(targets) != len(node_ids): raise ValueError( "{}: Targets must be the same length as node_ids".format( type(self).__name__ ) ) return ClusterNodeSequence( self.graph, self.clusters, targets=targets, node_ids=node_ids, q=self.q, lam=self.lam, name=name, ) class ClusterNodeSequence(Sequence): """ A Keras-compatible data generator for node inference using ClusterGCN model. Use this class with the Keras methods :meth:`keras.Model.fit_generator`, :meth:`keras.Model.evaluate_generator`, and :meth:`keras.Model.predict_generator`, This class should be created using the `.flow(...)` method of :class:`ClusterNodeGenerator`. Args: graph (StellarGraph): The graph clusters (list): A list of lists such that each sub-list indicates the nodes in a cluster. The length of this list, len(clusters) indicates the number of batches in one epoch. targets (np.ndarray, optional): An optional array of node targets of size (N x C), where C is the target size (e.g., number of classes for one-hot class targets) node_ids (iterable, optional): The node IDs for the target nodes. Required if targets is not None. normalize_adj (bool, optional): Specifies whether the adjacency matrix for each mini-batch should be normalized or not. The default is True. q (int, optional): The number of subgraphs to combine for each batch. The default value is 1 such that the generator treats each subgraph as a batch. lam (float, optional): The mixture coefficient for adjacency matrix normalisation (the 'diagonal enhancement' method). Valid values are in the interval [0, 1] and the default value is 0.1. name (str, optional): An optional name for this generator object. """ def __init__( self, graph, clusters, targets=None, node_ids=None, normalize_adj=True, q=1, lam=0.1, name=None, ): self.name = name self.clusters = list() self.clusters_original = copy.deepcopy(clusters) self.graph = graph self.node_list = list(graph.nodes()) self.normalize_adj = normalize_adj self.q = q self.lam = lam self.node_order = list() self._node_order_in_progress = list() self.__node_buffer = dict() self.target_ids = list() if len(clusters) % self.q != 0: raise ValueError( "The number of clusters should be exactly divisible by q. However, {} number of clusters is not exactly divisible by {}.".format( len(clusters), q ) ) if node_ids is not None: self.target_ids = list(node_ids) if targets is not None: if node_ids is None: raise ValueError( "Since targets is not None, node_ids must be given and cannot be None." ) if len(node_ids) != len(targets): raise ValueError( "When passed together targets and indices should be the same length." ) self.targets = np.asanyarray(targets) self.target_node_lookup = dict( zip(self.target_ids, range(len(self.target_ids))) ) else: self.targets = None self.on_epoch_end() def __len__(self): num_batches = len(self.clusters_original) // self.q return num_batches def __getitem__(self, index): # The next batch should be the adjacency matrix for the cluster and the corresponding feature vectors # and targets if available. cluster = self.clusters[index] adj_cluster = self.graph.to_adjacency_matrix(cluster) # The operations to normalize the adjacency matrix are too slow. # Either optimize this or implement as a layer(?) if self.normalize_adj: # add self loops adj_cluster.setdiag(1) # add self loops degree_matrix_diag = 1.0 / (adj_cluster.sum(axis=1) + 1) degree_matrix_diag = np.squeeze(np.asarray(degree_matrix_diag)) degree_matrix = sparse.lil_matrix(adj_cluster.shape) degree_matrix.setdiag(degree_matrix_diag) adj_cluster = degree_matrix.tocsr() @ adj_cluster adj_cluster.setdiag((1.0 + self.lam) * adj_cluster.diagonal()) adj_cluster = adj_cluster.toarray() g_node_list = list(cluster) # Determine the target nodes that exist in this cluster target_nodes_in_cluster = np.asanyarray( list(set(g_node_list).intersection(self.target_ids)) ) self.__node_buffer[index] = target_nodes_in_cluster # Dictionary to store node indices for quicker node index lookups node_lookup = dict(zip(g_node_list, range(len(g_node_list)))) # The list of indices of the target nodes in self.node_list target_node_indices = np.array( [node_lookup[n] for n in target_nodes_in_cluster] ) if index == (len(self.clusters_original) // self.q) - 1: # last batch self.__node_buffer_dict_to_list() cluster_targets = None # if self.targets is not None: # Dictionary to store node indices for quicker node index lookups # The list of indices of the target nodes in self.node_list cluster_target_indices = np.array( [self.target_node_lookup[n] for n in target_nodes_in_cluster] ) cluster_targets = self.targets[cluster_target_indices] cluster_targets = cluster_targets.reshape((1,) + cluster_targets.shape) features = self.graph.node_features(g_node_list) features = np.reshape(features, (1,) + features.shape) adj_cluster = adj_cluster.reshape((1,) + adj_cluster.shape) target_node_indices = target_node_indices[np.newaxis, np.newaxis, :] return [features, target_node_indices, adj_cluster], cluster_targets def __node_buffer_dict_to_list(self): self.node_order = [] for k, v in self.__node_buffer.items(): self.node_order.extend(v) def on_epoch_end(self): """ Shuffle all nodes at the end of each epoch """ if self.q > 1: # combine clusters cluster_indices = list(range(len(self.clusters_original))) random.shuffle(cluster_indices) self.clusters = [] for i in range(0, len(cluster_indices) - 1, self.q): cc = cluster_indices[i : i + self.q] tmp = [] for l in cc: tmp.extend(list(self.clusters_original[l])) self.clusters.append(tmp) else: self.clusters = copy.deepcopy(self.clusters_original) self.__node_buffer = dict() random.shuffle(self.clusters)
[ "scipy.sparse.lil_matrix", "numpy.reshape", "random.shuffle", "numpy.asarray", "numpy.asanyarray", "numpy.array", "copy.deepcopy" ]
[((9091, 9114), 'copy.deepcopy', 'copy.deepcopy', (['clusters'], {}), '(clusters)\n', (9104, 9114), False, 'import copy\n'), ((12049, 12108), 'numpy.array', 'np.array', (['[node_lookup[n] for n in target_nodes_in_cluster]'], {}), '([node_lookup[n] for n in target_nodes_in_cluster])\n', (12057, 12108), True, 'import numpy as np\n'), ((12865, 12908), 'numpy.reshape', 'np.reshape', (['features', '((1,) + features.shape)'], {}), '(features, (1,) + features.shape)\n', (12875, 12908), True, 'import numpy as np\n'), ((14000, 14029), 'random.shuffle', 'random.shuffle', (['self.clusters'], {}), '(self.clusters)\n', (14014, 14029), False, 'import random\n'), ((4847, 4872), 'random.shuffle', 'random.shuffle', (['all_nodes'], {}), '(all_nodes)\n', (4861, 4872), False, 'import random\n'), ((10212, 10234), 'numpy.asanyarray', 'np.asanyarray', (['targets'], {}), '(targets)\n', (10225, 10234), True, 'import numpy as np\n'), ((11245, 11281), 'scipy.sparse.lil_matrix', 'sparse.lil_matrix', (['adj_cluster.shape'], {}), '(adj_cluster.shape)\n', (11262, 11281), False, 'from scipy import sparse\n'), ((12534, 12605), 'numpy.array', 'np.array', (['[self.target_node_lookup[n] for n in target_nodes_in_cluster]'], {}), '([self.target_node_lookup[n] for n in target_nodes_in_cluster])\n', (12542, 12605), True, 'import numpy as np\n'), ((13532, 13563), 'random.shuffle', 'random.shuffle', (['cluster_indices'], {}), '(cluster_indices)\n', (13546, 13563), False, 'import random\n'), ((13916, 13953), 'copy.deepcopy', 'copy.deepcopy', (['self.clusters_original'], {}), '(self.clusters_original)\n', (13929, 13953), False, 'import copy\n'), ((11185, 11215), 'numpy.asarray', 'np.asarray', (['degree_matrix_diag'], {}), '(degree_matrix_diag)\n', (11195, 11215), True, 'import numpy as np\n')]
from typing import Optional, Any, Dict import numpy as np import pandas as pd from more_itertools import first from networkx import Graph, to_numpy_matrix import matplotlib.pyplot as plt import seaborn as sb from adam.semantics import Concept, KindConcept, ObjectConcept, ActionConcept class SemanticsManager: def __init__(self, semantics_graph: Graph) -> None: self.semantics_graph: Graph = Graph() # Create a new type of edge for each edge in the original semantics graph # If any of the nodes is an action concept, we want to make a distinct new node to track syntax for u, v, data in semantics_graph.edges(data=True): syntactic_position = data["slot"] new_u = ( self.concept_as_str_node(u, syntactic_position) if isinstance(u, ActionConcept) else self.concept_as_str_node(u) ) new_v = ( self.concept_as_str_node(v, syntactic_position) if isinstance(v, ActionConcept) else self.concept_as_str_node(v) ) self.semantics_graph.add_edge(new_u, new_v, weight=data["weight"]) self.nodes = list(self.semantics_graph.nodes) self.semantics_matrix = to_numpy_matrix(self.semantics_graph) def object_concept_embedding(self, concept: str) -> Any: # Get a numpy array weighted adjacency embedding of the concept from the graph return self.semantics_matrix[self.nodes.index(concept)] def kind_concept_embedding(self, concept: str) -> Any: # Get a numpy array weighted adjacency embedding averaging the members of a kind concept in the graph member_embeddings = np.vstack( [ self.object_concept_embedding(member) for member in self.semantics_graph.neighbors(concept) ] ) return np.mean(member_embeddings, axis=0) def evaluate_kind_membership(self, word: str, kind: str) -> float: word_node = self.concept_as_str_node(ObjectConcept(word)) kind_node = self.concept_as_str_node(KindConcept(kind)) if kind_node not in self.nodes or word_node not in self.nodes: return 0 return cos_sim( self.object_concept_embedding(word_node), self.kind_concept_embedding(kind_node), ) @staticmethod def concept_as_str_node(concept: Concept, syntactic_position="") -> str: if syntactic_position: return f"{concept.debug_string}_{str(type(concept))}_{syntactic_position}" else: return f"{concept.debug_string}_{str(type(concept))}" def get_concept_node_from_graph( identifier: str, semantics_graph: Graph ) -> Optional[Concept]: return first([n for n in semantics_graph.nodes if n.debug_string == identifier], None) def cos_sim(a, b) -> float: dot = np.dot(a.reshape(1, -1), b.reshape(-1, 1)) norma = np.linalg.norm(a.reshape(1, -1)) normb = np.linalg.norm(b.reshape(1, -1)) return dot / (norma * normb) def generate_heatmap(nodes_to_embeddings: Dict[Concept, Any], filename: str): if not nodes_to_embeddings: return similarity_matrix = np.zeros((len(nodes_to_embeddings), len(nodes_to_embeddings))) for i, (_, embedding_1) in enumerate(nodes_to_embeddings.items()): for j, (_, embedding_2) in enumerate(nodes_to_embeddings.items()): similarity_matrix[i][j] = cos_sim(embedding_1, embedding_2) names = [n.debug_string for n in nodes_to_embeddings.keys()] df = pd.DataFrame(data=similarity_matrix, index=names, columns=names) plt.rcParams["figure.figsize"] = (20.0, 20.0) plt.rcParams["font.family"] = "serif" sb.clustermap(df, row_cluster=True, col_cluster=True) plt.savefig(f"plots/{filename}.png") plt.close()
[ "numpy.mean", "adam.semantics.ObjectConcept", "matplotlib.pyplot.savefig", "adam.semantics.KindConcept", "seaborn.clustermap", "networkx.Graph", "matplotlib.pyplot.close", "pandas.DataFrame", "more_itertools.first", "networkx.to_numpy_matrix" ]
[((2782, 2861), 'more_itertools.first', 'first', (['[n for n in semantics_graph.nodes if n.debug_string == identifier]', 'None'], {}), '([n for n in semantics_graph.nodes if n.debug_string == identifier], None)\n', (2787, 2861), False, 'from more_itertools import first\n'), ((3574, 3638), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'similarity_matrix', 'index': 'names', 'columns': 'names'}), '(data=similarity_matrix, index=names, columns=names)\n', (3586, 3638), True, 'import pandas as pd\n'), ((3735, 3788), 'seaborn.clustermap', 'sb.clustermap', (['df'], {'row_cluster': '(True)', 'col_cluster': '(True)'}), '(df, row_cluster=True, col_cluster=True)\n', (3748, 3788), True, 'import seaborn as sb\n'), ((3793, 3829), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""plots/{filename}.png"""'], {}), "(f'plots/{filename}.png')\n", (3804, 3829), True, 'import matplotlib.pyplot as plt\n'), ((3834, 3845), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (3843, 3845), True, 'import matplotlib.pyplot as plt\n'), ((408, 415), 'networkx.Graph', 'Graph', ([], {}), '()\n', (413, 415), False, 'from networkx import Graph, to_numpy_matrix\n'), ((1268, 1305), 'networkx.to_numpy_matrix', 'to_numpy_matrix', (['self.semantics_graph'], {}), '(self.semantics_graph)\n', (1283, 1305), False, 'from networkx import Graph, to_numpy_matrix\n'), ((1905, 1939), 'numpy.mean', 'np.mean', (['member_embeddings'], {'axis': '(0)'}), '(member_embeddings, axis=0)\n', (1912, 1939), True, 'import numpy as np\n'), ((2057, 2076), 'adam.semantics.ObjectConcept', 'ObjectConcept', (['word'], {}), '(word)\n', (2070, 2076), False, 'from adam.semantics import Concept, KindConcept, ObjectConcept, ActionConcept\n'), ((2123, 2140), 'adam.semantics.KindConcept', 'KindConcept', (['kind'], {}), '(kind)\n', (2134, 2140), False, 'from adam.semantics import Concept, KindConcept, ObjectConcept, ActionConcept\n')]
"""test_dataio.py - tests the dataio module <NAME> (TRI/Austin, Inc.) """ __author__ = '<NAME>' import unittest from models import dataio from controllers import pathfinder from utils.skiptest import skipIfModuleNotInstalled import h5py import numpy as np import numpy.testing import scipy.misc import os import random class TestDataIO(unittest.TestCase): """Tests Data IO functions""" def setUp(self): self.sample_data = np.array(self.random_data()) self.sample_data_basename = "sample.dat" self.sample_data_file = os.path.join(os.path.dirname(__file__), self.sample_data_basename) with h5py.File(self.sample_data_file, 'w') as fidout: fidout.create_dataset(self.sample_data_basename, data=self.sample_data) def random_data(self): """Returns a list of random data""" return [random.uniform(-100, 100) for i in range(25)] def test_save_data(self): """Verify save_data function saves NumPy array to disk""" sample_filename = "test_savedata.dat" sample_path = os.path.join(os.path.dirname(__file__), sample_filename) dataio.save_data(sample_path, self.sample_data) self.assertTrue(os.path.exists(sample_path + ".hdf5")) with h5py.File(sample_path + ".hdf5", "r") as fidin: froot, ext = os.path.splitext(os.path.basename(sample_filename)) for key in fidin.keys(): if key.startswith(froot): read_data = fidin[key][...] self.assertTrue(np.array_equal(self.sample_data, read_data)) if os.path.exists(sample_path + ".hdf5"): os.remove(sample_path + ".hdf5") def test_get_data(self): """Verify get_data function returns a NumPy array""" read_data = dataio.get_data(self.sample_data_file) self.assertTrue(np.array_equal(self.sample_data, read_data)) def test_get_data_slice(self): """Verify get_data function returns a slice if specified""" slice_idx = np.s_[5:15] read_hyperslab = dataio.get_data(self.sample_data_file, slice_idx) self.assertTrue(np.array_equal(self.sample_data[slice_idx], read_hyperslab)) def test_get_txt_data(self): """Verify retrieval of ASCII delimited data""" sample_data_file = os.path.join(os.path.dirname(__file__), 'support_files', '1.25 from hole Single Column.asc') assert(os.path.exists(sample_data_file)) import_params = {'delimiter': None} expected_data = np.loadtxt(sample_data_file, delimiter=import_params['delimiter']) retrieved_data = dataio.get_txt_data(sample_data_file, **import_params) self.assertTrue(np.array_equal(expected_data, retrieved_data)) def test_import_txt(self): """Verify import of ASCII delimited data files""" sample_data_file = os.path.join(os.path.dirname(__file__), 'support_files', '1.25 from hole Single Column.asc') assert(os.path.exists(sample_data_file)) import_params = {'delimiter': None} expected_data = np.loadtxt(sample_data_file, delimiter=import_params['delimiter']) dataio.import_txt(sample_data_file, **import_params) dest_file = os.path.join(pathfinder.data_path(), os.path.basename(sample_data_file) + ".hdf5") self.assertTrue(os.path.exists(dest_file)) with h5py.File(dest_file, "r") as fidin: root, ext = os.path.splitext(os.path.basename(dest_file)) for key in fidin.keys(): if key.startswith(root): read_data = fidin[key][...] self.assertTrue(np.array_equal(expected_data, read_data)) try: if os.path.exists(dest_file): os.remove(dest_file) except WindowsError: # file in use pass def test_export_txt(self): """Verify export of data to delimited ASCII""" # Use integer data to avoid the floating point conversion to/from files sample_data = self.sample_data.astype(np.int64) sample_data_file = os.path.join(os.path.dirname(__file__), 'support_files', 'sample.hdf5') dest_file = os.path.join(os.path.dirname(__file__), 'support_files', 'sample.txt') with h5py.File(sample_data_file, "w") as fidout: fidout.create_dataset(os.path.basename(sample_data_file), data=sample_data) export_params = {'delimiter': ','} dataio.export_txt(dest_file, sample_data_file, **export_params) retrieved_data = np.genfromtxt(dest_file, delimiter=export_params['delimiter']) self.assertTrue(np.array_equal(sample_data, retrieved_data)) try: if os.path.exists(sample_data_file): os.remove(sample_data_file) if os.path.exists(dest_file): os.remove(dest_file) except WindowsError: # file in use pass def test_export3D_txt(self): """Verify export of 3D data to delimited ASCII""" x_size = 5 y_size = 4 z_size = 6 sample_data = np.empty((y_size, x_size, z_size)) for xidx in range(x_size): for yidx in range(y_size): for zidx in range(z_size): sample_data[yidx, xidx, zidx] = int(random.uniform(-100, 100)) sample_data_file = os.path.join(os.path.dirname(__file__), 'support_files', 'sample3d.hdf5') dest_file = os.path.join(os.path.dirname(__file__), 'support_files', 'sample3d.txt') with h5py.File(sample_data_file, "w") as fidout: fidout.create_dataset(os.path.basename(sample_data_file), data=sample_data) export_params = {'delimiter': ','} dataio.export_txt(dest_file, sample_data_file, **export_params) retrieved_data = np.empty(sample_data.shape) with open(dest_file, "rb") as fidin: zidx = 0 for line in fidin: if not line.startswith('#'): x, y, z = line.split(export_params['delimiter']) x = int(x) y = int(y) z = float(z.strip()) retrieved_data[y, x, zidx] = z zidx += 1 if zidx > sample_data.shape[2]-1: zidx = 0 self.assertTrue(np.array_equal(sample_data, retrieved_data)) try: if os.path.exists(sample_data_file): os.remove(sample_data_file) if os.path.exists(dest_file): os.remove(dest_file) except WindowsError: # file in use pass @skipIfModuleNotInstalled("dicom") def test_get_dicom_data(self): """Verify retrieval of DICOM / DICONDE data""" import dicom diconde_folder = os.path.join(os.path.dirname(__file__), 'support_files') for root, dirs, files in os.walk(diconde_folder): for fname in files: dicom_data_file = os.path.join(root, fname) basename, ext = os.path.splitext(dicom_data_file) # Simple check to ensure we're looking at DICOM files if ext.lower() == '.dcm': dicom_data = dicom.read_file(dicom_data_file) dicom_arr = dicom_data.pixel_array retrieved_data = dataio.get_dicom_data(dicom_data_file) self.assertTrue(np.array_equal(dicom_arr, retrieved_data)) @skipIfModuleNotInstalled("dicom") def test_import_dicom(self): """Verify import of DICOM / DICONDE data""" # Load the ASTM DICONDE example files, # save, then ensure the resulting arrays # are identical import dicom diconde_folder = os.path.join(os.path.dirname(__file__), 'support_files') for root, dirs, files in os.walk(diconde_folder): for fname in files: dicom_data_file = os.path.join(root, fname) basename, ext = os.path.splitext(dicom_data_file) # Simple check to ensure we're looking at DICOM files if ext.lower() == '.dcm': dicom_data = dicom.read_file(dicom_data_file) dicom_arr = dicom_data.pixel_array dataio.import_dicom(dicom_data_file) dest_file = os.path.join(pathfinder.data_path(), os.path.basename(dicom_data_file) + ".hdf5") self.assertTrue(os.path.exists(dest_file)) with h5py.File(dest_file, "r") as fidin: froot, ext = os.path.splitext(os.path.basename(dest_file)) for key in fidin.keys(): if key.startswith(froot): read_data = fidin[key][...] self.assertTrue(np.array_equal(dicom_arr, read_data)) try: if os.path.exists(dest_file): os.remove(dest_file) except WindowsError: # File in use pass def test_get_img_data(self): """Verify retrieval of bitmap data""" sample_data_file = os.path.join(os.path.dirname(__file__), 'support_files', 'austin_sky320x240.jpg') assert(os.path.exists(sample_data_file)) expected_data = scipy.misc.imread(sample_data_file, flatten=True) retrieved_data = dataio.get_img_data(sample_data_file, flatten=True) self.assertTrue(np.array_equal(expected_data, retrieved_data)) def test_import_img(self): """Verify import of images""" sample_data_file = os.path.join(os.path.dirname(__file__), 'support_files', 'austin_sky320x240.jpg') assert(os.path.exists(sample_data_file)) expected_data = scipy.misc.imread(sample_data_file, flatten=True) dataio.import_img(sample_data_file, flatten=True) dest_file = os.path.join(pathfinder.data_path(), os.path.basename(sample_data_file) + ".hdf5") self.assertTrue(os.path.exists(dest_file)) with h5py.File(dest_file, "r") as fidin: root, ext = os.path.splitext(os.path.basename(dest_file)) for key in fidin.keys(): if key.startswith(root): read_data = fidin[key][...] self.assertTrue(np.array_equal(expected_data, read_data)) try: if os.path.exists(dest_file): os.remove(dest_file) except WindowsError: # file in use pass def test_get_utwin_tof_data(self): """Verify retrieval of UTWin Time Of Flight data through convenience function""" sample_data_file = os.path.join(os.path.dirname(__file__), 'support_files', 'CScanData.csc') tof_data_file = os.path.join(os.path.dirname(__file__), 'support_files', 'CScanData_tofdata.npy') tof_resolution = 0.01 assert(os.path.exists(tof_data_file)) expected_tof_data = np.load(tof_data_file) * tof_resolution returned_tof_data = dataio.get_utwin_tof_data(sample_data_file)[0] numpy.testing.assert_array_almost_equal(expected_tof_data, returned_tof_data, decimal=3) def test_import_utwin_tof(self): """Verify import of UTWin Time Of Flight data through convenience function""" tof_data_file = os.path.join(os.path.dirname(__file__), 'support_files', 'CScanData_tofdata.npy') sample_data_file = os.path.join(os.path.dirname(__file__), 'support_files', 'CScanData.csc') tof_resolution = 0.01 expected_tof_data = np.load(tof_data_file) * tof_resolution root, ext = os.path.splitext(os.path.basename(sample_data_file)) dest_file = os.path.join(pathfinder.data_path(), os.path.basename(root) + "_tofdata0.csc.hdf5") dataio.import_utwin_tof(sample_data_file) self.assertTrue(os.path.exists(dest_file)) with h5py.File(dest_file, "r") as fidin: root, ext = os.path.splitext(os.path.basename(dest_file)) for key in fidin.keys(): if key.startswith(root): read_data = fidin[key][...] numpy.testing.assert_array_almost_equal(expected_tof_data, read_data, decimal=3) try: if os.path.exists(dest_file): os.remove(dest_file) except WindowsError: # file in use pass def test_get_utwin_amp_data(self): """Verify retrieval of UTWin amplitude data through convenience function""" sample_data_file = os.path.join(os.path.dirname(__file__), 'support_files', 'CScanData.csc') amp_data_file = os.path.join(os.path.dirname(__file__), 'support_files', 'CScanData_ampdata.npy') assert(os.path.exists(amp_data_file)) expected_tof_data = np.load(amp_data_file) self.assertTrue(np.array_equal(expected_tof_data, dataio.get_utwin_amp_data(sample_data_file)[0])) def test_import_utwin_amp(self): """Verify import of UTWin amplitude data through convenience function""" amp_data_file = os.path.join(os.path.dirname(__file__), 'support_files', 'CScanData_ampdata.npy') sample_data_file = os.path.join(os.path.dirname(__file__), 'support_files', 'CScanData.csc') expected_amp_data = np.load(amp_data_file) root, ext = os.path.splitext(os.path.basename(sample_data_file)) dest_file = os.path.join(pathfinder.data_path(), os.path.basename(root) + "_ampdata0.csc.hdf5") dataio.import_utwin_amp(sample_data_file) self.assertTrue(os.path.exists(dest_file)) with h5py.File(dest_file, "r") as fidin: root, ext = os.path.splitext(os.path.basename(dest_file)) for key in fidin.keys(): if key.startswith(root): read_data = fidin[key][...] self.assertTrue(np.array_equal(expected_amp_data, read_data)) try: if os.path.exists(dest_file): os.remove(dest_file) except WindowsError: # file in use pass def test_get_utwin_data(self): """Verify returning UTWin data""" sample_data_file = os.path.join(os.path.dirname(__file__), 'support_files', 'CScanData.csc') sample_reader = dataio.UTWinCScanDataFile(sample_data_file) sample_reader.read_data() expected_data = sample_reader.data returned_data = dataio.get_utwin_data(sample_data_file) for datatype in expected_data: self.assertTrue(np.array_equal(expected_data[datatype], returned_data[datatype])) def test_get_winspect_data(self): """Verify retrieval of Winspect data through convenience function""" sample_data_file = os.path.join(os.path.dirname(__file__), 'support_files', 'sample_data.sdt') assert(os.path.exists(sample_data_file)) scan_reader = dataio.WinspectReader(sample_data_file) expected_data_list = scan_reader.get_winspect_data() retrieved_data_list = dataio.get_winspect_data(sample_data_file) self.assertEqual(len(expected_data_list), len(retrieved_data_list)) for data_array_idx in range(len(expected_data_list)): self.assertTrue(np.array_equal(expected_data_list[data_array_idx].data, retrieved_data_list[data_array_idx].data)) def test_import_winspect(self): """Verify import of Winspect data through convenience function""" sample_data_file = os.path.join(os.path.dirname(__file__), 'support_files', 'sample_data.sdt') assert(os.path.exists(sample_data_file)) output_basename, ext = os.path.splitext(sample_data_file) amp_dest_file = os.path.join(pathfinder.data_path(), os.path.basename(output_basename) + "_ampdata0" + ext + ".hdf5") waveform_dest_file = os.path.join(pathfinder.data_path(), os.path.basename(output_basename) + "_waveformdata0" + ext + ".hdf5") dataio.import_winspect(sample_data_file) expected_data_list = dataio.get_winspect_data(sample_data_file) for dataset in expected_data_list: if "amplitude" in dataset.data_type: dest_file = amp_dest_file elif "waveform" in dataset.data_type: dest_file = waveform_dest_file with h5py.File(dest_file, "r") as fidin: root, ext = os.path.splitext(os.path.basename(dest_file)) for key in fidin.keys(): if key.startswith(root): read_data = fidin[key][...] self.assertTrue(np.array_equal(dataset.data, read_data)) try: if os.path.exists(dest_file): os.remove(dest_file) except WindowsError: # file in use pass def tearDown(self): if os.path.exists(self.sample_data_file + ".hdf5"): os.remove(self.sample_data_file + ".hdf5") if os.path.exists(self.sample_data_file): os.remove(self.sample_data_file) class TestUTWinCScanReader(unittest.TestCase): """Tests the UTWinCScanReader class""" def setUp(self): self.sample_data_file = os.path.join(os.path.dirname(__file__), 'support_files', 'CScanData.csc') assert(os.path.exists(self.sample_data_file)) self.cscan_reader = dataio.UTWinCscanReader() def test_basicfile_parameters(self): """Verify the basic parameters of the CSC file format are correct""" self.assertEqual(self.cscan_reader.header_string_length, 15) expected_message_ids = {'CSCAN_DATA': 2300, 'WAVEFORM_pre240': 2016, 'WAVEFORM_post240': 2303, 'UTSAVE_UTCD0': 2010, 'UTSAVE_UTCD1': 2011, 'UTSAVE_UTCD2': 2012, 'UTSAVE_UTCD4': 2014, 'UTSAVE_UTPro0': 253, 'PROJECT': 301, 'UTSAVE_UTHead': 100, 'UTSAVE_UTCScan0': 750, 'UTSAVE_UTCD10': 2020, 'UTSAVE_UTCScan3': 753} self.assertDictEqual(expected_message_ids, self.cscan_reader.message_ids) def test_is_cscanfile(self): """Verify reader correctly identifies CSC files""" self.assertTrue(self.cscan_reader.is_cscanfile(self.sample_data_file)) def test_msg_info(self): """Verify reader correctly returns message ID and length""" with open(self.sample_data_file, "rb") as fidin: fidin.seek(self.cscan_reader.header_string_length) first_message = (100, 14) self.assertTupleEqual(first_message, self.cscan_reader.msg_info(fidin)) def test_find_message(self): """Verify find_message returns the expected file positions""" expected_file_positions = ((2014, 38037), (2011, 38059), (2010, 38003), (2012, 422075), (2010, 38003), (2010, 38003)) for message_id, expected_pos in expected_file_positions: self.assertEqual(self.cscan_reader.find_message(self.sample_data_file, message_id), expected_pos) def test_find_blocks(self): """Verify find_blocks returns the file positions for the specified message ID""" # Search for UTSave_UTAD0 (Message ID 950) - contains A/D settings for each channel expected_filed_positions = [173, 920, 1667, 2414, 3161, 3908, 4655, 5402] self.assertListEqual(expected_filed_positions, self.cscan_reader.find_blocks(self.sample_data_file, 950)) def test_read_field(self): """Verify read_field correctly parses the specified message block""" start_pos = self.cscan_reader.find_message(self.sample_data_file, 950) self.assertTrue(start_pos != -1) with open(self.sample_data_file, "rb") as fidin: fidin.seek(start_pos) # Read a sample of A/D settings for the first channel expected_ad_delay = np.fromfile(fidin, self.cscan_reader.field_sizes['float'], 1)[0] expected_ad_width = np.fromfile(fidin, self.cscan_reader.field_sizes['float'], 1)[0] expected_ad_blanking_width = np.fromfile(fidin, self.cscan_reader.field_sizes['float'], 1)[0] expected_ad_gain = np.fromfile(fidin, self.cscan_reader.field_sizes['float'], 1)[0] expected_ad_offset = np.fromfile(fidin, self.cscan_reader.field_sizes['float'], 1)[0] expected_ad_trigger_level = np.fromfile(fidin, self.cscan_reader.field_sizes['float'], 1)[0] expected_ad_trigger_rate = np.fromfile(fidin, self.cscan_reader.field_sizes['float'], 1)[0] with open(self.sample_data_file, "rb") as fidin: fidin.seek(start_pos) ad_delay = self.cscan_reader.read_field(fidin, self.cscan_reader.field_sizes['float']) ad_width = self.cscan_reader.read_field(fidin, self.cscan_reader.field_sizes['float']) ad_blanking_width = self.cscan_reader.read_field(fidin, self.cscan_reader.field_sizes['float']) ad_gain = self.cscan_reader.read_field(fidin, self.cscan_reader.field_sizes['float']) ad_offset = self.cscan_reader.read_field(fidin, self.cscan_reader.field_sizes['float']) ad_trigger_level = self.cscan_reader.read_field(fidin, self.cscan_reader.field_sizes['float']) ad_trigger_rate = self.cscan_reader.read_field(fidin, self.cscan_reader.field_sizes['float']) self.assertAlmostEqual(expected_ad_delay, ad_delay) self.assertAlmostEqual(expected_ad_width, ad_width) self.assertAlmostEqual(expected_ad_blanking_width, ad_blanking_width) self.assertAlmostEqual(expected_ad_gain, ad_gain) self.assertAlmostEqual(expected_ad_offset, ad_offset) self.assertAlmostEqual(expected_ad_trigger_level, ad_trigger_level) self.assertAlmostEqual(expected_ad_trigger_rate, ad_trigger_rate) class TestUTWinCScanDataFile(unittest.TestCase): """Tests the UTWinCScanDataFile class. Note: the sample UTWin data files available to TRI as of May 2013 are export-controlled and can't be distributed, which in turn limits the tests that can be performed. The UTWinCScanDataFile class has been tested against real inspection data, however without additional sample files you should consider the code experimental. For more details, contact TRI. """ def setUp(self): self.sample_data_file = os.path.join(os.path.dirname(__file__), 'support_files', 'CScanData.csc') self.cscan_datafile = dataio.UTWinCScanDataFile(self.sample_data_file) def test_get_scan_version(self): """Verify get_scan_version returns the correct scan version""" self.assertEqual(self.cscan_datafile.get_scan_version(), 117) def test_read_scan_properties(self): """Verify read_scan_properties correctly compiles required scan settings""" # Read a sample of the most important properties, verify read important_scan_properties = {'n_height':320, 'n_width':600, 'rf_length':2994, 'channel_active':[1, 0, 0, 0, 0, 0, 0, 0]} for idx in important_scan_properties.keys(): prop = important_scan_properties[idx] if not isinstance(prop, list): self.assertEqual(prop, self.cscan_datafile.scan_properties[idx]) else: self.assertListEqual(prop, self.cscan_datafile.scan_properties[idx]) def test_read_tof_data(self): """Verify read_tof_data correctly reads Time Of Flight data""" # Verify one TOF dataset tof_data_file = os.path.join(os.path.dirname(__file__), 'support_files', 'CScanData_tofdata.npy') tof_resolution = 0.01 assert(os.path.exists(tof_data_file)) expected_tof_data = np.load(tof_data_file) * tof_resolution self.cscan_datafile.read_tof_data() numpy.testing.assert_array_almost_equal(expected_tof_data, self.cscan_datafile.data['tof'][0], decimal=3) def test_read_amplitude_data(self): """Verify read_amplitude_data correctly reads amplitude data""" amp_data_file = os.path.join(os.path.dirname(__file__), 'support_files', 'CScanData_ampdata.npy') assert(os.path.exists(amp_data_file)) expected_amp_data = np.load(amp_data_file) self.cscan_datafile.read_amplitude_data() self.assertTrue(np.array_equal(expected_amp_data, self.cscan_datafile.data['amplitude'][0])) def test_import_tof(self): """Verify import of Time Of Flight data""" tof_data_file = os.path.join(os.path.dirname(__file__), 'support_files', 'CScanData_tofdata.npy') tof_resolution = 0.01 csc_data_file = os.path.join(os.path.dirname(__file__), 'support_files', 'CScanData') assert(os.path.exists(tof_data_file)) expected_tof_data = np.load(tof_data_file) * tof_resolution dest_file = os.path.join(pathfinder.data_path(), os.path.basename(csc_data_file) + "_tofdata0.csc.hdf5") self.cscan_datafile.import_tof_data() self.assertTrue(os.path.exists(dest_file)) with h5py.File(dest_file, "r") as fidin: root, ext = os.path.splitext(os.path.basename(dest_file)) for key in fidin.keys(): if key.startswith(root): read_data = fidin[key][...] numpy.testing.assert_array_almost_equal(expected_tof_data, read_data, decimal=3) try: if os.path.exists(dest_file): os.remove(dest_file) except WindowsError: # file in use pass def test_import_amp(self): """Verify import of amplitude data""" amp_data_file = os.path.join(os.path.dirname(__file__), 'support_files', 'CScanData_ampdata.npy') csc_data_file = os.path.join(os.path.dirname(__file__), 'support_files', 'CScanData') assert(os.path.exists(amp_data_file)) expected_amp_data = np.load(amp_data_file) dest_file = os.path.join(pathfinder.data_path(), os.path.basename(csc_data_file) + "_ampdata0.csc.hdf5") self.cscan_datafile.import_amplitude_data() self.assertTrue(os.path.exists(dest_file)) with h5py.File(dest_file, "r") as fidin: root, ext = os.path.splitext(os.path.basename(dest_file)) for key in fidin.keys(): if key.startswith(root): read_data = fidin[key][...] self.assertTrue(np.array_equal(expected_amp_data, read_data)) try: if os.path.exists(dest_file): os.remove(dest_file) except WindowsError: # file in use pass class TestWinspectReader(unittest.TestCase): """Tests the WinspectReader class.""" def setUp(self): self.sample_data_file = os.path.join(os.path.dirname(__file__), 'support_files', 'sample_data.sdt') assert(os.path.exists(self.sample_data_file)) self.scan_reader = dataio.WinspectReader(self.sample_data_file) def test_find_numbers(self): """Verify find_numbers static method correctly pulls numbers from strings""" float_strings = {"0.000000 mm":0.0, "0.775995 Usec":0.775995} int_strings = {"35 18 0 22 3 112 ":[35, 18, 0, 22, 3, 112], "Number of Sample Points : 3500":3500} bad_strings = {"Ramshackle":[], "":[]} for string in float_strings: self.assertAlmostEqual(float_strings[string], self.scan_reader.find_numbers(string)) def test_get_winspect_data(self): """Verify returning the list of arrays read from the data file""" data_reader = dataio.WinspectDataFile(self.sample_data_file) data_reader.read_data() expected_data_list = data_reader.datasets retrieved_data_list = self.scan_reader.get_winspect_data() self.assertEqual(len(expected_data_list), len(retrieved_data_list)) for data_array_idx in range(len(expected_data_list)): self.assertTrue(np.array_equal(expected_data_list[data_array_idx].data, retrieved_data_list[data_array_idx].data)) def test_import_winspect(self): """Verify importing datasets""" output_basename, ext = os.path.splitext(self.sample_data_file) amp_dest_file = os.path.join(pathfinder.data_path(), os.path.basename(output_basename) + "_ampdata0" + ext + ".hdf5") waveform_dest_file = os.path.join(pathfinder.data_path(), os.path.basename(output_basename) + "_waveformdata0" + ext + ".hdf5") self.scan_reader.import_winspect() data_reader = dataio.WinspectDataFile(self.sample_data_file) data_reader.read_data() expected_data_list = data_reader.datasets for dataset in expected_data_list: if "amplitude" in dataset.data_type: dest_file = amp_dest_file elif "waveform" in dataset.data_type: dest_file = waveform_dest_file with h5py.File(dest_file, "r") as fidin: root, ext = os.path.splitext(os.path.basename(dest_file)) for key in fidin.keys(): if key.startswith(root): read_data = fidin[key][...] self.assertTrue(np.array_equal(dataset.data, read_data)) try: if os.path.exists(dest_file): os.remove(dest_file) except WindowsError: # file in use pass if __name__ == "__main__": random.seed() unittest.main()
[ "numpy.fromfile", "models.dataio.UTWinCscanReader", "models.dataio.import_dicom", "unittest.main", "numpy.genfromtxt", "os.walk", "models.dataio.get_txt_data", "models.dataio.UTWinCScanDataFile", "os.path.exists", "models.dataio.get_winspect_data", "models.dataio.import_winspect", "os.remove",...
[((6927, 6960), 'utils.skiptest.skipIfModuleNotInstalled', 'skipIfModuleNotInstalled', (['"""dicom"""'], {}), "('dicom')\n", (6951, 6960), False, 'from utils.skiptest import skipIfModuleNotInstalled\n'), ((7764, 7797), 'utils.skiptest.skipIfModuleNotInstalled', 'skipIfModuleNotInstalled', (['"""dicom"""'], {}), "('dicom')\n", (7788, 7797), False, 'from utils.skiptest import skipIfModuleNotInstalled\n'), ((30662, 30675), 'random.seed', 'random.seed', ([], {}), '()\n', (30673, 30675), False, 'import random\n'), ((30680, 30695), 'unittest.main', 'unittest.main', ([], {}), '()\n', (30693, 30695), False, 'import unittest\n'), ((1176, 1223), 'models.dataio.save_data', 'dataio.save_data', (['sample_path', 'self.sample_data'], {}), '(sample_path, self.sample_data)\n', (1192, 1223), False, 'from models import dataio\n'), ((1644, 1681), 'os.path.exists', 'os.path.exists', (["(sample_path + '.hdf5')"], {}), "(sample_path + '.hdf5')\n", (1658, 1681), False, 'import os\n'), ((1839, 1877), 'models.dataio.get_data', 'dataio.get_data', (['self.sample_data_file'], {}), '(self.sample_data_file)\n', (1854, 1877), False, 'from models import dataio\n'), ((2108, 2157), 'models.dataio.get_data', 'dataio.get_data', (['self.sample_data_file', 'slice_idx'], {}), '(self.sample_data_file, slice_idx)\n', (2123, 2157), False, 'from models import dataio\n'), ((2507, 2539), 'os.path.exists', 'os.path.exists', (['sample_data_file'], {}), '(sample_data_file)\n', (2521, 2539), False, 'import os\n'), ((2609, 2675), 'numpy.loadtxt', 'np.loadtxt', (['sample_data_file'], {'delimiter': "import_params['delimiter']"}), "(sample_data_file, delimiter=import_params['delimiter'])\n", (2619, 2675), True, 'import numpy as np\n'), ((2701, 2755), 'models.dataio.get_txt_data', 'dataio.get_txt_data', (['sample_data_file'], {}), '(sample_data_file, **import_params)\n', (2720, 2755), False, 'from models import dataio\n'), ((3092, 3124), 'os.path.exists', 'os.path.exists', (['sample_data_file'], {}), '(sample_data_file)\n', (3106, 3124), False, 'import os\n'), ((3194, 3260), 'numpy.loadtxt', 'np.loadtxt', (['sample_data_file'], {'delimiter': "import_params['delimiter']"}), "(sample_data_file, delimiter=import_params['delimiter'])\n", (3204, 3260), True, 'import numpy as np\n'), ((3269, 3321), 'models.dataio.import_txt', 'dataio.import_txt', (['sample_data_file'], {}), '(sample_data_file, **import_params)\n', (3286, 3321), False, 'from models import dataio\n'), ((5319, 5353), 'numpy.empty', 'np.empty', (['(y_size, x_size, z_size)'], {}), '((y_size, x_size, z_size))\n', (5327, 5353), True, 'import numpy as np\n'), ((7187, 7210), 'os.walk', 'os.walk', (['diconde_folder'], {}), '(diconde_folder)\n', (7194, 7210), False, 'import os\n'), ((8140, 8163), 'os.walk', 'os.walk', (['diconde_folder'], {}), '(diconde_folder)\n', (8147, 8163), False, 'import os\n'), ((9684, 9716), 'os.path.exists', 'os.path.exists', (['sample_data_file'], {}), '(sample_data_file)\n', (9698, 9716), False, 'import os\n'), ((9817, 9868), 'models.dataio.get_img_data', 'dataio.get_img_data', (['sample_data_file'], {'flatten': '(True)'}), '(sample_data_file, flatten=True)\n', (9836, 9868), False, 'from models import dataio\n'), ((10174, 10206), 'os.path.exists', 'os.path.exists', (['sample_data_file'], {}), '(sample_data_file)\n', (10188, 10206), False, 'import os\n'), ((10290, 10339), 'models.dataio.import_img', 'dataio.import_img', (['sample_data_file'], {'flatten': '(True)'}), '(sample_data_file, flatten=True)\n', (10307, 10339), False, 'from models import dataio\n'), ((11383, 11412), 'os.path.exists', 'os.path.exists', (['tof_data_file'], {}), '(tof_data_file)\n', (11397, 11412), False, 'import os\n'), ((12301, 12342), 'models.dataio.import_utwin_tof', 'dataio.import_utwin_tof', (['sample_data_file'], {}), '(sample_data_file)\n', (12324, 12342), False, 'from models import dataio\n'), ((13238, 13267), 'os.path.exists', 'os.path.exists', (['amp_data_file'], {}), '(amp_data_file)\n', (13252, 13267), False, 'import os\n'), ((13297, 13319), 'numpy.load', 'np.load', (['amp_data_file'], {}), '(amp_data_file)\n', (13304, 13319), True, 'import numpy as np\n'), ((13781, 13803), 'numpy.load', 'np.load', (['amp_data_file'], {}), '(amp_data_file)\n', (13788, 13803), True, 'import numpy as np\n'), ((14022, 14063), 'models.dataio.import_utwin_amp', 'dataio.import_utwin_amp', (['sample_data_file'], {}), '(sample_data_file)\n', (14045, 14063), False, 'from models import dataio\n'), ((14797, 14840), 'models.dataio.UTWinCScanDataFile', 'dataio.UTWinCScanDataFile', (['sample_data_file'], {}), '(sample_data_file)\n', (14822, 14840), False, 'from models import dataio\n'), ((14942, 14981), 'models.dataio.get_utwin_data', 'dataio.get_utwin_data', (['sample_data_file'], {}), '(sample_data_file)\n', (14963, 14981), False, 'from models import dataio\n'), ((15349, 15381), 'os.path.exists', 'os.path.exists', (['sample_data_file'], {}), '(sample_data_file)\n', (15363, 15381), False, 'import os\n'), ((15405, 15444), 'models.dataio.WinspectReader', 'dataio.WinspectReader', (['sample_data_file'], {}), '(sample_data_file)\n', (15426, 15444), False, 'from models import dataio\n'), ((15536, 15578), 'models.dataio.get_winspect_data', 'dataio.get_winspect_data', (['sample_data_file'], {}), '(sample_data_file)\n', (15560, 15578), False, 'from models import dataio\n'), ((16073, 16105), 'os.path.exists', 'os.path.exists', (['sample_data_file'], {}), '(sample_data_file)\n', (16087, 16105), False, 'import os\n'), ((16138, 16172), 'os.path.splitext', 'os.path.splitext', (['sample_data_file'], {}), '(sample_data_file)\n', (16154, 16172), False, 'import os\n'), ((16522, 16562), 'models.dataio.import_winspect', 'dataio.import_winspect', (['sample_data_file'], {}), '(sample_data_file)\n', (16544, 16562), False, 'from models import dataio\n'), ((16592, 16634), 'models.dataio.get_winspect_data', 'dataio.get_winspect_data', (['sample_data_file'], {}), '(sample_data_file)\n', (16616, 16634), False, 'from models import dataio\n'), ((17420, 17467), 'os.path.exists', 'os.path.exists', (["(self.sample_data_file + '.hdf5')"], {}), "(self.sample_data_file + '.hdf5')\n", (17434, 17467), False, 'import os\n'), ((17535, 17572), 'os.path.exists', 'os.path.exists', (['self.sample_data_file'], {}), '(self.sample_data_file)\n', (17549, 17572), False, 'import os\n'), ((17854, 17891), 'os.path.exists', 'os.path.exists', (['self.sample_data_file'], {}), '(self.sample_data_file)\n', (17868, 17891), False, 'import os\n'), ((17921, 17946), 'models.dataio.UTWinCscanReader', 'dataio.UTWinCscanReader', ([], {}), '()\n', (17944, 17946), False, 'from models import dataio\n'), ((23427, 23475), 'models.dataio.UTWinCScanDataFile', 'dataio.UTWinCScanDataFile', (['self.sample_data_file'], {}), '(self.sample_data_file)\n', (23452, 23475), False, 'from models import dataio\n'), ((24711, 24740), 'os.path.exists', 'os.path.exists', (['tof_data_file'], {}), '(tof_data_file)\n', (24725, 24740), False, 'import os\n'), ((25202, 25231), 'os.path.exists', 'os.path.exists', (['amp_data_file'], {}), '(amp_data_file)\n', (25216, 25231), False, 'import os\n'), ((25261, 25283), 'numpy.load', 'np.load', (['amp_data_file'], {}), '(amp_data_file)\n', (25268, 25283), True, 'import numpy as np\n'), ((25763, 25792), 'os.path.exists', 'os.path.exists', (['tof_data_file'], {}), '(tof_data_file)\n', (25777, 25792), False, 'import os\n'), ((26896, 26925), 'os.path.exists', 'os.path.exists', (['amp_data_file'], {}), '(amp_data_file)\n', (26910, 26925), False, 'import os\n'), ((26955, 26977), 'numpy.load', 'np.load', (['amp_data_file'], {}), '(amp_data_file)\n', (26962, 26977), True, 'import numpy as np\n'), ((27985, 28022), 'os.path.exists', 'os.path.exists', (['self.sample_data_file'], {}), '(self.sample_data_file)\n', (27999, 28022), False, 'import os\n'), ((28051, 28095), 'models.dataio.WinspectReader', 'dataio.WinspectReader', (['self.sample_data_file'], {}), '(self.sample_data_file)\n', (28072, 28095), False, 'from models import dataio\n'), ((28740, 28786), 'models.dataio.WinspectDataFile', 'dataio.WinspectDataFile', (['self.sample_data_file'], {}), '(self.sample_data_file)\n', (28763, 28786), False, 'from models import dataio\n'), ((29309, 29348), 'os.path.splitext', 'os.path.splitext', (['self.sample_data_file'], {}), '(self.sample_data_file)\n', (29325, 29348), False, 'import os\n'), ((29751, 29797), 'models.dataio.WinspectDataFile', 'dataio.WinspectDataFile', (['self.sample_data_file'], {}), '(self.sample_data_file)\n', (29774, 29797), False, 'from models import dataio\n'), ((567, 592), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (582, 592), False, 'import os\n'), ((679, 716), 'h5py.File', 'h5py.File', (['self.sample_data_file', '"""w"""'], {}), "(self.sample_data_file, 'w')\n", (688, 716), False, 'import h5py\n'), ((900, 925), 'random.uniform', 'random.uniform', (['(-100)', '(100)'], {}), '(-100, 100)\n', (914, 925), False, 'import random\n'), ((1124, 1149), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (1139, 1149), False, 'import os\n'), ((1248, 1285), 'os.path.exists', 'os.path.exists', (["(sample_path + '.hdf5')"], {}), "(sample_path + '.hdf5')\n", (1262, 1285), False, 'import os\n'), ((1300, 1337), 'h5py.File', 'h5py.File', (["(sample_path + '.hdf5')", '"""r"""'], {}), "(sample_path + '.hdf5', 'r')\n", (1309, 1337), False, 'import h5py\n'), ((1695, 1727), 'os.remove', 'os.remove', (["(sample_path + '.hdf5')"], {}), "(sample_path + '.hdf5')\n", (1704, 1727), False, 'import os\n'), ((1902, 1945), 'numpy.array_equal', 'np.array_equal', (['self.sample_data', 'read_data'], {}), '(self.sample_data, read_data)\n', (1916, 1945), True, 'import numpy as np\n'), ((2182, 2241), 'numpy.array_equal', 'np.array_equal', (['self.sample_data[slice_idx]', 'read_hyperslab'], {}), '(self.sample_data[slice_idx], read_hyperslab)\n', (2196, 2241), True, 'import numpy as np\n'), ((2372, 2397), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (2387, 2397), False, 'import os\n'), ((2780, 2825), 'numpy.array_equal', 'np.array_equal', (['expected_data', 'retrieved_data'], {}), '(expected_data, retrieved_data)\n', (2794, 2825), True, 'import numpy as np\n'), ((2957, 2982), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (2972, 2982), False, 'import os\n'), ((3355, 3377), 'controllers.pathfinder.data_path', 'pathfinder.data_path', ([], {}), '()\n', (3375, 3377), False, 'from controllers import pathfinder\n'), ((3482, 3507), 'os.path.exists', 'os.path.exists', (['dest_file'], {}), '(dest_file)\n', (3496, 3507), False, 'import os\n'), ((3522, 3547), 'h5py.File', 'h5py.File', (['dest_file', '"""r"""'], {}), "(dest_file, 'r')\n", (3531, 3547), False, 'import h5py\n'), ((3860, 3885), 'os.path.exists', 'os.path.exists', (['dest_file'], {}), '(dest_file)\n', (3874, 3885), False, 'import os\n'), ((4247, 4272), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (4262, 4272), False, 'import os\n'), ((4379, 4404), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (4394, 4404), False, 'import os\n'), ((4483, 4515), 'h5py.File', 'h5py.File', (['sample_data_file', '"""w"""'], {}), "(sample_data_file, 'w')\n", (4492, 4515), False, 'import h5py\n'), ((4674, 4737), 'models.dataio.export_txt', 'dataio.export_txt', (['dest_file', 'sample_data_file'], {}), '(dest_file, sample_data_file, **export_params)\n', (4691, 4737), False, 'from models import dataio\n'), ((4767, 4829), 'numpy.genfromtxt', 'np.genfromtxt', (['dest_file'], {'delimiter': "export_params['delimiter']"}), "(dest_file, delimiter=export_params['delimiter'])\n", (4780, 4829), True, 'import numpy as np\n'), ((4931, 4963), 'os.path.exists', 'os.path.exists', (['sample_data_file'], {}), '(sample_data_file)\n', (4945, 4963), False, 'import os\n'), ((5024, 5049), 'os.path.exists', 'os.path.exists', (['dest_file'], {}), '(dest_file)\n', (5038, 5049), False, 'import os\n'), ((5594, 5619), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (5609, 5619), False, 'import os\n'), ((5688, 5713), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (5703, 5713), False, 'import os\n'), ((5761, 5793), 'h5py.File', 'h5py.File', (['sample_data_file', '"""w"""'], {}), "(sample_data_file, 'w')\n", (5770, 5793), False, 'import h5py\n'), ((5952, 6015), 'models.dataio.export_txt', 'dataio.export_txt', (['dest_file', 'sample_data_file'], {}), '(dest_file, sample_data_file, **export_params)\n', (5969, 6015), False, 'from models import dataio\n'), ((6045, 6072), 'numpy.empty', 'np.empty', (['sample_data.shape'], {}), '(sample_data.shape)\n', (6053, 6072), True, 'import numpy as np\n'), ((6704, 6736), 'os.path.exists', 'os.path.exists', (['sample_data_file'], {}), '(sample_data_file)\n', (6718, 6736), False, 'import os\n'), ((6797, 6822), 'os.path.exists', 'os.path.exists', (['dest_file'], {}), '(dest_file)\n', (6811, 6822), False, 'import os\n'), ((7110, 7135), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (7125, 7135), False, 'import os\n'), ((8063, 8088), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (8078, 8088), False, 'import os\n'), ((9560, 9585), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (9575, 9585), False, 'import os\n'), ((9893, 9938), 'numpy.array_equal', 'np.array_equal', (['expected_data', 'retrieved_data'], {}), '(expected_data, retrieved_data)\n', (9907, 9938), True, 'import numpy as np\n'), ((10050, 10075), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (10065, 10075), False, 'import os\n'), ((10373, 10395), 'controllers.pathfinder.data_path', 'pathfinder.data_path', ([], {}), '()\n', (10393, 10395), False, 'from controllers import pathfinder\n'), ((10500, 10525), 'os.path.exists', 'os.path.exists', (['dest_file'], {}), '(dest_file)\n', (10514, 10525), False, 'import os\n'), ((10540, 10565), 'h5py.File', 'h5py.File', (['dest_file', '"""r"""'], {}), "(dest_file, 'r')\n", (10549, 10565), False, 'import h5py\n'), ((10878, 10903), 'os.path.exists', 'os.path.exists', (['dest_file'], {}), '(dest_file)\n', (10892, 10903), False, 'import os\n'), ((11171, 11196), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (11186, 11196), False, 'import os\n'), ((11269, 11294), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (11284, 11294), False, 'import os\n'), ((11442, 11464), 'numpy.load', 'np.load', (['tof_data_file'], {}), '(tof_data_file)\n', (11449, 11464), True, 'import numpy as np\n'), ((11510, 11553), 'models.dataio.get_utwin_tof_data', 'dataio.get_utwin_tof_data', (['sample_data_file'], {}), '(sample_data_file)\n', (11535, 11553), False, 'from models import dataio\n'), ((11815, 11840), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (11830, 11840), False, 'import os\n'), ((11924, 11949), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (11939, 11949), False, 'import os\n'), ((12043, 12065), 'numpy.load', 'np.load', (['tof_data_file'], {}), '(tof_data_file)\n', (12050, 12065), True, 'import numpy as np\n'), ((12120, 12154), 'os.path.basename', 'os.path.basename', (['sample_data_file'], {}), '(sample_data_file)\n', (12136, 12154), False, 'import os\n'), ((12189, 12211), 'controllers.pathfinder.data_path', 'pathfinder.data_path', ([], {}), '()\n', (12209, 12211), False, 'from controllers import pathfinder\n'), ((12367, 12392), 'os.path.exists', 'os.path.exists', (['dest_file'], {}), '(dest_file)\n', (12381, 12392), False, 'import os\n'), ((12407, 12432), 'h5py.File', 'h5py.File', (['dest_file', '"""r"""'], {}), "(dest_file, 'r')\n", (12416, 12432), False, 'import h5py\n'), ((12768, 12793), 'os.path.exists', 'os.path.exists', (['dest_file'], {}), '(dest_file)\n', (12782, 12793), False, 'import os\n'), ((13056, 13081), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (13071, 13081), False, 'import os\n'), ((13154, 13179), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (13169, 13179), False, 'import os\n'), ((13583, 13608), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (13598, 13608), False, 'import os\n'), ((13692, 13717), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (13707, 13717), False, 'import os\n'), ((13841, 13875), 'os.path.basename', 'os.path.basename', (['sample_data_file'], {}), '(sample_data_file)\n', (13857, 13875), False, 'import os\n'), ((13910, 13932), 'controllers.pathfinder.data_path', 'pathfinder.data_path', ([], {}), '()\n', (13930, 13932), False, 'from controllers import pathfinder\n'), ((14088, 14113), 'os.path.exists', 'os.path.exists', (['dest_file'], {}), '(dest_file)\n', (14102, 14113), False, 'import os\n'), ((14128, 14153), 'h5py.File', 'h5py.File', (['dest_file', '"""r"""'], {}), "(dest_file, 'r')\n", (14137, 14153), False, 'import h5py\n'), ((14470, 14495), 'os.path.exists', 'os.path.exists', (['dest_file'], {}), '(dest_file)\n', (14484, 14495), False, 'import os\n'), ((14712, 14737), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (14727, 14737), False, 'import os\n'), ((15271, 15296), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (15286, 15296), False, 'import os\n'), ((15995, 16020), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (16010, 16020), False, 'import os\n'), ((16210, 16232), 'controllers.pathfinder.data_path', 'pathfinder.data_path', ([], {}), '()\n', (16230, 16232), False, 'from controllers import pathfinder\n'), ((16378, 16400), 'controllers.pathfinder.data_path', 'pathfinder.data_path', ([], {}), '()\n', (16398, 16400), False, 'from controllers import pathfinder\n'), ((17481, 17523), 'os.remove', 'os.remove', (["(self.sample_data_file + '.hdf5')"], {}), "(self.sample_data_file + '.hdf5')\n", (17490, 17523), False, 'import os\n'), ((17586, 17618), 'os.remove', 'os.remove', (['self.sample_data_file'], {}), '(self.sample_data_file)\n', (17595, 17618), False, 'import os\n'), ((17778, 17803), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (17793, 17803), False, 'import os\n'), ((23336, 23361), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (23351, 23361), False, 'import os\n'), ((24597, 24622), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (24612, 24622), False, 'import os\n'), ((24770, 24792), 'numpy.load', 'np.load', (['tof_data_file'], {}), '(tof_data_file)\n', (24777, 24792), True, 'import numpy as np\n'), ((25118, 25143), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (25133, 25143), False, 'import os\n'), ((25358, 25433), 'numpy.array_equal', 'np.array_equal', (['expected_amp_data', "self.cscan_datafile.data['amplitude'][0]"], {}), "(expected_amp_data, self.cscan_datafile.data['amplitude'][0])\n", (25372, 25433), True, 'import numpy as np\n'), ((25555, 25580), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (25570, 25580), False, 'import os\n'), ((25691, 25716), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (25706, 25716), False, 'import os\n'), ((25822, 25844), 'numpy.load', 'np.load', (['tof_data_file'], {}), '(tof_data_file)\n', (25829, 25844), True, 'import numpy as np\n'), ((25895, 25917), 'controllers.pathfinder.data_path', 'pathfinder.data_path', ([], {}), '()\n', (25915, 25917), False, 'from controllers import pathfinder\n'), ((26078, 26103), 'os.path.exists', 'os.path.exists', (['dest_file'], {}), '(dest_file)\n', (26092, 26103), False, 'import os\n'), ((26118, 26143), 'h5py.File', 'h5py.File', (['dest_file', '"""r"""'], {}), "(dest_file, 'r')\n", (26127, 26143), False, 'import h5py\n'), ((26479, 26504), 'os.path.exists', 'os.path.exists', (['dest_file'], {}), '(dest_file)\n', (26493, 26504), False, 'import os\n'), ((26718, 26743), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (26733, 26743), False, 'import os\n'), ((26824, 26849), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (26839, 26849), False, 'import os\n'), ((27011, 27033), 'controllers.pathfinder.data_path', 'pathfinder.data_path', ([], {}), '()\n', (27031, 27033), False, 'from controllers import pathfinder\n'), ((27200, 27225), 'os.path.exists', 'os.path.exists', (['dest_file'], {}), '(dest_file)\n', (27214, 27225), False, 'import os\n'), ((27240, 27265), 'h5py.File', 'h5py.File', (['dest_file', '"""r"""'], {}), "(dest_file, 'r')\n", (27249, 27265), False, 'import h5py\n'), ((27582, 27607), 'os.path.exists', 'os.path.exists', (['dest_file'], {}), '(dest_file)\n', (27596, 27607), False, 'import os\n'), ((27862, 27887), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (27877, 27887), False, 'import os\n'), ((29386, 29408), 'controllers.pathfinder.data_path', 'pathfinder.data_path', ([], {}), '()\n', (29406, 29408), False, 'from controllers import pathfinder\n'), ((29550, 29572), 'controllers.pathfinder.data_path', 'pathfinder.data_path', ([], {}), '()\n', (29570, 29572), False, 'from controllers import pathfinder\n'), ((1390, 1423), 'os.path.basename', 'os.path.basename', (['sample_filename'], {}), '(sample_filename)\n', (1406, 1423), False, 'import os\n'), ((3412, 3446), 'os.path.basename', 'os.path.basename', (['sample_data_file'], {}), '(sample_data_file)\n', (3428, 3446), False, 'import os\n'), ((3599, 3626), 'os.path.basename', 'os.path.basename', (['dest_file'], {}), '(dest_file)\n', (3615, 3626), False, 'import os\n'), ((3903, 3923), 'os.remove', 'os.remove', (['dest_file'], {}), '(dest_file)\n', (3912, 3923), False, 'import os\n'), ((4561, 4595), 'os.path.basename', 'os.path.basename', (['sample_data_file'], {}), '(sample_data_file)\n', (4577, 4595), False, 'import os\n'), ((4858, 4901), 'numpy.array_equal', 'np.array_equal', (['sample_data', 'retrieved_data'], {}), '(sample_data, retrieved_data)\n', (4872, 4901), True, 'import numpy as np\n'), ((4981, 5008), 'os.remove', 'os.remove', (['sample_data_file'], {}), '(sample_data_file)\n', (4990, 5008), False, 'import os\n'), ((5067, 5087), 'os.remove', 'os.remove', (['dest_file'], {}), '(dest_file)\n', (5076, 5087), False, 'import os\n'), ((5839, 5873), 'os.path.basename', 'os.path.basename', (['sample_data_file'], {}), '(sample_data_file)\n', (5855, 5873), False, 'import os\n'), ((6631, 6674), 'numpy.array_equal', 'np.array_equal', (['sample_data', 'retrieved_data'], {}), '(sample_data, retrieved_data)\n', (6645, 6674), True, 'import numpy as np\n'), ((6754, 6781), 'os.remove', 'os.remove', (['sample_data_file'], {}), '(sample_data_file)\n', (6763, 6781), False, 'import os\n'), ((6840, 6860), 'os.remove', 'os.remove', (['dest_file'], {}), '(dest_file)\n', (6849, 6860), False, 'import os\n'), ((7278, 7303), 'os.path.join', 'os.path.join', (['root', 'fname'], {}), '(root, fname)\n', (7290, 7303), False, 'import os\n'), ((7336, 7369), 'os.path.splitext', 'os.path.splitext', (['dicom_data_file'], {}), '(dicom_data_file)\n', (7352, 7369), False, 'import os\n'), ((8231, 8256), 'os.path.join', 'os.path.join', (['root', 'fname'], {}), '(root, fname)\n', (8243, 8256), False, 'import os\n'), ((8289, 8322), 'os.path.splitext', 'os.path.splitext', (['dicom_data_file'], {}), '(dicom_data_file)\n', (8305, 8322), False, 'import os\n'), ((10430, 10464), 'os.path.basename', 'os.path.basename', (['sample_data_file'], {}), '(sample_data_file)\n', (10446, 10464), False, 'import os\n'), ((10617, 10644), 'os.path.basename', 'os.path.basename', (['dest_file'], {}), '(dest_file)\n', (10633, 10644), False, 'import os\n'), ((10921, 10941), 'os.remove', 'os.remove', (['dest_file'], {}), '(dest_file)\n', (10930, 10941), False, 'import os\n'), ((12246, 12268), 'os.path.basename', 'os.path.basename', (['root'], {}), '(root)\n', (12262, 12268), False, 'import os\n'), ((12484, 12511), 'os.path.basename', 'os.path.basename', (['dest_file'], {}), '(dest_file)\n', (12500, 12511), False, 'import os\n'), ((12811, 12831), 'os.remove', 'os.remove', (['dest_file'], {}), '(dest_file)\n', (12820, 12831), False, 'import os\n'), ((13967, 13989), 'os.path.basename', 'os.path.basename', (['root'], {}), '(root)\n', (13983, 13989), False, 'import os\n'), ((14205, 14232), 'os.path.basename', 'os.path.basename', (['dest_file'], {}), '(dest_file)\n', (14221, 14232), False, 'import os\n'), ((14513, 14533), 'os.remove', 'os.remove', (['dest_file'], {}), '(dest_file)\n', (14522, 14533), False, 'import os\n'), ((15049, 15113), 'numpy.array_equal', 'np.array_equal', (['expected_data[datatype]', 'returned_data[datatype]'], {}), '(expected_data[datatype], returned_data[datatype])\n', (15063, 15113), True, 'import numpy as np\n'), ((15745, 15847), 'numpy.array_equal', 'np.array_equal', (['expected_data_list[data_array_idx].data', 'retrieved_data_list[data_array_idx].data'], {}), '(expected_data_list[data_array_idx].data, retrieved_data_list\n [data_array_idx].data)\n', (15759, 15847), True, 'import numpy as np\n'), ((16883, 16908), 'h5py.File', 'h5py.File', (['dest_file', '"""r"""'], {}), "(dest_file, 'r')\n", (16892, 16908), False, 'import h5py\n'), ((17248, 17273), 'os.path.exists', 'os.path.exists', (['dest_file'], {}), '(dest_file)\n', (17262, 17273), False, 'import os\n'), ((20843, 20904), 'numpy.fromfile', 'np.fromfile', (['fidin', "self.cscan_reader.field_sizes['float']", '(1)'], {}), "(fidin, self.cscan_reader.field_sizes['float'], 1)\n", (20854, 20904), True, 'import numpy as np\n'), ((20940, 21001), 'numpy.fromfile', 'np.fromfile', (['fidin', "self.cscan_reader.field_sizes['float']", '(1)'], {}), "(fidin, self.cscan_reader.field_sizes['float'], 1)\n", (20951, 21001), True, 'import numpy as np\n'), ((21046, 21107), 'numpy.fromfile', 'np.fromfile', (['fidin', "self.cscan_reader.field_sizes['float']", '(1)'], {}), "(fidin, self.cscan_reader.field_sizes['float'], 1)\n", (21057, 21107), True, 'import numpy as np\n'), ((21142, 21203), 'numpy.fromfile', 'np.fromfile', (['fidin', "self.cscan_reader.field_sizes['float']", '(1)'], {}), "(fidin, self.cscan_reader.field_sizes['float'], 1)\n", (21153, 21203), True, 'import numpy as np\n'), ((21240, 21301), 'numpy.fromfile', 'np.fromfile', (['fidin', "self.cscan_reader.field_sizes['float']", '(1)'], {}), "(fidin, self.cscan_reader.field_sizes['float'], 1)\n", (21251, 21301), True, 'import numpy as np\n'), ((21345, 21406), 'numpy.fromfile', 'np.fromfile', (['fidin', "self.cscan_reader.field_sizes['float']", '(1)'], {}), "(fidin, self.cscan_reader.field_sizes['float'], 1)\n", (21356, 21406), True, 'import numpy as np\n'), ((21449, 21510), 'numpy.fromfile', 'np.fromfile', (['fidin', "self.cscan_reader.field_sizes['float']", '(1)'], {}), "(fidin, self.cscan_reader.field_sizes['float'], 1)\n", (21460, 21510), True, 'import numpy as np\n'), ((25952, 25983), 'os.path.basename', 'os.path.basename', (['csc_data_file'], {}), '(csc_data_file)\n', (25968, 25983), False, 'import os\n'), ((26195, 26222), 'os.path.basename', 'os.path.basename', (['dest_file'], {}), '(dest_file)\n', (26211, 26222), False, 'import os\n'), ((26522, 26542), 'os.remove', 'os.remove', (['dest_file'], {}), '(dest_file)\n', (26531, 26542), False, 'import os\n'), ((27068, 27099), 'os.path.basename', 'os.path.basename', (['csc_data_file'], {}), '(csc_data_file)\n', (27084, 27099), False, 'import os\n'), ((27317, 27344), 'os.path.basename', 'os.path.basename', (['dest_file'], {}), '(dest_file)\n', (27333, 27344), False, 'import os\n'), ((27625, 27645), 'os.remove', 'os.remove', (['dest_file'], {}), '(dest_file)\n', (27634, 27645), False, 'import os\n'), ((29102, 29204), 'numpy.array_equal', 'np.array_equal', (['expected_data_list[data_array_idx].data', 'retrieved_data_list[data_array_idx].data'], {}), '(expected_data_list[data_array_idx].data, retrieved_data_list\n [data_array_idx].data)\n', (29116, 29204), True, 'import numpy as np\n'), ((30128, 30153), 'h5py.File', 'h5py.File', (['dest_file', '"""r"""'], {}), "(dest_file, 'r')\n", (30137, 30153), False, 'import h5py\n'), ((30493, 30518), 'os.path.exists', 'os.path.exists', (['dest_file'], {}), '(dest_file)\n', (30507, 30518), False, 'import os\n'), ((7515, 7547), 'dicom.read_file', 'dicom.read_file', (['dicom_data_file'], {}), '(dicom_data_file)\n', (7530, 7547), False, 'import dicom\n'), ((7640, 7678), 'models.dataio.get_dicom_data', 'dataio.get_dicom_data', (['dicom_data_file'], {}), '(dicom_data_file)\n', (7661, 7678), False, 'from models import dataio\n'), ((8468, 8500), 'dicom.read_file', 'dicom.read_file', (['dicom_data_file'], {}), '(dicom_data_file)\n', (8483, 8500), False, 'import dicom\n'), ((8576, 8612), 'models.dataio.import_dicom', 'dataio.import_dicom', (['dicom_data_file'], {}), '(dicom_data_file)\n', (8595, 8612), False, 'from models import dataio\n'), ((13378, 13421), 'models.dataio.get_utwin_amp_data', 'dataio.get_utwin_amp_data', (['sample_data_file'], {}), '(sample_data_file)\n', (13403, 13421), False, 'from models import dataio\n'), ((16964, 16991), 'os.path.basename', 'os.path.basename', (['dest_file'], {}), '(dest_file)\n', (16980, 16991), False, 'import os\n'), ((17295, 17315), 'os.remove', 'os.remove', (['dest_file'], {}), '(dest_file)\n', (17304, 17315), False, 'import os\n'), ((30209, 30236), 'os.path.basename', 'os.path.basename', (['dest_file'], {}), '(dest_file)\n', (30225, 30236), False, 'import os\n'), ((30540, 30560), 'os.remove', 'os.remove', (['dest_file'], {}), '(dest_file)\n', (30549, 30560), False, 'import os\n'), ((1588, 1631), 'numpy.array_equal', 'np.array_equal', (['self.sample_data', 'read_data'], {}), '(self.sample_data, read_data)\n', (1602, 1631), True, 'import numpy as np\n'), ((3790, 3830), 'numpy.array_equal', 'np.array_equal', (['expected_data', 'read_data'], {}), '(expected_data, read_data)\n', (3804, 3830), True, 'import numpy as np\n'), ((5527, 5552), 'random.uniform', 'random.uniform', (['(-100)', '(100)'], {}), '(-100, 100)\n', (5541, 5552), False, 'import random\n'), ((7715, 7756), 'numpy.array_equal', 'np.array_equal', (['dicom_arr', 'retrieved_data'], {}), '(dicom_arr, retrieved_data)\n', (7729, 7756), True, 'import numpy as np\n'), ((8658, 8680), 'controllers.pathfinder.data_path', 'pathfinder.data_path', ([], {}), '()\n', (8678, 8680), False, 'from controllers import pathfinder\n'), ((8808, 8833), 'os.path.exists', 'os.path.exists', (['dest_file'], {}), '(dest_file)\n', (8822, 8833), False, 'import os\n'), ((8860, 8885), 'h5py.File', 'h5py.File', (['dest_file', '"""r"""'], {}), "(dest_file, 'r')\n", (8869, 8885), False, 'import h5py\n'), ((9280, 9305), 'os.path.exists', 'os.path.exists', (['dest_file'], {}), '(dest_file)\n', (9294, 9305), False, 'import os\n'), ((10808, 10848), 'numpy.array_equal', 'np.array_equal', (['expected_data', 'read_data'], {}), '(expected_data, read_data)\n', (10822, 10848), True, 'import numpy as np\n'), ((14396, 14440), 'numpy.array_equal', 'np.array_equal', (['expected_amp_data', 'read_data'], {}), '(expected_amp_data, read_data)\n', (14410, 14440), True, 'import numpy as np\n'), ((16271, 16304), 'os.path.basename', 'os.path.basename', (['output_basename'], {}), '(output_basename)\n', (16287, 16304), False, 'import os\n'), ((16444, 16477), 'os.path.basename', 'os.path.basename', (['output_basename'], {}), '(output_basename)\n', (16460, 16477), False, 'import os\n'), ((27508, 27552), 'numpy.array_equal', 'np.array_equal', (['expected_amp_data', 'read_data'], {}), '(expected_amp_data, read_data)\n', (27522, 27552), True, 'import numpy as np\n'), ((29443, 29476), 'os.path.basename', 'os.path.basename', (['output_basename'], {}), '(output_basename)\n', (29459, 29476), False, 'import os\n'), ((29616, 29649), 'os.path.basename', 'os.path.basename', (['output_basename'], {}), '(output_basename)\n', (29632, 29649), False, 'import os\n'), ((8727, 8760), 'os.path.basename', 'os.path.basename', (['dicom_data_file'], {}), '(dicom_data_file)\n', (8743, 8760), False, 'import os\n'), ((8950, 8977), 'os.path.basename', 'os.path.basename', (['dest_file'], {}), '(dest_file)\n', (8966, 8977), False, 'import os\n'), ((9335, 9355), 'os.remove', 'os.remove', (['dest_file'], {}), '(dest_file)\n', (9344, 9355), False, 'import os\n'), ((17171, 17210), 'numpy.array_equal', 'np.array_equal', (['dataset.data', 'read_data'], {}), '(dataset.data, read_data)\n', (17185, 17210), True, 'import numpy as np\n'), ((30416, 30455), 'numpy.array_equal', 'np.array_equal', (['dataset.data', 'read_data'], {}), '(dataset.data, read_data)\n', (30430, 30455), True, 'import numpy as np\n'), ((9190, 9226), 'numpy.array_equal', 'np.array_equal', (['dicom_arr', 'read_data'], {}), '(dicom_arr, read_data)\n', (9204, 9226), True, 'import numpy as np\n')]
from torch.utils.data import Dataset import os import scipy.io as sio import numpy as np import matplotlib.pyplot as plt import h5py import pandas as pd import random from scipy.io import loadmat import Utils from scipy import interpolate from scipy import signal import csv from scipy.signal import butter, lfilter, freqz import re from glob import glob import time import pickle """ It contains annotations about 6 different ECGs abnormalities: - 1st degree AV block (1dAVb); - right bundle branch block (RBBB); - left bundle branch block (LBBB); - sinus bradycardia (SB); - atrial fibrillation (AF); - sinus tachycardia (ST). Notation of multiclass_to_binary_type: [-1] Return multiclass [0] I-AVB, [1] RBBB, [2] LBBB, [3] SB, [4] AF, [5] ST """ PRINT_FLAG = False class ECG_Multilead_Dataset_Brazilian_records(Dataset): def __init__(self, root_dir=None, transform=None, multiclass=False, binary_class_type=1, apply_aurmentation=True, random_augmentation=True, augmentation_method=None, record_length=60, to_normalize=True, Uploading_method='HDD', old_format= False): # record_length [sec] # Uploading_method = 'HDD'\'RAM'\'cache' super().__init__() self.data = [] self.samples = None self.root_dir = root_dir self.transform = transform self.multiclass = multiclass self.binary_class_type = binary_class_type self.apply_aurmentation = apply_aurmentation self.random_augmentation = random_augmentation self.augmentation_method = augmentation_method self.database_length = 0 self.data_mutual_sample_rate = 500 self.record_length = record_length * self.data_mutual_sample_rate self.to_normalize = to_normalize self.Uploading_method = Uploading_method self.brazilian_database_path = None self.brazilian_annotations_path = None self.sample_rate = 400 self.maximal_length = self.sample_rate * self.record_length if not multiclass: assert binary_class_type >= 0, 'Class selection is mandatory for single class classification' if self.root_dir is None: paths = Utils.read_config_file() self.brazilian_database_path = paths[1] self.brazilian_annotations_path = paths[2] self.brazilian_annotations_dict_path = paths[3] else: self.brazilian_database_path = self.root_dir + dataset_filename self.f = h5py.File(self.brazilian_database_path, "r") self.data_ids = np.array(self.f['id_exam']) self.data = self.f['signal'] start = time.process_time() self.annotations = pd.read_csv(self.brazilian_annotations_path) end = time.process_time() print(f'Uploading annotations took {end-start} sec.') start = time.process_time() # Convert Data Frame to Dictionary (set_index method allows any column to be used as index) with open(self.brazilian_annotations_dict_path, 'rb') as handle: self.annotations_dict = pickle.load(handle) #self.annotations_dict = self.annotations.set_index('id_exam').transpose().to_dict(orient='dict') end = time.process_time() print(f'Uploading annotations dictionary took {end-start} sec.') print('finished') self.loaded_data = {} def __len__(self): return len(self.data) def __getitem__(self, idx): if idx not in self.loaded_data.keys(): sample = self.data[idx] data_id = self.data_ids[idx] sample = np.transpose(sample) annotation = self.annotations_dict[data_id] annotation = list(annotation.values())[3:] sample = (sample, annotation) else: sample = self.loaded_data[idx] if self.to_normalize: sample = self.normalization(sample) if self.binary_class_type >= 0 and not self.multiclass: sample[1] = sample[1][int(self.binary_class_type)] if self.multiclass: sample[1] = np.stack(sample[1]) if self.Uploading_method == 'cache' and idx not in self.loaded_data.keys(): self.loaded_data[idx] = sample if self.apply_aurmentation: sample = self.augmentation_algorithm(sample) return sample def find_annotations(self, id_to_find): a= list(self.annotations['id_exam']).index(id_to_find) return list(self.annotations.iloc[a].values[4:]) @staticmethod def plot(sample): item_to_plot = sample[0] fig, axes = plt.subplots(nrows=6, ncols=2) fig.suptitle(np.array2string(sample[1]), fontsize=14) titles = ['Lead1', 'Lead2', 'Lead3', 'aVR', 'aVL', 'aVF', 'V1', 'V2', 'V3', 'V4', 'V5', 'V6'] b = item_to_plot for ax, cntr in zip(axes.flatten(), range(12)): ax.plot(b[cntr, :], linewidth=1.0) ax.set(title=titles[cntr]) plt.plot() plt.show() return @staticmethod def plot_one_strip(one_strip): item_to_plot = one_strip plt.plot(item_to_plot) plt.show() return def augmentation_algorithm(self, record): current_record_length = record[0].shape[1] if current_record_length == self.record_length: return record if current_record_length <= self.record_length: # record is shorter than maximal length or similar new_sample = np.zeros((12, self.record_length)) index_for_pasting = random.sample(range(self.record_length - current_record_length), 1) new_sample[:, index_for_pasting[0]:index_for_pasting[0] + current_record_length] = record[0] else: # record is longer than maximal length index_for_pasting = random.sample(range(current_record_length - self.record_length), 1) new_sample = record[0][:, index_for_pasting[0]:index_for_pasting[0] + self.record_length] return [new_sample, record[1]] @staticmethod def normalization(record): sample = record[0] for i, strip in enumerate(sample): max_ = np.max(strip) min_ = np.min(strip) if max_ - min_ == 0: sample[i] = strip else: sample[i] = (strip - min_) / (max_ - min_) return [sample, record[1]] def test_Brazilian_db_dataloader(): print('Testing Brazilian database') ds = ECG_Multilead_Dataset_Brazilian_records() start = time.process_time() for record_counter in range(len(ds)): ds_record = ds[record_counter] # ds.plot(ds_record) if record_counter %10000 ==0: stop = time.process_time() print(f'Loaded record # {record_counter}, time : {stop-start}') print('Finished testing') if __name__ == "__main__": test_Brazilian_db_dataloader()
[ "pandas.read_csv", "numpy.array2string", "matplotlib.pyplot.plot", "pickle.load", "h5py.File", "numpy.max", "numpy.array", "numpy.stack", "numpy.zeros", "Utils.read_config_file", "numpy.min", "time.process_time", "numpy.transpose", "matplotlib.pyplot.subplots", "matplotlib.pyplot.show" ]
[((6608, 6627), 'time.process_time', 'time.process_time', ([], {}), '()\n', (6625, 6627), False, 'import time\n'), ((2547, 2591), 'h5py.File', 'h5py.File', (['self.brazilian_database_path', '"""r"""'], {}), "(self.brazilian_database_path, 'r')\n", (2556, 2591), False, 'import h5py\n'), ((2616, 2643), 'numpy.array', 'np.array', (["self.f['id_exam']"], {}), "(self.f['id_exam'])\n", (2624, 2643), True, 'import numpy as np\n'), ((2697, 2716), 'time.process_time', 'time.process_time', ([], {}), '()\n', (2714, 2716), False, 'import time\n'), ((2744, 2788), 'pandas.read_csv', 'pd.read_csv', (['self.brazilian_annotations_path'], {}), '(self.brazilian_annotations_path)\n', (2755, 2788), True, 'import pandas as pd\n'), ((2803, 2822), 'time.process_time', 'time.process_time', ([], {}), '()\n', (2820, 2822), False, 'import time\n'), ((2901, 2920), 'time.process_time', 'time.process_time', ([], {}), '()\n', (2918, 2920), False, 'import time\n'), ((3271, 3290), 'time.process_time', 'time.process_time', ([], {}), '()\n', (3288, 3290), False, 'import time\n'), ((4669, 4699), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(6)', 'ncols': '(2)'}), '(nrows=6, ncols=2)\n', (4681, 4699), True, 'import matplotlib.pyplot as plt\n'), ((5039, 5049), 'matplotlib.pyplot.plot', 'plt.plot', ([], {}), '()\n', (5047, 5049), True, 'import matplotlib.pyplot as plt\n'), ((5058, 5068), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5066, 5068), True, 'import matplotlib.pyplot as plt\n'), ((5179, 5201), 'matplotlib.pyplot.plot', 'plt.plot', (['item_to_plot'], {}), '(item_to_plot)\n', (5187, 5201), True, 'import matplotlib.pyplot as plt\n'), ((5210, 5220), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5218, 5220), True, 'import matplotlib.pyplot as plt\n'), ((2246, 2270), 'Utils.read_config_file', 'Utils.read_config_file', ([], {}), '()\n', (2268, 2270), False, 'import Utils\n'), ((3131, 3150), 'pickle.load', 'pickle.load', (['handle'], {}), '(handle)\n', (3142, 3150), False, 'import pickle\n'), ((3654, 3674), 'numpy.transpose', 'np.transpose', (['sample'], {}), '(sample)\n', (3666, 3674), True, 'import numpy as np\n'), ((4145, 4164), 'numpy.stack', 'np.stack', (['sample[1]'], {}), '(sample[1])\n', (4153, 4164), True, 'import numpy as np\n'), ((4721, 4747), 'numpy.array2string', 'np.array2string', (['sample[1]'], {}), '(sample[1])\n', (4736, 4747), True, 'import numpy as np\n'), ((5550, 5584), 'numpy.zeros', 'np.zeros', (['(12, self.record_length)'], {}), '((12, self.record_length))\n', (5558, 5584), True, 'import numpy as np\n'), ((6224, 6237), 'numpy.max', 'np.max', (['strip'], {}), '(strip)\n', (6230, 6237), True, 'import numpy as np\n'), ((6257, 6270), 'numpy.min', 'np.min', (['strip'], {}), '(strip)\n', (6263, 6270), True, 'import numpy as np\n'), ((6795, 6814), 'time.process_time', 'time.process_time', ([], {}), '()\n', (6812, 6814), False, 'import time\n')]
#!/bin/python import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.cbook as cbook import numpy as np import math # State vector: # 0-3: quaternions (q0, q1, q2, q3) # 4-6: Velocity - m/sec (North, East, Down) # 7-9: Position - m (North, East, Down) # 10-12: Delta Angle bias - rad (X,Y,Z) # 13: Accel offset # 14-15: Wind Vector - m/sec (North,East) # 16-18: Earth Magnetic Field Vector - milligauss (North, East, Down) # 19-21: Body Magnetic Field Vector - milligauss (X,Y,Z) # 22: Terrain try: data = np.genfromtxt('StateDataOut.txt', delimiter=' ', skip_header=1, skip_footer=1, names=['time', 'q1', 'q2', 'q3', 'q4', 'Vn', 'Ve', 'Vd', 'Pn', 'Pe', 'Pd', 'Bx', 'By', 'Bz', 'Aoff', 'Wn', 'We', 'Mn', 'Me', 'Md', 'Mbn', 'Mbe', 'Mbd', 'dist']) except ValueError: try: data = np.genfromtxt('StateDataOut.txt', delimiter=' ', skip_header=1, skip_footer=1, names=['time', 'q1', 'q2', 'q3', 'q4', 'Vn', 'Ve', 'Vd', 'Pn', 'Pe', 'Pd', 'Bx', 'By', 'Bz', 'Aoff', 'Wn', 'We', 'Mn', 'Me', 'Md', 'Mbn', 'Mbe', 'Mbd']) except ValueError: data = np.genfromtxt('StateDataOut.txt', delimiter=' ', skip_header=1, skip_footer=1, names=['time', 'q1', 'q2', 'q3', 'q4', 'Vn', 'Ve', 'Vd', 'Pn', 'Pe', 'Pd', 'Bx', 'By', 'Bz', 'Wn', 'We', 'Mn', 'Me', 'Md', 'Mbn', 'Mbe', 'Mbd']) fig = plt.figure() ax1 = fig.add_subplot(211) ax1.set_title("Wind Velocity") ax1.set_xlabel('time (s)') ax1.set_ylabel('Wind North') ax1.plot(data['time'], data['Wn'], color='r', label='Wind N') ax2 = fig.add_subplot(212) ax2.set_xlabel('time (s)') ax2.set_ylabel('Wind East') ax2.plot(data['time'], data['We'], color='g', label='Wind E') plt.show()
[ "matplotlib.pyplot.figure", "numpy.genfromtxt", "matplotlib.pyplot.show" ]
[((1319, 1331), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1329, 1331), True, 'import matplotlib.pyplot as plt\n'), ((1663, 1673), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1671, 1673), True, 'import matplotlib.pyplot as plt\n'), ((539, 791), 'numpy.genfromtxt', 'np.genfromtxt', (['"""StateDataOut.txt"""'], {'delimiter': '""" """', 'skip_header': '(1)', 'skip_footer': '(1)', 'names': "['time', 'q1', 'q2', 'q3', 'q4', 'Vn', 'Ve', 'Vd', 'Pn', 'Pe', 'Pd', 'Bx',\n 'By', 'Bz', 'Aoff', 'Wn', 'We', 'Mn', 'Me', 'Md', 'Mbn', 'Mbe', 'Mbd',\n 'dist']"}), "('StateDataOut.txt', delimiter=' ', skip_header=1, skip_footer\n =1, names=['time', 'q1', 'q2', 'q3', 'q4', 'Vn', 'Ve', 'Vd', 'Pn', 'Pe',\n 'Pd', 'Bx', 'By', 'Bz', 'Aoff', 'Wn', 'We', 'Mn', 'Me', 'Md', 'Mbn',\n 'Mbe', 'Mbd', 'dist'])\n", (552, 791), True, 'import numpy as np\n'), ((817, 1061), 'numpy.genfromtxt', 'np.genfromtxt', (['"""StateDataOut.txt"""'], {'delimiter': '""" """', 'skip_header': '(1)', 'skip_footer': '(1)', 'names': "['time', 'q1', 'q2', 'q3', 'q4', 'Vn', 'Ve', 'Vd', 'Pn', 'Pe', 'Pd', 'Bx',\n 'By', 'Bz', 'Aoff', 'Wn', 'We', 'Mn', 'Me', 'Md', 'Mbn', 'Mbe', 'Mbd']"}), "('StateDataOut.txt', delimiter=' ', skip_header=1, skip_footer\n =1, names=['time', 'q1', 'q2', 'q3', 'q4', 'Vn', 'Ve', 'Vd', 'Pn', 'Pe',\n 'Pd', 'Bx', 'By', 'Bz', 'Aoff', 'Wn', 'We', 'Mn', 'Me', 'Md', 'Mbn',\n 'Mbe', 'Mbd'])\n", (830, 1061), True, 'import numpy as np\n'), ((1082, 1314), 'numpy.genfromtxt', 'np.genfromtxt', (['"""StateDataOut.txt"""'], {'delimiter': '""" """', 'skip_header': '(1)', 'skip_footer': '(1)', 'names': "['time', 'q1', 'q2', 'q3', 'q4', 'Vn', 'Ve', 'Vd', 'Pn', 'Pe', 'Pd', 'Bx',\n 'By', 'Bz', 'Wn', 'We', 'Mn', 'Me', 'Md', 'Mbn', 'Mbe', 'Mbd']"}), "('StateDataOut.txt', delimiter=' ', skip_header=1, skip_footer\n =1, names=['time', 'q1', 'q2', 'q3', 'q4', 'Vn', 'Ve', 'Vd', 'Pn', 'Pe',\n 'Pd', 'Bx', 'By', 'Bz', 'Wn', 'We', 'Mn', 'Me', 'Md', 'Mbn', 'Mbe', 'Mbd'])\n", (1095, 1314), True, 'import numpy as np\n')]
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Dec 27 16:54:42 2017 @author: Xiaobo """ import numpy as np from mpi4py import MPI import commands import os import sys path = os.path.dirname(os.path.realpath(__file__)) sys.path.append(path) #sys.path.append('/Users/Xiaobo/git/CloudMerge/CloudMerge/cloudmerge-hpc') #sys.path.append('/home/ubuntu/cloudmerge/cloudmerge-hpc/') import multiway_merge as mm import argparse ############################################################################### def get_source(rank,size,rounds): divisor = np.power(2,rounds) new_rank = int(rank/divisor) new_size = int(size/divisor) if (new_rank%2 != 0) or (new_rank+1>=new_size): return [] elif (new_rank+2+1>=new_size) and (new_rank+2<new_size): return [divisor*(new_rank+1),divisor*(new_rank+2)] else: return [divisor*(new_rank+1),] #------------------------------------------------------------------------------ def get_dest(rank,size,rounds): SELF = -1 divisor = np.power(2,rounds) new_rank = int(rank/divisor) new_size = int(size/divisor) if new_rank % 2 !=0: dest = divisor*(new_rank-1) return dest elif (new_rank + 1) >= new_size: dest = divisor*(new_rank-2) return dest if dest >=0 else 0 else: return SELF #------------------------------------------------------------------------------ def splits(filenum,size): assigned = 0 sendcounts = np.zeros(size) disp = np.zeros(size) for i in range(size): nxt_sz = int((filenum-assigned)/(size-i)) disp[i] = assigned sendcounts[i] = nxt_sz assigned = assigned + nxt_sz return tuple(sendcounts),tuple(disp) #------------------------------------------------------------------------------ def get_output_name(localname,rcvname): if rcvname is None: return localname start = localname.split('_')[0] end = rcvname[-1].split('_')[-1] return start+'_'+end ############################################################################### parser = argparse.ArgumentParser(description='cloudmerge-hpc') parser.add_argument('-i',required=True,help='input file directory path',dest='input',metavar='/home/ubuntu/cloudmerge/input/') parser.add_argument('-o',required=True,help='output file directory path',dest='output',metavar='/home/ubuntu/cloudmerge/output/') parser.add_argument('-n',required=True,help='input file number',dest='filenum',metavar='10',type=int) parser.add_argument('-l',required=False,default='1',help='lower boundary of chrmosomes',dest='lower_chr',metavar='1') parser.add_argument('-u',required=False,default='M',help='upper boundary of chromosomes',dest='upper_chr',metavar='M') parser.add_argument('-g',required=False,default=9,help='genotype column number',dest='gtype_col',metavar='9',type=int) parser.add_argument('-f',required=False,default='PASS',help='filter value',dest='filter',metavar='PASS') args = parser.parse_args() #args = parser.parse_args('-i abc -o def -n 10 -l 1 -u 26 -g 9 -f PASS'.split()) #input_path = '/home/ubuntu/cloudmerge/input/' #output_path = '/home/ubuntu/cloudmerge/output/' #input_path = '/Users/Xiaobo/Desktop/input/' #output_path = '/Users/Xiaobo/Desktop/output/' input_path = args.input output_path = args.output filenum = args.filenum lower_chr = args.lower_chr upper_chr = args.upper_chr qfilter = args.filter genotype_col = args.gtype_col comm = MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() host = commands.getoutput("hostname") rounds = 0 sendcounts,disp = splits(filenum,size) if rank == 0: sendbuff = np.linspace(1,filenum,filenum) else: sendbuff = None rcvbuff = np.zeros(int(sendcounts[rank])) comm.Scatterv([sendbuff,sendcounts,disp,MPI.DOUBLE],rcvbuff,root=0) #local_input_files = map(lambda x: input_path+str(int(x))+'.bz2',rcvbuff) #for file in local_input_files: # print('unzipping files %s in rank %d' % (str(local_input_files),rank)) # os.system('bunzip2 '+file) local_input_files = map(lambda x: input_path+str(int(x))+'.bz2',rcvbuff) #local_merged_files = "_".join(map(lambda x: str(int(x)),rcvbuff)) local_merged_files = str(int(rcvbuff[0]))+'_'+str(int(rcvbuff[-1])) merger = mm.multiway_merger(local_input_files, output_path+local_merged_files,lower_chr,upper_chr,qfilter,genotype_col,merge_type='vcf') merger.start() print('merged_files %s'%local_merged_files) while True: src = get_source(rank,size,rounds) # if len(src) == 0: #only when no source, we need a destination dest = get_dest(rank,size,rounds) rounds = rounds+1 if len(src) == 0: if rank > 0: comm.send(local_merged_files,dest=dest,tag=0) print('i am rank %d, host is %s, sent merged files is %s, source is %s, dest is %d' %(rank,host,local_merged_files,str(src),dest)) break ## send the filename to dest process and quit elif len(src) == 1: local_files = [output_path+local_merged_files] rcv_merged_file = comm.recv(source=src[0],tag=0) local_files.extend([output_path+rcv_merged_file]) # local_merged_files = '_'.join([local_merged_files,rcv_merged_file]) local_merged_files = get_output_name(local_merged_files,[rcv_merged_file]) print('i am rank %d, host is %s, local merged file is %s, src is %s, dest is %d' %(rank,host,local_merged_files,str(src),dest)) else: local_files = [output_path+local_merged_files] rcv_merged_files = [] for i,s in enumerate(src): print('i am rank %d, host is %s, src is %s, dest is %d' %(rank,host,s,dest)) rcv_file = comm.recv(source=s,tag=0) local_files.extend([output_path+rcv_file]) rcv_merged_files.extend([rcv_file]) # local_merged_files = '_'.join([local_merged_files]+rcv_merged_files) local_merged_files = get_output_name(local_merged_files,rcv_merged_files) if rank == 0: src = get_source(rank,size,rounds) if len(src) == 0: #### the last merging step merger = mm.multiway_merger(local_files,output_path+local_merged_files,lower_chr,upper_chr,qfilter,genotype_col,False,merge_type='tped') merger.start() break; merger = mm.multiway_merger(local_files,output_path+local_merged_files,lower_chr,upper_chr,qfilter,genotype_col,merge_type='tped') merger.start() ################################################################################ # if rank >0: # comm.send(local_merged_files,dest=dest,tag=0) # print('i am rank %d, host is %s, send local merged files is %s, source is %s, dest is %d' %(rank,host,local_merged_files,str(src),dest)) #print('rank is %d, host is %s, data is %s' %(rank,host,str(rcvbuff))) # create numpy arrays to reduce #src = (np.arange(8) + rank*8).reshape(4,2) #dst = np.zeros_like(src) # #def myadd(xmem, ymem, dt): # x = np.frombuffer(xmem, dtype=src.dtype) # y = np.frombuffer(ymem, dtype=src.dtype) # # z = x + y # # print("Rank %d on host %s reducing %s (%s) and %s (%s), yielding %s" % (rank, host, x, type(x), y, type(y), z)) # # y[:] = z # #op = MPI.Op.Create(myadd) # #MPI.COMM_WORLD.Reduce(src, dst, op) # #if MPI.COMM_WORLD.rank == 0: # print("ANSWER: %s" % dst)
[ "commands.getoutput", "argparse.ArgumentParser", "numpy.power", "os.path.realpath", "numpy.zeros", "numpy.linspace", "sys.path.append", "multiway_merge.multiway_merger" ]
[((238, 259), 'sys.path.append', 'sys.path.append', (['path'], {}), '(path)\n', (253, 259), False, 'import sys\n'), ((2156, 2209), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""cloudmerge-hpc"""'}), "(description='cloudmerge-hpc')\n", (2179, 2209), False, 'import argparse\n'), ((3580, 3610), 'commands.getoutput', 'commands.getoutput', (['"""hostname"""'], {}), "('hostname')\n", (3598, 3610), False, 'import commands\n'), ((4302, 4440), 'multiway_merge.multiway_merger', 'mm.multiway_merger', (['local_input_files', '(output_path + local_merged_files)', 'lower_chr', 'upper_chr', 'qfilter', 'genotype_col'], {'merge_type': '"""vcf"""'}), "(local_input_files, output_path + local_merged_files,\n lower_chr, upper_chr, qfilter, genotype_col, merge_type='vcf')\n", (4320, 4440), True, 'import multiway_merge as mm\n'), ((210, 236), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (226, 236), False, 'import os\n'), ((567, 586), 'numpy.power', 'np.power', (['(2)', 'rounds'], {}), '(2, rounds)\n', (575, 586), True, 'import numpy as np\n'), ((1036, 1055), 'numpy.power', 'np.power', (['(2)', 'rounds'], {}), '(2, rounds)\n', (1044, 1055), True, 'import numpy as np\n'), ((1492, 1506), 'numpy.zeros', 'np.zeros', (['size'], {}), '(size)\n', (1500, 1506), True, 'import numpy as np\n'), ((1522, 1536), 'numpy.zeros', 'np.zeros', (['size'], {}), '(size)\n', (1530, 1536), True, 'import numpy as np\n'), ((3690, 3722), 'numpy.linspace', 'np.linspace', (['(1)', 'filenum', 'filenum'], {}), '(1, filenum, filenum)\n', (3701, 3722), True, 'import numpy as np\n'), ((6270, 6403), 'multiway_merge.multiway_merger', 'mm.multiway_merger', (['local_files', '(output_path + local_merged_files)', 'lower_chr', 'upper_chr', 'qfilter', 'genotype_col'], {'merge_type': '"""tped"""'}), "(local_files, output_path + local_merged_files, lower_chr,\n upper_chr, qfilter, genotype_col, merge_type='tped')\n", (6288, 6403), True, 'import multiway_merge as mm\n'), ((6089, 6229), 'multiway_merge.multiway_merger', 'mm.multiway_merger', (['local_files', '(output_path + local_merged_files)', 'lower_chr', 'upper_chr', 'qfilter', 'genotype_col', '(False)'], {'merge_type': '"""tped"""'}), "(local_files, output_path + local_merged_files, lower_chr,\n upper_chr, qfilter, genotype_col, False, merge_type='tped')\n", (6107, 6229), True, 'import multiway_merge as mm\n')]
#<NAME> #Purdue University #Email: <EMAIL> #DESCRIPTION: Code written to isolate the magnitudes of harmonics of a #given f_0 for a given audiofile/stimulus. #Additional Dependencies: scipy, numpy, matplotlib # pip3 install scipy # pip3 install numpy # pip3 install matplotlib #May require ffmpeg on Ubuntu/Linux as well # sudo apt-get install ffmpeg import numpy as np import matplotlib.pyplot as plt from scipy.io import wavfile def extract_harmonics(fname, fs = 44100, f_0 = 440, n_harms = 3): fs, x = wavfile.read(fname) #x = np.array(aud[0]) t_vect = np.arange(0,len(x))/fs f_vect = np.arange(1,n_harms+1)*f_0; #plt.plot(t_vect,x) #output = get_spect(x, fs, DR = 120, BW = 100, xlim = [0,0.5], ylim = [0,5000], colormap = 'magma') ## TODO: Try applying dpss to this. Might result in more accurate ## magnitudes? freq_time = np.multiply(np.asmatrix(f_vect).T,np.asmatrix(t_vect)) x_sin = np.multiply(np.asmatrix(x),np.sin(2*np.pi*freq_time)) x_cos = np.multiply(np.asmatrix(x),np.cos(2*np.pi*freq_time)) sin_sum = np.sum(x_sin,1); cos_sum = np.sum(x_cos,1); mags = np.sqrt(np.multiply(sin_sum,sin_sum) + np.multiply(cos_sum,cos_sum)) mags = np.squeeze(np.asarray(mags))/np.max(mags) phase = np.arctan(np.divide(sin_sum,cos_sum)); phase = np.squeeze(np.asarray(phase)); #phase = [0]; #plt.stem(f_vect,mags) return [f_vect, mags, phase, x, fs] from signal_processing import pure_tone_complex, sound, magphase import matplotlib.pyplot as plt #from playsound import playsound def resynthesize(mags, fname = 'resynth.wav', fs_Hz = 44100, freq_Hz = [0], dur_sec = 1, phi = [0], scale = .75, tone_shift = 1, env_fxn = 1, fs = 44100, type = 'sin', play_write = True, plot = True): harmonics = len(mags) #This handling should be added to pure_tone_complex at some point if len(phi)<harmonics: phi = np.ones(harmonics)*phi; if len(freq_Hz) <harmonics: freq_Hz = np.arange(1,n_harms+1)*440; tone = pure_tone_complex(freq_Hz*tone_shift, fs, dur_sec, mags, phi, type) tone = tone[1]*env_fxn; tone = scale*tone/np.max(tone); t_vect = np.arange(0,len(tone))/fs_Hz; if plot: plt.figure() plt.plot(tone); plt.xlim([0,len(tone)]) if play_write: sound(tone,fs_Hz,fname,1) return tone ################################################################################ import numpy as np def play_alma_mater(extract, freq_Hz, fname = 'alma_mater.wav', n_harms = 6, key = 1, tempo = 0.3, fxn = 'string', type = 'sin', short = True): shift_mat = [1.26/1.66, .85, .95, 1.00, 1.13, 1.26, 1.26, 1.32, 1.32, 1.32, 1, 1.13, 1.13, 1.26, 1.26/1.66, 1.26, 1.20, 1.26, 1.26, 1.13, 1.00, 1.13, 1.26, 1.26, 1.13, .85, .95, 1, .95, .85, 1.13, 1.26/1.66, 1.26/1.66, .85, .95, 1, 1.13, 1.26, 1.26, 1.26, 1.32, 1.32, 1, 1.13, 1.26, .85, .95, 1, .85, 1.26/1.66, 1, 1.26, 1.26/1.66, .85, 1.26, 1.13, 1, 1] dur_mat = [2, 1, 1, 1.5, .5, 1, 1, 1, .5, .5, 1, .5, .5, 1, 1, 1, 1, 2, 1, 1, 1.5, .5, 1, 1, 1, .5, .5, 1, .5, .5, 3, 1.5, .5, 1, 1, 1.5, .5, 1, .5, .5, 1, 1, 1, 1, 4, 1.5, .5, 1, 1, 1, 1, 1, 1, 1.5, .5, 1.5, .5, 3] scale_mat = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ,1 , 1, 1, 1, 1] #Truncate by default, otherwise listen to music for a few extra seconds... if short: shift_mat = shift_mat[:6]; dur_mat = dur_mat[:6]; scale_mat = scale_mat[:6]; fs = 44100; #Change tempo dur_mat = np.asarray(dur_mat)*tempo tone = []; for i in range(0,len(shift_mat)): t_vect = np.arange(0,dur_mat[i]*fs)/fs; if fxn == 'banjo': env_fxn = np.exp(-7*t_vect); elif fxn == 'string': env_fxn = (1+.25*np.sin(5*np.pi*2*t_vect))*np.sin(.5*np.pi*2*t_vect); else: env_fxn = 1; tone_temp = resynthesize(extract[1], freq_Hz = key*freq_Hz, dur_sec = dur_mat[i], phi = extract[2], scale = scale_mat[i], tone_shift = shift_mat[i], env_fxn = env_fxn, type = type, play_write = False, plot = False) print(tone_temp) tone = np.concatenate((tone,tone_temp), axis = 0) sound(tone, fs, fname, 1) return [tone,fs]; ########################## IMPLEMENTATION ##################################### # from signal_processing import pure_tone_complex, sound, magphase, get_spect # import matplotlib.pyplot as plt # from scipy.signal import spectrogram as sp # import numpy as np # ## TODO: Quantify Envelope, apply slepian sequences, verify magnitudes against DFT/PSD # #Can use the below line in Atom when running Hydrogen # #%matplotlib inline # harmonics = 7; # first = 0; # dur_sec = 1; # toPlay = np.array([0,1,2,3,4,5,6]) # extract = extract_harmonics('instruments/violin_A4_normal.wav', fs = 44100, f_0 = 440, n_harms = harmonics); # fs_Hz = extract[4]; # amp = extract[1][toPlay]; # phase = extract[2][toPlay]; # freq_Hz = extract[0][toPlay]; # t_vect = np.arange(0,dur_sec*fs_Hz)/fs_Hz; # env_banj = np.exp(-9*t_vect); # env_string = (1+0.15*np.sin(6*np.pi*2*t_vect))*np.sin(.5*np.pi*2*t_vect); # tone = resynthesize(amp, 'violin_all.wav', freq_Hz = freq_Hz, dur_sec = 1, phi = phase, scale = 1, tone_shift = 1, env_fxn = env_string, type = 'sin', play_write = True, plot = False) # sound(tone, fs_Hz) # get_spect(tone, fs_Hz, DR = 200, BW = 75, xlim = [0,1], ylim = [0,4000], colormap = 'cividis',title = 'Simulated Violin | All Harmonics'); # #Play Alma Mater # alma_mater = play_alma_mater(extract, freq_Hz, key = 1, fxn = 'strings', type = 'sin') # # plt.figure() # plt.plot(np.arange(0,len(alma_mater[0]))/alma_mater[1],alma_mater[0]); # output = get_spect(alma_mater[0],alma_mater[1], DR = 300, BW = 200, xlim = [0.01,2], ylim = [0,5000])
[ "numpy.multiply", "numpy.ones", "numpy.divide", "numpy.asmatrix", "matplotlib.pyplot.plot", "numpy.asarray", "numpy.max", "numpy.exp", "numpy.sum", "matplotlib.pyplot.figure", "scipy.io.wavfile.read", "numpy.cos", "signal_processing.pure_tone_complex", "numpy.concatenate", "numpy.sin", ...
[((514, 533), 'scipy.io.wavfile.read', 'wavfile.read', (['fname'], {}), '(fname)\n', (526, 533), False, 'from scipy.io import wavfile\n'), ((1073, 1089), 'numpy.sum', 'np.sum', (['x_sin', '(1)'], {}), '(x_sin, 1)\n', (1079, 1089), True, 'import numpy as np\n'), ((1104, 1120), 'numpy.sum', 'np.sum', (['x_cos', '(1)'], {}), '(x_cos, 1)\n', (1110, 1120), True, 'import numpy as np\n'), ((2022, 2091), 'signal_processing.pure_tone_complex', 'pure_tone_complex', (['(freq_Hz * tone_shift)', 'fs', 'dur_sec', 'mags', 'phi', 'type'], {}), '(freq_Hz * tone_shift, fs, dur_sec, mags, phi, type)\n', (2039, 2091), False, 'from signal_processing import pure_tone_complex, sound, magphase\n'), ((4308, 4333), 'signal_processing.sound', 'sound', (['tone', 'fs', 'fname', '(1)'], {}), '(tone, fs, fname, 1)\n', (4313, 4333), False, 'from signal_processing import pure_tone_complex, sound, magphase\n'), ((609, 634), 'numpy.arange', 'np.arange', (['(1)', '(n_harms + 1)'], {}), '(1, n_harms + 1)\n', (618, 634), True, 'import numpy as np\n'), ((906, 925), 'numpy.asmatrix', 'np.asmatrix', (['t_vect'], {}), '(t_vect)\n', (917, 925), True, 'import numpy as np\n'), ((951, 965), 'numpy.asmatrix', 'np.asmatrix', (['x'], {}), '(x)\n', (962, 965), True, 'import numpy as np\n'), ((966, 995), 'numpy.sin', 'np.sin', (['(2 * np.pi * freq_time)'], {}), '(2 * np.pi * freq_time)\n', (972, 995), True, 'import numpy as np\n'), ((1017, 1031), 'numpy.asmatrix', 'np.asmatrix', (['x'], {}), '(x)\n', (1028, 1031), True, 'import numpy as np\n'), ((1032, 1061), 'numpy.cos', 'np.cos', (['(2 * np.pi * freq_time)'], {}), '(2 * np.pi * freq_time)\n', (1038, 1061), True, 'import numpy as np\n'), ((1242, 1254), 'numpy.max', 'np.max', (['mags'], {}), '(mags)\n', (1248, 1254), True, 'import numpy as np\n'), ((1278, 1305), 'numpy.divide', 'np.divide', (['sin_sum', 'cos_sum'], {}), '(sin_sum, cos_sum)\n', (1287, 1305), True, 'import numpy as np\n'), ((1330, 1347), 'numpy.asarray', 'np.asarray', (['phase'], {}), '(phase)\n', (1340, 1347), True, 'import numpy as np\n'), ((2140, 2152), 'numpy.max', 'np.max', (['tone'], {}), '(tone)\n', (2146, 2152), True, 'import numpy as np\n'), ((2220, 2232), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2230, 2232), True, 'import matplotlib.pyplot as plt\n'), ((2241, 2255), 'matplotlib.pyplot.plot', 'plt.plot', (['tone'], {}), '(tone)\n', (2249, 2255), True, 'import matplotlib.pyplot as plt\n'), ((2317, 2345), 'signal_processing.sound', 'sound', (['tone', 'fs_Hz', 'fname', '(1)'], {}), '(tone, fs_Hz, fname, 1)\n', (2322, 2345), False, 'from signal_processing import pure_tone_complex, sound, magphase\n'), ((3646, 3665), 'numpy.asarray', 'np.asarray', (['dur_mat'], {}), '(dur_mat)\n', (3656, 3665), True, 'import numpy as np\n'), ((4260, 4301), 'numpy.concatenate', 'np.concatenate', (['(tone, tone_temp)'], {'axis': '(0)'}), '((tone, tone_temp), axis=0)\n', (4274, 4301), True, 'import numpy as np\n'), ((884, 903), 'numpy.asmatrix', 'np.asmatrix', (['f_vect'], {}), '(f_vect)\n', (895, 903), True, 'import numpy as np\n'), ((1141, 1170), 'numpy.multiply', 'np.multiply', (['sin_sum', 'sin_sum'], {}), '(sin_sum, sin_sum)\n', (1152, 1170), True, 'import numpy as np\n'), ((1172, 1201), 'numpy.multiply', 'np.multiply', (['cos_sum', 'cos_sum'], {}), '(cos_sum, cos_sum)\n', (1183, 1201), True, 'import numpy as np\n'), ((1224, 1240), 'numpy.asarray', 'np.asarray', (['mags'], {}), '(mags)\n', (1234, 1240), True, 'import numpy as np\n'), ((1907, 1925), 'numpy.ones', 'np.ones', (['harmonics'], {}), '(harmonics)\n', (1914, 1925), True, 'import numpy as np\n'), ((1982, 2007), 'numpy.arange', 'np.arange', (['(1)', '(n_harms + 1)'], {}), '(1, n_harms + 1)\n', (1991, 2007), True, 'import numpy as np\n'), ((3744, 3773), 'numpy.arange', 'np.arange', (['(0)', '(dur_mat[i] * fs)'], {}), '(0, dur_mat[i] * fs)\n', (3753, 3773), True, 'import numpy as np\n'), ((3825, 3844), 'numpy.exp', 'np.exp', (['(-7 * t_vect)'], {}), '(-7 * t_vect)\n', (3831, 3844), True, 'import numpy as np\n'), ((3929, 3961), 'numpy.sin', 'np.sin', (['(0.5 * np.pi * 2 * t_vect)'], {}), '(0.5 * np.pi * 2 * t_vect)\n', (3935, 3961), True, 'import numpy as np\n'), ((3903, 3933), 'numpy.sin', 'np.sin', (['(5 * np.pi * 2 * t_vect)'], {}), '(5 * np.pi * 2 * t_vect)\n', (3909, 3933), True, 'import numpy as np\n')]
import numpy as np from math import inf as infinity from itertools import product from collections import defaultdict import random import time # Initializing the Tic-Tac-Toe environment # Three rows-Three columns, creating an empty list of three empty lists state_space = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']] # No. of players = 2 : X & O players = ['X', 'O'] # Defining the play state_value, player and the cell number def play(sv, each_player, cell): if sv[int((cell - 1) / 3)][(cell - 1) % 3] is ' ': sv[int((cell - 1) / 3)][(cell - 1) % 3] = each_player else: cell = int(input(" Choose again, Cell is not empty: ")) play(sv, each_player, cell) # Defining new state function: which traverse over rows and columns and returns new state def new(state): ns = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']] for i in range(3): for j in range(3): ns[i][j] = state[i][j] return ns # Determining the current state value and determining the win def cur_state(state_space): if (state_space[0][0] == state_space[0][1] and state_space[0][1] == state_space[0][2] and state_space[0][ 0] is not ' '): return state_space[0][0], "Done" if (state_space[1][0] == state_space[1][1] and state_space[1][1] == state_space[1][2] and state_space[1][ 0] is not ' '): return state_space[1][0], "Done" if (state_space[2][0] == state_space[2][1] and state_space[2][1] == state_space[2][2] and state_space[2][ 0] is not ' '): return state_space[2][0], "Done" if (state_space[0][0] == state_space[1][0] and state_space[1][0] == state_space[2][0] and state_space[0][ 0] is not ' '): return state_space[0][0], "Done" if (state_space[0][1] == state_space[1][1] and state_space[1][1] == state_space[2][1] and state_space[0][ 1] is not ' '): return state_space[0][1], "Done" if (state_space[0][2] == state_space[1][2] and state_space[1][2] == state_space[2][2] and state_space[0][ 2] is not ' '): return state_space[0][2], "Done" if (state_space[0][0] == state_space[1][1] and state_space[1][1] == state_space[2][2] and state_space[0][ 0] is not ' '): return state_space[1][1], "Done" if (state_space[2][0] == state_space[1][1] and state_space[1][1] == state_space[0][2] and state_space[2][ 0] is not ' '): return state_space[1][1], "Done" # if none of the above is true there must be a draw draw = 0 for i in range(3): for j in range(3): if state_space[i][j] is ' ': draw = 1 if draw is 0: return None, "Draw" return None, "Not Done" # Defining the outline of the Tic-Tac Toe for the state_space or environment def outline(state_space): print('----------------') print('| ' + str(state_space[0][0]) + ' || ' + str(state_space[0][1]) + ' || ' + str(state_space[0][2]) + ' |') print('----------------') print('| ' + str(state_space[1][0]) + ' || ' + str(state_space[1][1]) + ' || ' + str(state_space[1][2]) + ' |') print('----------------') print('| ' + str(state_space[2][0]) + ' || ' + str(state_space[2][1]) + ' || ' + str(state_space[2][2]) + ' |') print('----------------') # Initializing state values each_player = ['X', 'O', ' '] states_dictionary = {} # listing all possible states states = [[list(i[0:3]), list(i[3:6]), list(i[6:10])] for i in product(each_player, repeat=9)] # getting Total number of states Total_states = len(states) print("Total number of states = ", Total_states) # Total number of moves/ actions in Tic-Tac-Toe is 9 Total_moves = 9 print("Total number of actions = ", Total_moves) # Intializing agent intial value as 0 sv_O = np.full(Total_states, 0.0) # Defining the state values for agent O for i in range(Total_states): states_dictionary[i] = states[i] won_by, _ = cur_state(states_dictionary[i]) if won_by == 'X': sv_O[i] = -1 elif won_by == 'O': sv_O[i] = 1 # Using Update rule of Temporal difference to update the state value of 'O' # V(s) <- V(s) + alpha * ((V(s^f) - V(s)) # current_state_value <- current_state_value + learning_rate * (new_state_value - current_state_value) def update_O(alpha, csv, nsv): # alpha: learning rate, csv: current state value, nsv: next state value sv_O[csv] = sv_O[csv] + alpha * sv_O[nsv] # Testing our Tic-Tac-Toe agent 'O' vs. Human # Temporal difference: A RL Algo. def TD(sv, each_player): actions = [] curr_state_values = [] empty_cells = [] for i in range(3): for j in range(3): if sv[i][j] is ' ': empty_cells.append(i * 3 + (j + 1)) for empty_cell in empty_cells: actions.append(empty_cell) new_state = new(sv) play(new_state, each_player, empty_cell) next_sid = list(states_dictionary.keys())[list(states_dictionary.values()).index(new_state)] curr_state_values.append(sv_O[next_sid]) print('Possible Action moves = ' + str(actions)) print('Action Move values = ' + str(curr_state_values)) best_move_id = np.argmax(curr_state_values) best_move = actions[best_move_id] return best_move # Now Playing # Loading policy or the trained state values sv_O = np.loadtxt('trained_O.txt', dtype=np.float64) play_more = "Y" while play_more == 'Y' or play_more == 'y': state_space = [[' ', ' ', ' '],[' ', ' ', ' '],[' ', ' ', ' ']] curr_state = "Not Done" print("\n Let's start New Game!") outline(state_space) input_choice = input("Choose which player to go first - X (Human) or O(RL Agent): ") won_by = None if input_choice == 'X' or input_choice == 'x': cid = 0 else: cid = 1 while curr_state == "Not Done": csv = list(states_dictionary.keys())[list(states_dictionary.values()).index(state_space)] if cid == 0: print("Now Human's turn:") cell_select = int(input("It's your turn! Choose a block to place X (1 to 9): ")) play(state_space, players[cid], cell_select) else: cell_select = TD(state_space,players[cid]) play(state_space,players[cid], cell_select) print("Agent O placed at" + str(cell_select)) outline(state_space) won_by, curr_state = cur_state(state_space) if won_by is not None: print(str(won_by) + " Won Won Won!") elif curr_state is "Draw": print("Draw Draw Draw!!!") else: cid = (cid + 1) % 2 play_more = input('Wanna Play more? Hit Y/N') print('See you again! :D')
[ "numpy.full", "numpy.loadtxt", "itertools.product", "numpy.argmax" ]
[((3773, 3799), 'numpy.full', 'np.full', (['Total_states', '(0.0)'], {}), '(Total_states, 0.0)\n', (3780, 3799), True, 'import numpy as np\n'), ((5312, 5357), 'numpy.loadtxt', 'np.loadtxt', (['"""trained_O.txt"""'], {'dtype': 'np.float64'}), "('trained_O.txt', dtype=np.float64)\n", (5322, 5357), True, 'import numpy as np\n'), ((5156, 5184), 'numpy.argmax', 'np.argmax', (['curr_state_values'], {}), '(curr_state_values)\n', (5165, 5184), True, 'import numpy as np\n'), ((3469, 3499), 'itertools.product', 'product', (['each_player'], {'repeat': '(9)'}), '(each_player, repeat=9)\n', (3476, 3499), False, 'from itertools import product\n')]
# Plotting tools and utility functions # Nested GridSpec : https://matplotlib.org/stable/gallery/subplots_axes_and_figures/gridspec_nested.html#sphx-glr-gallery-subplots-axes-and-figures-gridspec-nested-py # GridSpec : https://matplotlib.org/stable/gallery/subplots_axes_and_figures/gridspec_multicolumn.html#sphx-glr-gallery-subplots-axes-and-figures-gridspec-multicolumn-py # colorbar : https://matplotlib.org/stable/gallery/subplots_axes_and_figures/colorbar_placement.html#sphx-glr-gallery-subplots-axes-and-figures-colorbar-placement-py ############# ## Imports ## ############# ## General imports ## from matplotlib import pyplot as plt from matplotlib import colors import numpy as np import os ############### ## Constants ## ############### ############# ## Classes ## ############# class MidpointNormalize(colors.Normalize): """ Useful object enbling to normalize colorbar with a chosen midpoint. """ def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False): super(MidpointNormalize, self).__init__(vmin, vmax, clip) self.midpoint = midpoint def __call__(self, value, clip=None): x, y = [self.vmin, self.midpoint, self.vmax], [0,0.5,1] return np.ma.masked_array(np.interp(value, x, y)) class FigBase(): """ """ CREDITS = "Credit : EU, contains modified Copernicus Sentinel data, processed with custom script." def __init__(self, title : str, dim : tuple): self.title = title self.fig = plt.figure(figsize=dim) def _format(self): pass def show(self): pass ############### ## Functions ## ############### def main(): pass if __name__ == '__main__': main() else: print(f"Module {__name__} imported.", flush=True)
[ "matplotlib.pyplot.figure", "numpy.interp" ]
[((1439, 1462), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'dim'}), '(figsize=dim)\n', (1449, 1462), True, 'from matplotlib import pyplot as plt\n'), ((1203, 1225), 'numpy.interp', 'np.interp', (['value', 'x', 'y'], {}), '(value, x, y)\n', (1212, 1225), True, 'import numpy as np\n')]
import pdb import numpy as np import nose import cudamat as cm import learn as cl def setup(): cm.cublas_init() def teardown(): cm.cublas_shutdown() def test_mult_by_sigmoid_deriv(): m = 256 n = 128 c_targets = np.array(np.random.randn(m, n)*10, dtype=np.float32, order='F') c_acts = np.array(np.random.rand(m, n), dtype=np.float32, order='F') g_targets = cm.CUDAMatrix(c_targets) g_acts = cm.CUDAMatrix(c_acts) c_targets = c_targets * c_acts * (1. - c_acts) cl.mult_by_sigmoid_deriv(g_targets, g_acts) assert np.max(np.abs(c_acts - g_acts.asarray())) < 10**-2, "Error in cudamat.learn.mult_by_sigmoid_deriv exceeded threshold" if __name__ == '__main__': nose.runmodule()
[ "cudamat.cublas_init", "numpy.random.rand", "learn.mult_by_sigmoid_deriv", "cudamat.cublas_shutdown", "cudamat.CUDAMatrix", "nose.runmodule", "numpy.random.randn" ]
[((100, 116), 'cudamat.cublas_init', 'cm.cublas_init', ([], {}), '()\n', (114, 116), True, 'import cudamat as cm\n'), ((138, 158), 'cudamat.cublas_shutdown', 'cm.cublas_shutdown', ([], {}), '()\n', (156, 158), True, 'import cudamat as cm\n'), ((388, 412), 'cudamat.CUDAMatrix', 'cm.CUDAMatrix', (['c_targets'], {}), '(c_targets)\n', (401, 412), True, 'import cudamat as cm\n'), ((426, 447), 'cudamat.CUDAMatrix', 'cm.CUDAMatrix', (['c_acts'], {}), '(c_acts)\n', (439, 447), True, 'import cudamat as cm\n'), ((504, 547), 'learn.mult_by_sigmoid_deriv', 'cl.mult_by_sigmoid_deriv', (['g_targets', 'g_acts'], {}), '(g_targets, g_acts)\n', (528, 547), True, 'import learn as cl\n'), ((710, 726), 'nose.runmodule', 'nose.runmodule', ([], {}), '()\n', (724, 726), False, 'import nose\n'), ((320, 340), 'numpy.random.rand', 'np.random.rand', (['m', 'n'], {}), '(m, n)\n', (334, 340), True, 'import numpy as np\n'), ((243, 264), 'numpy.random.randn', 'np.random.randn', (['m', 'n'], {}), '(m, n)\n', (258, 264), True, 'import numpy as np\n')]
# This is a part of the program which removes the effect of the Differential Reddening from the main sequence of the masive star clusters. # Reference: <NAME> et al (2012) # The steps: 1. Plot a CMD, 2. Rotate the main sequence using theta = A_Filter_1/(A_Filter_I - A_Filter_II); A = Absorption Coefficients (Ref. Jansen et al 1#994) import math import numpy as np import matplotlib import matplotlib.pyplot as plt from matplotlib.pyplot import * import pandas as pd # Read the data from the data file my_data = np.loadtxt('cluster.dat') x_data = my_data[:,2] # Separate the columns y_data = my_data[:,0] # Separate the columns #print(x_data, y_data) #print(x_data.shape, y_data.shape) print("********* THIS IS CMD FOR NGC 1783 ************") plt.figure() plt.scatter(x_data, y_data, 0.3, 'black') plt.xlim(0,3.0) plt.ylim(18, 23) plt.gca().invert_yaxis() plt.xlabel("Colour") plt.ylabel("Magnitude") plt.title('CMD of NGC 1783') # Choose an arbitrary point on CMD plt.show() #Calculate the rotation angle # theta = np.radians(1.0928526307169) # theta = Af435w/(Af435w - Af814w); A = Absorption Coefficients (Ref. Jansen et al 1994) theta = 1.1780330682095217 xcos = (x_data - 0.4) * np.cos(theta) # old_x * cos(theta) ycos = (y_data - 20) * np.cos(theta) # old_y * cos(theta) xsin = (x_data - 0.4) * np.sin(theta) # old_x * sin(theta) ysin = (y_data - 20) * np.sin(theta) # old_y * sin(theta) xx_data = xcos + ysin # Will store the new X_coordinates yy_data = -xsin + ycos # Will store the new Y_coordinates print(xx_data, yy_data) print("****************** THIS IS A TRIAL PLOT FOR DEREDDENING PROCESS ***************") plt.figure() plt.scatter(xx_data, yy_data, 0.3, 'red') plt.xlim(-1,4) plt.ylim(0,0.8) plt.gca().invert_yaxis() plt.xlabel("abscissa") plt.ylabel("ordinate") plt.title('Rotated CMD') plt.show() # Define a dataframe for x data and y data df= pd.DataFrame({'x_data':xx_data,'y_data':yy_data}) # df1 will contain only those values which are in the range [X:-1 to 4] and [Y: 0 to 0.8] df1 = df[(df['x_data']<=4.0) & (df['x_data']>= -1.0) & (df['y_data']<=0.8) & (df['y_data']>=0.0)] #print(df1) bins = np.linspace(0.0, 0.8, num=10) # These are number of bins #print(bins) # md will contain the x and y median points which will be calculated by the following iteration loop. md = pd.DataFrame(np.zeros(((len(bins)-1), 2)), columns=['x_med','y_med']) # Save the median points after the loop calculation. #print(md) # Iteration over the bins to get the median points for each y bins for i in range(len(bins)-1): tempdf = df1[(df1['y_data'] >= bins[i]) & (df1['y_data'] <= bins[i+1]) ] x_median = np.median(tempdf['x_data']) y_median = np.median(tempdf['y_data']) md.iloc[i]=[x_median, y_median] #print(md) print("************* THIS IS FAMOUS FIDUCIAL LINE *****************") plt.figure() plt.plot(md['x_med'], md['y_med'], 'black') plt.scatter(df1['x_data'], df1['y_data'], 0.3, zorder=0) # zorder= is used when you are lazy. plt.xlim(-1,4) plt.ylim(0.0, 0.78) plt.gca().invert_yaxis() # Again. When you are lazy, use this. Being lazy is good and easy. plt.title('Fiducial Line through the Main Sequence') plt.show()
[ "numpy.median", "matplotlib.pyplot.title", "matplotlib.pyplot.xlim", "matplotlib.pyplot.ylabel", "numpy.sin", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "matplotlib.pyplot.gca", "matplotlib.pyplot.figure", "numpy.linspace", "numpy.cos", "matplotlib.pyplot.scatter", "pandas.DataFra...
[((516, 541), 'numpy.loadtxt', 'np.loadtxt', (['"""cluster.dat"""'], {}), "('cluster.dat')\n", (526, 541), True, 'import numpy as np\n'), ((748, 760), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (758, 760), True, 'import matplotlib.pyplot as plt\n'), ((761, 802), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x_data', 'y_data', '(0.3)', '"""black"""'], {}), "(x_data, y_data, 0.3, 'black')\n", (772, 802), True, 'import matplotlib.pyplot as plt\n'), ((803, 819), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(3.0)'], {}), '(0, 3.0)\n', (811, 819), True, 'import matplotlib.pyplot as plt\n'), ((819, 835), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(18)', '(23)'], {}), '(18, 23)\n', (827, 835), True, 'import matplotlib.pyplot as plt\n'), ((861, 881), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Colour"""'], {}), "('Colour')\n", (871, 881), True, 'import matplotlib.pyplot as plt\n'), ((882, 905), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Magnitude"""'], {}), "('Magnitude')\n", (892, 905), True, 'import matplotlib.pyplot as plt\n'), ((906, 934), 'matplotlib.pyplot.title', 'plt.title', (['"""CMD of NGC 1783"""'], {}), "('CMD of NGC 1783')\n", (915, 934), True, 'import matplotlib.pyplot as plt\n'), ((971, 981), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (979, 981), True, 'import matplotlib.pyplot as plt\n'), ((1637, 1649), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1647, 1649), True, 'import matplotlib.pyplot as plt\n'), ((1650, 1691), 'matplotlib.pyplot.scatter', 'plt.scatter', (['xx_data', 'yy_data', '(0.3)', '"""red"""'], {}), "(xx_data, yy_data, 0.3, 'red')\n", (1661, 1691), True, 'import matplotlib.pyplot as plt\n'), ((1692, 1707), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(-1)', '(4)'], {}), '(-1, 4)\n', (1700, 1707), True, 'import matplotlib.pyplot as plt\n'), ((1707, 1723), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(0.8)'], {}), '(0, 0.8)\n', (1715, 1723), True, 'import matplotlib.pyplot as plt\n'), ((1748, 1770), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""abscissa"""'], {}), "('abscissa')\n", (1758, 1770), True, 'import matplotlib.pyplot as plt\n'), ((1771, 1793), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""ordinate"""'], {}), "('ordinate')\n", (1781, 1793), True, 'import matplotlib.pyplot as plt\n'), ((1794, 1818), 'matplotlib.pyplot.title', 'plt.title', (['"""Rotated CMD"""'], {}), "('Rotated CMD')\n", (1803, 1818), True, 'import matplotlib.pyplot as plt\n'), ((1819, 1829), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1827, 1829), True, 'import matplotlib.pyplot as plt\n'), ((1878, 1930), 'pandas.DataFrame', 'pd.DataFrame', (["{'x_data': xx_data, 'y_data': yy_data}"], {}), "({'x_data': xx_data, 'y_data': yy_data})\n", (1890, 1930), True, 'import pandas as pd\n'), ((2135, 2164), 'numpy.linspace', 'np.linspace', (['(0.0)', '(0.8)'], {'num': '(10)'}), '(0.0, 0.8, num=10)\n', (2146, 2164), True, 'import numpy as np\n'), ((2824, 2836), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2834, 2836), True, 'import matplotlib.pyplot as plt\n'), ((2837, 2880), 'matplotlib.pyplot.plot', 'plt.plot', (["md['x_med']", "md['y_med']", '"""black"""'], {}), "(md['x_med'], md['y_med'], 'black')\n", (2845, 2880), True, 'import matplotlib.pyplot as plt\n'), ((2881, 2937), 'matplotlib.pyplot.scatter', 'plt.scatter', (["df1['x_data']", "df1['y_data']", '(0.3)'], {'zorder': '(0)'}), "(df1['x_data'], df1['y_data'], 0.3, zorder=0)\n", (2892, 2937), True, 'import matplotlib.pyplot as plt\n'), ((2976, 2991), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(-1)', '(4)'], {}), '(-1, 4)\n', (2984, 2991), True, 'import matplotlib.pyplot as plt\n'), ((2991, 3010), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0.0)', '(0.78)'], {}), '(0.0, 0.78)\n', (2999, 3010), True, 'import matplotlib.pyplot as plt\n'), ((3104, 3156), 'matplotlib.pyplot.title', 'plt.title', (['"""Fiducial Line through the Main Sequence"""'], {}), "('Fiducial Line through the Main Sequence')\n", (3113, 3156), True, 'import matplotlib.pyplot as plt\n'), ((3157, 3167), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3165, 3167), True, 'import matplotlib.pyplot as plt\n'), ((1192, 1205), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (1198, 1205), True, 'import numpy as np\n'), ((1251, 1264), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (1257, 1264), True, 'import numpy as np\n'), ((1311, 1324), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (1317, 1324), True, 'import numpy as np\n'), ((1370, 1383), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (1376, 1383), True, 'import numpy as np\n'), ((2636, 2663), 'numpy.median', 'np.median', (["tempdf['x_data']"], {}), "(tempdf['x_data'])\n", (2645, 2663), True, 'import numpy as np\n'), ((2679, 2706), 'numpy.median', 'np.median', (["tempdf['y_data']"], {}), "(tempdf['y_data'])\n", (2688, 2706), True, 'import numpy as np\n'), ((836, 845), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (843, 845), True, 'import matplotlib.pyplot as plt\n'), ((1723, 1732), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (1730, 1732), True, 'import matplotlib.pyplot as plt\n'), ((3011, 3020), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (3018, 3020), True, 'import matplotlib.pyplot as plt\n')]
import numpy as np import pandas as pd import pytest from rs_metrics.metrics import _ndcg_score from rs_metrics import * from rs_metrics.statistics import item_pop def test_dcg_score_1(): assert _ndcg_score([1], [1], 1) == 1 def test_dcg_score_0(): assert _ndcg_score([1], [0], 1) == 0 def test_dcg_score_half(): idcg2 = (1 / np.log2(2) + 1 / np.log2(3)) dcg = 1 / np.log2(3) assert _ndcg_score([1, 2], [0, 2], 2) == dcg / idcg2 def test_ndcg_test_less_than_k(): y_true = {1: [1, 2, 3]} assert ndcg(y_true, y_true, 5) == ndcg(y_true, y_true, 3) == 1 def test_ndcg(): y_true = {1: [1, 2], 2: [1, 2]} y_pred = {1: [1, 2], 2: [0, 0]} assert ndcg(y_true, y_pred, 2) == 0.5 def test_ndcg_pandas(): y_true = pd.DataFrame([[1, 1], [1, 2]], columns=['user_idx', 'item_id']) y_pred = pd.DataFrame([[1, 1], [1, 0]], columns=['user_idx', 'item_id']) idcg2 = (1 / np.log2(2) + 1 / np.log2(3)) dcg = 1 / np.log2(2) assert ndcg(y_true, y_pred, 2, user_col='user_idx') == dcg / idcg2 def test_a_ndcg_one_user(): y_true = {1: [1, 2, 3]} y_pred = {1: [1, 2, 3]} sp = {1: [{1}, {2}, {3}]} assert a_ndcg(y_true, y_pred, sp, 3) == 1 def test_a_ndcg(): y_true = {1: [1, 2, 3], 2: [1, 2, 3]} y_pred = {1: [1, 2, 3], 2: [0, 0, 0]} sp = {1: [{1, 2}, {3}], 2: [{1, 2, 3}]} u1_score = (1 + 0.4/np.log2(3) + 1/np.log2(4)) / (1 + 1/np.log2(3) + 0.4/np.log2(4)) answer = (u1_score + 0) / 2 assert a_ndcg(y_true, y_pred, sp, 3, 0.6) == answer def test_hitrate(): y_true = {1: [1, 2], 2: [1, 2]} y_pred = {1: [0, 1], 2: [0, 0]} assert hitrate(y_true, y_pred, 2) == 0.5 def test_precision(): y_true = {1: [1, 0, 0, 2], 2: [1, 2]} y_pred = {1: [1, 2], 2: [1, 3]} assert precision(y_true, y_pred, 2) == 0.75 def test_recall(): y_true = {1: [1, 2], 2: [1, 2]} y_pred = {1: [1, 3], 2: [0, 0]} assert recall(y_true, y_pred, 2) == 0.25 def test_mrr(): y_true = {1: [1, 2], 2: [1, 2]} y_pred = {1: [1, 3], 2: [0, 1]} assert mrr(y_true, y_pred, 2) == 0.75 def test_map(): y_true = {1: [1, 2], 2: [1, 2]} y_pred = {1: [1, 3], 2: [0, 1]} assert mapr(y_true, y_pred, 2) == 0.75 def test_mar(): y_true = {1: [1, 2], 2: [1, 2]} y_pred = {1: [1, 3], 2: [0, 1]} assert mar(y_true, y_pred, 2) == 0.25 def test_coverage(): items = [1, 2, 3, 4] pred = {1: [1, 2], 2: [2, 5]} assert coverage(items, pred) == 0.5 @pytest.fixture def log(): return pd.DataFrame({'user_id': [1, 1, 2], 'item_id': [1, 2, 2]}) def test_item_pop(log): pops = item_pop(log) assert sum(pops) == 1.5 def test_popularity(log): pred = {1: [2], 2: [1]} assert popularity(log, pred, 2) == 0.75 def test_surprisal(): df = pd.DataFrame({'user_id': [1, 2], 'item_id': [1, 2]}) pred = {1: [2], 2: [1]} assert surprisal(df, pred, 2) == 1
[ "pandas.DataFrame", "numpy.log2", "rs_metrics.statistics.item_pop", "rs_metrics.metrics._ndcg_score" ]
[((759, 822), 'pandas.DataFrame', 'pd.DataFrame', (['[[1, 1], [1, 2]]'], {'columns': "['user_idx', 'item_id']"}), "([[1, 1], [1, 2]], columns=['user_idx', 'item_id'])\n", (771, 822), True, 'import pandas as pd\n'), ((836, 899), 'pandas.DataFrame', 'pd.DataFrame', (['[[1, 1], [1, 0]]'], {'columns': "['user_idx', 'item_id']"}), "([[1, 1], [1, 0]], columns=['user_idx', 'item_id'])\n", (848, 899), True, 'import pandas as pd\n'), ((2516, 2574), 'pandas.DataFrame', 'pd.DataFrame', (["{'user_id': [1, 1, 2], 'item_id': [1, 2, 2]}"], {}), "({'user_id': [1, 1, 2], 'item_id': [1, 2, 2]})\n", (2528, 2574), True, 'import pandas as pd\n'), ((2612, 2625), 'rs_metrics.statistics.item_pop', 'item_pop', (['log'], {}), '(log)\n', (2620, 2625), False, 'from rs_metrics.statistics import item_pop\n'), ((2787, 2839), 'pandas.DataFrame', 'pd.DataFrame', (["{'user_id': [1, 2], 'item_id': [1, 2]}"], {}), "({'user_id': [1, 2], 'item_id': [1, 2]})\n", (2799, 2839), True, 'import pandas as pd\n'), ((202, 226), 'rs_metrics.metrics._ndcg_score', '_ndcg_score', (['[1]', '[1]', '(1)'], {}), '([1], [1], 1)\n', (213, 226), False, 'from rs_metrics.metrics import _ndcg_score\n'), ((269, 293), 'rs_metrics.metrics._ndcg_score', '_ndcg_score', (['[1]', '[0]', '(1)'], {}), '([1], [0], 1)\n', (280, 293), False, 'from rs_metrics.metrics import _ndcg_score\n'), ((388, 398), 'numpy.log2', 'np.log2', (['(3)'], {}), '(3)\n', (395, 398), True, 'import numpy as np\n'), ((410, 440), 'rs_metrics.metrics._ndcg_score', '_ndcg_score', (['[1, 2]', '[0, 2]', '(2)'], {}), '([1, 2], [0, 2], 2)\n', (421, 440), False, 'from rs_metrics.metrics import _ndcg_score\n'), ((960, 970), 'numpy.log2', 'np.log2', (['(2)'], {}), '(2)\n', (967, 970), True, 'import numpy as np\n'), ((345, 355), 'numpy.log2', 'np.log2', (['(2)'], {}), '(2)\n', (352, 355), True, 'import numpy as np\n'), ((362, 372), 'numpy.log2', 'np.log2', (['(3)'], {}), '(3)\n', (369, 372), True, 'import numpy as np\n'), ((917, 927), 'numpy.log2', 'np.log2', (['(2)'], {}), '(2)\n', (924, 927), True, 'import numpy as np\n'), ((934, 944), 'numpy.log2', 'np.log2', (['(3)'], {}), '(3)\n', (941, 944), True, 'import numpy as np\n'), ((1392, 1402), 'numpy.log2', 'np.log2', (['(4)'], {}), '(4)\n', (1399, 1402), True, 'import numpy as np\n'), ((1430, 1440), 'numpy.log2', 'np.log2', (['(4)'], {}), '(4)\n', (1437, 1440), True, 'import numpy as np\n'), ((1377, 1387), 'numpy.log2', 'np.log2', (['(3)'], {}), '(3)\n', (1384, 1387), True, 'import numpy as np\n'), ((1413, 1423), 'numpy.log2', 'np.log2', (['(3)'], {}), '(3)\n', (1420, 1423), True, 'import numpy as np\n')]
import os, sys sys.path.insert(0,os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import sa_utils import netgen_csg import numpy as np if __name__ == '__main__': prefix = 'oht_8layers_3patches' logger = sa_utils.LogWrapper(prefix+'/'+prefix) netgen_csg.create_patches(box = np.array([0., 0., 0., 6, 1.5, 0.0592]), hole_radius = 0.125, layers = 8, max_resolution = 0.25, max_refines = 5, num = 0, create_inclusions = False, prefix = prefix, logger = logger, alpha = 1.25, beta = 5.0, patch_nums = np.array([3, 1, 1]))
[ "os.path.realpath", "numpy.array", "sa_utils.LogWrapper" ]
[((226, 268), 'sa_utils.LogWrapper', 'sa_utils.LogWrapper', (["(prefix + '/' + prefix)"], {}), "(prefix + '/' + prefix)\n", (245, 268), False, 'import sa_utils\n'), ((65, 91), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (81, 91), False, 'import os, sys\n'), ((302, 343), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0, 6, 1.5, 0.0592]'], {}), '([0.0, 0.0, 0.0, 6, 1.5, 0.0592])\n', (310, 343), True, 'import numpy as np\n'), ((554, 573), 'numpy.array', 'np.array', (['[3, 1, 1]'], {}), '([3, 1, 1])\n', (562, 573), True, 'import numpy as np\n')]
import numpy as np from gym.spaces import Box from metaworld.envs import reward_utils from metaworld.envs.asset_path_utils import full_v2_path_for from metaworld.envs.mujoco.sawyer_xyz.sawyer_xyz_env import SawyerXYZEnv, _assert_task_is_set class SawyerBinPickingEnvV2(SawyerXYZEnv): """ Motivation for V2: V1 was often unsolvable because the cube could be located outside of the starting bin. It could even be near the base of the Sawyer and out of reach of the gripper. V2 changes the `obj_low` and `obj_high` bounds to fix this. Changelog from V1 to V2: - (7/20/20) Changed object initialization space - (7/24/20) Added Byron's XML changes - (11/23/20) Updated reward function to new pick-place style """ def __init__(self): hand_low = (-0.5, 0.40, 0.07) hand_high = (0.5, 1, 0.5) obj_low = (-0.21, 0.65, 0.02) obj_high = (-0.03, 0.75, 0.02) # Small bounds around the center of the target bin goal_low = np.array([0.1199, 0.699, -0.001]) goal_high = np.array([0.1201, 0.701, +0.001]) super().__init__( self.model_name, hand_low=hand_low, hand_high=hand_high, ) self.init_config = { 'obj_init_angle': 0.3, 'obj_init_pos': np.array([-0.12, 0.7, 0.02]), 'hand_init_pos': np.array((0, 0.6, 0.2)), } self.goal = np.array([0.12, 0.7, 0.02]) self.obj_init_pos = self.init_config['obj_init_pos'] self.obj_init_angle = self.init_config['obj_init_angle'] self.hand_init_pos = self.init_config['hand_init_pos'] self._target_to_obj_init = None self.hand_and_obj_space = Box( np.hstack((self.hand_low, obj_low)), np.hstack((self.hand_high, obj_high)), ) self.goal_and_obj_space = Box( np.hstack((goal_low[:2], obj_low[:2])), np.hstack((goal_high[:2], obj_high[:2])), ) self.goal_space = Box(goal_low, goal_high) self._random_reset_space = Box( np.hstack((obj_low, goal_low)), np.hstack((obj_high, goal_high)), ) @property def model_name(self): return full_v2_path_for('sawyer_xyz/sawyer_bin_picking.xml') @_assert_task_is_set def evaluate_state(self, obs, action): ( reward, near_object, grasp_success, obj_to_target, grasp_reward, in_place_reward ) = self.compute_reward(action, obs) info = { 'success': float(obj_to_target <= 0.05), 'near_object': float(near_object), 'grasp_success': float(grasp_success), 'grasp_reward': grasp_reward, 'in_place_reward': in_place_reward, 'obj_to_target': obj_to_target, 'unscaled_reward': reward, } return reward, info @property def _target_site_config(self): return [] def _get_id_main_object(self): return self.unwrapped.model.geom_name2id('objGeom') def _get_pos_objects(self): return self.get_body_com('obj') def _get_quat_objects(self): return self.sim.data.get_body_xquat('obj') def reset_model(self): self._reset_hand() self._target_pos = self.goal.copy() self.obj_init_pos = self.init_config['obj_init_pos'] self.obj_init_angle = self.init_config['obj_init_angle'] obj_height = self.get_body_com('obj')[2] if self.random_init: self.obj_init_pos = self._get_state_rand_vec()[:2] self.obj_init_pos = np.concatenate((self.obj_init_pos, [obj_height])) self._set_obj_xyz(self.obj_init_pos) self._target_pos = self.get_body_com('bin_goal') self._target_to_obj_init = None return self._get_obs() def compute_reward(self, action, obs): hand = obs[:3] obj = obs[4:7] target_to_obj = np.linalg.norm(obj - self._target_pos) if self._target_to_obj_init is None: self._target_to_obj_init = target_to_obj in_place = reward_utils.tolerance( target_to_obj, bounds=(0, self.TARGET_RADIUS), margin=self._target_to_obj_init, sigmoid='long_tail', ) threshold = 0.03 radii = [ np.linalg.norm(hand[:2] - self.obj_init_pos[:2]), np.linalg.norm(hand[:2] - self._target_pos[:2]) ] # floor is a *pair* of 3D funnels centered on (1) the object's initial # position and (2) the desired final position floor = min([ 0.02 * np.log(radius - threshold) + 0.2 if radius > threshold else 0.0 for radius in radii ]) # prevent the hand from running into the edge of the bins by keeping # it above the "floor" above_floor = 1.0 if hand[2] >= floor else reward_utils.tolerance( max(floor - hand[2], 0.0), bounds=(0.0, 0.01), margin=0.05, sigmoid='long_tail', ) object_grasped = self._gripper_caging_reward( action, obj, obj_radius=0.015, pad_success_thresh=0.05, object_reach_radius=0.01, xz_thresh=0.01, desired_gripper_effort=0.7, high_density=True, ) reward = reward_utils.hamacher_product(object_grasped, in_place) near_object = np.linalg.norm(obj - hand) < 0.04 pinched_without_obj = obs[3] < 0.43 lifted = obj[2] - 0.02 > self.obj_init_pos[2] # Increase reward when properly grabbed obj grasp_success = near_object and lifted and not pinched_without_obj if grasp_success: reward += 1. + 5. * reward_utils.hamacher_product( above_floor, in_place ) # Maximize reward on success if target_to_obj < self.TARGET_RADIUS: reward = 10. return ( reward, near_object, grasp_success, target_to_obj, object_grasped, in_place )
[ "numpy.hstack", "metaworld.envs.asset_path_utils.full_v2_path_for", "numpy.log", "gym.spaces.Box", "numpy.array", "numpy.concatenate", "numpy.linalg.norm", "metaworld.envs.reward_utils.hamacher_product", "metaworld.envs.reward_utils.tolerance" ]
[((1036, 1069), 'numpy.array', 'np.array', (['[0.1199, 0.699, -0.001]'], {}), '([0.1199, 0.699, -0.001])\n', (1044, 1069), True, 'import numpy as np\n'), ((1090, 1123), 'numpy.array', 'np.array', (['[0.1201, 0.701, +0.001]'], {}), '([0.1201, 0.701, +0.001])\n', (1098, 1123), True, 'import numpy as np\n'), ((1461, 1488), 'numpy.array', 'np.array', (['[0.12, 0.7, 0.02]'], {}), '([0.12, 0.7, 0.02])\n', (1469, 1488), True, 'import numpy as np\n'), ((2052, 2076), 'gym.spaces.Box', 'Box', (['goal_low', 'goal_high'], {}), '(goal_low, goal_high)\n', (2055, 2076), False, 'from gym.spaces import Box\n'), ((2273, 2326), 'metaworld.envs.asset_path_utils.full_v2_path_for', 'full_v2_path_for', (['"""sawyer_xyz/sawyer_bin_picking.xml"""'], {}), "('sawyer_xyz/sawyer_bin_picking.xml')\n", (2289, 2326), False, 'from metaworld.envs.asset_path_utils import full_v2_path_for\n'), ((4046, 4084), 'numpy.linalg.norm', 'np.linalg.norm', (['(obj - self._target_pos)'], {}), '(obj - self._target_pos)\n', (4060, 4084), True, 'import numpy as np\n'), ((4203, 4330), 'metaworld.envs.reward_utils.tolerance', 'reward_utils.tolerance', (['target_to_obj'], {'bounds': '(0, self.TARGET_RADIUS)', 'margin': 'self._target_to_obj_init', 'sigmoid': '"""long_tail"""'}), "(target_to_obj, bounds=(0, self.TARGET_RADIUS),\n margin=self._target_to_obj_init, sigmoid='long_tail')\n", (4225, 4330), False, 'from metaworld.envs import reward_utils\n'), ((5500, 5555), 'metaworld.envs.reward_utils.hamacher_product', 'reward_utils.hamacher_product', (['object_grasped', 'in_place'], {}), '(object_grasped, in_place)\n', (5529, 5555), False, 'from metaworld.envs import reward_utils\n'), ((1347, 1375), 'numpy.array', 'np.array', (['[-0.12, 0.7, 0.02]'], {}), '([-0.12, 0.7, 0.02])\n', (1355, 1375), True, 'import numpy as np\n'), ((1406, 1429), 'numpy.array', 'np.array', (['(0, 0.6, 0.2)'], {}), '((0, 0.6, 0.2))\n', (1414, 1429), True, 'import numpy as np\n'), ((1771, 1806), 'numpy.hstack', 'np.hstack', (['(self.hand_low, obj_low)'], {}), '((self.hand_low, obj_low))\n', (1780, 1806), True, 'import numpy as np\n'), ((1820, 1857), 'numpy.hstack', 'np.hstack', (['(self.hand_high, obj_high)'], {}), '((self.hand_high, obj_high))\n', (1829, 1857), True, 'import numpy as np\n'), ((1921, 1959), 'numpy.hstack', 'np.hstack', (['(goal_low[:2], obj_low[:2])'], {}), '((goal_low[:2], obj_low[:2]))\n', (1930, 1959), True, 'import numpy as np\n'), ((1973, 2013), 'numpy.hstack', 'np.hstack', (['(goal_high[:2], obj_high[:2])'], {}), '((goal_high[:2], obj_high[:2]))\n', (1982, 2013), True, 'import numpy as np\n'), ((2129, 2159), 'numpy.hstack', 'np.hstack', (['(obj_low, goal_low)'], {}), '((obj_low, goal_low))\n', (2138, 2159), True, 'import numpy as np\n'), ((2173, 2205), 'numpy.hstack', 'np.hstack', (['(obj_high, goal_high)'], {}), '((obj_high, goal_high))\n', (2182, 2205), True, 'import numpy as np\n'), ((3706, 3755), 'numpy.concatenate', 'np.concatenate', (['(self.obj_init_pos, [obj_height])'], {}), '((self.obj_init_pos, [obj_height]))\n', (3720, 3755), True, 'import numpy as np\n'), ((4442, 4490), 'numpy.linalg.norm', 'np.linalg.norm', (['(hand[:2] - self.obj_init_pos[:2])'], {}), '(hand[:2] - self.obj_init_pos[:2])\n', (4456, 4490), True, 'import numpy as np\n'), ((4504, 4551), 'numpy.linalg.norm', 'np.linalg.norm', (['(hand[:2] - self._target_pos[:2])'], {}), '(hand[:2] - self._target_pos[:2])\n', (4518, 4551), True, 'import numpy as np\n'), ((5579, 5605), 'numpy.linalg.norm', 'np.linalg.norm', (['(obj - hand)'], {}), '(obj - hand)\n', (5593, 5605), True, 'import numpy as np\n'), ((5896, 5948), 'metaworld.envs.reward_utils.hamacher_product', 'reward_utils.hamacher_product', (['above_floor', 'in_place'], {}), '(above_floor, in_place)\n', (5925, 5948), False, 'from metaworld.envs import reward_utils\n'), ((4736, 4762), 'numpy.log', 'np.log', (['(radius - threshold)'], {}), '(radius - threshold)\n', (4742, 4762), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- import numpy as np from numba import jit import matplotlib.pyplot as plt import seaborn as sns class BaseWindow(): """Base window class.""" def __init__(self): pass def plot(self): """Show window. """ _, ax = plt.subplots(1) sns.heatmap(self.matrix.T, vmin=0, vmax=1, xticklabels=self.matrix.shape[0]//10, yticklabels=self.matrix.shape[1]//10, ax=ax) ax.invert_yaxis() ax.set_title(self.label) ax.set_xlabel("query index") ax.set_ylabel("reference index") plt.show() class NoWindow(BaseWindow): label = "no window" def __init__(self, len_x, len_y): """No window class which will be used for no constraint. Parameters ---------- len_x : int Length of query. len_y : int Length of reference. """ self._gen_window(len_x, len_y) def _gen_window(self, len_x, len_y): self.matrix = np.ones([len_x, len_y], dtype=bool) self.list = np.argwhere(self.matrix == True) class SakoechibaWindow(BaseWindow): label = "sakoechiba window" def __init__(self, len_x, len_y, size): """Sakoechiba window. Parameters ---------- len_x : int Length of query. len_y : int Length of reference. size : int Size of window width. """ self._gen_window(len_x, len_y, size) def _gen_window(self, len_x, len_y, size): xx = np.arange(len_x) yy = np.arange(len_y) self.matrix = np.abs(xx[:,np.newaxis] - yy[np.newaxis, :]) <= size self.list = np.argwhere(self.matrix == True) class ItakuraWindow(BaseWindow): label = "itakura window" def __init__(self, len_x, len_y): """Itakura window. Parameters ---------- len_x : int Length of query. len_y : int Length of reference. """ self._gen_window(len_x, len_y) def _gen_window(self, len_x, len_y): self.matrix = _gen_itakura_window(len_x, len_y).astype(np.bool) self.list = np.argwhere(self.matrix == True) @jit(nopython=True) def _gen_itakura_window(len_x, len_y): matrix = np.zeros((len_x, len_y), dtype=np.int8) for xidx in range(len_x): for yidx in range(len_y): if (yidx < 2*xidx + 1) and (xidx <= 2*yidx + 1) and \ (xidx >= len_x - 2*(len_y - yidx)) and \ (yidx > len_y - 2*(len_x - xidx)): matrix[xidx, yidx] = 1 return matrix class UserWindow(BaseWindow): label = "user defined window" def __init__(self, len_x, len_y, win_func, *args, **kwargs): """Initialize user defined window. Parameters ---------- len_x : int Length of query. len_y : int Length of reference. win_func : callable Any function which returns bool. *args, **kwargs : Arguments for win_func """ self._gen_window(len_x, len_y, win_func, *args, **kwargs) def _gen_window(self, len_x, len_y, win_func, *args, **kwargs): matrix = np.zeros((len_x, len_y), dtype=np.bool) for xidx in range(len_x): for yidx in range(len_y): if win_func(xidx, yidx, *args, **kwargs): matrix[xidx,yidx] = True self.matrix = matrix self.list = np.argwhere(self.matrix == True)
[ "numpy.abs", "numpy.ones", "seaborn.heatmap", "numpy.zeros", "numba.jit", "numpy.argwhere", "matplotlib.pyplot.subplots", "numpy.arange", "matplotlib.pyplot.show" ]
[((2283, 2301), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (2286, 2301), False, 'from numba import jit\n'), ((2354, 2393), 'numpy.zeros', 'np.zeros', (['(len_x, len_y)'], {'dtype': 'np.int8'}), '((len_x, len_y), dtype=np.int8)\n', (2362, 2393), True, 'import numpy as np\n'), ((282, 297), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)'], {}), '(1)\n', (294, 297), True, 'import matplotlib.pyplot as plt\n'), ((306, 439), 'seaborn.heatmap', 'sns.heatmap', (['self.matrix.T'], {'vmin': '(0)', 'vmax': '(1)', 'xticklabels': '(self.matrix.shape[0] // 10)', 'yticklabels': '(self.matrix.shape[1] // 10)', 'ax': 'ax'}), '(self.matrix.T, vmin=0, vmax=1, xticklabels=self.matrix.shape[0] //\n 10, yticklabels=self.matrix.shape[1] // 10, ax=ax)\n', (317, 439), True, 'import seaborn as sns\n'), ((613, 623), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (621, 623), True, 'import matplotlib.pyplot as plt\n'), ((1038, 1073), 'numpy.ones', 'np.ones', (['[len_x, len_y]'], {'dtype': 'bool'}), '([len_x, len_y], dtype=bool)\n', (1045, 1073), True, 'import numpy as np\n'), ((1094, 1126), 'numpy.argwhere', 'np.argwhere', (['(self.matrix == True)'], {}), '(self.matrix == True)\n', (1105, 1126), True, 'import numpy as np\n'), ((1604, 1620), 'numpy.arange', 'np.arange', (['len_x'], {}), '(len_x)\n', (1613, 1620), True, 'import numpy as np\n'), ((1634, 1650), 'numpy.arange', 'np.arange', (['len_y'], {}), '(len_y)\n', (1643, 1650), True, 'import numpy as np\n'), ((1746, 1778), 'numpy.argwhere', 'np.argwhere', (['(self.matrix == True)'], {}), '(self.matrix == True)\n', (1757, 1778), True, 'import numpy as np\n'), ((2247, 2279), 'numpy.argwhere', 'np.argwhere', (['(self.matrix == True)'], {}), '(self.matrix == True)\n', (2258, 2279), True, 'import numpy as np\n'), ((3304, 3343), 'numpy.zeros', 'np.zeros', (['(len_x, len_y)'], {'dtype': 'np.bool'}), '((len_x, len_y), dtype=np.bool)\n', (3312, 3343), True, 'import numpy as np\n'), ((3568, 3600), 'numpy.argwhere', 'np.argwhere', (['(self.matrix == True)'], {}), '(self.matrix == True)\n', (3579, 3600), True, 'import numpy as np\n'), ((1673, 1718), 'numpy.abs', 'np.abs', (['(xx[:, np.newaxis] - yy[np.newaxis, :])'], {}), '(xx[:, np.newaxis] - yy[np.newaxis, :])\n', (1679, 1718), True, 'import numpy as np\n')]
import numpy from methods.dna import PatternDNA from methods.fuser import Fuser from methods.fuser import init_indices from methods.fuser import init_matched_group L = PatternDNA(["L"], dna_strand=numpy.array([["T", "T", "R"], ["C", "T", "N"]])) R = PatternDNA(["R"], dna_strand=numpy.array([["C", "G", "N"], ["A", "G", "R"]])) S = PatternDNA(["S"], dna_strand=numpy.array([["A", "G", "Y"], ["T", "C", "N"]])) # stop codon s = PatternDNA(["s"], dna_strand=numpy.array([["T", "A", "R"], ["T", "G", "A"]])) fork_names = ["L", "R", "S", "s"] forks = [L, R, S, s] for index_1 in range(4): for index_2 in range(4): fuser = Fuser(init_indices(fork_names[index_2], forks[index_2])) overlap_length = fuser.calculate_overlap(init_matched_group(fork_names[index_2], forks[index_2])) print("maximum overlap = " + str(overlap_length))
[ "numpy.array", "methods.fuser.init_indices", "methods.fuser.init_matched_group" ]
[((206, 253), 'numpy.array', 'numpy.array', (["[['T', 'T', 'R'], ['C', 'T', 'N']]"], {}), "([['T', 'T', 'R'], ['C', 'T', 'N']])\n", (217, 253), False, 'import numpy\n'), ((289, 336), 'numpy.array', 'numpy.array', (["[['C', 'G', 'N'], ['A', 'G', 'R']]"], {}), "([['C', 'G', 'N'], ['A', 'G', 'R']])\n", (300, 336), False, 'import numpy\n'), ((372, 419), 'numpy.array', 'numpy.array', (["[['A', 'G', 'Y'], ['T', 'C', 'N']]"], {}), "([['A', 'G', 'Y'], ['T', 'C', 'N']])\n", (383, 419), False, 'import numpy\n'), ((469, 516), 'numpy.array', 'numpy.array', (["[['T', 'A', 'R'], ['T', 'G', 'A']]"], {}), "([['T', 'A', 'R'], ['T', 'G', 'A']])\n", (480, 516), False, 'import numpy\n'), ((658, 707), 'methods.fuser.init_indices', 'init_indices', (['fork_names[index_2]', 'forks[index_2]'], {}), '(fork_names[index_2], forks[index_2])\n', (670, 707), False, 'from methods.fuser import init_indices\n'), ((759, 814), 'methods.fuser.init_matched_group', 'init_matched_group', (['fork_names[index_2]', 'forks[index_2]'], {}), '(fork_names[index_2], forks[index_2])\n', (777, 814), False, 'from methods.fuser import init_matched_group\n')]
# -*- coding: utf-8 -*- """ Python Flight Mechanics Engine (PyFME). Copyright (c) AeroPython Development Team. Distributed under the terms of the MIT License. Frames of Reference orientation test functions ---------------------------------------------- """ import pytest import numpy as np from numpy.testing import (assert_array_almost_equal) from pyfme.utils.coordinates import (body2hor, hor2body, check_theta_phi_psi_range, hor2wind, wind2hor, check_gamma_mu_chi_range, body2wind, wind2body, check_alpha_beta_range) def test_check_theta_range(): wrong_values = (3 * np.pi, - 3 * np.pi) for value in wrong_values: # 0 is always a correct value with pytest.raises(ValueError) as excinfo: check_theta_phi_psi_range(value, 0, 0) assert ("ValueError: Theta value is not inside correct range" in excinfo.exconly()) def test_check_phi_range(): wrong_values = (3 * np.pi, - 3 * np.pi) for value in wrong_values: # 0 is always a correct value with pytest.raises(ValueError) as excinfo: check_theta_phi_psi_range(0, value, 0) assert ("ValueError: Phi value is not inside correct range" in excinfo.exconly()) def test_check_psi_range(): wrong_values = (3 * np.pi, - 3 * np.pi) for value in wrong_values: # 0 is always a correct value with pytest.raises(ValueError) as excinfo: check_theta_phi_psi_range(0, 0, value) assert ("ValueError: Psi value is not inside correct range" in excinfo.exconly()) def test_body2hor(): # Test with a pitch rotation vector_body = np.array([1, 1, 1]) theta, phi, psi = np.deg2rad(45), 0, 0 vector_hor = body2hor(vector_body, theta, phi, psi) vector_hor_expected = np.array([2 * 0.70710678118654757, 1, 0]) assert_array_almost_equal(vector_hor, vector_hor_expected) # Test with a roll rotation vector_body = np.array([1, 1, 1]) theta, phi, psi = 0, np.deg2rad(45), 0 vector_hor = body2hor(vector_body, theta, phi, psi) vector_hor_expected = np.array([1, 0, 2 * 0.70710678118654757]) assert_array_almost_equal(vector_hor, vector_hor_expected) # Test with a yaw rotation vector_body = np.array([1, 1, 1]) theta, phi, psi = 0, 0, np.deg2rad(45) vector_hor = body2hor(vector_body, theta, phi, psi) vector_hor_expected = np.array([0, 2 * 0.70710678118654757, 1]) assert_array_almost_equal(vector_hor, vector_hor_expected) def test_hor2body(): # Test with a pitch rotation vector_hor = np.array([2 * 0.70710678118654757, 1, 0]) theta, phi, psi = np.deg2rad(45), 0, 0 vector_body_expected = np.array([1, 1, 1]) vector_body = hor2body(vector_hor, theta, phi, psi) assert_array_almost_equal(vector_body, vector_body_expected) # Test with a roll rotation vector_hor = np.array([1, 0, 2 * 0.70710678118654757]) theta, phi, psi = 0, np.deg2rad(45), 0 vector_body_expected = np.array([1, 1, 1]) vector_body = hor2body(vector_hor, theta, phi, psi) assert_array_almost_equal(vector_body, vector_body_expected) # Test with a yaw rotation vector_hor = np.array([0, 2 * 0.70710678118654757, 1]) theta, phi, psi = 0, 0, np.deg2rad(45) vector_body_expected = np.array([1, 1, 1]) vector_body = hor2body(vector_hor, theta, phi, psi) assert_array_almost_equal(vector_body, vector_body_expected) def test_check_gamma_mu_chi_range(): wrong_values = (3 * np.pi, - 3 * np.pi) for value in wrong_values: # 0 is always a correct value angles = [0, 0, 0] for ii in range(3): angles[ii] = value with pytest.raises(ValueError): check_gamma_mu_chi_range(*angles) def test_check_gamma_range(): wrong_values = (3 * np.pi, - 3 * np.pi) for value in wrong_values: # 0 is always a correct value with pytest.raises(ValueError) as excinfo: check_gamma_mu_chi_range(value, 0, 0) assert ("ValueError: Gamma value is not inside correct range" in excinfo.exconly()) def test_check_mu_range(): wrong_values = (3 * np.pi, - 3 * np.pi) for value in wrong_values: # 0 is always a correct value with pytest.raises(ValueError) as excinfo: check_gamma_mu_chi_range(0, value, 0) assert ("ValueError: Mu value is not inside correct range" in excinfo.exconly()) def test_check_chi_range(): wrong_values = (3 * np.pi, - 3 * np.pi) for value in wrong_values: # 0 is always a correct value with pytest.raises(ValueError) as excinfo: check_gamma_mu_chi_range(0, 0, value) assert ("ValueError: Chi value is not inside correct range" in excinfo.exconly()) def test_wind2hor(): # Test with a pitch rotation vector_wind = np.array([1, 1, 1]) gamma, mu, chi = np.deg2rad(45), 0, 0 vector_hor = wind2hor(vector_wind, gamma, mu, chi) vector_hor_expected = np.array([2 * 0.70710678118654757, 1, 0]) assert_array_almost_equal(vector_hor, vector_hor_expected) # Test with a roll rotation vector_wind = np.array([1, 1, 1]) gamma, mu, chi = 0, np.deg2rad(45), 0 vector_hor = wind2hor(vector_wind, gamma, mu, chi) vector_hor_expected = np.array([1, 0, 2 * 0.70710678118654757]) assert_array_almost_equal(vector_hor, vector_hor_expected) # Test with a yaw rotation vector_wind = np.array([1, 1, 1]) gamma, mu, chi = 0, 0, np.deg2rad(45) vector_hor = wind2hor(vector_wind, gamma, mu, chi) vector_hor_expected = np.array([0, 2 * 0.70710678118654757, 1]) assert_array_almost_equal(vector_hor, vector_hor_expected) def test_hor2wind(): # Test with a pitch rotation vector_hor = np.array([2 * 0.70710678118654757, 1, 0]) gamma, mu, chi = np.deg2rad(45), 0, 0 vector_wind_expected = np.array([1, 1, 1]) vector_wind = hor2wind(vector_hor, gamma, mu, chi) assert_array_almost_equal(vector_wind, vector_wind_expected) # Test with a roll rotation vector_hor = np.array([1, 0, 2 * 0.70710678118654757]) gamma, mu, chi = 0, np.deg2rad(45), 0 vector_wind_expected = np.array([1, 1, 1]) vector_wind = hor2wind(vector_hor, gamma, mu, chi) assert_array_almost_equal(vector_wind, vector_wind_expected) # Test with a yaw rotation vector_hor = np.array([0, 2 * 0.70710678118654757, 1]) gamma, mu, chi = 0, 0, np.deg2rad(45) vector_wind_expected = np.array([1, 1, 1]) vector_wind = hor2wind(vector_hor, gamma, mu, chi) assert_array_almost_equal(vector_wind, vector_wind_expected) def test_check_alpha_beta_range(): wrong_values = (3 * np.pi, - 3 * np.pi) for value in wrong_values: # 0 is always a correct value angles = [0, 0] for ii in range(2): angles[ii] = value with pytest.raises(ValueError): check_alpha_beta_range(*angles) def test_check_alpha_range(): wrong_values = (3 * np.pi, - 3 * np.pi) for value in wrong_values: # 0 is always a correct value with pytest.raises(ValueError) as excinfo: check_alpha_beta_range(value, 0) assert ("ValueError: Alpha value is not inside correct range" in excinfo.exconly()) def test_check_beta_range(): wrong_values = (3 * np.pi, - 3 * np.pi) for value in wrong_values: # 0 is always a correct value with pytest.raises(ValueError) as excinfo: check_alpha_beta_range(0, value) assert ("ValueError: Beta value is not inside correct range" in excinfo.exconly()) def test_wind2body(): # Test with an increment of the angle of attack vector_wind = np.array([1, 1, 1]) alpha, beta = np.deg2rad(45), 0 vector_body = wind2body(vector_wind, alpha, beta) vector_body_expected = np.array([0, 1, 2 * 0.70710678118654757]) assert_array_almost_equal(vector_body, vector_body_expected) # Test with an increment of the sideslip angle vector_wind = np.array([1, 1, 1]) alpha, beta = 0, np.deg2rad(45) vector_body = wind2body(vector_wind, alpha, beta) vector_body_expected = np.array([0, 2 * 0.70710678118654757, 1]) assert_array_almost_equal(vector_body, vector_body_expected) def test_body2wind(): # Test with an increment of the angle of attack vector_body = np.array([0, 1, 2 * 0.70710678118654757]) alpha, beta = np.deg2rad(45), 0 vector_wind = body2wind(vector_body, alpha, beta) vector_wind_expected = np.array([1, 1, 1]) assert_array_almost_equal(vector_wind, vector_wind_expected) # Test with an increment of the sideslip angle vector_body = np.array([0, 2 * 0.70710678118654757, 1]) alpha, beta = 0, np.deg2rad(45) vector_wind = body2wind(vector_body, alpha, beta) vector_wind_expected = np.array([1, 1, 1]) assert_array_almost_equal(vector_wind, vector_wind_expected)
[ "pyfme.utils.coordinates.hor2body", "numpy.testing.assert_array_almost_equal", "pyfme.utils.coordinates.check_alpha_beta_range", "pyfme.utils.coordinates.hor2wind", "pyfme.utils.coordinates.body2wind", "pyfme.utils.coordinates.check_theta_phi_psi_range", "numpy.array", "pyfme.utils.coordinates.wind2ho...
[((1909, 1928), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (1917, 1928), True, 'import numpy as np\n'), ((1993, 2031), 'pyfme.utils.coordinates.body2hor', 'body2hor', (['vector_body', 'theta', 'phi', 'psi'], {}), '(vector_body, theta, phi, psi)\n', (2001, 2031), False, 'from pyfme.utils.coordinates import body2hor, hor2body, check_theta_phi_psi_range, hor2wind, wind2hor, check_gamma_mu_chi_range, body2wind, wind2body, check_alpha_beta_range\n'), ((2061, 2101), 'numpy.array', 'np.array', (['[2 * 0.7071067811865476, 1, 0]'], {}), '([2 * 0.7071067811865476, 1, 0])\n', (2069, 2101), True, 'import numpy as np\n'), ((2110, 2168), 'numpy.testing.assert_array_almost_equal', 'assert_array_almost_equal', (['vector_hor', 'vector_hor_expected'], {}), '(vector_hor, vector_hor_expected)\n', (2135, 2168), False, 'from numpy.testing import assert_array_almost_equal\n'), ((2223, 2242), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (2231, 2242), True, 'import numpy as np\n'), ((2307, 2345), 'pyfme.utils.coordinates.body2hor', 'body2hor', (['vector_body', 'theta', 'phi', 'psi'], {}), '(vector_body, theta, phi, psi)\n', (2315, 2345), False, 'from pyfme.utils.coordinates import body2hor, hor2body, check_theta_phi_psi_range, hor2wind, wind2hor, check_gamma_mu_chi_range, body2wind, wind2body, check_alpha_beta_range\n'), ((2375, 2415), 'numpy.array', 'np.array', (['[1, 0, 2 * 0.7071067811865476]'], {}), '([1, 0, 2 * 0.7071067811865476])\n', (2383, 2415), True, 'import numpy as np\n'), ((2424, 2482), 'numpy.testing.assert_array_almost_equal', 'assert_array_almost_equal', (['vector_hor', 'vector_hor_expected'], {}), '(vector_hor, vector_hor_expected)\n', (2449, 2482), False, 'from numpy.testing import assert_array_almost_equal\n'), ((2536, 2555), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (2544, 2555), True, 'import numpy as np\n'), ((2620, 2658), 'pyfme.utils.coordinates.body2hor', 'body2hor', (['vector_body', 'theta', 'phi', 'psi'], {}), '(vector_body, theta, phi, psi)\n', (2628, 2658), False, 'from pyfme.utils.coordinates import body2hor, hor2body, check_theta_phi_psi_range, hor2wind, wind2hor, check_gamma_mu_chi_range, body2wind, wind2body, check_alpha_beta_range\n'), ((2688, 2728), 'numpy.array', 'np.array', (['[0, 2 * 0.7071067811865476, 1]'], {}), '([0, 2 * 0.7071067811865476, 1])\n', (2696, 2728), True, 'import numpy as np\n'), ((2737, 2795), 'numpy.testing.assert_array_almost_equal', 'assert_array_almost_equal', (['vector_hor', 'vector_hor_expected'], {}), '(vector_hor, vector_hor_expected)\n', (2762, 2795), False, 'from numpy.testing import assert_array_almost_equal\n'), ((2876, 2916), 'numpy.array', 'np.array', (['[2 * 0.7071067811865476, 1, 0]'], {}), '([2 * 0.7071067811865476, 1, 0])\n', (2884, 2916), True, 'import numpy as np\n'), ((2993, 3012), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (3001, 3012), True, 'import numpy as np\n'), ((3034, 3071), 'pyfme.utils.coordinates.hor2body', 'hor2body', (['vector_hor', 'theta', 'phi', 'psi'], {}), '(vector_hor, theta, phi, psi)\n', (3042, 3071), False, 'from pyfme.utils.coordinates import body2hor, hor2body, check_theta_phi_psi_range, hor2wind, wind2hor, check_gamma_mu_chi_range, body2wind, wind2body, check_alpha_beta_range\n'), ((3079, 3139), 'numpy.testing.assert_array_almost_equal', 'assert_array_almost_equal', (['vector_body', 'vector_body_expected'], {}), '(vector_body, vector_body_expected)\n', (3104, 3139), False, 'from numpy.testing import assert_array_almost_equal\n'), ((3193, 3233), 'numpy.array', 'np.array', (['[1, 0, 2 * 0.7071067811865476]'], {}), '([1, 0, 2 * 0.7071067811865476])\n', (3201, 3233), True, 'import numpy as np\n'), ((3309, 3328), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (3317, 3328), True, 'import numpy as np\n'), ((3350, 3387), 'pyfme.utils.coordinates.hor2body', 'hor2body', (['vector_hor', 'theta', 'phi', 'psi'], {}), '(vector_hor, theta, phi, psi)\n', (3358, 3387), False, 'from pyfme.utils.coordinates import body2hor, hor2body, check_theta_phi_psi_range, hor2wind, wind2hor, check_gamma_mu_chi_range, body2wind, wind2body, check_alpha_beta_range\n'), ((3395, 3455), 'numpy.testing.assert_array_almost_equal', 'assert_array_almost_equal', (['vector_body', 'vector_body_expected'], {}), '(vector_body, vector_body_expected)\n', (3420, 3455), False, 'from numpy.testing import assert_array_almost_equal\n'), ((3508, 3548), 'numpy.array', 'np.array', (['[0, 2 * 0.7071067811865476, 1]'], {}), '([0, 2 * 0.7071067811865476, 1])\n', (3516, 3548), True, 'import numpy as np\n'), ((3624, 3643), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (3632, 3643), True, 'import numpy as np\n'), ((3665, 3702), 'pyfme.utils.coordinates.hor2body', 'hor2body', (['vector_hor', 'theta', 'phi', 'psi'], {}), '(vector_hor, theta, phi, psi)\n', (3673, 3702), False, 'from pyfme.utils.coordinates import body2hor, hor2body, check_theta_phi_psi_range, hor2wind, wind2hor, check_gamma_mu_chi_range, body2wind, wind2body, check_alpha_beta_range\n'), ((3710, 3770), 'numpy.testing.assert_array_almost_equal', 'assert_array_almost_equal', (['vector_body', 'vector_body_expected'], {}), '(vector_body, vector_body_expected)\n', (3735, 3770), False, 'from numpy.testing import assert_array_almost_equal\n'), ((5293, 5312), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (5301, 5312), True, 'import numpy as np\n'), ((5376, 5413), 'pyfme.utils.coordinates.wind2hor', 'wind2hor', (['vector_wind', 'gamma', 'mu', 'chi'], {}), '(vector_wind, gamma, mu, chi)\n', (5384, 5413), False, 'from pyfme.utils.coordinates import body2hor, hor2body, check_theta_phi_psi_range, hor2wind, wind2hor, check_gamma_mu_chi_range, body2wind, wind2body, check_alpha_beta_range\n'), ((5443, 5483), 'numpy.array', 'np.array', (['[2 * 0.7071067811865476, 1, 0]'], {}), '([2 * 0.7071067811865476, 1, 0])\n', (5451, 5483), True, 'import numpy as np\n'), ((5492, 5550), 'numpy.testing.assert_array_almost_equal', 'assert_array_almost_equal', (['vector_hor', 'vector_hor_expected'], {}), '(vector_hor, vector_hor_expected)\n', (5517, 5550), False, 'from numpy.testing import assert_array_almost_equal\n'), ((5605, 5624), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (5613, 5624), True, 'import numpy as np\n'), ((5688, 5725), 'pyfme.utils.coordinates.wind2hor', 'wind2hor', (['vector_wind', 'gamma', 'mu', 'chi'], {}), '(vector_wind, gamma, mu, chi)\n', (5696, 5725), False, 'from pyfme.utils.coordinates import body2hor, hor2body, check_theta_phi_psi_range, hor2wind, wind2hor, check_gamma_mu_chi_range, body2wind, wind2body, check_alpha_beta_range\n'), ((5755, 5795), 'numpy.array', 'np.array', (['[1, 0, 2 * 0.7071067811865476]'], {}), '([1, 0, 2 * 0.7071067811865476])\n', (5763, 5795), True, 'import numpy as np\n'), ((5804, 5862), 'numpy.testing.assert_array_almost_equal', 'assert_array_almost_equal', (['vector_hor', 'vector_hor_expected'], {}), '(vector_hor, vector_hor_expected)\n', (5829, 5862), False, 'from numpy.testing import assert_array_almost_equal\n'), ((5916, 5935), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (5924, 5935), True, 'import numpy as np\n'), ((5999, 6036), 'pyfme.utils.coordinates.wind2hor', 'wind2hor', (['vector_wind', 'gamma', 'mu', 'chi'], {}), '(vector_wind, gamma, mu, chi)\n', (6007, 6036), False, 'from pyfme.utils.coordinates import body2hor, hor2body, check_theta_phi_psi_range, hor2wind, wind2hor, check_gamma_mu_chi_range, body2wind, wind2body, check_alpha_beta_range\n'), ((6066, 6106), 'numpy.array', 'np.array', (['[0, 2 * 0.7071067811865476, 1]'], {}), '([0, 2 * 0.7071067811865476, 1])\n', (6074, 6106), True, 'import numpy as np\n'), ((6115, 6173), 'numpy.testing.assert_array_almost_equal', 'assert_array_almost_equal', (['vector_hor', 'vector_hor_expected'], {}), '(vector_hor, vector_hor_expected)\n', (6140, 6173), False, 'from numpy.testing import assert_array_almost_equal\n'), ((6254, 6294), 'numpy.array', 'np.array', (['[2 * 0.7071067811865476, 1, 0]'], {}), '([2 * 0.7071067811865476, 1, 0])\n', (6262, 6294), True, 'import numpy as np\n'), ((6370, 6389), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (6378, 6389), True, 'import numpy as np\n'), ((6411, 6447), 'pyfme.utils.coordinates.hor2wind', 'hor2wind', (['vector_hor', 'gamma', 'mu', 'chi'], {}), '(vector_hor, gamma, mu, chi)\n', (6419, 6447), False, 'from pyfme.utils.coordinates import body2hor, hor2body, check_theta_phi_psi_range, hor2wind, wind2hor, check_gamma_mu_chi_range, body2wind, wind2body, check_alpha_beta_range\n'), ((6455, 6515), 'numpy.testing.assert_array_almost_equal', 'assert_array_almost_equal', (['vector_wind', 'vector_wind_expected'], {}), '(vector_wind, vector_wind_expected)\n', (6480, 6515), False, 'from numpy.testing import assert_array_almost_equal\n'), ((6569, 6609), 'numpy.array', 'np.array', (['[1, 0, 2 * 0.7071067811865476]'], {}), '([1, 0, 2 * 0.7071067811865476])\n', (6577, 6609), True, 'import numpy as np\n'), ((6684, 6703), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (6692, 6703), True, 'import numpy as np\n'), ((6725, 6761), 'pyfme.utils.coordinates.hor2wind', 'hor2wind', (['vector_hor', 'gamma', 'mu', 'chi'], {}), '(vector_hor, gamma, mu, chi)\n', (6733, 6761), False, 'from pyfme.utils.coordinates import body2hor, hor2body, check_theta_phi_psi_range, hor2wind, wind2hor, check_gamma_mu_chi_range, body2wind, wind2body, check_alpha_beta_range\n'), ((6769, 6829), 'numpy.testing.assert_array_almost_equal', 'assert_array_almost_equal', (['vector_wind', 'vector_wind_expected'], {}), '(vector_wind, vector_wind_expected)\n', (6794, 6829), False, 'from numpy.testing import assert_array_almost_equal\n'), ((6882, 6922), 'numpy.array', 'np.array', (['[0, 2 * 0.7071067811865476, 1]'], {}), '([0, 2 * 0.7071067811865476, 1])\n', (6890, 6922), True, 'import numpy as np\n'), ((6997, 7016), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (7005, 7016), True, 'import numpy as np\n'), ((7038, 7074), 'pyfme.utils.coordinates.hor2wind', 'hor2wind', (['vector_hor', 'gamma', 'mu', 'chi'], {}), '(vector_hor, gamma, mu, chi)\n', (7046, 7074), False, 'from pyfme.utils.coordinates import body2hor, hor2body, check_theta_phi_psi_range, hor2wind, wind2hor, check_gamma_mu_chi_range, body2wind, wind2body, check_alpha_beta_range\n'), ((7082, 7142), 'numpy.testing.assert_array_almost_equal', 'assert_array_almost_equal', (['vector_wind', 'vector_wind_expected'], {}), '(vector_wind, vector_wind_expected)\n', (7107, 7142), False, 'from numpy.testing import assert_array_almost_equal\n'), ((8308, 8327), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (8316, 8327), True, 'import numpy as np\n'), ((8386, 8421), 'pyfme.utils.coordinates.wind2body', 'wind2body', (['vector_wind', 'alpha', 'beta'], {}), '(vector_wind, alpha, beta)\n', (8395, 8421), False, 'from pyfme.utils.coordinates import body2hor, hor2body, check_theta_phi_psi_range, hor2wind, wind2hor, check_gamma_mu_chi_range, body2wind, wind2body, check_alpha_beta_range\n'), ((8452, 8492), 'numpy.array', 'np.array', (['[0, 1, 2 * 0.7071067811865476]'], {}), '([0, 1, 2 * 0.7071067811865476])\n', (8460, 8492), True, 'import numpy as np\n'), ((8501, 8561), 'numpy.testing.assert_array_almost_equal', 'assert_array_almost_equal', (['vector_body', 'vector_body_expected'], {}), '(vector_body, vector_body_expected)\n', (8526, 8561), False, 'from numpy.testing import assert_array_almost_equal\n'), ((8635, 8654), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (8643, 8654), True, 'import numpy as np\n'), ((8713, 8748), 'pyfme.utils.coordinates.wind2body', 'wind2body', (['vector_wind', 'alpha', 'beta'], {}), '(vector_wind, alpha, beta)\n', (8722, 8748), False, 'from pyfme.utils.coordinates import body2hor, hor2body, check_theta_phi_psi_range, hor2wind, wind2hor, check_gamma_mu_chi_range, body2wind, wind2body, check_alpha_beta_range\n'), ((8779, 8819), 'numpy.array', 'np.array', (['[0, 2 * 0.7071067811865476, 1]'], {}), '([0, 2 * 0.7071067811865476, 1])\n', (8787, 8819), True, 'import numpy as np\n'), ((8828, 8888), 'numpy.testing.assert_array_almost_equal', 'assert_array_almost_equal', (['vector_body', 'vector_body_expected'], {}), '(vector_body, vector_body_expected)\n', (8853, 8888), False, 'from numpy.testing import assert_array_almost_equal\n'), ((8990, 9030), 'numpy.array', 'np.array', (['[0, 1, 2 * 0.7071067811865476]'], {}), '([0, 1, 2 * 0.7071067811865476])\n', (8998, 9030), True, 'import numpy as np\n'), ((9090, 9125), 'pyfme.utils.coordinates.body2wind', 'body2wind', (['vector_body', 'alpha', 'beta'], {}), '(vector_body, alpha, beta)\n', (9099, 9125), False, 'from pyfme.utils.coordinates import body2hor, hor2body, check_theta_phi_psi_range, hor2wind, wind2hor, check_gamma_mu_chi_range, body2wind, wind2body, check_alpha_beta_range\n'), ((9156, 9175), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (9164, 9175), True, 'import numpy as np\n'), ((9183, 9243), 'numpy.testing.assert_array_almost_equal', 'assert_array_almost_equal', (['vector_wind', 'vector_wind_expected'], {}), '(vector_wind, vector_wind_expected)\n', (9208, 9243), False, 'from numpy.testing import assert_array_almost_equal\n'), ((9317, 9357), 'numpy.array', 'np.array', (['[0, 2 * 0.7071067811865476, 1]'], {}), '([0, 2 * 0.7071067811865476, 1])\n', (9325, 9357), True, 'import numpy as np\n'), ((9417, 9452), 'pyfme.utils.coordinates.body2wind', 'body2wind', (['vector_body', 'alpha', 'beta'], {}), '(vector_body, alpha, beta)\n', (9426, 9452), False, 'from pyfme.utils.coordinates import body2hor, hor2body, check_theta_phi_psi_range, hor2wind, wind2hor, check_gamma_mu_chi_range, body2wind, wind2body, check_alpha_beta_range\n'), ((9483, 9502), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (9491, 9502), True, 'import numpy as np\n'), ((9510, 9570), 'numpy.testing.assert_array_almost_equal', 'assert_array_almost_equal', (['vector_wind', 'vector_wind_expected'], {}), '(vector_wind, vector_wind_expected)\n', (9535, 9570), False, 'from numpy.testing import assert_array_almost_equal\n'), ((1952, 1966), 'numpy.deg2rad', 'np.deg2rad', (['(45)'], {}), '(45)\n', (1962, 1966), True, 'import numpy as np\n'), ((2269, 2283), 'numpy.deg2rad', 'np.deg2rad', (['(45)'], {}), '(45)\n', (2279, 2283), True, 'import numpy as np\n'), ((2585, 2599), 'numpy.deg2rad', 'np.deg2rad', (['(45)'], {}), '(45)\n', (2595, 2599), True, 'import numpy as np\n'), ((2942, 2956), 'numpy.deg2rad', 'np.deg2rad', (['(45)'], {}), '(45)\n', (2952, 2956), True, 'import numpy as np\n'), ((3261, 3275), 'numpy.deg2rad', 'np.deg2rad', (['(45)'], {}), '(45)\n', (3271, 3275), True, 'import numpy as np\n'), ((3579, 3593), 'numpy.deg2rad', 'np.deg2rad', (['(45)'], {}), '(45)\n', (3589, 3593), True, 'import numpy as np\n'), ((5335, 5349), 'numpy.deg2rad', 'np.deg2rad', (['(45)'], {}), '(45)\n', (5345, 5349), True, 'import numpy as np\n'), ((5650, 5664), 'numpy.deg2rad', 'np.deg2rad', (['(45)'], {}), '(45)\n', (5660, 5664), True, 'import numpy as np\n'), ((5964, 5978), 'numpy.deg2rad', 'np.deg2rad', (['(45)'], {}), '(45)\n', (5974, 5978), True, 'import numpy as np\n'), ((6319, 6333), 'numpy.deg2rad', 'np.deg2rad', (['(45)'], {}), '(45)\n', (6329, 6333), True, 'import numpy as np\n'), ((6636, 6650), 'numpy.deg2rad', 'np.deg2rad', (['(45)'], {}), '(45)\n', (6646, 6650), True, 'import numpy as np\n'), ((6952, 6966), 'numpy.deg2rad', 'np.deg2rad', (['(45)'], {}), '(45)\n', (6962, 6966), True, 'import numpy as np\n'), ((8347, 8361), 'numpy.deg2rad', 'np.deg2rad', (['(45)'], {}), '(45)\n', (8357, 8361), True, 'import numpy as np\n'), ((8677, 8691), 'numpy.deg2rad', 'np.deg2rad', (['(45)'], {}), '(45)\n', (8687, 8691), True, 'import numpy as np\n'), ((9051, 9065), 'numpy.deg2rad', 'np.deg2rad', (['(45)'], {}), '(45)\n', (9061, 9065), True, 'import numpy as np\n'), ((9381, 9395), 'numpy.deg2rad', 'np.deg2rad', (['(45)'], {}), '(45)\n', (9391, 9395), True, 'import numpy as np\n'), ((898, 923), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (911, 923), False, 'import pytest\n'), ((949, 987), 'pyfme.utils.coordinates.check_theta_phi_psi_range', 'check_theta_phi_psi_range', (['value', '(0)', '(0)'], {}), '(value, 0, 0)\n', (974, 987), False, 'from pyfme.utils.coordinates import body2hor, hor2body, check_theta_phi_psi_range, hor2wind, wind2hor, check_gamma_mu_chi_range, body2wind, wind2body, check_alpha_beta_range\n'), ((1265, 1290), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1278, 1290), False, 'import pytest\n'), ((1316, 1354), 'pyfme.utils.coordinates.check_theta_phi_psi_range', 'check_theta_phi_psi_range', (['(0)', 'value', '(0)'], {}), '(0, value, 0)\n', (1341, 1354), False, 'from pyfme.utils.coordinates import body2hor, hor2body, check_theta_phi_psi_range, hor2wind, wind2hor, check_gamma_mu_chi_range, body2wind, wind2body, check_alpha_beta_range\n'), ((1630, 1655), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1643, 1655), False, 'import pytest\n'), ((1681, 1719), 'pyfme.utils.coordinates.check_theta_phi_psi_range', 'check_theta_phi_psi_range', (['(0)', '(0)', 'value'], {}), '(0, 0, value)\n', (1706, 1719), False, 'from pyfme.utils.coordinates import body2hor, hor2body, check_theta_phi_psi_range, hor2wind, wind2hor, check_gamma_mu_chi_range, body2wind, wind2body, check_alpha_beta_range\n'), ((4287, 4312), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (4300, 4312), False, 'import pytest\n'), ((4338, 4375), 'pyfme.utils.coordinates.check_gamma_mu_chi_range', 'check_gamma_mu_chi_range', (['value', '(0)', '(0)'], {}), '(value, 0, 0)\n', (4362, 4375), False, 'from pyfme.utils.coordinates import body2hor, hor2body, check_theta_phi_psi_range, hor2wind, wind2hor, check_gamma_mu_chi_range, body2wind, wind2body, check_alpha_beta_range\n'), ((4652, 4677), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (4665, 4677), False, 'import pytest\n'), ((4703, 4740), 'pyfme.utils.coordinates.check_gamma_mu_chi_range', 'check_gamma_mu_chi_range', (['(0)', 'value', '(0)'], {}), '(0, value, 0)\n', (4727, 4740), False, 'from pyfme.utils.coordinates import body2hor, hor2body, check_theta_phi_psi_range, hor2wind, wind2hor, check_gamma_mu_chi_range, body2wind, wind2body, check_alpha_beta_range\n'), ((5015, 5040), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (5028, 5040), False, 'import pytest\n'), ((5066, 5103), 'pyfme.utils.coordinates.check_gamma_mu_chi_range', 'check_gamma_mu_chi_range', (['(0)', '(0)', 'value'], {}), '(0, 0, value)\n', (5090, 5103), False, 'from pyfme.utils.coordinates import body2hor, hor2body, check_theta_phi_psi_range, hor2wind, wind2hor, check_gamma_mu_chi_range, body2wind, wind2body, check_alpha_beta_range\n'), ((7652, 7677), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (7665, 7677), False, 'import pytest\n'), ((7703, 7735), 'pyfme.utils.coordinates.check_alpha_beta_range', 'check_alpha_beta_range', (['value', '(0)'], {}), '(value, 0)\n', (7725, 7735), False, 'from pyfme.utils.coordinates import body2hor, hor2body, check_theta_phi_psi_range, hor2wind, wind2hor, check_gamma_mu_chi_range, body2wind, wind2body, check_alpha_beta_range\n'), ((8014, 8039), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (8027, 8039), False, 'import pytest\n'), ((8065, 8097), 'pyfme.utils.coordinates.check_alpha_beta_range', 'check_alpha_beta_range', (['(0)', 'value'], {}), '(0, value)\n', (8087, 8097), False, 'from pyfme.utils.coordinates import body2hor, hor2body, check_theta_phi_psi_range, hor2wind, wind2hor, check_gamma_mu_chi_range, body2wind, wind2body, check_alpha_beta_range\n'), ((4040, 4065), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (4053, 4065), False, 'import pytest\n'), ((4084, 4117), 'pyfme.utils.coordinates.check_gamma_mu_chi_range', 'check_gamma_mu_chi_range', (['*angles'], {}), '(*angles)\n', (4108, 4117), False, 'from pyfme.utils.coordinates import body2hor, hor2body, check_theta_phi_psi_range, hor2wind, wind2hor, check_gamma_mu_chi_range, body2wind, wind2body, check_alpha_beta_range\n'), ((7407, 7432), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (7420, 7432), False, 'import pytest\n'), ((7451, 7482), 'pyfme.utils.coordinates.check_alpha_beta_range', 'check_alpha_beta_range', (['*angles'], {}), '(*angles)\n', (7473, 7482), False, 'from pyfme.utils.coordinates import body2hor, hor2body, check_theta_phi_psi_range, hor2wind, wind2hor, check_gamma_mu_chi_range, body2wind, wind2body, check_alpha_beta_range\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 20 19:00:38 2020 @author: Mradumay """ import math import matplotlib.pyplot as plt from scipy.integrate import quad import numpy as np import pandas as pd from colorama import Fore, Style import os import glob import sys num=int(input("Enter number of planets to be plotted:")) num1=round(math.sqrt(num)) col=num1 row=math.ceil(num/num1) cwd=os.getcwd() extension = 'csv' cwd1=cwd+"/Exoplanet_Catalogs" cwd2=cwd+"/Limb_darkening_data" os.chdir(cwd1) files = glob.glob('*.{}'.format(extension)) l=len(files) namef="exoplanet.eu_catalog.csv" exo=[] fig=plt.figure(figsize=(row**2+2*row+7,col**2+3*col+3),constrained_layout=False) newa=[] for te in range(1,num+1): itr=0 for entry in files: if entry==namef and l==1: catalog=0 print(Fore.WHITE +"Exoplanet.eu catalog found") print(Style.RESET_ALL) break else: catalog=float(input("Enter 0 for Exoplanet.eu, 1 for NASA arxiv, and 2 for entering manually:")) break if l==0: print(Fore.RED +"No catalog found. Enter parameters manually") print(Style.RESET_ALL) catalog=2 while catalog!=0 and catalog!=1 and catalog!=2: catalog=float(input(Fore.RED +"Wrong option entered. Please re-enter:")) print(Style.RESET_ALL) if catalog==0: for entry in files: itr=itr+1 if entry==namef: break if entry!=namef and itr==l: sys.exit(Fore.RED +"Exoplanet.eu catalog not found") print(Style.RESET_ALL) data=pd.read_csv(os.path.join(cwd1,"exoplanet.eu_catalog.csv")) df=pd.DataFrame(data) starrad=df["star_radius"] planrad=df["radius"] temp=df["star_teff"] semiax=df["semi_major_axis"] name=data["# name"] eccentricity=data["eccentricity"] Mass=data["star_mass"] metallicity=data["star_metallicity"] exoplanet=input("Enter the name of exoplanet:") exo.append(exoplanet) opt=float(input("Enter 1 if you wish to change st_rad,2 for pl_rad, 3 for Teff, 4 for sm_axis else enter any #: ")) g=1 while g!=0: for i in range(len(starrad)): if name[i]==exoplanet: g=0 break elif name[i]!=exoplanet and i==len(starrad)-1: exoplanet=input(Fore.RED +"Exoplanet not found. Please check the name and type again:") print(Style.RESET_ALL) for i in range(len(starrad)): if name[i]==exoplanet: rp1=planrad[i] rs1=starrad[i] fa1=temp[i] al1=semiax[i] ecc=eccentricity[i] M1=Mass[i] met=metallicity[i] if opt==1 or opt==12 or opt==13 or opt==14: rs1=float(input("Enter stellar radius:")) if opt==2 or opt==12 or opt==23 or opt==24: rp1=float(input("Enter planet radius:")) if opt==3 or opt==13 or opt==23 or opt==34: fa1=float(input("Enter effective temperature:")) if opt==4 or opt==14 or opt==24 or opt==34: al1=float(input("Enter semi-major axis:")) if catalog==1: filename=input("Enter name of NASA arxiv csv file:") it=0 for entry in files: it=it+1 if entry==filename: g1=0 break if it==len(files): sys.exit(Fore.RED +"File name incorrect or file missing. Please check file or re-type") print(Style.RESET_ALL) data=pd.read_csv(os.path.join(cwd1,filename),error_bad_lines=False,skiprows=361,low_memory=False) df=pd.DataFrame(data) planrad=df["pl_radj"] starrad=df["st_rad"] temp=df["st_teff"] semiax=df["pl_orbsmax"] name=data["pl_name"] eccentricity=data["pl_orbeccen"] Mass=data["st_mass"] metallicity=data["st_metfe"] exoplanet=input("Enter the name of exoplanet:") exo.append(exoplanet) opt=float(input("Enter 1 if you wish to change st_rad,2 for pl_rad, 3 for Teff, 4 for sm_axis else enter any #: ")) g2=1 while g2!=0: for i in range(len(starrad)): if name[i]==exoplanet: g2=0 break elif name[i]!=exoplanet and i==len(starrad)-1: exoplanet=input(Fore.RED +"Exoplanet not found. Please check the name and type again:") print(Style.RESET_ALL) for i in range(len(starrad)): if name[i]==exoplanet: rp1=planrad[i] rs1=starrad[i] fa1=temp[i] al1=semiax[i] ecc=eccentricity[i] M1=Mass[i] met=metallicity[i] if opt==1 or opt==12 or opt==13 or opt==14: rs1=float(input("Enter stellar radius:")) if opt==2 or opt==12 or opt==23 or opt==24: rp1=float(input("Enter planet radius:")) if opt==3 or opt==13 or opt==23 or opt==34: fa1=float(input("Enter effective temperature:")) if opt==4 or opt==14 or opt==24 or opt==34: al1=float(input("Enter semi-major axis:")) para=1 while para!=4 and para!=1 and para!=2: para=float(input(Fore.RED +'Wrong option entered. Please re-enter:')) print(Style.RESET_ALL) if catalog==2: print(Style.RESET_ALL) rp1=float(input("Enter radius of planet in Jupiter radii:")) rs1=float(input("Enter radius of the host star in units of solar radius:")) fa1=float(input("Enter effective Temperature of host star in K:")) al1=float(input("Enter semi-major axis of the planet from the star in AU:")) ecc=float(input("Enter eccentricity:")) exoplanet=input("Enter name:") if para==4: M1=float(input("Enter stellar mass(solar units):")) met=float(input("Enter metallicity[Fe/H]:")) if para==1: u=0.6 met=0 M1=1 if para==2: u1=float(input("Enter bolometric quadratic coefficient(u1):")) u2=float(input("Enter bolometric quadratic coefficient(u2):")) met=0 M1=1 if np.isnan(rs1)==True or np.isnan(fa1)==True or np.isnan(al1)==True: print(Fore.RED +"Crucial parameter missing") print(Style.RESET_ALL) else: if np.isnan(rp1)==True: rp1=input(Fore.RED +"Radius of planet is missing. Please enter value in Rj units:") print(Style.RESET_ALL) rp1=float(rp1) if np.isnan(met)==True: met=float(input(Fore.RED +"Metallicity[Fe/H] missing in dataset. Enter manually:")) print(Style.RESET_ALL) if np.isnan(M1)==True: M1=float(input(Fore.RED +"Stellar mass missing in dataset. Enter manually:")) print(Style.RESET_ALL) number=1 obli=0 if np.isnan(ecc)==True: ecc=0 elif ecc!=0 and ecc<0.3: print(Fore.WHITE +"Eccentric orbit detected, calculating values at periastron \033[1;30;47m") print(Style.RESET_ALL) elif ecc>0.3: number=4 print(Fore.WHITE +"Highly eccentric orbit(e>0.3). Calculating annual mean \033[1;30;47m") print(Style.RESET_ALL) true1=np.linspace(0,270,number) if te==num: print(Fore.WHITE +'Generating Plot, Please wait.. \033[1;30;47m') print(Style.RESET_ALL) average=[] inverse=[] for j in range(0,number): true=true1[j]*np.pi/180 ob1=float(obli) ob=ob1*np.pi/180 rp1=float(rp1) rs1=float(rs1) al1=float(al1) fa1=float(fa1) ecc=float(ecc) M=M1*2*10**(30) rs=rs1*6.955*10**8 rp=rp1*6.4*10**6*11.21 al2=al1*1.496*10**11 al=al2*(1-ecc**2)/(1+ecc*abs(math.cos(true))) d=al-rs-rp ch=math.acos(rp/(d+rp)) s3=math.floor(57.3*math.asin(abs(rs-rp)/al)) s1=np.pi/2+s3/57.3 s=np.pi/2 symp=math.acos((rs+rp)/al)*57.3 la1=np.linspace(-s1,s1,500) la2=np.linspace((-s1+ob)*180/np.pi,(s1-ob)*180/np.pi,500) surfgrav=100*6.67*10**(-11)*M/rs**(2) logg=math.log10(surfgrav) oldfor=[] final=[] denom=[] numer=[] if para==1 and u==0.6: fa=fa1*1.0573 if para==1 and u==0: fa=fa1 P=5.67*10**(-8)*fa**(4)*4*np.pi*rs**2 zalist=[] for k in range(len(la1)): la=la1[k] beta=al+rp*math.cos(np.pi-la) y1=math.acos((rs**2-rp**2*(math.sin(la))**2)/(beta*rs - rp*math.sin(la)*(math.sqrt(rp**2*(math.sin(la))**2-rs**2+beta**2))))*180/np.pi y4=math.acos((rs**2-rp**2*(math.sin(la))**2)/(beta*rs + rp*math.sin(la)*(math.sqrt(rp**2*(math.sin(la))**2-rs**2+beta**2))))*180/np.pi y5=math.acos(rs/math.sqrt(al**2+rp**2-2*al*rp*math.cos(la)))*180/np.pi y6=math.acos((rs+rp*math.sin(la))/al) y=(y1)*np.pi/180 y2=(y4)*np.pi/180 y3=(y5)*np.pi/180 y7=math.acos((rs+rp*math.sin(la))/al) ad1=180*math.atan(rs*math.sin(y)/(d+rs-(rs*math.cos(y))))/np.pi ad=math.floor(ad1)*np.pi/180 vis=math.acos(rs/(math.sqrt(al**2+rp**2-2*al*rp*math.cos(la)))) P1=5.67*10**(-8)*fa1**(4)*4*np.pi*(rs)**2 def function(x,th,la): a=-rs*math.sin(th)*math.cos(th)*math.sin(np.pi-la)+al*math.cos(np.pi-la)*math.cos(th)+rp*math.cos(th) b=rs*math.cos(np.pi-la)*(math.cos(th))**2 c=rs**2+al**2+rp**2 - 2*rs*rp*math.sin(th)*math.sin(la)+ 2*al*rp*math.cos(np.pi-la) e=-2*(al+rp*math.cos(np.pi-la))*rs*math.cos(th) mu=abs(-rs+(al+rp*math.cos(np.pi-la))*math.cos(th)*math.cos(x)+rp*math.sin(th)*math.sin(la))/(c+e*math.cos(x))**(1/2) if para==1: lf=1-u*(1-mu) if para==2: lf=1-u1*(1-mu)-u2*(1-mu)**2 return abs(a-b*math.cos(x))*lf*mu/(c+e*math.cos(x))**(3/2) def integration(th,la): return quad(function,-y3,y3,args=(th,la))[0] ll=-y ul=y if la>0: ll=-y ul=y2 if la<0: ll=-y2 ul=y if la>=y and la<np.pi/2 and la<=ch: ll=-math.acos((al*math.cos(la)-rp)*math.cos(la)/rs+ math.sin(la)*math.sqrt(rs**2-(al*math.cos(la)-rp)**2)/rs) if la>ch and rs>rp: ll=math.acos((al*math.cos(la)-rp)*math.cos(la)/rs+ math.sin(la)*math.sqrt(rs**2-(al*math.cos(la)-rp)**2)/rs) if la>=np.pi/2 and rs>rp: ll=math.acos((al*math.cos(la)-rp)*math.cos(la)/rs+ math.sin(la)*math.sqrt(rs**2-(al*math.cos(la)-rp)**2)/rs) if abs(la)>y2 and la<0 and la>-np.pi/2 and abs(la)<=ch: ul=math.acos((al*math.cos(la)-rp)*math.cos(la)/rs- math.sin(la)*math.sqrt(rs**2-(al*math.cos(la)-rp)**2)/rs) if abs(la)>ch and la<0 and rs>rp: ul=-math.acos((al*math.cos(la)-rp)*math.cos(la)/rs- math.sin(la)*math.sqrt(rs**2-(al*math.cos(la)-rp)**2)/rs) if la<=-np.pi/2 and rs>rp: ul=-math.acos((al*math.cos(la)-rp)*math.cos(la)/rs- math.sin(la)*math.sqrt(rs**2-(al*math.cos(la)-rp)**2)/rs) xarr=np.linspace(-y,y,100) tharr=np.linspace(ll,ul,100) def anglefunc(x,th,la): a=-rs*math.sin(th)*math.sin(np.pi-la)+al*math.cos(np.pi-la)+rp b=rs*math.cos(np.pi-la)*(math.cos(th))**1 c=rs**2+al**2+rp**2 - 2*rs*rp*math.sin(th)*math.sin(la)+ 2*al*rp*math.cos(np.pi-la) e=-2*(al+rp*math.cos(np.pi-la))*rs*math.cos(th) return math.acos(abs(a-b*math.cos(x))/(c+e*math.cos(x))**(1/2)) multpoint=[] fluxpoint=[] for it in range(len(xarr)): x=xarr[it] th=tharr[it] pointflux=function(x,th,la) angle=anglefunc(x,th,la) zapoint=pointflux*angle multpoint.append(zapoint) fluxpoint.append(pointflux) la5=math.atan(al*math.tan(la)*math.cos(la)/(al*math.cos(la)-rp)) if la5<0: newp=la newa.append(newp) za=sum(multpoint)/sum(fluxpoint) zalist.append(za*180/np.pi) value=quad(lambda th: integration(th,la),ll, ul)[0] value2=value*P/(4*np.pi*np.pi) final.append(value2/1000) denom.append(math.cos(za)*value2) numer.append(abs(za)*math.cos(za)*value2) old=P1*math.cos(la5)/(4*np.pi*(al**2+rp**2-2*al*rp*math.cos(la))) if la>0 and la5<0: old=0 if la<0 and la5>0: old=0 oldfor.append(old/1000) err=abs(oldfor[250]-final[250]) inverse.append(oldfor) average.append(final) aver=np.asarray(average) inve=np.asarray(inverse) inve1=np.mean(inve,axis=0) aver1=np.mean(aver,axis=0) zaav=np.round(sum(numer)/sum(denom)*180/np.pi,3) maxlatitude=s1*57.3 minlatitude=newa[0]*57.3 tickarray2=np.array([-150,-130,-110,-90,-70,-50,-30,-10,10,30,50,70,90,110,130,150]) plt.subplot(row,col,te) plt.plot(la2,aver1,'k-',label="Geometric Model") plt.plot(la2,inve1,'k--', label="Inverse-square law") plt.xticks(tickarray2) plt.axvline(x=57.3*newa[0],color='gray',linestyle='--',label='Terminator limit for IS law') plt.axvline(x=-57.3*newa[0],color='gray',linestyle='--') plt.axvline(x=symp+4,color='gray',linestyle='dashdot',label='Critical point of symmetry') plt.axvline(x=-symp-4,color='gray',linestyle='dashdot') plt.title("{0},[a={1},Rs={2},Teff={3},Rp={4}]".format(exoplanet,round(al1,4),round(rs1,2),fa1,round(rp1,2)),fontsize=10) plt.grid() plt.xlabel("Latitude",fontsize=12) plt.ylabel("Irradiance (kW/m^2)",fontsize=12) plt.legend() imagename=exoplanet+".jpg" if num>1: imagename=input("Saving image..Enter image name and format:") plt.savefig(imagename,dpi=100,quality=95) plt.show() """ opt=float(input("Enter 0 for displaying the zenith angle plot else press 1 to quit:")) if opt==0: plt.figure(figsize=(row**2+2*row+7,col**2+3*col+3)) for te in range(1,num+1): exoplanet=exo[te-1] plt.subplot(row,col,te) plt.plot(la2,zalist,'k') plt.xlabel("Latitude",fontsize=12) plt.ylabel("Zenith angle",fontsize=12) plt.title("{0}".format(exoplanet)) plt.savefig("Zenith_angle",dpi=500,quality=95) plt.show() """
[ "matplotlib.pyplot.grid", "matplotlib.pyplot.ylabel", "math.acos", "math.floor", "math.sqrt", "math.cos", "numpy.array", "sys.exit", "math.log10", "numpy.mean", "math.tan", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "numpy.asarray", "numpy.linspace", "pandas.DataFrame", "m...
[((390, 411), 'math.ceil', 'math.ceil', (['(num / num1)'], {}), '(num / num1)\n', (399, 411), False, 'import math\n'), ((414, 425), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (423, 425), False, 'import os\n'), ((507, 521), 'os.chdir', 'os.chdir', (['cwd1'], {}), '(cwd1)\n', (515, 521), False, 'import os\n'), ((623, 721), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(row ** 2 + 2 * row + 7, col ** 2 + 3 * col + 3)', 'constrained_layout': '(False)'}), '(figsize=(row ** 2 + 2 * row + 7, col ** 2 + 3 * col + 3),\n constrained_layout=False)\n', (633, 721), True, 'import matplotlib.pyplot as plt\n'), ((15124, 15167), 'matplotlib.pyplot.savefig', 'plt.savefig', (['imagename'], {'dpi': '(100)', 'quality': '(95)'}), '(imagename, dpi=100, quality=95)\n', (15135, 15167), True, 'import matplotlib.pyplot as plt\n'), ((15166, 15176), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (15174, 15176), True, 'import matplotlib.pyplot as plt\n'), ((361, 375), 'math.sqrt', 'math.sqrt', (['num'], {}), '(num)\n', (370, 375), False, 'import math\n'), ((1735, 1753), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (1747, 1753), True, 'import pandas as pd\n'), ((3836, 3854), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (3848, 3854), True, 'import pandas as pd\n'), ((7614, 7641), 'numpy.linspace', 'np.linspace', (['(0)', '(270)', 'number'], {}), '(0, 270, number)\n', (7625, 7641), True, 'import numpy as np\n'), ((14168, 14261), 'numpy.array', 'np.array', (['[-150, -130, -110, -90, -70, -50, -30, -10, 10, 30, 50, 70, 90, 110, 130, 150]'], {}), '([-150, -130, -110, -90, -70, -50, -30, -10, 10, 30, 50, 70, 90, \n 110, 130, 150])\n', (14176, 14261), True, 'import numpy as np\n'), ((14250, 14275), 'matplotlib.pyplot.subplot', 'plt.subplot', (['row', 'col', 'te'], {}), '(row, col, te)\n', (14261, 14275), True, 'import matplotlib.pyplot as plt\n'), ((14286, 14337), 'matplotlib.pyplot.plot', 'plt.plot', (['la2', 'aver1', '"""k-"""'], {'label': '"""Geometric Model"""'}), "(la2, aver1, 'k-', label='Geometric Model')\n", (14294, 14337), True, 'import matplotlib.pyplot as plt\n'), ((14343, 14398), 'matplotlib.pyplot.plot', 'plt.plot', (['la2', 'inve1', '"""k--"""'], {'label': '"""Inverse-square law"""'}), "(la2, inve1, 'k--', label='Inverse-square law')\n", (14351, 14398), True, 'import matplotlib.pyplot as plt\n'), ((14405, 14427), 'matplotlib.pyplot.xticks', 'plt.xticks', (['tickarray2'], {}), '(tickarray2)\n', (14415, 14427), True, 'import matplotlib.pyplot as plt\n'), ((14436, 14537), 'matplotlib.pyplot.axvline', 'plt.axvline', ([], {'x': '(57.3 * newa[0])', 'color': '"""gray"""', 'linestyle': '"""--"""', 'label': '"""Terminator limit for IS law"""'}), "(x=57.3 * newa[0], color='gray', linestyle='--', label=\n 'Terminator limit for IS law')\n", (14447, 14537), True, 'import matplotlib.pyplot as plt\n'), ((14536, 14596), 'matplotlib.pyplot.axvline', 'plt.axvline', ([], {'x': '(-57.3 * newa[0])', 'color': '"""gray"""', 'linestyle': '"""--"""'}), "(x=-57.3 * newa[0], color='gray', linestyle='--')\n", (14547, 14596), True, 'import matplotlib.pyplot as plt\n'), ((14601, 14700), 'matplotlib.pyplot.axvline', 'plt.axvline', ([], {'x': '(symp + 4)', 'color': '"""gray"""', 'linestyle': '"""dashdot"""', 'label': '"""Critical point of symmetry"""'}), "(x=symp + 4, color='gray', linestyle='dashdot', label=\n 'Critical point of symmetry')\n", (14612, 14700), True, 'import matplotlib.pyplot as plt\n'), ((14699, 14758), 'matplotlib.pyplot.axvline', 'plt.axvline', ([], {'x': '(-symp - 4)', 'color': '"""gray"""', 'linestyle': '"""dashdot"""'}), "(x=-symp - 4, color='gray', linestyle='dashdot')\n", (14710, 14758), True, 'import matplotlib.pyplot as plt\n'), ((14892, 14902), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (14900, 14902), True, 'import matplotlib.pyplot as plt\n'), ((14911, 14946), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Latitude"""'], {'fontsize': '(12)'}), "('Latitude', fontsize=12)\n", (14921, 14946), True, 'import matplotlib.pyplot as plt\n'), ((14954, 15000), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Irradiance (kW/m^2)"""'], {'fontsize': '(12)'}), "('Irradiance (kW/m^2)', fontsize=12)\n", (14964, 15000), True, 'import matplotlib.pyplot as plt\n'), ((15008, 15020), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (15018, 15020), True, 'import matplotlib.pyplot as plt\n'), ((1677, 1723), 'os.path.join', 'os.path.join', (['cwd1', '"""exoplanet.eu_catalog.csv"""'], {}), "(cwd1, 'exoplanet.eu_catalog.csv')\n", (1689, 1723), False, 'import os\n'), ((3596, 3688), 'sys.exit', 'sys.exit', (["(Fore.RED + 'File name incorrect or file missing. Please check file or re-type'\n )"], {}), "(Fore.RED +\n 'File name incorrect or file missing. Please check file or re-type')\n", (3604, 3688), False, 'import sys\n'), ((3744, 3772), 'os.path.join', 'os.path.join', (['cwd1', 'filename'], {}), '(cwd1, filename)\n', (3756, 3772), False, 'import os\n'), ((6490, 6503), 'numpy.isnan', 'np.isnan', (['rs1'], {}), '(rs1)\n', (6498, 6503), True, 'import numpy as np\n'), ((6513, 6526), 'numpy.isnan', 'np.isnan', (['fa1'], {}), '(fa1)\n', (6521, 6526), True, 'import numpy as np\n'), ((6536, 6549), 'numpy.isnan', 'np.isnan', (['al1'], {}), '(al1)\n', (6544, 6549), True, 'import numpy as np\n'), ((6666, 6679), 'numpy.isnan', 'np.isnan', (['rp1'], {}), '(rp1)\n', (6674, 6679), True, 'import numpy as np\n'), ((6856, 6869), 'numpy.isnan', 'np.isnan', (['met'], {}), '(met)\n', (6864, 6869), True, 'import numpy as np\n'), ((7019, 7031), 'numpy.isnan', 'np.isnan', (['M1'], {}), '(M1)\n', (7027, 7031), True, 'import numpy as np\n'), ((7207, 7220), 'numpy.isnan', 'np.isnan', (['ecc'], {}), '(ecc)\n', (7215, 7220), True, 'import numpy as np\n'), ((8292, 8316), 'math.acos', 'math.acos', (['(rp / (d + rp))'], {}), '(rp / (d + rp))\n', (8301, 8316), False, 'import math\n'), ((8483, 8508), 'numpy.linspace', 'np.linspace', (['(-s1)', 's1', '(500)'], {}), '(-s1, s1, 500)\n', (8494, 8508), True, 'import numpy as np\n'), ((8523, 8590), 'numpy.linspace', 'np.linspace', (['((-s1 + ob) * 180 / np.pi)', '((s1 - ob) * 180 / np.pi)', '(500)'], {}), '((-s1 + ob) * 180 / np.pi, (s1 - ob) * 180 / np.pi, 500)\n', (8534, 8590), True, 'import numpy as np\n'), ((8644, 8664), 'math.log10', 'math.log10', (['surfgrav'], {}), '(surfgrav)\n', (8654, 8664), False, 'import math\n'), ((13890, 13909), 'numpy.asarray', 'np.asarray', (['average'], {}), '(average)\n', (13900, 13909), True, 'import numpy as np\n'), ((13927, 13946), 'numpy.asarray', 'np.asarray', (['inverse'], {}), '(inverse)\n', (13937, 13946), True, 'import numpy as np\n'), ((13965, 13986), 'numpy.mean', 'np.mean', (['inve'], {'axis': '(0)'}), '(inve, axis=0)\n', (13972, 13986), True, 'import numpy as np\n'), ((14004, 14025), 'numpy.mean', 'np.mean', (['aver'], {'axis': '(0)'}), '(aver, axis=0)\n', (14011, 14025), True, 'import numpy as np\n'), ((1560, 1613), 'sys.exit', 'sys.exit', (["(Fore.RED + 'Exoplanet.eu catalog not found')"], {}), "(Fore.RED + 'Exoplanet.eu catalog not found')\n", (1568, 1613), False, 'import sys\n'), ((8440, 8465), 'math.acos', 'math.acos', (['((rs + rp) / al)'], {}), '((rs + rp) / al)\n', (8449, 8465), False, 'import math\n'), ((12080, 12103), 'numpy.linspace', 'np.linspace', (['(-y)', 'y', '(100)'], {}), '(-y, y, 100)\n', (12091, 12103), True, 'import numpy as np\n'), ((12124, 12148), 'numpy.linspace', 'np.linspace', (['ll', 'ul', '(100)'], {}), '(ll, ul, 100)\n', (12135, 12148), True, 'import numpy as np\n'), ((9037, 9057), 'math.cos', 'math.cos', (['(np.pi - la)'], {}), '(np.pi - la)\n', (9045, 9057), False, 'import math\n'), ((9753, 9768), 'math.floor', 'math.floor', (['ad1'], {}), '(ad1)\n', (9763, 9768), False, 'import math\n'), ((10299, 10311), 'math.cos', 'math.cos', (['th'], {}), '(th)\n', (10307, 10311), False, 'import math\n'), ((10750, 10788), 'scipy.integrate.quad', 'quad', (['function', '(-y3)', 'y3'], {'args': '(th, la)'}), '(function, -y3, y3, args=(th, la))\n', (10754, 10788), False, 'from scipy.integrate import quad\n'), ((12491, 12503), 'math.cos', 'math.cos', (['th'], {}), '(th)\n', (12499, 12503), False, 'import math\n'), ((13437, 13449), 'math.cos', 'math.cos', (['za'], {}), '(za)\n', (13445, 13449), False, 'import math\n'), ((13539, 13552), 'math.cos', 'math.cos', (['la5'], {}), '(la5)\n', (13547, 13552), False, 'import math\n'), ((8237, 8251), 'math.cos', 'math.cos', (['true'], {}), '(true)\n', (8245, 8251), False, 'import math\n'), ((10065, 10077), 'math.cos', 'math.cos', (['th'], {}), '(th)\n', (10073, 10077), False, 'import math\n'), ((10103, 10123), 'math.cos', 'math.cos', (['(np.pi - la)'], {}), '(np.pi - la)\n', (10111, 10123), False, 'import math\n'), ((10123, 10135), 'math.cos', 'math.cos', (['th'], {}), '(th)\n', (10131, 10135), False, 'import math\n'), ((10225, 10245), 'math.cos', 'math.cos', (['(np.pi - la)'], {}), '(np.pi - la)\n', (10233, 10245), False, 'import math\n'), ((12295, 12315), 'math.cos', 'math.cos', (['(np.pi - la)'], {}), '(np.pi - la)\n', (12303, 12315), False, 'import math\n'), ((12315, 12327), 'math.cos', 'math.cos', (['th'], {}), '(th)\n', (12323, 12327), False, 'import math\n'), ((12417, 12437), 'math.cos', 'math.cos', (['(np.pi - la)'], {}), '(np.pi - la)\n', (12425, 12437), False, 'import math\n'), ((13031, 13043), 'math.cos', 'math.cos', (['la'], {}), '(la)\n', (13039, 13043), False, 'import math\n'), ((13495, 13507), 'math.cos', 'math.cos', (['za'], {}), '(za)\n', (13503, 13507), False, 'import math\n'), ((9481, 9493), 'math.sin', 'math.sin', (['la'], {}), '(la)\n', (9489, 9493), False, 'import math\n'), ((9636, 9648), 'math.sin', 'math.sin', (['la'], {}), '(la)\n', (9644, 9648), False, 'import math\n'), ((10008, 10028), 'math.sin', 'math.sin', (['(np.pi - la)'], {}), '(np.pi - la)\n', (10016, 10028), False, 'import math\n'), ((10049, 10061), 'math.cos', 'math.cos', (['th'], {}), '(th)\n', (10057, 10061), False, 'import math\n'), ((10203, 10215), 'math.sin', 'math.sin', (['la'], {}), '(la)\n', (10211, 10215), False, 'import math\n'), ((12226, 12246), 'math.sin', 'math.sin', (['(np.pi - la)'], {}), '(np.pi - la)\n', (12234, 12246), False, 'import math\n'), ((12248, 12268), 'math.cos', 'math.cos', (['(np.pi - la)'], {}), '(np.pi - la)\n', (12256, 12268), False, 'import math\n'), ((12395, 12407), 'math.sin', 'math.sin', (['la'], {}), '(la)\n', (12403, 12407), False, 'import math\n'), ((13018, 13030), 'math.tan', 'math.tan', (['la'], {}), '(la)\n', (13026, 13030), False, 'import math\n'), ((13048, 13060), 'math.cos', 'math.cos', (['la'], {}), '(la)\n', (13056, 13060), False, 'import math\n'), ((13583, 13595), 'math.cos', 'math.cos', (['la'], {}), '(la)\n', (13591, 13595), False, 'import math\n'), ((9691, 9702), 'math.sin', 'math.sin', (['y'], {}), '(y)\n', (9699, 9702), False, 'import math\n'), ((9843, 9855), 'math.cos', 'math.cos', (['la'], {}), '(la)\n', (9851, 9855), False, 'import math\n'), ((9995, 10007), 'math.cos', 'math.cos', (['th'], {}), '(th)\n', (10003, 10007), False, 'import math\n'), ((10030, 10050), 'math.cos', 'math.cos', (['(np.pi - la)'], {}), '(np.pi - la)\n', (10038, 10050), False, 'import math\n'), ((10190, 10202), 'math.sin', 'math.sin', (['th'], {}), '(th)\n', (10198, 10202), False, 'import math\n'), ((10411, 10423), 'math.sin', 'math.sin', (['la'], {}), '(la)\n', (10419, 10423), False, 'import math\n'), ((10430, 10441), 'math.cos', 'math.cos', (['x'], {}), '(x)\n', (10438, 10441), False, 'import math\n'), ((10663, 10674), 'math.cos', 'math.cos', (['x'], {}), '(x)\n', (10671, 10674), False, 'import math\n'), ((11259, 11271), 'math.cos', 'math.cos', (['la'], {}), '(la)\n', (11267, 11271), False, 'import math\n'), ((11276, 11288), 'math.sin', 'math.sin', (['la'], {}), '(la)\n', (11284, 11288), False, 'import math\n'), ((11430, 11442), 'math.cos', 'math.cos', (['la'], {}), '(la)\n', (11438, 11442), False, 'import math\n'), ((11447, 11459), 'math.sin', 'math.sin', (['la'], {}), '(la)\n', (11455, 11459), False, 'import math\n'), ((11631, 11643), 'math.cos', 'math.cos', (['la'], {}), '(la)\n', (11639, 11643), False, 'import math\n'), ((11648, 11660), 'math.sin', 'math.sin', (['la'], {}), '(la)\n', (11656, 11660), False, 'import math\n'), ((12213, 12225), 'math.sin', 'math.sin', (['th'], {}), '(th)\n', (12221, 12225), False, 'import math\n'), ((12382, 12394), 'math.sin', 'math.sin', (['th'], {}), '(th)\n', (12390, 12394), False, 'import math\n'), ((9713, 9724), 'math.cos', 'math.cos', (['y'], {}), '(y)\n', (9721, 9724), False, 'import math\n'), ((9982, 9994), 'math.sin', 'math.sin', (['th'], {}), '(th)\n', (9990, 9994), False, 'import math\n'), ((10276, 10296), 'math.cos', 'math.cos', (['(np.pi - la)'], {}), '(np.pi - la)\n', (10284, 10296), False, 'import math\n'), ((10383, 10394), 'math.cos', 'math.cos', (['x'], {}), '(x)\n', (10391, 10394), False, 'import math\n'), ((10398, 10410), 'math.sin', 'math.sin', (['th'], {}), '(th)\n', (10406, 10410), False, 'import math\n'), ((11094, 11106), 'math.cos', 'math.cos', (['la'], {}), '(la)\n', (11102, 11106), False, 'import math\n'), ((11111, 11123), 'math.sin', 'math.sin', (['la'], {}), '(la)\n', (11119, 11123), False, 'import math\n'), ((11811, 11823), 'math.cos', 'math.cos', (['la'], {}), '(la)\n', (11819, 11823), False, 'import math\n'), ((11828, 11840), 'math.sin', 'math.sin', (['la'], {}), '(la)\n', (11836, 11840), False, 'import math\n'), ((11984, 11996), 'math.cos', 'math.cos', (['la'], {}), '(la)\n', (11992, 11996), False, 'import math\n'), ((12001, 12013), 'math.sin', 'math.sin', (['la'], {}), '(la)\n', (12009, 12013), False, 'import math\n'), ((12468, 12488), 'math.cos', 'math.cos', (['(np.pi - la)'], {}), '(np.pi - la)\n', (12476, 12488), False, 'import math\n'), ((12549, 12560), 'math.cos', 'math.cos', (['x'], {}), '(x)\n', (12557, 12560), False, 'import math\n'), ((12567, 12578), 'math.cos', 'math.cos', (['x'], {}), '(x)\n', (12575, 12578), False, 'import math\n'), ((9099, 9111), 'math.sin', 'math.sin', (['la'], {}), '(la)\n', (9107, 9111), False, 'import math\n'), ((9131, 9143), 'math.sin', 'math.sin', (['la'], {}), '(la)\n', (9139, 9143), False, 'import math\n'), ((9250, 9262), 'math.sin', 'math.sin', (['la'], {}), '(la)\n', (9258, 9262), False, 'import math\n'), ((9282, 9294), 'math.sin', 'math.sin', (['la'], {}), '(la)\n', (9290, 9294), False, 'import math\n'), ((9420, 9432), 'math.cos', 'math.cos', (['la'], {}), '(la)\n', (9428, 9432), False, 'import math\n'), ((10370, 10382), 'math.cos', 'math.cos', (['th'], {}), '(th)\n', (10378, 10382), False, 'import math\n'), ((10639, 10650), 'math.cos', 'math.cos', (['x'], {}), '(x)\n', (10647, 10650), False, 'import math\n'), ((11242, 11254), 'math.cos', 'math.cos', (['la'], {}), '(la)\n', (11250, 11254), False, 'import math\n'), ((11413, 11425), 'math.cos', 'math.cos', (['la'], {}), '(la)\n', (11421, 11425), False, 'import math\n'), ((11614, 11626), 'math.cos', 'math.cos', (['la'], {}), '(la)\n', (11622, 11626), False, 'import math\n'), ((11077, 11089), 'math.cos', 'math.cos', (['la'], {}), '(la)\n', (11085, 11089), False, 'import math\n'), ((11794, 11806), 'math.cos', 'math.cos', (['la'], {}), '(la)\n', (11802, 11806), False, 'import math\n'), ((11967, 11979), 'math.cos', 'math.cos', (['la'], {}), '(la)\n', (11975, 11979), False, 'import math\n'), ((10350, 10370), 'math.cos', 'math.cos', (['(np.pi - la)'], {}), '(np.pi - la)\n', (10358, 10370), False, 'import math\n'), ((11309, 11321), 'math.cos', 'math.cos', (['la'], {}), '(la)\n', (11317, 11321), False, 'import math\n'), ((11480, 11492), 'math.cos', 'math.cos', (['la'], {}), '(la)\n', (11488, 11492), False, 'import math\n'), ((11681, 11693), 'math.cos', 'math.cos', (['la'], {}), '(la)\n', (11689, 11693), False, 'import math\n'), ((9162, 9174), 'math.sin', 'math.sin', (['la'], {}), '(la)\n', (9170, 9174), False, 'import math\n'), ((9313, 9325), 'math.sin', 'math.sin', (['la'], {}), '(la)\n', (9321, 9325), False, 'import math\n'), ((11144, 11156), 'math.cos', 'math.cos', (['la'], {}), '(la)\n', (11152, 11156), False, 'import math\n'), ((11861, 11873), 'math.cos', 'math.cos', (['la'], {}), '(la)\n', (11869, 11873), False, 'import math\n'), ((12034, 12046), 'math.cos', 'math.cos', (['la'], {}), '(la)\n', (12042, 12046), False, 'import math\n')]
import numpy as np import pandas as pd from joblib import Parallel, delayed from sklearn.exceptions import NotFittedError from sklearn.base import clone from sklearn.linear_model import LinearRegression, Lasso from sklearn.model_selection import KFold REQUIRED_COLS = ['start_date', 'lat', 'lon', 'gt'] def _get_rmse(train_df, preds): df_aux = train_df[REQUIRED_COLS].copy() df_aux['pred'] = preds groups = df_aux.groupby(['start_date']) return np.mean([np.sqrt(np.square(df['pred']-df['gt']).mean()) for _, df in groups]) class LinearEnsemble: def __init__(self, local=True, dynamic=True): self.dynamic = dynamic self.local = local self.models = {} self.cols_to_train_on = None def fit(self, train_dataframe): # Check dataframe has required columns for c in REQUIRED_COLS: if c not in train_dataframe.columns: raise ValueError( "Column {} is required by the algorithm, but no such column was found in the training data.".format( c)) # Set columns to train on self.cols_to_train_on = np.setdiff1d( train_dataframe.columns, REQUIRED_COLS, assume_unique=True) # Train partition-wise or global model if self.dynamic: if self.local: groups = train_dataframe.groupby(['lon', 'lat']) # Train on groups in parallel results = Parallel(n_jobs=-1, verbose=1, backend='threading')( delayed(self._train_partition_lr)(g) for g in groups) else: self._train_partition_lr(("global", train_dataframe)) def predict(self, test_dataframe): if self.cols_to_train_on is None: raise NotFittedError( 'This instance of LinearEnsemble has not been fitted yet.') if self.local: df = test_dataframe.apply(lambda r: self._predict_on_row( r), axis=1).reset_index(drop=True) else: df = self._predict_global(test_dataframe) df = df.reset_index(drop=True) return df def _train_partition_lr(self, group): name, df = group # lr = LinearRegression(fit_intercept=False) lr = Lasso(alpha=0.001, positive=True, fit_intercept=False, max_iter=3000) lr.fit(df[self.cols_to_train_on].values, df['gt'].values) self.models[name] = lr def _predict_on_row(self, r): lr = self.models[(r['lon'], r['lat'])] r_new = r[['start_date', 'lon', 'lat']].copy() r_new['pred'] = lr.predict( r[self.cols_to_train_on].values.reshape(1, -1))[0] return r_new def _predict_global(self, df): df_new = df[['start_date', 'lon', 'lat']].copy() if self.dynamic: lr = self.models["global"] df_new['pred'] = lr.predict( df[self.cols_to_train_on].values) else: df_new['pred'] = df[self.cols_to_train_on].mean(axis=1).values return df_new class StepwiseFeatureSelectionWrapper: def __init__(self, model, tolerance=0.01): self.model = model self.tolerance = tolerance def fit(self, train_dataframe): self.candidate_cols = np.setdiff1d( train_dataframe.columns, REQUIRED_COLS, assume_unique=True) # Split data for CV with KFold split_indices = list(KFold(n_splits=2).split(train_dataframe)) # Find RMSE with all columns included target_rmse = self._train_and_eval_model( self.candidate_cols, train_dataframe, split_indices) print("RMSE when including all columns: {0:.3f}".format(target_rmse)) # Track loop execution converged = False selected_cols = np.copy(self.candidate_cols) while not converged and len(selected_cols) > 1: # Train without one column at a time and get predictions # Train in parallel if not local column_sets = [np.setdiff1d( selected_cols, [c], assume_unique=True) for c in selected_cols] if self.model.local: candidate_rmses = np.asarray([self._train_and_eval_model( cols, train_dataframe, split_indices) for cols in column_sets]) else: # Parallel execution candidate_rmses = np.asarray( Parallel(n_jobs=-1, verbose=1, backend='threading')( delayed(self._train_and_eval_model)(cols, train_dataframe, split_indices) for cols in column_sets) ) # Get RMSEs for all predictions, choose smallest RMSE, update cadidate columns delta_rmses = target_rmse - candidate_rmses print("Candidate RMSEs: ", candidate_rmses) print("Delta RMSEs: ", delta_rmses) if delta_rmses.max() > - self.tolerance: max_idx = np.argmax(delta_rmses) selected_cols = np.delete(selected_cols, max_idx) target_rmse = candidate_rmses.min() else: converged = True print("Selected features after this step: ", selected_cols) print("\n") # Fit the best model (on selected columns) self.model.fit(train_dataframe[np.concatenate( (REQUIRED_COLS, selected_cols))]) # Print selected features print("Features selected after stepwise feature selection: {}".format( ", ".join(selected_cols))) print("RMSE after stepwise feature selection: {0:.3f}".format( target_rmse)) def predict(self, test_dataframe): return self.model.predict(test_dataframe) def _train_and_eval_model(self, candidate_cols, train_df, split_indices): candidate_cols = np.concatenate((REQUIRED_COLS, candidate_cols)) preds = np.zeros(train_df.shape[0]) for train_idx, test_idx in split_indices: model = clone(self.model, safe=False) model.fit(train_df[candidate_cols].iloc[train_idx]) preds[test_idx] = model.predict( train_df[candidate_cols].iloc[test_idx])['pred'].values return _get_rmse(train_df, preds)
[ "numpy.copy", "sklearn.exceptions.NotFittedError", "sklearn.linear_model.Lasso", "sklearn.base.clone", "numpy.delete", "numpy.argmax", "numpy.square", "joblib.Parallel", "numpy.zeros", "numpy.setdiff1d", "numpy.concatenate", "joblib.delayed", "sklearn.model_selection.KFold" ]
[((1170, 1242), 'numpy.setdiff1d', 'np.setdiff1d', (['train_dataframe.columns', 'REQUIRED_COLS'], {'assume_unique': '(True)'}), '(train_dataframe.columns, REQUIRED_COLS, assume_unique=True)\n', (1182, 1242), True, 'import numpy as np\n'), ((2306, 2375), 'sklearn.linear_model.Lasso', 'Lasso', ([], {'alpha': '(0.001)', 'positive': '(True)', 'fit_intercept': '(False)', 'max_iter': '(3000)'}), '(alpha=0.001, positive=True, fit_intercept=False, max_iter=3000)\n', (2311, 2375), False, 'from sklearn.linear_model import LinearRegression, Lasso\n'), ((3325, 3397), 'numpy.setdiff1d', 'np.setdiff1d', (['train_dataframe.columns', 'REQUIRED_COLS'], {'assume_unique': '(True)'}), '(train_dataframe.columns, REQUIRED_COLS, assume_unique=True)\n', (3337, 3397), True, 'import numpy as np\n'), ((3841, 3869), 'numpy.copy', 'np.copy', (['self.candidate_cols'], {}), '(self.candidate_cols)\n', (3848, 3869), True, 'import numpy as np\n'), ((5880, 5927), 'numpy.concatenate', 'np.concatenate', (['(REQUIRED_COLS, candidate_cols)'], {}), '((REQUIRED_COLS, candidate_cols))\n', (5894, 5927), True, 'import numpy as np\n'), ((5944, 5971), 'numpy.zeros', 'np.zeros', (['train_df.shape[0]'], {}), '(train_df.shape[0])\n', (5952, 5971), True, 'import numpy as np\n'), ((1807, 1881), 'sklearn.exceptions.NotFittedError', 'NotFittedError', (['"""This instance of LinearEnsemble has not been fitted yet."""'], {}), "('This instance of LinearEnsemble has not been fitted yet.')\n", (1821, 1881), False, 'from sklearn.exceptions import NotFittedError\n'), ((6042, 6071), 'sklearn.base.clone', 'clone', (['self.model'], {'safe': '(False)'}), '(self.model, safe=False)\n', (6047, 6071), False, 'from sklearn.base import clone\n'), ((4067, 4119), 'numpy.setdiff1d', 'np.setdiff1d', (['selected_cols', '[c]'], {'assume_unique': '(True)'}), '(selected_cols, [c], assume_unique=True)\n', (4079, 4119), True, 'import numpy as np\n'), ((4997, 5019), 'numpy.argmax', 'np.argmax', (['delta_rmses'], {}), '(delta_rmses)\n', (5006, 5019), True, 'import numpy as np\n'), ((5052, 5085), 'numpy.delete', 'np.delete', (['selected_cols', 'max_idx'], {}), '(selected_cols, max_idx)\n', (5061, 5085), True, 'import numpy as np\n'), ((5375, 5421), 'numpy.concatenate', 'np.concatenate', (['(REQUIRED_COLS, selected_cols)'], {}), '((REQUIRED_COLS, selected_cols))\n', (5389, 5421), True, 'import numpy as np\n'), ((1492, 1543), 'joblib.Parallel', 'Parallel', ([], {'n_jobs': '(-1)', 'verbose': '(1)', 'backend': '"""threading"""'}), "(n_jobs=-1, verbose=1, backend='threading')\n", (1500, 1543), False, 'from joblib import Parallel, delayed\n'), ((3479, 3496), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': '(2)'}), '(n_splits=2)\n', (3484, 3496), False, 'from sklearn.model_selection import KFold\n'), ((481, 513), 'numpy.square', 'np.square', (["(df['pred'] - df['gt'])"], {}), "(df['pred'] - df['gt'])\n", (490, 513), True, 'import numpy as np\n'), ((4473, 4524), 'joblib.Parallel', 'Parallel', ([], {'n_jobs': '(-1)', 'verbose': '(1)', 'backend': '"""threading"""'}), "(n_jobs=-1, verbose=1, backend='threading')\n", (4481, 4524), False, 'from joblib import Parallel, delayed\n'), ((1565, 1598), 'joblib.delayed', 'delayed', (['self._train_partition_lr'], {}), '(self._train_partition_lr)\n', (1572, 1598), False, 'from joblib import Parallel, delayed\n'), ((4550, 4585), 'joblib.delayed', 'delayed', (['self._train_and_eval_model'], {}), '(self._train_and_eval_model)\n', (4557, 4585), False, 'from joblib import Parallel, delayed\n')]
# Copyright (c) 2021 Graphcore Ltd. All rights reserved. import os import numpy import tensorflow as tf import time from tensorflow.python import ipu from tensorflow.python.ipu import ipu_compiler, scopes, config tf.compat.v1.disable_v2_behavior() def matrix_solve_graph(A, b): outputs = { "output_types": [tf.float16], "output_shapes": [b.shape], } base_path = os.path.realpath(os.path.dirname(__file__)) lib_path = os.path.join(base_path, "libmatrix_solve_ce_op.so") gp_path = os.path.join(base_path, "matrix_solve_codelets.gp") return ipu.custom_ops.precompiled_user_op([A, b], lib_path, gp_path, outs=outputs) def main(): print('kriging start') channel_cnt = numpy.int32(128*1024) loop_cnt = numpy.int32(100) slope_nugget = numpy.array([0.08119393835012971, 1.181032796509736], dtype=numpy.float32) gridx = numpy.arange(0.0, 6.0, 0.5, dtype=numpy.float32) gridy = numpy.arange(0.0, 6.0, 0.5, dtype=numpy.float32) x1, x2 = numpy.meshgrid(gridx, gridx) y1, y2 = numpy.meshgrid(gridy, gridy) dx = (x1 - x2) dy = (y1 - y2) d = numpy.sqrt(numpy.square(dx) + numpy.square(dy)) kriging_mat = -(slope_nugget[0] * d + slope_nugget[1]) kriging_mat_ext = numpy.pad(kriging_mat, ((0, 1), (0, 1)), 'constant', constant_values=1.0) diag_x = numpy.diag(numpy.diag(kriging_mat_ext)) kriging_mat = kriging_mat_ext - diag_x kriging_mat = numpy.expand_dims(kriging_mat, axis=0) kriging_mat = numpy.repeat(kriging_mat, channel_cnt, axis=0) kriging_mat_cpy = numpy.copy(kriging_mat) print('kriging_mat_cpy.shape: {}'.format(kriging_mat_cpy.shape)) b = numpy.array([1.2, 1.1, 1.3, 1.4, 1.6, 1.5, 1.7, 1.8, 1.9, 2.0, 2.1, 1.1, 1.4], dtype=numpy.float32) b = numpy.expand_dims(b, axis=0) b = numpy.expand_dims(b, axis=2) b = numpy.repeat(b, channel_cnt, axis=0) print('kriging_mat.shape: {}'.format(kriging_mat.shape)) print('b.shape: {}'.format(b.shape)) time_start = time.time() x = numpy.linalg.solve(kriging_mat, b) time_end = time.time() print('numpy total time elapsed: {}'.format((time_end - time_start))) print(x) kriging_mat = numpy.float16(kriging_mat) b = numpy.float16(b) print('kriging_mat.shape: {}'.format(kriging_mat.shape)) print('b.shape: {}'.format(b.shape)) connection_type = config.DeviceConnectionType.ALWAYS cfg = config.IPUConfig() cfg.auto_select_ipus = 1 cfg.device_connection.type = connection_type cfg.configure_ipu_system() with tf.device("cpu"): p_A = tf.compat.v1.placeholder(numpy.float16, kriging_mat.shape, name="A") p_b = tf.compat.v1.placeholder(numpy.float16, b.shape, name="b") with scopes.ipu_scope("/device:IPU:0"): mat_solve_model = ipu_compiler.compile(matrix_solve_graph, [p_A, p_b]) with tf.compat.v1.Session() as sess: fd_solve = {p_A: kriging_mat, p_b: b} mat_solve_res = sess.run(mat_solve_model, fd_solve) print(mat_solve_res) time_start = time.time() for i in range(loop_cnt): fd_solve = {p_A: kriging_mat, p_b: b} mat_solve_res = sess.run(mat_solve_model, fd_solve) time_end = time.time() print('ipu total time elapsed: {}'.format((time_end - time_start))) cmp_diff = numpy.abs(mat_solve_res[0] - x) max_diff = numpy.max(cmp_diff) min_diff = numpy.min(cmp_diff) avg_diff = numpy.average(cmp_diff) print('max_diff: {:.8f}, min_diff: {:.8f}, avg_diff: {:.8f}'.format(max_diff, min_diff, avg_diff)) if __name__ == "__main__": main()
[ "tensorflow.compat.v1.disable_v2_behavior", "tensorflow.python.ipu.config.IPUConfig", "numpy.int32", "numpy.array", "tensorflow.python.ipu.ipu_compiler.compile", "tensorflow.compat.v1.Session", "numpy.arange", "tensorflow.compat.v1.placeholder", "numpy.repeat", "numpy.max", "numpy.min", "numpy...
[((216, 250), 'tensorflow.compat.v1.disable_v2_behavior', 'tf.compat.v1.disable_v2_behavior', ([], {}), '()\n', (248, 250), True, 'import tensorflow as tf\n'), ((455, 506), 'os.path.join', 'os.path.join', (['base_path', '"""libmatrix_solve_ce_op.so"""'], {}), "(base_path, 'libmatrix_solve_ce_op.so')\n", (467, 506), False, 'import os\n'), ((521, 572), 'os.path.join', 'os.path.join', (['base_path', '"""matrix_solve_codelets.gp"""'], {}), "(base_path, 'matrix_solve_codelets.gp')\n", (533, 572), False, 'import os\n'), ((584, 659), 'tensorflow.python.ipu.custom_ops.precompiled_user_op', 'ipu.custom_ops.precompiled_user_op', (['[A, b]', 'lib_path', 'gp_path'], {'outs': 'outputs'}), '([A, b], lib_path, gp_path, outs=outputs)\n', (618, 659), False, 'from tensorflow.python import ipu\n'), ((720, 743), 'numpy.int32', 'numpy.int32', (['(128 * 1024)'], {}), '(128 * 1024)\n', (731, 743), False, 'import numpy\n'), ((757, 773), 'numpy.int32', 'numpy.int32', (['(100)'], {}), '(100)\n', (768, 773), False, 'import numpy\n'), ((793, 867), 'numpy.array', 'numpy.array', (['[0.08119393835012971, 1.181032796509736]'], {'dtype': 'numpy.float32'}), '([0.08119393835012971, 1.181032796509736], dtype=numpy.float32)\n', (804, 867), False, 'import numpy\n'), ((880, 928), 'numpy.arange', 'numpy.arange', (['(0.0)', '(6.0)', '(0.5)'], {'dtype': 'numpy.float32'}), '(0.0, 6.0, 0.5, dtype=numpy.float32)\n', (892, 928), False, 'import numpy\n'), ((941, 989), 'numpy.arange', 'numpy.arange', (['(0.0)', '(6.0)', '(0.5)'], {'dtype': 'numpy.float32'}), '(0.0, 6.0, 0.5, dtype=numpy.float32)\n', (953, 989), False, 'import numpy\n'), ((1003, 1031), 'numpy.meshgrid', 'numpy.meshgrid', (['gridx', 'gridx'], {}), '(gridx, gridx)\n', (1017, 1031), False, 'import numpy\n'), ((1045, 1073), 'numpy.meshgrid', 'numpy.meshgrid', (['gridy', 'gridy'], {}), '(gridy, gridy)\n', (1059, 1073), False, 'import numpy\n'), ((1250, 1323), 'numpy.pad', 'numpy.pad', (['kriging_mat', '((0, 1), (0, 1))', '"""constant"""'], {'constant_values': '(1.0)'}), "(kriging_mat, ((0, 1), (0, 1)), 'constant', constant_values=1.0)\n", (1259, 1323), False, 'import numpy\n'), ((1439, 1477), 'numpy.expand_dims', 'numpy.expand_dims', (['kriging_mat'], {'axis': '(0)'}), '(kriging_mat, axis=0)\n', (1456, 1477), False, 'import numpy\n'), ((1496, 1542), 'numpy.repeat', 'numpy.repeat', (['kriging_mat', 'channel_cnt'], {'axis': '(0)'}), '(kriging_mat, channel_cnt, axis=0)\n', (1508, 1542), False, 'import numpy\n'), ((1566, 1589), 'numpy.copy', 'numpy.copy', (['kriging_mat'], {}), '(kriging_mat)\n', (1576, 1589), False, 'import numpy\n'), ((1668, 1772), 'numpy.array', 'numpy.array', (['[1.2, 1.1, 1.3, 1.4, 1.6, 1.5, 1.7, 1.8, 1.9, 2.0, 2.1, 1.1, 1.4]'], {'dtype': 'numpy.float32'}), '([1.2, 1.1, 1.3, 1.4, 1.6, 1.5, 1.7, 1.8, 1.9, 2.0, 2.1, 1.1, \n 1.4], dtype=numpy.float32)\n', (1679, 1772), False, 'import numpy\n'), ((1776, 1804), 'numpy.expand_dims', 'numpy.expand_dims', (['b'], {'axis': '(0)'}), '(b, axis=0)\n', (1793, 1804), False, 'import numpy\n'), ((1813, 1841), 'numpy.expand_dims', 'numpy.expand_dims', (['b'], {'axis': '(2)'}), '(b, axis=2)\n', (1830, 1841), False, 'import numpy\n'), ((1850, 1886), 'numpy.repeat', 'numpy.repeat', (['b', 'channel_cnt'], {'axis': '(0)'}), '(b, channel_cnt, axis=0)\n', (1862, 1886), False, 'import numpy\n'), ((2008, 2019), 'time.time', 'time.time', ([], {}), '()\n', (2017, 2019), False, 'import time\n'), ((2028, 2062), 'numpy.linalg.solve', 'numpy.linalg.solve', (['kriging_mat', 'b'], {}), '(kriging_mat, b)\n', (2046, 2062), False, 'import numpy\n'), ((2078, 2089), 'time.time', 'time.time', ([], {}), '()\n', (2087, 2089), False, 'import time\n'), ((2196, 2222), 'numpy.float16', 'numpy.float16', (['kriging_mat'], {}), '(kriging_mat)\n', (2209, 2222), False, 'import numpy\n'), ((2231, 2247), 'numpy.float16', 'numpy.float16', (['b'], {}), '(b)\n', (2244, 2247), False, 'import numpy\n'), ((2418, 2436), 'tensorflow.python.ipu.config.IPUConfig', 'config.IPUConfig', ([], {}), '()\n', (2434, 2436), False, 'from tensorflow.python.ipu import ipu_compiler, scopes, config\n'), ((413, 438), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (428, 438), False, 'import os\n'), ((1348, 1375), 'numpy.diag', 'numpy.diag', (['kriging_mat_ext'], {}), '(kriging_mat_ext)\n', (1358, 1375), False, 'import numpy\n'), ((2555, 2571), 'tensorflow.device', 'tf.device', (['"""cpu"""'], {}), "('cpu')\n", (2564, 2571), True, 'import tensorflow as tf\n'), ((2587, 2655), 'tensorflow.compat.v1.placeholder', 'tf.compat.v1.placeholder', (['numpy.float16', 'kriging_mat.shape'], {'name': '"""A"""'}), "(numpy.float16, kriging_mat.shape, name='A')\n", (2611, 2655), True, 'import tensorflow as tf\n'), ((2671, 2729), 'tensorflow.compat.v1.placeholder', 'tf.compat.v1.placeholder', (['numpy.float16', 'b.shape'], {'name': '"""b"""'}), "(numpy.float16, b.shape, name='b')\n", (2695, 2729), True, 'import tensorflow as tf\n'), ((2740, 2773), 'tensorflow.python.ipu.scopes.ipu_scope', 'scopes.ipu_scope', (['"""/device:IPU:0"""'], {}), "('/device:IPU:0')\n", (2756, 2773), False, 'from tensorflow.python.ipu import ipu_compiler, scopes, config\n'), ((2801, 2853), 'tensorflow.python.ipu.ipu_compiler.compile', 'ipu_compiler.compile', (['matrix_solve_graph', '[p_A, p_b]'], {}), '(matrix_solve_graph, [p_A, p_b])\n', (2821, 2853), False, 'from tensorflow.python.ipu import ipu_compiler, scopes, config\n'), ((2864, 2886), 'tensorflow.compat.v1.Session', 'tf.compat.v1.Session', ([], {}), '()\n', (2884, 2886), True, 'import tensorflow as tf\n'), ((3052, 3063), 'time.time', 'time.time', ([], {}), '()\n', (3061, 3063), False, 'import time\n'), ((3231, 3242), 'time.time', 'time.time', ([], {}), '()\n', (3240, 3242), False, 'import time\n'), ((3338, 3369), 'numpy.abs', 'numpy.abs', (['(mat_solve_res[0] - x)'], {}), '(mat_solve_res[0] - x)\n', (3347, 3369), False, 'import numpy\n'), ((3389, 3408), 'numpy.max', 'numpy.max', (['cmp_diff'], {}), '(cmp_diff)\n', (3398, 3408), False, 'import numpy\n'), ((3428, 3447), 'numpy.min', 'numpy.min', (['cmp_diff'], {}), '(cmp_diff)\n', (3437, 3447), False, 'import numpy\n'), ((3467, 3490), 'numpy.average', 'numpy.average', (['cmp_diff'], {}), '(cmp_diff)\n', (3480, 3490), False, 'import numpy\n'), ((1131, 1147), 'numpy.square', 'numpy.square', (['dx'], {}), '(dx)\n', (1143, 1147), False, 'import numpy\n'), ((1150, 1166), 'numpy.square', 'numpy.square', (['dy'], {}), '(dy)\n', (1162, 1166), False, 'import numpy\n')]
from keras.utils import np_utils import numpy as np import math import matplotlib.pyplot as plt class ChunkTest: def __init__(self, time_delay): self.chunk= 0 self.output_size = 10 self.counter = -1 self.time_delay = time_delay self.time_counter = time_delay self.output_class= 0 self.previous_output_class= None self.sequenceA_length = 4 self.sequenceB_length = 4 #np.random.randint(2)+5 def trueLabel(self): ''' TODO ''' return None def getOutputSize(self): return self.output_size def updateTimeDelay(self): self.time_counter+= 1 if self.time_counter > self.time_delay: self.time_counter = 0 return True else: return False #create an input pattern for the system def getInput(self, reset = False): if reset == True: self.chunk=0 self.counter=-1 update = self.updateTimeDelay() if update == True: if self.chunk == 0: if self.counter > self.sequenceA_length: self.chunk = 1 self.counter= 0 else: self.counter+= 1 else: if self.counter > self.sequenceB_length: #self.sequenceB_length = np.random.randint(20)+5 self.chunk = 0 self.counter= 0 else: self.counter+= 1 if self.chunk == 0: #input_value = np.random.randint(10) #input_value= self.counter self.previous_output_class= self.output_class #possible output: 0,1,2,3 self.output_class = np.random.randint(4) else: self.previous_output_class= self.output_class #possible output: 5,6,7,8 self.output_class = 5+np.random.randint(4) noise_intensity= 0 if self.previous_output_class is None or self.previous_output_class == self.output_class: input_value = np_utils.to_categorical(self.output_class, self.output_size)*np.exp(-0.1*self.time_counter) + np.random.randn(self.output_size)*noise_intensity else: input_value = np_utils.to_categorical(self.output_class, self.output_size)*np.exp(-0.1*self.time_counter) + np.random.randn(self.output_size)*noise_intensity + np_utils.to_categorical(self.previous_output_class, self.output_size)*np.exp(-0.1*(self.time_counter+self.time_delay)) #input_value = np_utils.to_categorical(input_value, 10) + np.random.rand(10)*0.2 return input_value def getSequence(self, iterations): input_class = np.empty(iterations) input_sequence = np.empty((iterations, self.output_size)) for i in range(iterations): input_value = self.getInput() #input_class.append(self.chunk) #input_sequence.append(input_value) input_class[i] = self.chunk input_sequence[i] = input_value return input_sequence, input_class def plot(self, input_class, input_sequence = None, save = False): a = np.asarray(input_class) t = [i for i,value in enumerate(a)] plt.plot(t, a) if input_sequence != None: sequence = [np.argmax(x) for x in input_sequence] plt.plot(t, sequence) if save == True: plt.savefig("plot.png") plt.show() plt.close() def plotSuperposed(self, input_class, input_sequence = None, save = False): input_sequence= np.asarray(input_sequence) t = [i for i,value in enumerate(input_sequence)] print(input_sequence.shape) #exit() for i in range(input_sequence.shape[1]): a = input_sequence[:,i] plt.plot(t, a) a = np.asarray(input_class) plt.plot(t, a) if save == True: plt.savefig("plot.png") plt.show() plt.close()
[ "matplotlib.pyplot.savefig", "matplotlib.pyplot.plot", "numpy.asarray", "numpy.argmax", "matplotlib.pyplot.close", "numpy.exp", "numpy.random.randint", "keras.utils.np_utils.to_categorical", "numpy.empty", "numpy.random.randn", "matplotlib.pyplot.show" ]
[((2282, 2302), 'numpy.empty', 'np.empty', (['iterations'], {}), '(iterations)\n', (2290, 2302), True, 'import numpy as np\n'), ((2322, 2362), 'numpy.empty', 'np.empty', (['(iterations, self.output_size)'], {}), '((iterations, self.output_size))\n', (2330, 2362), True, 'import numpy as np\n'), ((2686, 2709), 'numpy.asarray', 'np.asarray', (['input_class'], {}), '(input_class)\n', (2696, 2709), True, 'import numpy as np\n'), ((2751, 2765), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'a'], {}), '(t, a)\n', (2759, 2765), True, 'import matplotlib.pyplot as plt\n'), ((2928, 2938), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2936, 2938), True, 'import matplotlib.pyplot as plt\n'), ((2941, 2952), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (2950, 2952), True, 'import matplotlib.pyplot as plt\n'), ((3052, 3078), 'numpy.asarray', 'np.asarray', (['input_sequence'], {}), '(input_sequence)\n', (3062, 3078), True, 'import numpy as np\n'), ((3273, 3296), 'numpy.asarray', 'np.asarray', (['input_class'], {}), '(input_class)\n', (3283, 3296), True, 'import numpy as np\n'), ((3299, 3313), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'a'], {}), '(t, a)\n', (3307, 3313), True, 'import matplotlib.pyplot as plt\n'), ((3366, 3376), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3374, 3376), True, 'import matplotlib.pyplot as plt\n'), ((3379, 3390), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (3388, 3390), True, 'import matplotlib.pyplot as plt\n'), ((2854, 2875), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'sequence'], {}), '(t, sequence)\n', (2862, 2875), True, 'import matplotlib.pyplot as plt\n'), ((2899, 2922), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""plot.png"""'], {}), "('plot.png')\n", (2910, 2922), True, 'import matplotlib.pyplot as plt\n'), ((3249, 3263), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'a'], {}), '(t, a)\n', (3257, 3263), True, 'import matplotlib.pyplot as plt\n'), ((3337, 3360), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""plot.png"""'], {}), "('plot.png')\n", (3348, 3360), True, 'import matplotlib.pyplot as plt\n'), ((1399, 1419), 'numpy.random.randint', 'np.random.randint', (['(4)'], {}), '(4)\n', (1416, 1419), True, 'import numpy as np\n'), ((2813, 2825), 'numpy.argmax', 'np.argmax', (['x'], {}), '(x)\n', (2822, 2825), True, 'import numpy as np\n'), ((1535, 1555), 'numpy.random.randint', 'np.random.randint', (['(4)'], {}), '(4)\n', (1552, 1555), True, 'import numpy as np\n'), ((1687, 1747), 'keras.utils.np_utils.to_categorical', 'np_utils.to_categorical', (['self.output_class', 'self.output_size'], {}), '(self.output_class, self.output_size)\n', (1710, 1747), False, 'from keras.utils import np_utils\n'), ((1748, 1780), 'numpy.exp', 'np.exp', (['(-0.1 * self.time_counter)'], {}), '(-0.1 * self.time_counter)\n', (1754, 1780), True, 'import numpy as np\n'), ((1781, 1814), 'numpy.random.randn', 'np.random.randn', (['self.output_size'], {}), '(self.output_size)\n', (1796, 1814), True, 'import numpy as np\n'), ((2002, 2071), 'keras.utils.np_utils.to_categorical', 'np_utils.to_categorical', (['self.previous_output_class', 'self.output_size'], {}), '(self.previous_output_class, self.output_size)\n', (2025, 2071), False, 'from keras.utils import np_utils\n'), ((2072, 2124), 'numpy.exp', 'np.exp', (['(-0.1 * (self.time_counter + self.time_delay))'], {}), '(-0.1 * (self.time_counter + self.time_delay))\n', (2078, 2124), True, 'import numpy as np\n'), ((1856, 1916), 'keras.utils.np_utils.to_categorical', 'np_utils.to_categorical', (['self.output_class', 'self.output_size'], {}), '(self.output_class, self.output_size)\n', (1879, 1916), False, 'from keras.utils import np_utils\n'), ((1917, 1949), 'numpy.exp', 'np.exp', (['(-0.1 * self.time_counter)'], {}), '(-0.1 * self.time_counter)\n', (1923, 1949), True, 'import numpy as np\n'), ((1950, 1983), 'numpy.random.randn', 'np.random.randn', (['self.output_size'], {}), '(self.output_size)\n', (1965, 1983), True, 'import numpy as np\n')]
import numpy as np import librosa import json import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import sys sys.path.append('vggish/') from math import pi import pandas as pd from tqdm import tqdm from sklearn.preprocessing import OneHotEncoder import pickle import xgboost as xgb from scipy.fftpack import fft, hilbert import warnings warnings.filterwarnings("ignore") import tensorflow.compat.v1 as tf tf.disable_v2_behavior() SR = 22050 # sample rate FRAME_LEN = int(SR / 10) # 100 ms HOP = int(FRAME_LEN / 2) # 50% overlap, meaning 5ms hop length MFCC_dim = 13 # the MFCC dimension SR_VGG = 16000 # VGG pretrained model sample rate checkpoint_path = "vggish/vggish_model.ckpt" def sta_fun(np_data): """Extract various statistical features from the numpy array provided as input. :param np_data: the numpy array to extract the features from :type np_data: numpy.ndarray :return: The extracted features as a vector :rtype: numpy.ndarray """ # perform a sanity check if np_data is None: raise ValueError("Input array cannot be None") # perform the feature extraction dat_min = np.min(np_data) dat_max = np.max(np_data) dat_mean = np.mean(np_data) dat_rms = np.sqrt(np.sum(np.square(np_data)) / len(np_data)) dat_median = np.median(np_data) dat_qrl1 = np.percentile(np_data, 25) dat_qrl3 = np.percentile(np_data, 75) dat_lower_q = np.quantile(np_data, 0.25, interpolation="lower") dat_higher_q = np.quantile(np_data, 0.75, interpolation="higher") dat_iqrl = dat_higher_q - dat_lower_q dat_std = np.std(np_data) s = pd.Series(np_data) dat_skew = s.skew() dat_kurt = s.kurt() # finally return the features in a concatenated array (as a vector) return np.array([dat_mean, dat_min, dat_max, dat_std, dat_rms, dat_median, dat_qrl1, dat_qrl3, dat_iqrl, dat_skew, dat_kurt]) def sta_fun_2(npdata): # 1D np array """Extract various statistical features from the VGG output. :param np_data: the numpy array to extract the features from :type np_data: numpy.ndarray :return: The extracted features as a vector :rtype: numpy.ndarray """ # perform a sanity check if npdata is None: raise ValueError("Input array cannot be None") # perform the feature extraction Mean = np.mean(npdata, axis=0) Std = np.std(npdata, axis=0) # finally return the features in a concatenated array (as a vector) return np.concatenate((Mean, Std), axis=0).reshape(1, -1) def get_period(signal, signal_sr): """Extract the period from the the provided signal :param signal: the signal to extract the period from :type signal: numpy.ndarray :param signal_sr: the sampling rate of the input signal :type signal_sr: integer :return: a vector containing the signal period :rtype: numpy.ndarray """ # perform a sanity check if signal is None: raise ValueError("Input signal cannot be None") # transform the signal to the hilbert space hy = hilbert(signal) ey = np.sqrt(signal ** 2 + hy ** 2) min_time = 1.0 / signal_sr tot_time = len(ey) * min_time pow_ft = np.abs(fft(ey)) peak_freq = pow_ft[3: int(len(pow_ft) / 2)] peak_freq_pos = peak_freq.argmax() peak_freq_val = 2 * pi * (peak_freq_pos + 2) / tot_time period = 2 * pi / peak_freq_val return np.array([period]) def extract_signal_features(signal, signal_sr): """Extract part of handcrafted features from the input signal. :param signal: the signal the extract features from :type signal: numpy.ndarray :param signal_sr: the sample rate of the signal :type signal_sr: integer :return: the populated feature vector :rtype: numpy.ndarray """ # normalise the sound signal before processing signal = signal / np.max(np.abs(signal)) signal = np.nan_to_num(signal) # trim the signal to the appropriate length trimmed_signal, idc = librosa.effects.trim(signal, frame_length=FRAME_LEN, hop_length=HOP) # extract the signal duration signal_duration = librosa.get_duration(y=trimmed_signal, sr=signal_sr) # use librosa to track the beats tempo, beats = librosa.beat.beat_track(y=trimmed_signal, sr=signal_sr) # find the onset strength of the trimmed signal o_env = librosa.onset.onset_strength(trimmed_signal, sr=signal_sr) # find the frames of the onset onset_frames = librosa.onset.onset_detect(onset_envelope=o_env, sr=signal_sr) # keep only the first onset frame onsets = onset_frames.shape[0] # decompose the signal into its magnitude and the phase components such that signal = mag * phase mag, phase = librosa.magphase(librosa.stft(trimmed_signal, n_fft=FRAME_LEN, hop_length=HOP)) # extract the rms from the magnitude component rms = librosa.feature.rms(y=trimmed_signal)[0] # extract the spectral centroid of the magnitude cent = librosa.feature.spectral_centroid(S=mag)[0] # extract the spectral rolloff point from the magnitude rolloff = librosa.feature.spectral_rolloff(S=mag, sr=signal_sr)[0] # extract the zero crossing rate from the trimmed signal using the predefined frame and hop lengths zcr = librosa.feature.zero_crossing_rate(trimmed_signal, frame_length=FRAME_LEN, hop_length=HOP)[0] # pack the extracted features into the feature vector to be returned signal_features = np.concatenate( ( np.array([signal_duration, tempo, onsets]), get_period(signal, signal_sr=signal_sr), sta_fun(rms), sta_fun(cent), sta_fun(rolloff), sta_fun(zcr), ), axis=0, ) # finally, return the gathered features and the trimmed signal return signal_features, trimmed_signal def extract_mfcc(signal, signal_sr=SR, n_fft=FRAME_LEN, hop_length=HOP, n_mfcc=MFCC_dim): """Extracts the Mel-frequency cepstral coefficients (MFCC) from the provided signal :param signal: the signal to extract the mfcc from :type signal: numpy.ndarray :param signal_sr: the signal sample rate :type signal_sr: integer :param n_fft: the fft window size :type n_fft: integer :param hop_length: the hop length :type hop_length: integer :param n_mfcc: the dimension of the mfcc :type n_mfcc: integer :return: the populated feature vector :rtype: numpy.ndarray """ # compute the mfcc of the input signal mfcc = librosa.feature.mfcc( y=signal, sr=signal_sr, n_fft=n_fft, hop_length=hop_length, n_mfcc=n_mfcc, dct_type=3 ) # extract the first and second order deltas from the retrieved mfcc's mfcc_delta = librosa.feature.delta(mfcc, order=1, mode='nearest') mfcc_delta2 = librosa.feature.delta(mfcc, order=2, mode='nearest') # create the mfcc array mfccs = [] # populate it using the extracted features for i in range(n_mfcc): mfccs.extend(sta_fun(mfcc[i, :])) for i in range(n_mfcc): mfccs.extend(sta_fun(mfcc_delta[i, :])) for i in range(n_mfcc): mfccs.extend(sta_fun(mfcc_delta2[i, :])) # finally return the coefficients return mfccs def extract_features_hc(signal, signal_sr): """Extract hancrafted features from the input signal. :param signal: the signal the extract features from :type signal: numpy.ndarray :param signal_sr: the sample rate of the signal :type signal_sr: integer :return: the extracted feature vector :rtype: numpy.ndarray """ # extract the signal features signal_features, trimmed_signal = extract_signal_features(signal, signal_sr) # extract the mfcc's from the trimmed signal and get the statistical feature. mfccs = extract_mfcc(trimmed_signal) return np.concatenate((signal_features, mfccs), axis=0) def extract_sound_features(metadata, audio_dataset_path): """Extract all sound features (handcrafted + VGG) from the input signal :param metadata: the metadata dataframe with audio links :type metadata: pandas dataframe :param audio_dataset_path: path to the audio folder :type audio_dataset_path: string :return: the extracted feature vector :rtype: numpy.ndarray """ import vggish_input import vggish_params import vggish_slim with tf.Graph().as_default(), tf.Session() as sess: # load pre-trained vggish model vggish_slim.define_vggish_slim() vggish_slim.load_vggish_slim_checkpoint(sess, checkpoint_path) features_tensor = sess.graph.get_tensor_by_name(vggish_params.INPUT_TENSOR_NAME) embedding_tensor = sess.graph.get_tensor_by_name( vggish_params.OUTPUT_TENSOR_NAME ) sound_features = [] # loop through the dataset using information from the metadata file for index_num, row in tqdm(metadata.iterrows()): # get the file path file_name = os.path.join(os.path.abspath(audio_dataset_path),str(row['file_path'])) # extract basic sound data audio, sample_rate = librosa.load(file_name, sr=SR, mono=True, offset=0.0, duration=None) # extract vgg features yt, index = librosa.effects.trim(audio, frame_length=FRAME_LEN, hop_length=HOP) input_batch = vggish_input.waveform_to_examples(yt, SR_VGG) [features_vgg] = sess.run( [embedding_tensor], feed_dict={features_tensor: input_batch} ) features_vgg = sta_fun_2(features_vgg) features_vgg = features_vgg.reshape(features_vgg.shape[-1],) # extract hc features audio, sample_rate = librosa.load(file_name, res_type='kaiser_fast') features_hc = extract_features_hc(audio, sample_rate) # concat features features = np.concatenate((features_hc, features_vgg), axis=0) sound_features.append(features) return sound_features def extract_metadata_features(metadata, encoder_path): """Extract all metadata features :param metadata: the metadata dataframe with audio links :type metadata: pandas dataframe :param encoder_path: path to the saved one hot encoder :type encoder_path: string :return: the extracted feature vector :rtype: numpy.ndarray """ # process age column mean_age = metadata['subject_age'].mean() metadata['subject_age'] = metadata['subject_age'].fillna(mean_age) # process gender column with open(encoder_path, 'rb') as f: encoder = pickle.load(f) x_gender = encoder.transform(np.array(metadata['subject_gender']).reshape(-1, 1)).toarray() x_gender = np.delete(x_gender, -1, 1) metadata_features = np.concatenate([x_gender, np.array(metadata['subject_age']).reshape(-1,1)], axis=1) return metadata_features
[ "tensorflow.compat.v1.disable_v2_behavior", "numpy.sqrt", "librosa.feature.zero_crossing_rate", "librosa.feature.mfcc", "numpy.array", "scipy.fftpack.fft", "scipy.fftpack.hilbert", "librosa.effects.trim", "sys.path.append", "librosa.feature.rms", "librosa.feature.spectral_centroid", "tensorflo...
[((111, 137), 'sys.path.append', 'sys.path.append', (['"""vggish/"""'], {}), "('vggish/')\n", (126, 137), False, 'import sys\n'), ((341, 374), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (364, 374), False, 'import warnings\n'), ((410, 434), 'tensorflow.compat.v1.disable_v2_behavior', 'tf.disable_v2_behavior', ([], {}), '()\n', (432, 434), True, 'import tensorflow.compat.v1 as tf\n'), ((1143, 1158), 'numpy.min', 'np.min', (['np_data'], {}), '(np_data)\n', (1149, 1158), True, 'import numpy as np\n'), ((1173, 1188), 'numpy.max', 'np.max', (['np_data'], {}), '(np_data)\n', (1179, 1188), True, 'import numpy as np\n'), ((1204, 1220), 'numpy.mean', 'np.mean', (['np_data'], {}), '(np_data)\n', (1211, 1220), True, 'import numpy as np\n'), ((1303, 1321), 'numpy.median', 'np.median', (['np_data'], {}), '(np_data)\n', (1312, 1321), True, 'import numpy as np\n'), ((1337, 1363), 'numpy.percentile', 'np.percentile', (['np_data', '(25)'], {}), '(np_data, 25)\n', (1350, 1363), True, 'import numpy as np\n'), ((1379, 1405), 'numpy.percentile', 'np.percentile', (['np_data', '(75)'], {}), '(np_data, 75)\n', (1392, 1405), True, 'import numpy as np\n'), ((1424, 1473), 'numpy.quantile', 'np.quantile', (['np_data', '(0.25)'], {'interpolation': '"""lower"""'}), "(np_data, 0.25, interpolation='lower')\n", (1435, 1473), True, 'import numpy as np\n'), ((1493, 1543), 'numpy.quantile', 'np.quantile', (['np_data', '(0.75)'], {'interpolation': '"""higher"""'}), "(np_data, 0.75, interpolation='higher')\n", (1504, 1543), True, 'import numpy as np\n'), ((1600, 1615), 'numpy.std', 'np.std', (['np_data'], {}), '(np_data)\n', (1606, 1615), True, 'import numpy as np\n'), ((1624, 1642), 'pandas.Series', 'pd.Series', (['np_data'], {}), '(np_data)\n', (1633, 1642), True, 'import pandas as pd\n'), ((1775, 1897), 'numpy.array', 'np.array', (['[dat_mean, dat_min, dat_max, dat_std, dat_rms, dat_median, dat_qrl1,\n dat_qrl3, dat_iqrl, dat_skew, dat_kurt]'], {}), '([dat_mean, dat_min, dat_max, dat_std, dat_rms, dat_median,\n dat_qrl1, dat_qrl3, dat_iqrl, dat_skew, dat_kurt])\n', (1783, 1897), True, 'import numpy as np\n'), ((2362, 2385), 'numpy.mean', 'np.mean', (['npdata'], {'axis': '(0)'}), '(npdata, axis=0)\n', (2369, 2385), True, 'import numpy as np\n'), ((2396, 2418), 'numpy.std', 'np.std', (['npdata'], {'axis': '(0)'}), '(npdata, axis=0)\n', (2402, 2418), True, 'import numpy as np\n'), ((3081, 3096), 'scipy.fftpack.hilbert', 'hilbert', (['signal'], {}), '(signal)\n', (3088, 3096), False, 'from scipy.fftpack import fft, hilbert\n'), ((3107, 3137), 'numpy.sqrt', 'np.sqrt', (['(signal ** 2 + hy ** 2)'], {}), '(signal ** 2 + hy ** 2)\n', (3114, 3137), True, 'import numpy as np\n'), ((3427, 3445), 'numpy.array', 'np.array', (['[period]'], {}), '([period])\n', (3435, 3445), True, 'import numpy as np\n'), ((3918, 3939), 'numpy.nan_to_num', 'np.nan_to_num', (['signal'], {}), '(signal)\n', (3931, 3939), True, 'import numpy as np\n'), ((4014, 4082), 'librosa.effects.trim', 'librosa.effects.trim', (['signal'], {'frame_length': 'FRAME_LEN', 'hop_length': 'HOP'}), '(signal, frame_length=FRAME_LEN, hop_length=HOP)\n', (4034, 4082), False, 'import librosa\n'), ((4139, 4191), 'librosa.get_duration', 'librosa.get_duration', ([], {'y': 'trimmed_signal', 'sr': 'signal_sr'}), '(y=trimmed_signal, sr=signal_sr)\n', (4159, 4191), False, 'import librosa\n'), ((4248, 4303), 'librosa.beat.beat_track', 'librosa.beat.beat_track', ([], {'y': 'trimmed_signal', 'sr': 'signal_sr'}), '(y=trimmed_signal, sr=signal_sr)\n', (4271, 4303), False, 'import librosa\n'), ((4368, 4426), 'librosa.onset.onset_strength', 'librosa.onset.onset_strength', (['trimmed_signal'], {'sr': 'signal_sr'}), '(trimmed_signal, sr=signal_sr)\n', (4396, 4426), False, 'import librosa\n'), ((4481, 4543), 'librosa.onset.onset_detect', 'librosa.onset.onset_detect', ([], {'onset_envelope': 'o_env', 'sr': 'signal_sr'}), '(onset_envelope=o_env, sr=signal_sr)\n', (4507, 4543), False, 'import librosa\n'), ((6522, 6634), 'librosa.feature.mfcc', 'librosa.feature.mfcc', ([], {'y': 'signal', 'sr': 'signal_sr', 'n_fft': 'n_fft', 'hop_length': 'hop_length', 'n_mfcc': 'n_mfcc', 'dct_type': '(3)'}), '(y=signal, sr=signal_sr, n_fft=n_fft, hop_length=\n hop_length, n_mfcc=n_mfcc, dct_type=3)\n', (6542, 6634), False, 'import librosa\n'), ((6736, 6788), 'librosa.feature.delta', 'librosa.feature.delta', (['mfcc'], {'order': '(1)', 'mode': '"""nearest"""'}), "(mfcc, order=1, mode='nearest')\n", (6757, 6788), False, 'import librosa\n'), ((6807, 6859), 'librosa.feature.delta', 'librosa.feature.delta', (['mfcc'], {'order': '(2)', 'mode': '"""nearest"""'}), "(mfcc, order=2, mode='nearest')\n", (6828, 6859), False, 'import librosa\n'), ((7836, 7884), 'numpy.concatenate', 'np.concatenate', (['(signal_features, mfccs)'], {'axis': '(0)'}), '((signal_features, mfccs), axis=0)\n', (7850, 7884), True, 'import numpy as np\n'), ((10764, 10790), 'numpy.delete', 'np.delete', (['x_gender', '(-1)', '(1)'], {}), '(x_gender, -1, 1)\n', (10773, 10790), True, 'import numpy as np\n'), ((3223, 3230), 'scipy.fftpack.fft', 'fft', (['ey'], {}), '(ey)\n', (3226, 3230), False, 'from scipy.fftpack import fft, hilbert\n'), ((4753, 4814), 'librosa.stft', 'librosa.stft', (['trimmed_signal'], {'n_fft': 'FRAME_LEN', 'hop_length': 'HOP'}), '(trimmed_signal, n_fft=FRAME_LEN, hop_length=HOP)\n', (4765, 4814), False, 'import librosa\n'), ((4877, 4914), 'librosa.feature.rms', 'librosa.feature.rms', ([], {'y': 'trimmed_signal'}), '(y=trimmed_signal)\n', (4896, 4914), False, 'import librosa\n'), ((4982, 5022), 'librosa.feature.spectral_centroid', 'librosa.feature.spectral_centroid', ([], {'S': 'mag'}), '(S=mag)\n', (5015, 5022), False, 'import librosa\n'), ((5100, 5153), 'librosa.feature.spectral_rolloff', 'librosa.feature.spectral_rolloff', ([], {'S': 'mag', 'sr': 'signal_sr'}), '(S=mag, sr=signal_sr)\n', (5132, 5153), False, 'import librosa\n'), ((5271, 5365), 'librosa.feature.zero_crossing_rate', 'librosa.feature.zero_crossing_rate', (['trimmed_signal'], {'frame_length': 'FRAME_LEN', 'hop_length': 'HOP'}), '(trimmed_signal, frame_length=FRAME_LEN,\n hop_length=HOP)\n', (5305, 5365), False, 'import librosa\n'), ((8397, 8409), 'tensorflow.compat.v1.Session', 'tf.Session', ([], {}), '()\n', (8407, 8409), True, 'import tensorflow.compat.v1 as tf\n'), ((8467, 8499), 'vggish_slim.define_vggish_slim', 'vggish_slim.define_vggish_slim', ([], {}), '()\n', (8497, 8499), False, 'import vggish_slim\n'), ((8508, 8570), 'vggish_slim.load_vggish_slim_checkpoint', 'vggish_slim.load_vggish_slim_checkpoint', (['sess', 'checkpoint_path'], {}), '(sess, checkpoint_path)\n', (8547, 8570), False, 'import vggish_slim\n'), ((10638, 10652), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (10649, 10652), False, 'import pickle\n'), ((2507, 2542), 'numpy.concatenate', 'np.concatenate', (['(Mean, Std)'], {'axis': '(0)'}), '((Mean, Std), axis=0)\n', (2521, 2542), True, 'import numpy as np\n'), ((3889, 3903), 'numpy.abs', 'np.abs', (['signal'], {}), '(signal)\n', (3895, 3903), True, 'import numpy as np\n'), ((5499, 5541), 'numpy.array', 'np.array', (['[signal_duration, tempo, onsets]'], {}), '([signal_duration, tempo, onsets])\n', (5507, 5541), True, 'import numpy as np\n'), ((9157, 9225), 'librosa.load', 'librosa.load', (['file_name'], {'sr': 'SR', 'mono': '(True)', 'offset': '(0.0)', 'duration': 'None'}), '(file_name, sr=SR, mono=True, offset=0.0, duration=None)\n', (9169, 9225), False, 'import librosa\n'), ((9286, 9353), 'librosa.effects.trim', 'librosa.effects.trim', (['audio'], {'frame_length': 'FRAME_LEN', 'hop_length': 'HOP'}), '(audio, frame_length=FRAME_LEN, hop_length=HOP)\n', (9306, 9353), False, 'import librosa\n'), ((9380, 9425), 'vggish_input.waveform_to_examples', 'vggish_input.waveform_to_examples', (['yt', 'SR_VGG'], {}), '(yt, SR_VGG)\n', (9413, 9425), False, 'import vggish_input\n'), ((9749, 9796), 'librosa.load', 'librosa.load', (['file_name'], {'res_type': '"""kaiser_fast"""'}), "(file_name, res_type='kaiser_fast')\n", (9761, 9796), False, 'import librosa\n'), ((9917, 9968), 'numpy.concatenate', 'np.concatenate', (['(features_hc, features_vgg)'], {'axis': '(0)'}), '((features_hc, features_vgg), axis=0)\n', (9931, 9968), True, 'import numpy as np\n'), ((1250, 1268), 'numpy.square', 'np.square', (['np_data'], {}), '(np_data)\n', (1259, 1268), True, 'import numpy as np\n'), ((8372, 8382), 'tensorflow.compat.v1.Graph', 'tf.Graph', ([], {}), '()\n', (8380, 8382), True, 'import tensorflow.compat.v1 as tf\n'), ((9013, 9048), 'os.path.abspath', 'os.path.abspath', (['audio_dataset_path'], {}), '(audio_dataset_path)\n', (9028, 9048), False, 'import os\n'), ((10845, 10878), 'numpy.array', 'np.array', (["metadata['subject_age']"], {}), "(metadata['subject_age'])\n", (10853, 10878), True, 'import numpy as np\n'), ((10686, 10722), 'numpy.array', 'np.array', (["metadata['subject_gender']"], {}), "(metadata['subject_gender'])\n", (10694, 10722), True, 'import numpy as np\n')]
from __future__ import absolute_import from __future__ import print_function import os import glob import numpy as np from scipy.interpolate import UnivariateSpline from .core import file_finder, load_probe, load_fs, load_clusters, load_spikes from .core import find_info, find_kwd, find_kwik, find_kwx import h5py as h5 import json from six.moves import range @file_finder def find_mean_waveforms(block_path, cluster, cluster_store=0, clustering='main'): ''' Returns the mean waveform file for a given cluster found in the block path Parameters ------ block_path : str path to the block cluster : int the cluster identifier cluster_store : int the cluster store identifier clustering : str, optional ID of clustering Returns ------ mean_waveforms_file : full path name to mean_waveforms file ''' return os.path.join(block_path, '*.phy', 'cluster_store', str(cluster_store), clustering, '{}.mean_waveforms'.format(cluster) ) @file_finder def find_mean_masks(block_path, cluster, cluster_store=0, clustering='main'): ''' Returns the mean masks file for a given cluster found in the block path Parameters ------ block_path : str path to the block cluster : int the cluster identifier cluster_store : int the cluster store identifier clustering : str, optional ID of clustering Returns ------ mean_masks_file : full path name to mean_waveforms file ''' return os.path.join(block_path, '*.phy', 'cluster_store', str(cluster_store), clustering, '{}.mean_masks'.format(cluster) ) def mean_masks_w(block_path, cluster): ''' Weights are equivalent to the mean_mask values for the channel. Parameters ------ block_path : str the path to the block cluster : int the cluster identifier Returns ------ w : weight vector ''' mean_masks = find_mean_masks(block_path, cluster) mean_masks_arr = np.fromfile(mean_masks, dtype=np.float32) return mean_masks_arr def max_masks_w(block_path, cluster): ''' Places all weight on the channel(s) which have the largest mean mask values. If more than one channel have a mean_mask value equal to the max, these channels will be weighted equally. Parameters ------ block_path : str the path to the block cluster : int the cluster identifier Returns ------ w : weight vector ''' w = mean_masks_w(block_path, cluster) return w == w.max() def get_cluster_coords(block_path, cluster, weight_func=None): ''' Returns the location of a given cluster on the probe in x,y coordinates in whatever units and reference the probe file uses. Parameters ------ block_path : str the path to the block cluster : int the cluster identifier weight_func : function function which takes `block_path` and `cluster` as args and returns a weight vector for the coordinates. default: max_masks_w Returns ------ xy : numpy array of coordinates ''' if weight_func is None: weight_func = max_masks_w w = weight_func(block_path, cluster) prb_info = load_probe(block_path) channels = prb_info.channel_groups[0]['channels'] geometry = prb_info.channel_groups[0]['geometry'] coords = np.array([geometry[ch] for ch in channels]) return np.dot(w, coords) / w.sum() # spike shapes def upsample_spike(spike_shape, fs, new_fs=1000000.0): ''' upsamples a spike shape to prepare it for computing the spike width Parameters ------ spike_shape : numpy array the spike shape fs : float the sampling rate of the spike shape new_fs : float sampling rate to upsample to (default=200Hz) Returns ------ time : numpy array array of sample times in seconds new_spike_shape : upsampled spike shape ''' t_max = spike_shape.shape[0] / fs t = np.arange(0, t_max, 1 / fs)[:spike_shape.shape[0]] spl = UnivariateSpline(t, spike_shape) ts = np.arange(0, t_max, 1 / new_fs) return ts, spl(ts) def get_troughpeak(time, spike_shape): ''' Grabs the time of the trough and peak Parameters ------ time : numpy array time series of spike data spike_shape : numpy array the spike shape Returns ------ trough_time : float time of trough in seconds peak_time : float time of peak in seconds ''' trough_i = spike_shape.argmin() peak_i = spike_shape[trough_i:].argmax() + trough_i return time[trough_i], time[peak_i] def get_width_half_height(time,spike_shape): ''' grabs the time between the zero crossings around trough after normalize to min height and offset by 0.5 Parameters ------ time : numpy array spike_shape : numpy array %should be up-sampled to at least 100000 before calculating Returns ------ width_half_height : float time between crossings in seconds ''' width = np.nan; trough,peak = get_troughpeak(time,spike_shape) ind = np.where(time == trough) troughind = ind[0][0] spike_shape /= -spike_shape.min() spike_shape = spike_shape + 0.5 zero_crossings = np.where(np.diff(np.sign(spike_shape)))[0] i = zero_crossings < troughind j = zero_crossings > troughind if (True in i) & (True in j): # zero crossings before trough i = (np.where(i)) pre_ind = zero_crossings[max(i[0])] # zero crossings after trough j = (np.where(j)) post_ind = zero_crossings[min(j[0])] width = time[post_ind] - time[pre_ind] return width def get_width(block_path, cluster, new_fs=1000000.0): ''' grabs the time of the trough and peak Parameters ------ block_path : str the path to the block cluster : int the cluster identifier new_fs : float sampling rate to upsample to (default=200Hz) Returns ------ width : float the width of the spike in seconds ''' fs = load_fs(block_path) exemplar = get_spike_exemplar(block_path, cluster) trough, peak = get_troughpeak(*upsample_spike(exemplar, fs, new_fs=new_fs)) return peak - trough def get_mean_waveform_array(block_path, cluster): ''' returns the mean spike shape on all channels Parameters ------ block_path : str the path to the block cluster : int the cluster identifier Returns ------ mean_waveform_array : numpy array mean waveform on principal channel. shape: (time_samples,channels) ''' prb_info = load_probe(block_path) mean_waveform = find_mean_waveforms(block_path, cluster) shape = (-1, len(prb_info.channel_groups[0]['channels'])) return np.fromfile(mean_waveform, dtype=np.float32).reshape(shape) def get_spike_exemplar(block_path, cluster): ''' Returns an exemplar of the spike shape on the principal channel Parameters ------ block_path : str the path to the block cluster : int the cluster identifier Returns ------ exemplar : numpy array mean waveform on principal channel ''' mean_waveform = find_mean_waveforms(block_path, cluster) arr = get_mean_waveform_array(block_path, cluster) mean_masks = find_mean_masks(block_path, cluster) mean_masks_arr = np.fromfile(mean_masks, dtype=np.float32) return arr[:, mean_masks_arr.argmax()] def get_wide_narrow(block_path, cluster_list, thresh): ''' Return lists of clusters Parameters ------ block_path : str the path to the block cluster_list : array a list of cluster identifiers thresh : float minimum duration of spike to be considered wide Returns ------ wide : list of clusters with width greater than the threshold narrow : list of clusters with width less than the threshold ''' wide = [] narrow = [] for cluster in cluster_list: sw = get_width(block_path, cluster) if sw >= thresh: wide.append(cluster) else: narrow.append(cluster) return (wide, narrow) def make_phy_folder(block_path): ''' Create a directory for phy clusters Parameters ------ block_path : str the path to the block Returns ------ phy folder: string path to phy directory ''' kwikf = find_kwik(block_path) kwikfname = os.path.split(kwikf)[1] kwikname = os.path.splitext(kwikfname)[0] phy_fold = os.path.join(block_path, kwikname + '.phy') phy_fold = os.path.abspath(os.path.join(phy_fold, 'cluster_store/0/main/')) if not os.path.exists(phy_fold): os.makedirs(phy_fold) return phy_fold def spikeindices(block_path, cluster, channel_group=0, clustering='main'): ''' Return a list of indices of spikes for a cluster Parameters ------ block_path : str the path to the block cluster : int the cluster identifier channel_group : the channel group identifier clustering : str, optional ID of clustering Returns ------ indices : numpy array indices of spikes in a specified cluster ''' with h5.File(find_kwik(block_path), 'r') as kwikf: sptimes = kwikf[ '/channel_groups/{}/spikes/clusters/{}'.format(channel_group, clustering)][:] return (sptimes == cluster) def compute_cluster_waveforms(block_path): ''' legacy method for computing cluster waveforms Parameters ------ block_path : str the path to the block ''' with open(find_info(block_path), 'rb') as infofile: info = json.load(infofile) prespike = info['params']['prespike'] postspike = info['params']['postspike'] nchans = info['params']['nchan'] spikes = load_spikes(block_path) clusters = spikes['cluster'].unique() phy_fold = make_phy_folder(block_path) for cluster in clusters: print("Cluster: {}".format(cluster)) cluspikes = spikes[spikes['cluster'] == cluster] cluspiketimes = cluspikes['time_samples'].values mean_waveform = np.zeros((prespike + postspike, nchans)) waveforms = np.zeros((len(cluspiketimes), prespike + postspike, nchans)) with h5.File(find_kwd(block_path), 'r') as kwdf: for ind, sptime in enumerate(cluspiketimes): test = np.zeros((prespike + postspike, nchans)) start_ind = max((int(sptime - prespike)), 0) start_ind2 = abs(min(int(sptime - prespike), 0)) test[start_ind2:] = kwdf['/recordings/0/data'][start_ind:int(sptime + postspike), :] waveforms[ind, :, :] = test mean_waveform += test waveforms = waveforms.flatten() mean_waveform /= len(cluspiketimes) mean_waveform = mean_waveform.flatten() with h5.File(find_kwx(block_path), 'r') as kwxf: cluster_spike_inds = spikeindices(block_path, cluster) nspike = np.count_nonzero(cluster_spike_inds) masks = kwxf['/channel_groups/0/features_masks'][cluster_spike_inds, :, 1] masks = np.reshape(masks, (nspike, nchans, -1)) masks = np.mean(masks, axis=2) mean_masks = np.mean(masks, axis=0) features = kwxf['/channel_groups/0/features_masks'][cluster_spike_inds, :, 0] mean_features = np.mean(features, axis=0) features = features.flatten() masks = masks.flatten() # make phy folder waveforms.tofile(os.path.join(phy_fold, '{}.waveforms'.format(cluster))) mean_waveform.tofile(os.path.join(phy_fold, '{}.mean_waveforms'.format(cluster))) masks.tofile(os.path.join(phy_fold, '{}.masks'.format(cluster))) mean_masks.tofile(os.path.join(phy_fold, '{}.mean_masks'.format(cluster))) mean_features.tofile(os.path.join(phy_fold, '{}.mean_features'.format(cluster))) features.tofile(os.path.join(phy_fold, '{}.features'.format(cluster))) def compute_cluster_waveforms_fast(block_path, spikes, before=10, after=30, n_chans=-1): ''' compute spike waveforms for unique clusters Parameters ------ block_path : str the path to the block spikes : pandas dataframe spike dataframe from core before : int number of samples before the wave after : int number of samples after the wave n_chans : int number of recording channels observed Returns ------ waveforms : numpy array array of waveforms for plotting. 3-dimensional of cluster id, wavelength width, and recorded spike data cluster_map : numpy array array of indexed clusters of unique spikes ''' wave_length = before + 1 + after kwd = find_kwd(block_path) with h5.File(kwd, 'r') as kwd_f: if n_chans == -1: recordings = np.sort( np.array(list(kwd_f['recordings'].keys()), dtype=int)).astype('unicode') for recording in recordings: assert n_chans == -1 or n_chans == kwd_f['recordings'][recording]['data'].shape[1] n_chans = kwd_f['recordings'][recording]['data'].shape[1] num_clusters = len(spikes['cluster'].unique()) counts = np.zeros(num_clusters) waveforms = np.zeros((num_clusters, wave_length, n_chans)) cluster_map = spikes['cluster'].unique() cluster_map.sort() cluster_map = {cluster: idx for idx, cluster in enumerate(cluster_map)} for recording, recording_group in spikes.groupby('recording'): recording_data = kwd_f['recordings'][str(recording)]['data'][:, :] for cluster, cluster_spikes in recording_group.groupby('cluster'): starts = cluster_spikes['time_samples'].values - before starts = starts[starts > 0] starts = starts[starts + wave_length < recording_data.shape[0]] counts[cluster_map[cluster]] += len(starts) for i in range(wave_length): waveforms[cluster_map[cluster], i, :] += np.sum(recording_data[starts + i, :], axis=0) waveforms /= counts.reshape((num_clusters, 1, 1)) return waveforms, cluster_map
[ "numpy.fromfile", "numpy.count_nonzero", "numpy.array", "numpy.arange", "os.path.exists", "numpy.mean", "numpy.reshape", "numpy.where", "os.path.split", "numpy.dot", "os.path.splitext", "h5py.File", "numpy.sign", "scipy.interpolate.UnivariateSpline", "six.moves.range", "os.makedirs", ...
[((2311, 2352), 'numpy.fromfile', 'np.fromfile', (['mean_masks'], {'dtype': 'np.float32'}), '(mean_masks, dtype=np.float32)\n', (2322, 2352), True, 'import numpy as np\n'), ((3708, 3751), 'numpy.array', 'np.array', (['[geometry[ch] for ch in channels]'], {}), '([geometry[ch] for ch in channels])\n', (3716, 3751), True, 'import numpy as np\n'), ((4413, 4445), 'scipy.interpolate.UnivariateSpline', 'UnivariateSpline', (['t', 'spike_shape'], {}), '(t, spike_shape)\n', (4429, 4445), False, 'from scipy.interpolate import UnivariateSpline\n'), ((4455, 4486), 'numpy.arange', 'np.arange', (['(0)', 't_max', '(1 / new_fs)'], {}), '(0, t_max, 1 / new_fs)\n', (4464, 4486), True, 'import numpy as np\n'), ((5517, 5541), 'numpy.where', 'np.where', (['(time == trough)'], {}), '(time == trough)\n', (5525, 5541), True, 'import numpy as np\n'), ((7868, 7909), 'numpy.fromfile', 'np.fromfile', (['mean_masks'], {'dtype': 'np.float32'}), '(mean_masks, dtype=np.float32)\n', (7879, 7909), True, 'import numpy as np\n'), ((9048, 9091), 'os.path.join', 'os.path.join', (['block_path', "(kwikname + '.phy')"], {}), "(block_path, kwikname + '.phy')\n", (9060, 9091), False, 'import os\n'), ((3764, 3781), 'numpy.dot', 'np.dot', (['w', 'coords'], {}), '(w, coords)\n', (3770, 3781), True, 'import numpy as np\n'), ((4352, 4379), 'numpy.arange', 'np.arange', (['(0)', 't_max', '(1 / fs)'], {}), '(0, t_max, 1 / fs)\n', (4361, 4379), True, 'import numpy as np\n'), ((5873, 5884), 'numpy.where', 'np.where', (['i'], {}), '(i)\n', (5881, 5884), True, 'import numpy as np\n'), ((5990, 6001), 'numpy.where', 'np.where', (['j'], {}), '(j)\n', (5998, 6001), True, 'import numpy as np\n'), ((8963, 8983), 'os.path.split', 'os.path.split', (['kwikf'], {}), '(kwikf)\n', (8976, 8983), False, 'import os\n'), ((9002, 9029), 'os.path.splitext', 'os.path.splitext', (['kwikfname'], {}), '(kwikfname)\n', (9018, 9029), False, 'import os\n'), ((9123, 9170), 'os.path.join', 'os.path.join', (['phy_fold', '"""cluster_store/0/main/"""'], {}), "(phy_fold, 'cluster_store/0/main/')\n", (9135, 9170), False, 'import os\n'), ((9183, 9207), 'os.path.exists', 'os.path.exists', (['phy_fold'], {}), '(phy_fold)\n', (9197, 9207), False, 'import os\n'), ((9217, 9238), 'os.makedirs', 'os.makedirs', (['phy_fold'], {}), '(phy_fold)\n', (9228, 9238), False, 'import os\n'), ((10206, 10225), 'json.load', 'json.load', (['infofile'], {}), '(infofile)\n', (10215, 10225), False, 'import json\n'), ((10696, 10736), 'numpy.zeros', 'np.zeros', (['(prespike + postspike, nchans)'], {}), '((prespike + postspike, nchans))\n', (10704, 10736), True, 'import numpy as np\n'), ((13417, 13434), 'h5py.File', 'h5.File', (['kwd', '"""r"""'], {}), "(kwd, 'r')\n", (13424, 13434), True, 'import h5py as h5\n'), ((13881, 13903), 'numpy.zeros', 'np.zeros', (['num_clusters'], {}), '(num_clusters)\n', (13889, 13903), True, 'import numpy as np\n'), ((13924, 13970), 'numpy.zeros', 'np.zeros', (['(num_clusters, wave_length, n_chans)'], {}), '((num_clusters, wave_length, n_chans))\n', (13932, 13970), True, 'import numpy as np\n'), ((7263, 7307), 'numpy.fromfile', 'np.fromfile', (['mean_waveform'], {'dtype': 'np.float32'}), '(mean_waveform, dtype=np.float32)\n', (7274, 7307), True, 'import numpy as np\n'), ((11585, 11621), 'numpy.count_nonzero', 'np.count_nonzero', (['cluster_spike_inds'], {}), '(cluster_spike_inds)\n', (11601, 11621), True, 'import numpy as np\n'), ((11729, 11768), 'numpy.reshape', 'np.reshape', (['masks', '(nspike, nchans, -1)'], {}), '(masks, (nspike, nchans, -1))\n', (11739, 11768), True, 'import numpy as np\n'), ((11789, 11811), 'numpy.mean', 'np.mean', (['masks'], {'axis': '(2)'}), '(masks, axis=2)\n', (11796, 11811), True, 'import numpy as np\n'), ((11837, 11859), 'numpy.mean', 'np.mean', (['masks'], {'axis': '(0)'}), '(masks, axis=0)\n', (11844, 11859), True, 'import numpy as np\n'), ((11978, 12003), 'numpy.mean', 'np.mean', (['features'], {'axis': '(0)'}), '(features, axis=0)\n', (11985, 12003), True, 'import numpy as np\n'), ((5685, 5705), 'numpy.sign', 'np.sign', (['spike_shape'], {}), '(spike_shape)\n', (5692, 5705), True, 'import numpy as np\n'), ((10956, 10996), 'numpy.zeros', 'np.zeros', (['(prespike + postspike, nchans)'], {}), '((prespike + postspike, nchans))\n', (10964, 10996), True, 'import numpy as np\n'), ((14639, 14657), 'six.moves.range', 'range', (['wave_length'], {}), '(wave_length)\n', (14644, 14657), False, 'from six.moves import range\n'), ((14750, 14795), 'numpy.sum', 'np.sum', (['recording_data[starts + i, :]'], {'axis': '(0)'}), '(recording_data[starts + i, :], axis=0)\n', (14756, 14795), True, 'import numpy as np\n')]
import json import os import pickle import sys import cv2 import numpy as np this_filepath = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(this_filepath, '../src/detectron2/projects/DensePose/')) from densepose import add_densepose_config, add_hrnet_config from densepose.data.structures import DensePoseResult from densepose.vis.base import CompoundVisualizer from densepose.vis.bounding_box import ScoredBoundingBoxVisualizer from densepose.vis.densepose import (DensePoseResultsContourVisualizer, DensePoseResultsFineSegmentationVisualizer, DensePoseResultsUVisualizer, DensePoseResultsVVisualizer) from densepose.vis.extractor import CompoundExtractor, create_extractor from detectron2.config import get_cfg from detectron2.engine import DefaultPredictor from src.dataset.MINDS import MINDSDataset from src.utils.image import (create_context, recover_original_mask_size, select_body_parts) from tqdm import tqdm def run_on_video(video, model, extractor): # run for whole video annotations = dict() for frame_nb, frame in tqdm(enumerate(video.frame_by_frame()), total=(video.get_nb_frames() - 1)): annotations[f'frame_{frame_nb:03d}'] = dict() # MINDS FRAMES ARE FULL HD, we resize it before run model frame = cv2.resize(frame, (640, 480), interpolation=cv2.INTER_CUBIC) outputs = model(frame) data = extractor(outputs['instances']) iuv_arr = DensePoseResult.decode_png_data(*(data[-1].results[0])) i = iuv_arr[0, :, :].tolist() bbox = data[-1].boxes_xywh[0] annotations[f'frame_{frame_nb:03d}']['bbox'] = bbox annotations[f'frame_{frame_nb:03d}']['segm'] = i return annotations def run_on_dataset(dataset, model, extractor, body_parts=[ 'RightHand', 'LeftHand', 'UpperArmLeft', 'UpperArmRight', 'LowerArmLeft', 'LowerArmRight', 'Head', ]): for video in tqdm(dataset, total=len(dataset)): # MINDS FRAMES ARE FULL HD, we resized it before run model w, h = 640, 480 path_save = os.path.dirname(video.filepath) path_save_segm = path_save.replace('MINDS-Libras_RGB-D', os.path.join('MINDS-Libras_RGB-D', 'segm')) path_save_gei = path_save.replace('MINDS-Libras_RGB-D', os.path.join('MINDS-Libras_RGB-D', 'gei')) os.makedirs(path_save_segm, exist_ok=True) os.makedirs(path_save_gei, exist_ok=True) all_masks = [] for frame, annotations in run_on_video(video, model, extractor).items(): mask = recover_original_mask_size(annotations, (w, h)) mask_body_parts = select_body_parts(mask, body_parts) all_masks.append(mask_body_parts) gei = np.mean(all_masks, axis=0) with open(os.path.join(path_save_segm, video.video_name.replace('.mp4', '.json')), 'w') as outfile: json.dump(annotations, outfile) with open(os.path.join(path_save_gei, video.video_name.replace('.mp4', '.pkl')), 'wb') as f: pickle.dump(gei, f, pickle.HIGHEST_PROTOCOL) cv2.imwrite(os.path.join(path_save_gei, video.video_name.replace('.mp4', '.png')), (gei * 255).astype('int')) # return annotations def main(): config_file = os.path.join( this_filepath, '../src/detectron2/projects/DensePose/configs/densepose_rcnn_R_50_FPN_s1x.yaml') model_url = 'https://dl.fbaipublicfiles.com/densepose/densepose_rcnn_R_50_FPN_s1x/165712039/model_final_162be9.pkl' dataset_path_root = os.path.join(this_filepath, '../data/MINDS-Libras_RGB-D') ufop_dataset = MINDSDataset(dataset_path_root) # Inference with a keypoint detection model cfg = get_cfg() add_densepose_config(cfg) add_hrnet_config(cfg) cfg.merge_from_file(config_file) cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.7 # set threshold for this model cfg.MODEL.WEIGHTS = model_url predictor = DefaultPredictor(cfg) context = create_context(( 'bbox', 'dp_segm', )) # visualizer = context["visualizer"] extractor = context["extractor"] run_on_dataset(ufop_dataset, predictor, extractor) if __name__ == "__main__": main()
[ "numpy.mean", "pickle.dump", "detectron2.config.get_cfg", "densepose.add_hrnet_config", "densepose.data.structures.DensePoseResult.decode_png_data", "os.makedirs", "src.utils.image.recover_original_mask_size", "src.utils.image.create_context", "os.path.join", "src.dataset.MINDS.MINDSDataset", "o...
[((111, 136), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (126, 136), False, 'import os\n'), ((154, 222), 'os.path.join', 'os.path.join', (['this_filepath', '"""../src/detectron2/projects/DensePose/"""'], {}), "(this_filepath, '../src/detectron2/projects/DensePose/')\n", (166, 222), False, 'import os\n'), ((3679, 3796), 'os.path.join', 'os.path.join', (['this_filepath', '"""../src/detectron2/projects/DensePose/configs/densepose_rcnn_R_50_FPN_s1x.yaml"""'], {}), "(this_filepath,\n '../src/detectron2/projects/DensePose/configs/densepose_rcnn_R_50_FPN_s1x.yaml'\n )\n", (3691, 3796), False, 'import os\n'), ((3950, 4007), 'os.path.join', 'os.path.join', (['this_filepath', '"""../data/MINDS-Libras_RGB-D"""'], {}), "(this_filepath, '../data/MINDS-Libras_RGB-D')\n", (3962, 4007), False, 'import os\n'), ((4027, 4058), 'src.dataset.MINDS.MINDSDataset', 'MINDSDataset', (['dataset_path_root'], {}), '(dataset_path_root)\n', (4039, 4058), False, 'from src.dataset.MINDS import MINDSDataset\n'), ((4118, 4127), 'detectron2.config.get_cfg', 'get_cfg', ([], {}), '()\n', (4125, 4127), False, 'from detectron2.config import get_cfg\n'), ((4133, 4158), 'densepose.add_densepose_config', 'add_densepose_config', (['cfg'], {}), '(cfg)\n', (4153, 4158), False, 'from densepose import add_densepose_config, add_hrnet_config\n'), ((4163, 4184), 'densepose.add_hrnet_config', 'add_hrnet_config', (['cfg'], {}), '(cfg)\n', (4179, 4184), False, 'from densepose import add_densepose_config, add_hrnet_config\n'), ((4354, 4375), 'detectron2.engine.DefaultPredictor', 'DefaultPredictor', (['cfg'], {}), '(cfg)\n', (4370, 4375), False, 'from detectron2.engine import DefaultPredictor\n'), ((4390, 4425), 'src.utils.image.create_context', 'create_context', (["('bbox', 'dp_segm')"], {}), "(('bbox', 'dp_segm'))\n", (4404, 4425), False, 'from src.utils.image import create_context, recover_original_mask_size, select_body_parts\n'), ((1389, 1449), 'cv2.resize', 'cv2.resize', (['frame', '(640, 480)'], {'interpolation': 'cv2.INTER_CUBIC'}), '(frame, (640, 480), interpolation=cv2.INTER_CUBIC)\n', (1399, 1449), False, 'import cv2\n'), ((1548, 1601), 'densepose.data.structures.DensePoseResult.decode_png_data', 'DensePoseResult.decode_png_data', (['*data[-1].results[0]'], {}), '(*data[-1].results[0])\n', (1579, 1601), False, 'from densepose.data.structures import DensePoseResult\n'), ((2389, 2420), 'os.path.dirname', 'os.path.dirname', (['video.filepath'], {}), '(video.filepath)\n', (2404, 2420), False, 'import os\n'), ((2730, 2772), 'os.makedirs', 'os.makedirs', (['path_save_segm'], {'exist_ok': '(True)'}), '(path_save_segm, exist_ok=True)\n', (2741, 2772), False, 'import os\n'), ((2781, 2822), 'os.makedirs', 'os.makedirs', (['path_save_gei'], {'exist_ok': '(True)'}), '(path_save_gei, exist_ok=True)\n', (2792, 2822), False, 'import os\n'), ((3123, 3149), 'numpy.mean', 'np.mean', (['all_masks'], {'axis': '(0)'}), '(all_masks, axis=0)\n', (3130, 3149), True, 'import numpy as np\n'), ((2529, 2571), 'os.path.join', 'os.path.join', (['"""MINDS-Libras_RGB-D"""', '"""segm"""'], {}), "('MINDS-Libras_RGB-D', 'segm')\n", (2541, 2571), False, 'import os\n'), ((2679, 2720), 'os.path.join', 'os.path.join', (['"""MINDS-Libras_RGB-D"""', '"""gei"""'], {}), "('MINDS-Libras_RGB-D', 'gei')\n", (2691, 2720), False, 'import os\n'), ((2947, 2994), 'src.utils.image.recover_original_mask_size', 'recover_original_mask_size', (['annotations', '(w, h)'], {}), '(annotations, (w, h))\n', (2973, 2994), False, 'from src.utils.image import create_context, recover_original_mask_size, select_body_parts\n'), ((3025, 3060), 'src.utils.image.select_body_parts', 'select_body_parts', (['mask', 'body_parts'], {}), '(mask, body_parts)\n', (3042, 3060), False, 'from src.utils.image import create_context, recover_original_mask_size, select_body_parts\n'), ((3289, 3320), 'json.dump', 'json.dump', (['annotations', 'outfile'], {}), '(annotations, outfile)\n', (3298, 3320), False, 'import json\n'), ((3435, 3479), 'pickle.dump', 'pickle.dump', (['gei', 'f', 'pickle.HIGHEST_PROTOCOL'], {}), '(gei, f, pickle.HIGHEST_PROTOCOL)\n', (3446, 3479), False, 'import pickle\n')]
from PIL import Image import cv2 from decimal import getcontext, Decimal import pickle import network import numpy as np def convert_image(): image = Image.open('z.jpg').convert('L') new_image = image.resize((28, 28), Image.ANTIALIAS) quality_val = 100 new_image.save('img_28.jpg', quality=quality_val) gray_img = cv2.imread('img_28.jpg', cv2.IMREAD_GRAYSCALE) """Removing noise from images""" for i in range(28): for j in range(28): if gray_img[i, j] < 70: gray_img[i, j] = 0 elif gray_img[i, j] >= 70 and gray_img[i, j] <= 100: gray_img[i, j] = 85 elif gray_img[i, j] >= 101 and gray_img[i, j] <= 130: gray_img[i, j] = 115 elif gray_img[i, j] >= 131 and gray_img[i, j] <= 160: gray_img[i, j] = 145 else: gray_img[i, j] = 255 input_data = np.ndarray(shape=(784,1)) getcontext().prec = 1 for i in range(28): for j in range(28): input_data[i*28+j] = (round(float(255.0-gray_img[i, j])/(255.0), 1)) return input_data
[ "numpy.ndarray", "decimal.getcontext", "cv2.imread", "PIL.Image.open" ]
[((337, 383), 'cv2.imread', 'cv2.imread', (['"""img_28.jpg"""', 'cv2.IMREAD_GRAYSCALE'], {}), "('img_28.jpg', cv2.IMREAD_GRAYSCALE)\n", (347, 383), False, 'import cv2\n'), ((852, 878), 'numpy.ndarray', 'np.ndarray', ([], {'shape': '(784, 1)'}), '(shape=(784, 1))\n', (862, 878), True, 'import numpy as np\n'), ((882, 894), 'decimal.getcontext', 'getcontext', ([], {}), '()\n', (892, 894), False, 'from decimal import getcontext, Decimal\n'), ((156, 175), 'PIL.Image.open', 'Image.open', (['"""z.jpg"""'], {}), "('z.jpg')\n", (166, 175), False, 'from PIL import Image\n')]
import numpy as np import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) PAR_DIR = os.path.dirname(os.path.dirname(BASE_DIR)) RLG_DIR = os.path.join(PAR_DIR,'result/rot_log') LOG_FOUT = open(os.path.join(BASE_DIR, 'calShape.txt'), 'w') NUM_CLASSES = 40 SHAPE_NAMES = [line.rstrip() for line in \ open(os.path.join(BASE_DIR, 'shape_names.txt'))] def log_string(out_str): LOG_FOUT.write(out_str+'\n') LOG_FOUT.flush() print(out_str) if __name__=='__main__': for name in SHAPE_NAMES: filename = '%s.npz'%name filename = os.path.join(RLG_DIR,filename) arr = dict(np.load(filename)) log_string(name +':'+len(arr).__str__()) LOG_FOUT.close()
[ "os.path.abspath", "os.path.dirname", "numpy.load", "os.path.join" ]
[((148, 187), 'os.path.join', 'os.path.join', (['PAR_DIR', '"""result/rot_log"""'], {}), "(PAR_DIR, 'result/rot_log')\n", (160, 187), False, 'import os\n'), ((57, 82), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (72, 82), False, 'import os\n'), ((111, 136), 'os.path.dirname', 'os.path.dirname', (['BASE_DIR'], {}), '(BASE_DIR)\n', (126, 136), False, 'import os\n'), ((205, 243), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""calShape.txt"""'], {}), "(BASE_DIR, 'calShape.txt')\n", (217, 243), False, 'import os\n'), ((571, 602), 'os.path.join', 'os.path.join', (['RLG_DIR', 'filename'], {}), '(RLG_DIR, filename)\n', (583, 602), False, 'import os\n'), ((320, 361), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""shape_names.txt"""'], {}), "(BASE_DIR, 'shape_names.txt')\n", (332, 361), False, 'import os\n'), ((621, 638), 'numpy.load', 'np.load', (['filename'], {}), '(filename)\n', (628, 638), True, 'import numpy as np\n')]
#!/usr/bin/env python3 import gym import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from torch.nn import init from tqdm import tqdm import random import math import operator import matplotlib.pyplot as plt import numpy as np use_cuda = torch.cuda.is_available() class Net(nn.Module): def __init__(self, num_input_channels, num_output_channels, out2, pool_size, stride, linear_nodes): super(Net, self).__init__() self.num_input_channels = num_input_channels self.num_output_channels = num_output_channels self.out2 = out2 self.pool_size = pool_size self.stride = stride self.linear_nodes = linear_nodes #layers self.conv1 = nn.Conv2d(num_input_channels, num_output_channels, stride) self.pool = nn.MaxPool2d(pool_size, pool_size) self.conv2 = nn.Conv2d(num_output_channels, out2, stride) self.fc1 = nn.Linear(out2*(stride+2)**2*(stride+num_output_channels), linear_nodes[0]) self.fc2 = nn.Linear(linear_nodes[0], linear_nodes[1]) self.fc3 = nn.Linear(linear_nodes[1], linear_nodes[2]) def forward(self, input): res = self.pool(F.relu(self.conv1(input))) res = self.pool(F.relu(self.conv2(res))) res = res.view(-1, self.out2*(self.stride+2)**2*(self.stride+self.num_output_channels)) res = F.relu(self.fc1(res)) res = F.relu(self.fc2(res)) res = self.fc3(res) return res def getParams(self): return self.num_input_channels, self.num_output_channels, self.out2, self.pool_size, self.stride, self.linear_nodes #makes a bunch of different nets def makeNets(numNets): nets = [] print("MAKING NETS") for i in tqdm(range(numNets)): num_input_channels = 3 num_output_channels = random.randrange(1, 100) out2 = random.randrange(1, 100) pool_size = random.randrange(1, 5) stride = random.randrange(1,5) linear_nodes = [random.randrange(100,300), random.randrange(30, 100), 2] net = Net(num_input_channels, num_output_channels, out2, pool_size, stride, linear_nodes) nn.init.xavier_uniform(net.conv1.weight) nn.init.xavier_uniform(net.conv2.weight) nn.init.xavier_uniform(net.fc1.weight) nn.init.xavier_uniform(net.fc2.weight) nn.init.xavier_uniform(net.fc3.weight) nn.init.uniform(net.conv1.bias) nn.init.uniform(net.conv2.bias) nn.init.uniform(net.fc1.bias) nn.init.uniform(net.conv1.bias) nn.init.uniform(net.fc2.bias) nn.init.uniform(net.fc3.bias) net = net.cuda() if use_cuda else net nets.append(net) return nets #running nets in environment def inference(nets): env = gym.make("Pong-v0") num_episodes = 5 num_iters = 10000 rewards = np.array([]) for net in nets: total_reward = 0 observation = env.reset() for i_episode in tqdm(range(num_episodes)): for _ in range(num_iters): res = net(Variable(observation.view(1, 3, 210, 160))) action = 2 if res.data[0][0] > res.data[0][1] else 3 observation, reward, done, info = env.step(action) total_reward += reward if done: print("Finished after %d timesteps", _) break if i_episode == num_iters - 1: print("gone through %d iters", num_iters) np.append(rewards, total_reward) return rewards #Editing Nets based off of results def evolution(rewards, nets, survival_rate, exploration_rate, combine_rate): evolved_nets = [] numNets = len(nets) numSurvivors = math.floor(numNets*survival_rate) numRescued = math.floor(numNets*exploration_rate) numCombined = math.floor(numNets*combine_rate) numMutated = numNets - numSurvivors - numRescued - numCombined def naturalSelection(): index, value = max(enumerate(rewards), key=operator.itemgetter(1)) evolved_nets.append(nets[index]) rewards.pop(index) nets.pop(index) def combine(tensor1, tensor2): #cross products size1 = tensor1.size() size2 = tensor2.size() tensor1 = tensor1.view(1, -1) tensor2 = tensor2.view(1, -1) tensor1Len = tensor1.size()[1] tensor2Len = tensor2.size()[1] if tensor1Len > tensor2Len: res = torch.cat(torch.cross(tensor1[:,:tensor2Len + 1], tensor2), tensor1[:,tensor2Len + 1:]).view(size1) elif tensor1Len < tensor2Len: res = torch.cat(torch.cross(tensor2[:,:tensor1Len + 1], tensor1), tensor2[:,tensor1Len + 1:]).view(size2) else: res = torch.cross(tensor1, tensor2).view(size1) return res def mutate(tensor): size = tensor.size() tensor = tensor.view(1, -1) for element in tensor: element = random.random() return tensor.view(size) #pick survivors for i in range(numSurvivors): naturalSelection() #Combine some for i in range(numCombined): net1 = random.choice(evolved_nets) net2 = random.choice(evolved_nets) net1Params = net1.getParams() net2Params = net2.getParams() newNet = Net(3, max(net1Params[1], net2Params[1]), max(net1Params[2], net2Params[2]), max(net1Params[3], net2Params[3]), max(net1Params[4], net2Params[4]), max(net1Params[5], net2Params[5])) newNet.conv1.weight = combine(net1.conv1.weight, net2.conv1.weight) newNet.conv2.weight = combine(net1.conv2.weight, net2.conv2.weight) newNet.fc1.weight = combine(net1.fc1.weight, net2.fc1.weight) newNet.fc2.weight = combine(net1.fc2.weight, net2.fc2.weight) newNet.fc3.weight = combine(net1.fc3.weight, net2.fc3.combine) newNet.conv1.bias = combine(net1.conv1.bias, net2.conv1.bias) newNet.conv2.bias = combine(net1.conv2.bias, net2.conv2.bias) newNet.fc1.bias = combine(net1.fc1.bias, net2.fc1.bias) newNet.fc2.bias = combine(net1.fc2.bias, net2.fc2.bias) newNet.fc3.bias = combine(net1.fc3.bias, net2.fc3.bias) newNet = newNet.cuda() if use_cuda else newNet evolved_nets.append(newNet) #pick Rescued for i in range(numRescued): rescuee = random.choice(nets) idx = nets.index(rescuee) evolved_nets.append(rescuee) nets.pop(rescuee) #mutate Some for i in range(numMutated): chosenNet = random.choice(nets) idx = nets.index(chosenNet) chosenNet.conv2.weight = mutate(chosenNet.conv2.weight) chosenNet.fc1.weight = mutate(chosenNet.fc1.weight) chosenNet.fc2.weight = mutate(chosenNet.fc2.weight) chosenNet.fc3.weight = mutate(chosenNet.fc3.weight) chosenNet.conv1.bias = mutate(chosenNet.conv1.bias) chosenNet.conv2.bias = mutate(chosenNet.conv2.bias) chosenNet.fc1.bias = mutate(chosenNet.fc1.bias) chosenNet.fc2.bias = mutate(chosenNet.fc2.bias) chosenNet.fc3.bias = mutate(chosenNet.fc3.bias) evolved_nets.append(chosenNet) nets.pop(idx) return evolved_nets #TRAINING survival_rate = 0.4 exploration_rate = 0.3 combine_rate = 0.2 numEvolutions = 10000 numNets = 10000 def train(survival_rate, exploration_rate, combine_rate, numEvolutions=10000, numNets=10000): avgRewards = np.array([]) nets = makeNets(numNets) print("TRAINING") #analyzation def stats(rewards, iteration, print_every=500): index, value = max(enumerate(rewards), key=operator.itemgetter(1)) avg_reward = sum(rewards)/float(len(rewards)) np.append(avgRewards, avg_reward) if iteration % print_every == 0: print("Average Reward: %f" % avg_reward) print("Best Net: Net %d\n Score: %f" % (index, value)) iterations = np.array([i for i in range(iteration)]) fig, ax = plt.subplots() fit = np.polyfit(iterations, avgRewards, deg=1) ax.plot(x, fit[0] * x + fit[1], color='red') print("Change in Average Reward per Iteration: %d" % fit[0]) ax.scatter(iterations, avgRewards) fig.show() plt.savefig('plt.png') # EVOLVING for n_iter in tqdm(range(numEvolutions)): print("EVOLVING") rewards = inference(nets) nets = evolution(rewards, nets, survival_rate, exploration_rate, combine_rate) stats(rewards, n_iter) exploration_rate = 0.3 - n_iter/6000 combine_rate = 0.2 + n_iter/9000 totalRewards = np.zeros(numNets) for n_iter in tqdm(range(numEvolutions/10)): print("TESTING") rewards = inference(nets) totalRewards += rewards totalRewards /= numEvolutions/10 index, value = max(enumerate(totalRewards), key=operator.itemgetter(1)) bestNet = nets[index] return bestNet bestNet = train(survival_rate, exploration_rate, combine_rate) torch.save(bestNet, 'Pongexpert.pt') def play(net): env = gym.make("Pong-v0") num_episodes = 5 num_iters = 10000 observation = env.reset() total_reward = 0 for i_episode in tqdm(range(num_episodes)): for _ in range(num_iters): res = net(Variable(observation.view(1, 3, 210, 160))) action = 2 if res.data[0][0] > res.data[0][1] else 3 observation, reward, done, info = env.step(action) total_reward += reward if done: print("Finished after %d timesteps", _) break if i_episode == num_iters - 1: print("gone through %d iters", num_iters) return total_reward
[ "math.floor", "numpy.polyfit", "numpy.array", "torch.cuda.is_available", "torch.nn.init.xavier_uniform", "operator.itemgetter", "gym.make", "random.choice", "matplotlib.pyplot.savefig", "random.randrange", "torch.nn.init.uniform", "torch.save", "torch.nn.Conv2d", "numpy.append", "numpy.z...
[((290, 315), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (313, 315), False, 'import torch\n'), ((8047, 8083), 'torch.save', 'torch.save', (['bestNet', '"""Pongexpert.pt"""'], {}), "(bestNet, 'Pongexpert.pt')\n", (8057, 8083), False, 'import torch\n'), ((2525, 2544), 'gym.make', 'gym.make', (['"""Pong-v0"""'], {}), "('Pong-v0')\n", (2533, 2544), False, 'import gym\n'), ((2593, 2605), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2601, 2605), True, 'import numpy as np\n'), ((3325, 3360), 'math.floor', 'math.floor', (['(numNets * survival_rate)'], {}), '(numNets * survival_rate)\n', (3335, 3360), False, 'import math\n'), ((3373, 3411), 'math.floor', 'math.floor', (['(numNets * exploration_rate)'], {}), '(numNets * exploration_rate)\n', (3383, 3411), False, 'import math\n'), ((3425, 3459), 'math.floor', 'math.floor', (['(numNets * combine_rate)'], {}), '(numNets * combine_rate)\n', (3435, 3459), False, 'import math\n'), ((6655, 6667), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (6663, 6667), True, 'import numpy as np\n'), ((7697, 7714), 'numpy.zeros', 'np.zeros', (['numNets'], {}), '(numNets)\n', (7705, 7714), True, 'import numpy as np\n'), ((8107, 8126), 'gym.make', 'gym.make', (['"""Pong-v0"""'], {}), "('Pong-v0')\n", (8115, 8126), False, 'import gym\n'), ((702, 760), 'torch.nn.Conv2d', 'nn.Conv2d', (['num_input_channels', 'num_output_channels', 'stride'], {}), '(num_input_channels, num_output_channels, stride)\n', (711, 760), True, 'import torch.nn as nn\n'), ((775, 809), 'torch.nn.MaxPool2d', 'nn.MaxPool2d', (['pool_size', 'pool_size'], {}), '(pool_size, pool_size)\n', (787, 809), True, 'import torch.nn as nn\n'), ((825, 869), 'torch.nn.Conv2d', 'nn.Conv2d', (['num_output_channels', 'out2', 'stride'], {}), '(num_output_channels, out2, stride)\n', (834, 869), True, 'import torch.nn as nn\n'), ((883, 972), 'torch.nn.Linear', 'nn.Linear', (['(out2 * (stride + 2) ** 2 * (stride + num_output_channels))', 'linear_nodes[0]'], {}), '(out2 * (stride + 2) ** 2 * (stride + num_output_channels),\n linear_nodes[0])\n', (892, 972), True, 'import torch.nn as nn\n'), ((972, 1015), 'torch.nn.Linear', 'nn.Linear', (['linear_nodes[0]', 'linear_nodes[1]'], {}), '(linear_nodes[0], linear_nodes[1])\n', (981, 1015), True, 'import torch.nn as nn\n'), ((1029, 1072), 'torch.nn.Linear', 'nn.Linear', (['linear_nodes[1]', 'linear_nodes[2]'], {}), '(linear_nodes[1], linear_nodes[2])\n', (1038, 1072), True, 'import torch.nn as nn\n'), ((1687, 1711), 'random.randrange', 'random.randrange', (['(1)', '(100)'], {}), '(1, 100)\n', (1703, 1711), False, 'import random\n'), ((1721, 1745), 'random.randrange', 'random.randrange', (['(1)', '(100)'], {}), '(1, 100)\n', (1737, 1745), False, 'import random\n'), ((1760, 1782), 'random.randrange', 'random.randrange', (['(1)', '(5)'], {}), '(1, 5)\n', (1776, 1782), False, 'import random\n'), ((1794, 1816), 'random.randrange', 'random.randrange', (['(1)', '(5)'], {}), '(1, 5)\n', (1810, 1816), False, 'import random\n'), ((1986, 2026), 'torch.nn.init.xavier_uniform', 'nn.init.xavier_uniform', (['net.conv1.weight'], {}), '(net.conv1.weight)\n', (2008, 2026), True, 'import torch.nn as nn\n'), ((2029, 2069), 'torch.nn.init.xavier_uniform', 'nn.init.xavier_uniform', (['net.conv2.weight'], {}), '(net.conv2.weight)\n', (2051, 2069), True, 'import torch.nn as nn\n'), ((2072, 2110), 'torch.nn.init.xavier_uniform', 'nn.init.xavier_uniform', (['net.fc1.weight'], {}), '(net.fc1.weight)\n', (2094, 2110), True, 'import torch.nn as nn\n'), ((2113, 2151), 'torch.nn.init.xavier_uniform', 'nn.init.xavier_uniform', (['net.fc2.weight'], {}), '(net.fc2.weight)\n', (2135, 2151), True, 'import torch.nn as nn\n'), ((2154, 2192), 'torch.nn.init.xavier_uniform', 'nn.init.xavier_uniform', (['net.fc3.weight'], {}), '(net.fc3.weight)\n', (2176, 2192), True, 'import torch.nn as nn\n'), ((2196, 2227), 'torch.nn.init.uniform', 'nn.init.uniform', (['net.conv1.bias'], {}), '(net.conv1.bias)\n', (2211, 2227), True, 'import torch.nn as nn\n'), ((2230, 2261), 'torch.nn.init.uniform', 'nn.init.uniform', (['net.conv2.bias'], {}), '(net.conv2.bias)\n', (2245, 2261), True, 'import torch.nn as nn\n'), ((2264, 2293), 'torch.nn.init.uniform', 'nn.init.uniform', (['net.fc1.bias'], {}), '(net.fc1.bias)\n', (2279, 2293), True, 'import torch.nn as nn\n'), ((2296, 2327), 'torch.nn.init.uniform', 'nn.init.uniform', (['net.conv1.bias'], {}), '(net.conv1.bias)\n', (2311, 2327), True, 'import torch.nn as nn\n'), ((2330, 2359), 'torch.nn.init.uniform', 'nn.init.uniform', (['net.fc2.bias'], {}), '(net.fc2.bias)\n', (2345, 2359), True, 'import torch.nn as nn\n'), ((2362, 2391), 'torch.nn.init.uniform', 'nn.init.uniform', (['net.fc3.bias'], {}), '(net.fc3.bias)\n', (2377, 2391), True, 'import torch.nn as nn\n'), ((3106, 3138), 'numpy.append', 'np.append', (['rewards', 'total_reward'], {}), '(rewards, total_reward)\n', (3115, 3138), True, 'import numpy as np\n'), ((4561, 4588), 'random.choice', 'random.choice', (['evolved_nets'], {}), '(evolved_nets)\n', (4574, 4588), False, 'import random\n'), ((4598, 4625), 'random.choice', 'random.choice', (['evolved_nets'], {}), '(evolved_nets)\n', (4611, 4625), False, 'import random\n'), ((5667, 5686), 'random.choice', 'random.choice', (['nets'], {}), '(nets)\n', (5680, 5686), False, 'import random\n'), ((5825, 5844), 'random.choice', 'random.choice', (['nets'], {}), '(nets)\n', (5838, 5844), False, 'import random\n'), ((6897, 6930), 'numpy.append', 'np.append', (['avgRewards', 'avg_reward'], {}), '(avgRewards, avg_reward)\n', (6906, 6930), True, 'import numpy as np\n'), ((1834, 1860), 'random.randrange', 'random.randrange', (['(100)', '(300)'], {}), '(100, 300)\n', (1850, 1860), False, 'import random\n'), ((1861, 1886), 'random.randrange', 'random.randrange', (['(30)', '(100)'], {}), '(30, 100)\n', (1877, 1886), False, 'import random\n'), ((4391, 4406), 'random.random', 'random.random', ([], {}), '()\n', (4404, 4406), False, 'import random\n'), ((7137, 7151), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (7149, 7151), True, 'import matplotlib.pyplot as plt\n'), ((7161, 7202), 'numpy.polyfit', 'np.polyfit', (['iterations', 'avgRewards'], {'deg': '(1)'}), '(iterations, avgRewards, deg=1)\n', (7171, 7202), True, 'import numpy as np\n'), ((7370, 7392), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""plt.png"""'], {}), "('plt.png')\n", (7381, 7392), True, 'import matplotlib.pyplot as plt\n'), ((7919, 7941), 'operator.itemgetter', 'operator.itemgetter', (['(1)'], {}), '(1)\n', (7938, 7941), False, 'import operator\n'), ((3593, 3615), 'operator.itemgetter', 'operator.itemgetter', (['(1)'], {}), '(1)\n', (3612, 3615), False, 'import operator\n'), ((6823, 6845), 'operator.itemgetter', 'operator.itemgetter', (['(1)'], {}), '(1)\n', (6842, 6845), False, 'import operator\n'), ((3971, 4020), 'torch.cross', 'torch.cross', (['tensor1[:, :tensor2Len + 1]', 'tensor2'], {}), '(tensor1[:, :tensor2Len + 1], tensor2)\n', (3982, 4020), False, 'import torch\n'), ((4219, 4248), 'torch.cross', 'torch.cross', (['tensor1', 'tensor2'], {}), '(tensor1, tensor2)\n', (4230, 4248), False, 'import torch\n'), ((4112, 4161), 'torch.cross', 'torch.cross', (['tensor2[:, :tensor1Len + 1]', 'tensor1'], {}), '(tensor2[:, :tensor1Len + 1], tensor1)\n', (4123, 4161), False, 'import torch\n')]
#!/usr/bin/env python3 import csv import datetime import os import shelve from time import time import matplotlib.pyplot as plt import numpy as np from scipy.special import expit as activation_function # sigmoid function from scipy.special import logit as inverse_activation_function import wget # CONFIG DATA_DIR = "data" DATA_FILE = "data.db" # for statistics # DEBUG = True will use smaller dataset, single run and show pictures DEBUG = False INPUT_NODES = 28**2 OUTPUT_NODES = 10 DATA_DIR = "test_data/" TRAIN_FILE = os.path.join(DATA_DIR, "mnist_train.csv") TEST_FILE = os.path.join(DATA_DIR, "mnist_test.csv") TRAINFILE_URL = "http://www.pjreddie.com/media/files/mnist_train.csv" TESTFILE_URL = "http://www.pjreddie.com/media/files/mnist_test.csv" def reversed_enumerate(sequence): return zip( reversed(range(len(sequence))), reversed(sequence), ) class NeuralNetwork: def __init__(self, hidden_layers, input_nodes, hidden_nodes, output_nodes, learning_rate): """ set number of nodes in each input, hidden, output layer """ self.lr = learning_rate # defining weights # input to hidden layer l_ih = self.__init_weights(input_nodes, hidden_nodes) # hidden to hidden layer l_hh = self.__init_weights(hidden_nodes, hidden_nodes) # hidden to output layer l_ho = self.__init_weights(hidden_nodes, output_nodes) self.layer_weights = [l_ih] for i in range(0, hidden_layers - 1): self.layer_weights.append(l_hh) self.layer_weights.append(l_ho) # closing with output layer def __init_weights(self, this_layer, next_layer): return np.random.normal(0.0, pow(next_layer, -0.5), (next_layer, this_layer)) def __calculate_outputs(self, weights, inputs): # Step 1 - calculate signals into hidden layer weighted_inputs = np.dot(weights, inputs) # calculate the signals emerging from hidden layer outputs = activation_function(weighted_inputs) return outputs def __update_weights(self, this_errors, this_outputs, previous_outputs): x = this_errors * this_outputs * (1.0 - this_outputs) updated_weights = self.lr * np.dot(x, np.transpose(previous_outputs)) return updated_weights def __propagate(self, inputs_list): # convert inputs list to 2d array inputs = np.array(inputs_list, ndmin=2).T # initialize with inputs, as "outputs from picture" outputs_list = [inputs] for i, weights in enumerate(self.layer_weights): this_output = self.__calculate_outputs(weights, outputs_list[i]) outputs_list.append(this_output) return outputs_list def train(self, inputs_list, targets_list): outputs_list = self.__propagate(inputs_list) # transpose the inputs list to a vertical array targets = np.array(targets_list, ndmin=2).T # backpropagate new_weights_rev = [] this_errors = targets - outputs_list[-1] # starting with output_errors for i, weights in reversed_enumerate(self.layer_weights): # print(i) # for weights, outputs in reversed(list(zip(self.layer_weights, outputs_list))): w_delta = self.__update_weights(this_errors, outputs_list[i + 1], outputs_list[i]) new_weight = weights + w_delta new_weights_rev.append(new_weight) this_errors = np.dot(weights.T, this_errors) # update weights self.layer_weights = new_weights_rev[::-1] # must be reversed def query(self, inputs_list): output_list = self.__propagate(inputs_list) return output_list[-1] # return final outputs # backquery the neural network # we'll use the same termnimology to each item, # eg target are the values at the right of the network, albeit used as input # eg hidden_output is the signal to the right of the middle nodes def backquery(self, targets_list): # transpose the targets list to a vertical array outputs = np.array(targets_list, ndmin=2).T for weights in reversed(self.layer_weights): # calculate the signal into the final output layer inputs = inverse_activation_function(outputs) # calculate the signal out of the hidden layer outputs = np.dot(weights.T, inputs) # scale them back to 0.01 to .99 outputs -= np.min(outputs) outputs /= np.max(outputs) outputs *= 0.98 outputs += 0.01 return outputs # HELPER FUNCTIONS ----------------------------------- def ensure_files(): if not os.path.exists(DATA_DIR): os.makedirs(DATA_DIR) if not os.path.exists(TRAIN_FILE): print("Downloading: {}".format(TRAIN_FILE)) wget.download(TRAINFILE_URL, out=DATA_DIR) if not os.path.exists(TEST_FILE): print("Downloading: {}".format(TEST_FILE)) wget.download(TESTFILE_URL, out=DATA_DIR) def scale_matrix(matrix): """ nn works best with values between 0.01 and 1 """ return matrix / 255 * 0.99 + 0.01 def import_data(file_name): with open(file_name, "r") as f: reader = csv.reader(f) for row in reader: label = int(row.pop(0)) matrix = scale_matrix(np.asfarray(row)) # .reshape((28, 28))) yield label, matrix def gen_target_array(onodes): """ generates list of lists, like: [[0.01, 0.01, 0.01, 0.01, 0.01, 0.99, 0.01, 0.01, 0.01, 0.01], ... ] """ o_list = [] for index in range(onodes): targets = np.zeros(onodes) + 0.01 targets[index] = 0.99 o_list.append(targets) return o_list def plot_matrix(matrix): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_aspect('equal') plt.imshow( matrix, interpolation='nearest', cmap=plt.cm.Greys) plt.colorbar() plt.show() def calc_accuracy(scorecard): scorecard_array = np.asarray(scorecard) accuracy = scorecard_array.sum() / scorecard_array.size return accuracy def get_sample_size(file_name): if DEBUG: return 1000 sample_size = 0 with open(file_name, "r") as f: reader = csv.reader(f) sample_size = len(list(reader)) return sample_size def best_accuracy(list): max_L = max(records, key=lambda x: x["accuracy"]) return max_L["accuracy"] def run_experiment(hidden_layers, hidden_nodes, learning_rate, epochs): # init network nn = NeuralNetwork( input_nodes=INPUT_NODES, hidden_layers=hidden_layers, hidden_nodes=hidden_nodes, output_nodes=OUTPUT_NODES, learning_rate=learning_rate ) target_ar = gen_target_array(OUTPUT_NODES) # train network training_data = import_data(TRAIN_FILE) if DEBUG: # use less training data for debug training_data = list(training_data)[1000:] t0 = time() for e in range(epochs): for record in training_data: label, matrix = record nn.train(inputs_list=matrix, targets_list=target_ar[label]) t1 = time() - t0 # test network scorecard = [] # scorecard for how well the network performs test_data = import_data(TEST_FILE) if DEBUG: # use less test data for debug test_data = list(test_data)[100:] for record in test_data: correct_label, matrix = record outputs = nn.query(matrix) label = np.argmax( outputs) # the index of the highest value corresponds to the label if (label == correct_label): # network's answer matches correct answer, add 1 to scorecard scorecard.append(1) else: # network's answer doesn't match correct answer, add 0 to scorecard scorecard.append(0) accuracy = calc_accuracy(scorecard) training_time = str(datetime.timedelta(seconds=t1)) # print some info regarding training run print("accuracy: {0:.1f}%".format(calc_accuracy(scorecard) * 100)) print("training time: {}".format(training_time)) #print("sample size: {}".format(get_sample_size(TRAIN_FILE))) print("epochs: {}".format(epochs)) print("hidden layers: {}".format(hidden_layers)) print("hidden nodes: {}".format(hidden_nodes)) print("learning rate: {}".format(learning_rate)) print("-" * 15 + "\n") if DEBUG: print("\n\nBackquerying the network") for i, t in enumerate(target_ar): image_data = nn.backquery(t) plt.imshow(image_data.reshape(28, 28), cmap='Greys', interpolation='None') plt.title("Target: " + str(i)) plt.show() else: # save current model to db if it has better accuracy d = shelve.open(DATA_FILE, writeback=True) records = d["records"] # # get best accuracy if records: # list must be non-empty current_best = best_accuracy(records) # save model only if accuracy higher than current best if accuracy > current_best: # del d["data"] # TODO: is this needed? or just writeback=True? d["model"] = nn.layer_weights # save current parameter set for later analysis records.append({ "accuracy": 0, "hidden_layers": 0, "hidden_nodes": 0, "learning_rate": 0, "training_time": training_time, "epochs": 0}) # don't forget to close db connection d.close() def init_db(): d = shelve.open(DATA_FILE, writeback=True) try: d["records"] except KeyError: d["records"] = [] # initialize records list try: d["model"] except KeyError: d["model"] = [] # initialize model list d.close() if __name__ == '__main__': ensure_files() # download training and test data if not present init_db() # make sure key value pairs are present if DEBUG: print("Running in DEBUG mode.\n\n") run_experiment(hidden_layers=0, hidden_nodes=50, learning_rate=0.2, epochs=1) else: start_time = time() print("Running combinatorial query over parameters.\n\n") for hidden_layers in range(2): for hidden_nodes in [50, 80, 150, 200, 300]: for learning_rate in [0.05, 0.1, 0.2, 0.3, 0.5]: for epochs in [2, 3, 5]: run_experiment(hidden_layers, hidden_nodes, learning_rate, epochs) time_delta = time() - start_time # print some summarizing statistics d = shelve.open(DATA_FILE, writeback=False) records = d["records"] d.close() current_best = best_accuracy(records) print("-" * 15) print("Best accuracy: {}".format()) print("Total training time: {}".format(str(datetime.timedelta(seconds=time_delta)))) print("Number of experiments: {}".format(len(records))) print("Sample size: {}".format(get_sample_size(TRAIN_FILE))) print("-" * 15) print("\n\nBest model saved to db file. Access via key \"model\" and have fun!")
[ "wget.download", "numpy.asfarray", "numpy.array", "shelve.open", "datetime.timedelta", "matplotlib.pyplot.imshow", "os.path.exists", "numpy.asarray", "numpy.max", "numpy.dot", "numpy.min", "csv.reader", "numpy.argmax", "scipy.special.expit", "numpy.transpose", "time.time", "matplotli...
[((529, 570), 'os.path.join', 'os.path.join', (['DATA_DIR', '"""mnist_train.csv"""'], {}), "(DATA_DIR, 'mnist_train.csv')\n", (541, 570), False, 'import os\n'), ((583, 623), 'os.path.join', 'os.path.join', (['DATA_DIR', '"""mnist_test.csv"""'], {}), "(DATA_DIR, 'mnist_test.csv')\n", (595, 623), False, 'import os\n'), ((5812, 5824), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (5822, 5824), True, 'import matplotlib.pyplot as plt\n'), ((5891, 5953), 'matplotlib.pyplot.imshow', 'plt.imshow', (['matrix'], {'interpolation': '"""nearest"""', 'cmap': 'plt.cm.Greys'}), "(matrix, interpolation='nearest', cmap=plt.cm.Greys)\n", (5901, 5953), True, 'import matplotlib.pyplot as plt\n'), ((5977, 5991), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (5989, 5991), True, 'import matplotlib.pyplot as plt\n'), ((5996, 6006), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6004, 6006), True, 'import matplotlib.pyplot as plt\n'), ((6061, 6082), 'numpy.asarray', 'np.asarray', (['scorecard'], {}), '(scorecard)\n', (6071, 6082), True, 'import numpy as np\n'), ((7012, 7018), 'time.time', 'time', ([], {}), '()\n', (7016, 7018), False, 'from time import time\n'), ((9661, 9699), 'shelve.open', 'shelve.open', (['DATA_FILE'], {'writeback': '(True)'}), '(DATA_FILE, writeback=True)\n', (9672, 9699), False, 'import shelve\n'), ((1898, 1921), 'numpy.dot', 'np.dot', (['weights', 'inputs'], {}), '(weights, inputs)\n', (1904, 1921), True, 'import numpy as np\n'), ((1999, 2035), 'scipy.special.expit', 'activation_function', (['weighted_inputs'], {}), '(weighted_inputs)\n', (2018, 2035), True, 'from scipy.special import expit as activation_function\n'), ((4724, 4748), 'os.path.exists', 'os.path.exists', (['DATA_DIR'], {}), '(DATA_DIR)\n', (4738, 4748), False, 'import os\n'), ((4758, 4779), 'os.makedirs', 'os.makedirs', (['DATA_DIR'], {}), '(DATA_DIR)\n', (4769, 4779), False, 'import os\n'), ((4792, 4818), 'os.path.exists', 'os.path.exists', (['TRAIN_FILE'], {}), '(TRAIN_FILE)\n', (4806, 4818), False, 'import os\n'), ((4880, 4922), 'wget.download', 'wget.download', (['TRAINFILE_URL'], {'out': 'DATA_DIR'}), '(TRAINFILE_URL, out=DATA_DIR)\n', (4893, 4922), False, 'import wget\n'), ((4935, 4960), 'os.path.exists', 'os.path.exists', (['TEST_FILE'], {}), '(TEST_FILE)\n', (4949, 4960), False, 'import os\n'), ((5021, 5062), 'wget.download', 'wget.download', (['TESTFILE_URL'], {'out': 'DATA_DIR'}), '(TESTFILE_URL, out=DATA_DIR)\n', (5034, 5062), False, 'import wget\n'), ((5270, 5283), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (5280, 5283), False, 'import csv\n'), ((6304, 6317), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (6314, 6317), False, 'import csv\n'), ((7200, 7206), 'time.time', 'time', ([], {}), '()\n', (7204, 7206), False, 'from time import time\n'), ((7544, 7562), 'numpy.argmax', 'np.argmax', (['outputs'], {}), '(outputs)\n', (7553, 7562), True, 'import numpy as np\n'), ((7972, 8002), 'datetime.timedelta', 'datetime.timedelta', ([], {'seconds': 't1'}), '(seconds=t1)\n', (7990, 8002), False, 'import datetime\n'), ((8865, 8903), 'shelve.open', 'shelve.open', (['DATA_FILE'], {'writeback': '(True)'}), '(DATA_FILE, writeback=True)\n', (8876, 8903), False, 'import shelve\n'), ((10246, 10252), 'time.time', 'time', ([], {}), '()\n', (10250, 10252), False, 'from time import time\n'), ((10714, 10753), 'shelve.open', 'shelve.open', (['DATA_FILE'], {'writeback': '(False)'}), '(DATA_FILE, writeback=False)\n', (10725, 10753), False, 'import shelve\n'), ((2419, 2449), 'numpy.array', 'np.array', (['inputs_list'], {'ndmin': '(2)'}), '(inputs_list, ndmin=2)\n', (2427, 2449), True, 'import numpy as np\n'), ((2927, 2958), 'numpy.array', 'np.array', (['targets_list'], {'ndmin': '(2)'}), '(targets_list, ndmin=2)\n', (2935, 2958), True, 'import numpy as np\n'), ((3491, 3521), 'numpy.dot', 'np.dot', (['weights.T', 'this_errors'], {}), '(weights.T, this_errors)\n', (3497, 3521), True, 'import numpy as np\n'), ((4115, 4146), 'numpy.array', 'np.array', (['targets_list'], {'ndmin': '(2)'}), '(targets_list, ndmin=2)\n', (4123, 4146), True, 'import numpy as np\n'), ((4287, 4323), 'scipy.special.logit', 'inverse_activation_function', (['outputs'], {}), '(outputs)\n', (4314, 4323), True, 'from scipy.special import logit as inverse_activation_function\n'), ((4406, 4431), 'numpy.dot', 'np.dot', (['weights.T', 'inputs'], {}), '(weights.T, inputs)\n', (4412, 4431), True, 'import numpy as np\n'), ((4500, 4515), 'numpy.min', 'np.min', (['outputs'], {}), '(outputs)\n', (4506, 4515), True, 'import numpy as np\n'), ((4539, 4554), 'numpy.max', 'np.max', (['outputs'], {}), '(outputs)\n', (4545, 4554), True, 'import numpy as np\n'), ((5668, 5684), 'numpy.zeros', 'np.zeros', (['onodes'], {}), '(onodes)\n', (5676, 5684), True, 'import numpy as np\n'), ((8771, 8781), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (8779, 8781), True, 'import matplotlib.pyplot as plt\n'), ((10637, 10643), 'time.time', 'time', ([], {}), '()\n', (10641, 10643), False, 'from time import time\n'), ((2256, 2286), 'numpy.transpose', 'np.transpose', (['previous_outputs'], {}), '(previous_outputs)\n', (2268, 2286), True, 'import numpy as np\n'), ((5381, 5397), 'numpy.asfarray', 'np.asfarray', (['row'], {}), '(row)\n', (5392, 5397), True, 'import numpy as np\n'), ((10969, 11007), 'datetime.timedelta', 'datetime.timedelta', ([], {'seconds': 'time_delta'}), '(seconds=time_delta)\n', (10987, 11007), False, 'import datetime\n')]
import numpy as np def compute_fans(shape): if len(shape) == 2: fan_in, fan_out = shape[0], shape[1] else: fan_in, fan_out = np.prod(shape[1:]), shape[0] return fan_in, fan_out class initializer(object): def __call__(self, shape): return self.init(shape).astype(np.float32) def init(self, shape): raise NotImplementedError class constant(initializer): def __init__(self, val): self._val = val def init(self, shape): return np.full(shape=shape, fill_value=self._val).astype(np.float32) class zeros(constant): def __init__(self): super(zeros, self).__init__(0.0) class xavieruniform(initializer): def __init__(self, gain=1.0): self._gain = gain def init(self, shape): fan_in, fan_out = compute_fans(shape) a = self._gain * np.sqrt(6.0 / (fan_in + fan_out)) return np.random.uniform(low=-a, high=a, size=shape).astype(np.float32)
[ "numpy.prod", "numpy.sqrt", "numpy.full", "numpy.random.uniform" ]
[((151, 169), 'numpy.prod', 'np.prod', (['shape[1:]'], {}), '(shape[1:])\n', (158, 169), True, 'import numpy as np\n'), ((854, 887), 'numpy.sqrt', 'np.sqrt', (['(6.0 / (fan_in + fan_out))'], {}), '(6.0 / (fan_in + fan_out))\n', (861, 887), True, 'import numpy as np\n'), ((507, 549), 'numpy.full', 'np.full', ([], {'shape': 'shape', 'fill_value': 'self._val'}), '(shape=shape, fill_value=self._val)\n', (514, 549), True, 'import numpy as np\n'), ((903, 948), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-a)', 'high': 'a', 'size': 'shape'}), '(low=-a, high=a, size=shape)\n', (920, 948), True, 'import numpy as np\n')]
# (c) 2017 <NAME> import numpy as np from scipy.special import digamma from scipy.stats import poisson, gamma from matplotlib import pyplot as plt euler = 0.577215664901532 t = np.linspace(0, 10, 1000) plt.plot(t, t*np.exp(t)/np.expm1(t)) plt.show() exit() #plt.plot(t, digamma(t)) #plt.plot(t, np.log(t/(1 - np.exp(-t))), ".-") # def summand(k, b): return digamma(k)*poisson.pmf(k, b) def f(b, N=50): k = np.arange(1, N) return np.sum(summand(k, b))*1./np.expm1(b) - np.log(b*np.exp(b)/np.expm1(b)) def finv(x): return x/euler + 1 #plt.plot(t, [(f(x) + euler - x*euler + 0.74694*x**2 - 0.336*x**3) for x in t], ".-") plt.plot(t, [finv(f(x)) for x in t], ".-") plt.plot(t, t) #plt.figure() k = np.arange(1, 20) #plt.plot(k, summand(k, 0.01), "s--") plt.show()
[ "scipy.special.digamma", "scipy.stats.poisson.pmf", "matplotlib.pyplot.plot", "numpy.expm1", "numpy.exp", "numpy.linspace", "numpy.arange", "matplotlib.pyplot.show" ]
[((179, 203), 'numpy.linspace', 'np.linspace', (['(0)', '(10)', '(1000)'], {}), '(0, 10, 1000)\n', (190, 203), True, 'import numpy as np\n'), ((241, 251), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (249, 251), True, 'from matplotlib import pyplot as plt\n'), ((684, 698), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 't'], {}), '(t, t)\n', (692, 698), True, 'from matplotlib import pyplot as plt\n'), ((718, 734), 'numpy.arange', 'np.arange', (['(1)', '(20)'], {}), '(1, 20)\n', (727, 734), True, 'import numpy as np\n'), ((773, 783), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (781, 783), True, 'from matplotlib import pyplot as plt\n'), ((419, 434), 'numpy.arange', 'np.arange', (['(1)', 'N'], {}), '(1, N)\n', (428, 434), True, 'import numpy as np\n'), ((228, 239), 'numpy.expm1', 'np.expm1', (['t'], {}), '(t)\n', (236, 239), True, 'import numpy as np\n'), ((365, 375), 'scipy.special.digamma', 'digamma', (['k'], {}), '(k)\n', (372, 375), False, 'from scipy.special import digamma\n'), ((376, 393), 'scipy.stats.poisson.pmf', 'poisson.pmf', (['k', 'b'], {}), '(k, b)\n', (387, 393), False, 'from scipy.stats import poisson, gamma\n'), ((218, 227), 'numpy.exp', 'np.exp', (['t'], {}), '(t)\n', (224, 227), True, 'import numpy as np\n'), ((471, 482), 'numpy.expm1', 'np.expm1', (['b'], {}), '(b)\n', (479, 482), True, 'import numpy as np\n'), ((504, 515), 'numpy.expm1', 'np.expm1', (['b'], {}), '(b)\n', (512, 515), True, 'import numpy as np\n'), ((494, 503), 'numpy.exp', 'np.exp', (['b'], {}), '(b)\n', (500, 503), True, 'import numpy as np\n')]
#!/usr/bin/env python3 """ Module to implement the Modified Seminario Method Originally written by <NAME>, TCM, University of Cambridge Modified by <NAME> and rewritten by <NAME>, Newcastle University Reference using AEA Allen, MC Payne, DJ Cole, J. Chem. Theory Comput. (2018), doi:10.1021/acs.jctc.7b00785 """ from QUBEKit.utils import constants from QUBEKit.utils.decorators import for_all_methods, timer_logger from operator import itemgetter import numpy as np class ModSemMaths: """Static methods for various mathematical functions relevant to the modified Seminario method.""" def __repr__(self): return f'{self.__class__.__name__}({self.__dict__!r})' @staticmethod def unit_vector_normal_to_bond(u_bc, u_ab): """Calculates unit vector which is normal to the plane abc.""" cross = np.cross(u_bc, u_ab) return cross / np.linalg.norm(cross) @staticmethod def unit_vector_along_bond(coords, bond): """Calculates the unit vector along a bond.""" atom_a, atom_b = bond diff_ab = coords[atom_b] - coords[atom_a] return diff_ab / np.linalg.norm(diff_ab) @staticmethod def u_pa_from_angles(angle, coords): """This gives the vector in the plane a, b, c and perpendicular to a to b.""" atom_a, atom_b, atom_c = angle u_ab = ModSemMaths.unit_vector_along_bond(coords, (atom_a, atom_b)) u_cb = ModSemMaths.unit_vector_along_bond(coords, (atom_c, atom_b)) u_n = ModSemMaths.unit_vector_normal_to_bond(u_cb, u_ab) return ModSemMaths.unit_vector_normal_to_bond(u_n, u_ab) @staticmethod def dot_product(u_pa, eig_ab): return sum(u_pa[i] * eig_ab[i].conjugate() for i in range(3)) @staticmethod def force_constant_bond(bond, eigenvals, eigenvecs, coords): """Force Constant - Equation 10 of Seminario paper - gives force constant for bond.""" atom_a, atom_b = bond eigenvals_ab = eigenvals[atom_a, atom_b, :] eigenvecs_ab = eigenvecs[:, :, atom_a, atom_b] unit_vectors_ab = ModSemMaths.unit_vector_along_bond(coords, bond) return -0.5 * sum(eigenvals_ab[i] * abs(np.dot(unit_vectors_ab, eigenvecs_ab[:, i])) for i in range(3)) @staticmethod def force_constant_angle(angle, bond_lens, eigenvals, eigenvecs, coords, scalings): """ Force Constant - Equation 14 of Seminario paper - gives force constant for angle (in kcal/mol/rad^2) and equilibrium angle (in degrees). """ atom_a, atom_b, atom_c = angle u_ab = ModSemMaths.unit_vector_along_bond(coords, (atom_a, atom_b)) u_cb = ModSemMaths.unit_vector_along_bond(coords, (atom_c, atom_b)) bond_len_ab = bond_lens[atom_a, atom_b] eigenvals_ab = eigenvals[atom_a, atom_b, :] eigenvecs_ab = eigenvecs[:3, :3, atom_a, atom_b] bond_len_bc = bond_lens[atom_b, atom_c] eigenvals_cb = eigenvals[atom_c, atom_b, :] eigenvecs_cb = eigenvecs[:3, :3, atom_c, atom_b] # Normal vector to angle plane found u_n = ModSemMaths.unit_vector_normal_to_bond(u_cb, u_ab) # Angle is linear: if abs(np.linalg.norm(u_cb - u_ab)) < 0.01 or (1.99 < abs(np.linalg.norm(u_cb - u_ab)) < 2.01): # Scalings are set to 1. k_theta, theta_0 = ModSemMaths.f_c_a_special_case( u_ab, u_cb, [bond_len_ab, bond_len_bc], [eigenvals_ab, eigenvals_cb], [eigenvecs_ab, eigenvecs_cb]) else: u_pa = ModSemMaths.unit_vector_normal_to_bond(u_n, u_ab) u_pc = ModSemMaths.unit_vector_normal_to_bond(u_cb, u_n) # Scaling due to additional angles - Modified Seminario Part sum_first = sum(eigenvals_ab[i] * abs(ModSemMaths.dot_product(u_pa, eigenvecs_ab[:, i])) for i in range(3)) / scalings[0] sum_second = sum(eigenvals_cb[i] * abs(ModSemMaths.dot_product(u_pc, eigenvecs_cb[:, i])) for i in range(3)) / scalings[1] # Added as two springs in series k_theta = (1 / ((bond_len_ab ** 2) * sum_first)) + (1 / ((bond_len_bc ** 2) * sum_second)) k_theta = 1 / k_theta # Change to OPLS form k_theta = abs(k_theta * 0.5) # Equilibrium Angle theta_0 = np.degrees(np.arccos(np.dot(u_ab, u_cb))) return k_theta, theta_0 @staticmethod def f_c_a_special_case(u_ab, u_cb, bond_lens, eigenvals, eigenvecs): """ Force constant angle special case, for example nitrile groups. This is for when the bond is linear, and therefore cannot be sampled around in the same way. The perpendicular vector is not defined for a linear bond. """ # Number of samples around the bond. n_samples = 200 k_theta_array = np.zeros(n_samples) for theta in range(n_samples): u_n = [np.sin(theta) * np.cos(theta), np.sin(theta) * np.sin(theta), np.cos(theta)] u_pa = ModSemMaths.unit_vector_normal_to_bond(u_n, u_ab) u_pc = ModSemMaths.unit_vector_normal_to_bond(u_cb, u_n) sum_first = sum(eigenvals[0][i] * abs(ModSemMaths.dot_product(u_pa, eigenvecs[0][:, i])) for i in range(3)) sum_second = sum(eigenvals[1][i] * abs(ModSemMaths.dot_product(u_pc, eigenvecs[1][:, i])) for i in range(3)) k_theta_i = (1 / ((bond_lens[0] ** 2) * sum_first)) + (1 / ((bond_lens[1] ** 2) * sum_second)) k_theta_i = 1 / k_theta_i k_theta_array[theta] = abs(k_theta_i * 0.5) k_theta = np.average(k_theta_array) theta_0 = np.degrees(np.arccos(np.dot(u_ab, u_cb))) return k_theta, theta_0 @for_all_methods(timer_logger) class ModSeminario: def __init__(self, molecule): self.molecule = molecule self.size_mol = len(self.molecule.atoms) # Find bond lengths and create empty matrix of correct size. self.bond_lens = np.zeros((self.size_mol, self.size_mol)) self.coords = self.molecule.coords['qm'] def __repr__(self): return f'{self.__class__.__name__}({self.__dict__!r})' def modified_seminario_method(self): """ Calculate the new bond and angle terms after being passed the symmetric Hessian and optimised molecule coordinates. """ eigenvecs = np.empty((3, 3, self.size_mol, self.size_mol), dtype=complex) eigenvals = np.empty((self.size_mol, self.size_mol, 3), dtype=complex) for i in range(self.size_mol): for j in range(self.size_mol): diff_i_j = self.coords[i, :] - self.coords[j, :] self.bond_lens[i, j] = np.linalg.norm(diff_i_j) partial_hessian = self.molecule.hessian[(i * 3):((i + 1) * 3), (j * 3):((j + 1) * 3)] eigenvals[i, j, :], eigenvecs[:, :, i, j] = np.linalg.eig(partial_hessian) # The bond and angle values are calculated and written to file. self.calculate_bonds(eigenvals, eigenvecs) self.calculate_angles(eigenvals, eigenvecs) def calculate_angles(self, eigenvals, eigenvecs): """ Uses the modified Seminario method to find the angle parameters and prints them to file. """ # A structure is created with the index giving the central atom of the angle; # an array then lists the angles with that central atom. # e.g. central_atoms_angles[3] contains an array of angles with central atom 3. # Connectivity information for Modified Seminario Method central_atoms_angles = [] for coord in range(self.size_mol): central_atoms_angles.append([]) for count, angle in enumerate(self.molecule.angles): if coord == angle[1]: # For angle abc, atoms a, c are written to array central_atoms_angles[coord].append([angle[0], angle[2], count]) # For angle abc, atoms c a are written to array central_atoms_angles[coord].append([angle[2], angle[0], count]) # Sort rows by atom number for coord in range(self.size_mol): central_atoms_angles[coord] = sorted(central_atoms_angles[coord], key=itemgetter(0)) # Find normals u_pa for each angle unit_pa_all_angles = [] for i in range(len(central_atoms_angles)): unit_pa_all_angles.append([]) for j in range(len(central_atoms_angles[i])): # For the angle at central_atoms_angles[i][j,:] the u_pa value is found for plane abc and bond ab, # where abc corresponds to the order of the arguments. This is why the reverse order was also added. angle = central_atoms_angles[i][j][0], i, central_atoms_angles[i][j][1] unit_pa_all_angles[i].append(ModSemMaths.u_pa_from_angles(angle, self.coords)) # Finds the contributing factors from the other angle terms scaling_factor_all_angles = [] for i in range(len(central_atoms_angles)): scaling_factor_all_angles.append([]) for j in range(len(central_atoms_angles[i])): n = m = 1 angles_around = extra_contribs = 0 scaling_factor_all_angles[i].append([0, 0]) # Position in angle list scaling_factor_all_angles[i][j][1] = central_atoms_angles[i][j][2] # Goes through the list of angles with the same central atom, then computes the term needed for MSM. # Forwards direction, finds the same bonds with the central atom i while ((j + n) < len(central_atoms_angles[i])) and central_atoms_angles[i][j][0] == central_atoms_angles[i][j + n][0]: extra_contribs += (abs(np.dot(unit_pa_all_angles[i][j][:], unit_pa_all_angles[i][j + n][:]))) ** 2 n += 1 angles_around += 1 # Backwards direction, finds the same bonds with the central atom i while ((j - m) >= 0) and central_atoms_angles[i][j][0] == central_atoms_angles[i][j - m][0]: extra_contribs += (abs(np.dot(unit_pa_all_angles[i][j][:], unit_pa_all_angles[i][j - m][:]))) ** 2 m += 1 angles_around += 1 scaling_factor_all_angles[i][j][0] = 1 if n != 1 or m != 1: # Finds the mean value of the additional contribution scaling_factor_all_angles[i][j][0] += (extra_contribs / (m + n - 2)) scaling_factors_angles_list = [[]] * len(self.molecule.angles) # Orders the scaling factors according to the angle list for i in range(len(central_atoms_angles)): for j in range(len(central_atoms_angles[i])): scaling_factors_angles_list[scaling_factor_all_angles[i][j][1]].append(scaling_factor_all_angles[i][j][0]) k_theta, theta_0 = np.zeros(len(self.molecule.angles)), np.zeros(len(self.molecule.angles)) conversion = constants.KCAL_TO_KJ * 2 with open('Modified_Seminario_Angles.txt', f'{"w" if self.molecule.restart else "a+"}') as angle_file: for i, angle in enumerate(self.molecule.angles): scalings = scaling_factors_angles_list[i][:2] # Ensures that there is no difference when the ordering is changed. ab_k_theta, ab_theta_0 = ModSemMaths.force_constant_angle(angle, self.bond_lens, eigenvals, eigenvecs, self.coords, scalings) ba_k_theta, ba_theta_0 = ModSemMaths.force_constant_angle(angle[::-1], self.bond_lens, eigenvals, eigenvecs, self.coords, scalings[::-1]) # Vib_scaling takes into account DFT deficiencies / anharmonicity. k_theta[i] = ((ab_k_theta + ba_k_theta) / 2) * (self.molecule.vib_scaling ** 2) theta_0[i] = (ab_theta_0 + ba_theta_0) / 2 angle_file.write(f'{self.molecule.atoms[angle[0]].atom_name}-{self.molecule.atoms[angle[1]].atom_name}-{self.molecule.atoms[angle[2]].atom_name} ') angle_file.write(f'{k_theta[i]:.3f} {theta_0[i]:.3f} {angle[0]} {angle[1]} {angle[2]}\n') # Add ModSem values to ligand object. self.molecule.HarmonicAngleForce[angle] = [theta_0[i] * constants.DEG_TO_RAD, k_theta[i] * conversion] def calculate_bonds(self, eigenvals, eigenvecs): """ Uses the modified Seminario method to find the bond parameters and print them to file. """ bonds = self.molecule.topology.edges conversion = constants.KCAL_TO_KJ * 200 k_b, bond_len_list = np.zeros(len(bonds)), np.zeros(len(bonds)) with open('Modified_Seminario_Bonds.txt', f'{"w" if self.molecule.restart else "a+"}') as bond_file: for pos, bond in enumerate(bonds): ab = ModSemMaths.force_constant_bond(bond, eigenvals, eigenvecs, self.coords) ba = ModSemMaths.force_constant_bond(bond[::-1], eigenvals, eigenvecs, self.coords) # Order of bonds sometimes causes slight differences; find the mean and apply vib_scaling. k_b[pos] = np.real((ab + ba) / 2) * (self.molecule.vib_scaling ** 2) bond_len_list[pos] = self.bond_lens[bond] bond_file.write(f'{self.molecule.atoms[bond[0]].atom_name}-{self.molecule.atoms[bond[1]].atom_name} ') bond_file.write(f'{k_b[pos]:.3f} {bond_len_list[pos]:.3f} {bond[0]} {bond[1]}\n') # Add ModSem values to ligand object. self.molecule.HarmonicBondForce[bond] = [bond_len_list[pos] / 10, conversion * k_b[pos]] def symmetrise_bonded_parameters(self): """ Apply symmetry to the bonded parameters stored in the molecule based on types from rdkit. """ if (self.molecule.bond_types is None) or (not self.molecule.symmetry): return # Collect all of the bond values from the HarmonicBondForce dict for bonds in self.molecule.bond_types.values(): bond_lens, bond_forces = zip(*[self.molecule.HarmonicBondForce[bond] for bond in bonds]) # Average bond_lens, bond_forces = sum(bond_lens) / len(bond_lens), sum(bond_forces) / len(bond_forces) # Replace with averaged values for bond in bonds: self.molecule.HarmonicBondForce[bond] = [bond_lens, bond_forces] # Collect all of the angle values from the HarmonicAngleForce dict for angles in self.molecule.angle_types.values(): angle_vals, angle_forces = zip(*[self.molecule.HarmonicAngleForce[angle] for angle in angles]) # Average angle_vals, angle_forces = sum(angle_vals) / len(angle_vals), sum(angle_forces) / len(angle_forces) # Replace with averaged values for angle in angles: self.molecule.HarmonicAngleForce[angle] = [angle_vals, angle_forces]
[ "numpy.cross", "numpy.linalg.eig", "numpy.average", "numpy.real", "numpy.zeros", "numpy.dot", "numpy.empty", "numpy.cos", "numpy.linalg.norm", "numpy.sin", "operator.itemgetter", "QUBEKit.utils.decorators.for_all_methods" ]
[((5725, 5754), 'QUBEKit.utils.decorators.for_all_methods', 'for_all_methods', (['timer_logger'], {}), '(timer_logger)\n', (5740, 5754), False, 'from QUBEKit.utils.decorators import for_all_methods, timer_logger\n'), ((837, 857), 'numpy.cross', 'np.cross', (['u_bc', 'u_ab'], {}), '(u_bc, u_ab)\n', (845, 857), True, 'import numpy as np\n'), ((4843, 4862), 'numpy.zeros', 'np.zeros', (['n_samples'], {}), '(n_samples)\n', (4851, 4862), True, 'import numpy as np\n'), ((5603, 5628), 'numpy.average', 'np.average', (['k_theta_array'], {}), '(k_theta_array)\n', (5613, 5628), True, 'import numpy as np\n'), ((5987, 6027), 'numpy.zeros', 'np.zeros', (['(self.size_mol, self.size_mol)'], {}), '((self.size_mol, self.size_mol))\n', (5995, 6027), True, 'import numpy as np\n'), ((6384, 6445), 'numpy.empty', 'np.empty', (['(3, 3, self.size_mol, self.size_mol)'], {'dtype': 'complex'}), '((3, 3, self.size_mol, self.size_mol), dtype=complex)\n', (6392, 6445), True, 'import numpy as np\n'), ((6466, 6524), 'numpy.empty', 'np.empty', (['(self.size_mol, self.size_mol, 3)'], {'dtype': 'complex'}), '((self.size_mol, self.size_mol, 3), dtype=complex)\n', (6474, 6524), True, 'import numpy as np\n'), ((882, 903), 'numpy.linalg.norm', 'np.linalg.norm', (['cross'], {}), '(cross)\n', (896, 903), True, 'import numpy as np\n'), ((1131, 1154), 'numpy.linalg.norm', 'np.linalg.norm', (['diff_ab'], {}), '(diff_ab)\n', (1145, 1154), True, 'import numpy as np\n'), ((4985, 4998), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (4991, 4998), True, 'import numpy as np\n'), ((5668, 5686), 'numpy.dot', 'np.dot', (['u_ab', 'u_cb'], {}), '(u_ab, u_cb)\n', (5674, 5686), True, 'import numpy as np\n'), ((6712, 6736), 'numpy.linalg.norm', 'np.linalg.norm', (['diff_i_j'], {}), '(diff_i_j)\n', (6726, 6736), True, 'import numpy as np\n'), ((6901, 6931), 'numpy.linalg.eig', 'np.linalg.eig', (['partial_hessian'], {}), '(partial_hessian)\n', (6914, 6931), True, 'import numpy as np\n'), ((3204, 3231), 'numpy.linalg.norm', 'np.linalg.norm', (['(u_cb - u_ab)'], {}), '(u_cb - u_ab)\n', (3218, 3231), True, 'import numpy as np\n'), ((3255, 3282), 'numpy.linalg.norm', 'np.linalg.norm', (['(u_cb - u_ab)'], {}), '(u_cb - u_ab)\n', (3269, 3282), True, 'import numpy as np\n'), ((4340, 4358), 'numpy.dot', 'np.dot', (['u_ab', 'u_cb'], {}), '(u_ab, u_cb)\n', (4346, 4358), True, 'import numpy as np\n'), ((4923, 4936), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (4929, 4936), True, 'import numpy as np\n'), ((4939, 4952), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (4945, 4952), True, 'import numpy as np\n'), ((4954, 4967), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (4960, 4967), True, 'import numpy as np\n'), ((4970, 4983), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (4976, 4983), True, 'import numpy as np\n'), ((8282, 8295), 'operator.itemgetter', 'itemgetter', (['(0)'], {}), '(0)\n', (8292, 8295), False, 'from operator import itemgetter\n'), ((13282, 13304), 'numpy.real', 'np.real', (['((ab + ba) / 2)'], {}), '((ab + ba) / 2)\n', (13289, 13304), True, 'import numpy as np\n'), ((2193, 2236), 'numpy.dot', 'np.dot', (['unit_vectors_ab', 'eigenvecs_ab[:, i]'], {}), '(unit_vectors_ab, eigenvecs_ab[:, i])\n', (2199, 2236), True, 'import numpy as np\n'), ((9849, 9917), 'numpy.dot', 'np.dot', (['unit_pa_all_angles[i][j][:]', 'unit_pa_all_angles[i][j + n][:]'], {}), '(unit_pa_all_angles[i][j][:], unit_pa_all_angles[i][j + n][:])\n', (9855, 9917), True, 'import numpy as np\n'), ((10228, 10296), 'numpy.dot', 'np.dot', (['unit_pa_all_angles[i][j][:]', 'unit_pa_all_angles[i][j - m][:]'], {}), '(unit_pa_all_angles[i][j][:], unit_pa_all_angles[i][j - m][:])\n', (10234, 10296), True, 'import numpy as np\n')]
"""Utility functions for operating on geometry. See the :class:`Geometry3D` documentation for the core geometry class. .. versionadded:: 0.8.6 [functions moved here from :mod:`klampt.model.sensing`] Working with geometric primitives ================================= :func:`box` and :func:`sphere` are aliases for the functions in :mod:`klampt.model.create.primitives`. Working with point clouds ========================= :func:`point_cloud_normals` estimates normals from a normal-free :class:`PointCloud`. The :func:`fit_plane`, :func:`fit_plane3`, and :class:`PlaneFitter` class help with plane estimation. :func:`point_cloud_simplify` simplifies a PointCloud. :func:`point_cloud_colors` and :func:`point_cloud_set_colors` sets / gets colors from a PointCloud. """ from ..robotsim import Geometry3D,PointCloud import math from .create import primitives from ..math import vectorops,so3,se3 _has_numpy = False _tried_numpy_import = False np = None _has_scipy = False _tried_scipy_import = False sp = None box = primitives.box """Alias for :func:`klampt.model.create.primitives.box`""" sphere = primitives.sphere """Alias for :func:`klampt.model.create.primitives.sphere`""" def _try_numpy_import(): global _has_numpy,_tried_numpy_import global np if _tried_numpy_import: return _has_numpy _tried_numpy_import = True try: import numpy as np _has_numpy = True #sys.modules['numpy'] = numpy except ImportError: import warnings warnings.warn("klampt.model.geometry.py: numpy not available.",ImportWarning) _has_numpy = False return _has_numpy def _try_scipy_import(): global _has_scipy,_tried_scipy_import global sp if _tried_scipy_import: return _has_scipy _tried_scipy_import = True try: import scipy as sp _has_scipy = True #sys.modules['scipy'] = scipy except ImportError: import warnings warnings.warn("klampt.model.geometry.py: scipy not available.",ImportWarning) _has_scipy = False return _has_scipy class PlaneFitter: """ Online fitting of planes through 3D point clouds Attributes: normal (3-vector): best-fit normal centroid (3-vector): centroid of points count (int): # of points sse (float): fitting sum of squared errors cov (3x3 array): covariance of points """ def __init__(self,points=None): _try_numpy_import() if points is None: self.count = 0 self.centroid = np.zeros(3) self.cov = np.zeros((3,3)) self.normal = np.array([0,0,1]) self.sse = 0 else: self.count = len(points) self.centroid = np.average(points,axis=0) pprime = points - [self.centroid]*len(points) self.cov = np.dot(pprime.T,pprime)/self.count self._update_plane() def plane_equation(self): """Returns (a,b,c,d) with ax+by+cz+d=0 the plane equation""" offset = np.dot(self.centroid,self.normal) return (self.normal[0],self.normal[1],self.normal[2],-offset) def goodness_of_fit(self): """Returns corrected RMSE""" if self.count <= 3: return float('inf') return math.sqrt(self.sse*self.count / (self.count-3)) def add_point(self,pt): """Online estimation of best fit plane""" new_count = self.count + 1 new_centroid = self.centroid + (pt-self.centroid)/new_count old_sse = (self.cov + np.outer(self.centroid,self.centroid))*self.count new_sse = old_sse + np.outer(pt,pt) new_cov = new_sse/new_count - np.outer(new_centroid,new_centroid) self.count = new_count self.centroid = new_centroid self.cov = new_cov self._update_plane() def merge(self,fitter,inplace = False): """Online merging of two plane fitters. If inplace = False, returns a new PlaneFitter. If inplace = True, self is updated with the result. """ if not inplace: res = PlaneFitter() else: res = self new_count = self.count + fitter.count old_sum = self.centroid*self.count new_sum = old_sum + fitter.centroid*fitter.count new_centroid = new_sum/new_count old_sse = (self.cov + np.outer(self.centroid,self.centroid))*self.count fitter_sse = (fitter.cov + np.outer(fitter.centroid,fitter.centroid))*fitter.count new_sse = old_sse + fitter_sse new_cov = new_sse/new_count - np.outer(new_centroid,new_centroid) res.count = new_count res.centroid = new_centroid res.cov = new_cov res._update_plane() return res def distance(self,pt): """Returns the signed distance to this plane""" return np.dot(self.normal,pt)-np.dot(self.normal,self.centroid) def _update_plane(self): w,v = np.linalg.eig(self.cov) index = np.argmin(w) self.normal = v[:,index] self.sse = self.count * np.dot(self.normal,np.dot(self.cov,self.normal)) def point_cloud_simplify(pc,radius): """Simplifies a point cloud by averaging points within neighborhoods. Uses a fast hash grid data structure. Args: pc (Geometry3D or PointCloud): the point cloud radius (float): the neighborhood radius. """ if radius <= 0: raise ValueError("radius must be > 0") if isinstance(pc,Geometry3D): assert pc.type() == 'PointCloud',"Must provide a point cloud to point_cloud_simplify" return pc.convert('PointCloud',radius) else: return Geometry3D(pc).convert('PointCloud',radius).getPointCloud() def point_cloud_normals(pc,estimation_radius=None,estimation_knn=None,estimation_viewpoint=None,add=True): """Returns the normals of the point cloud. If pc has the standard ``normal_x, normal_y, normal_z`` properties, these will be returned. Otherwise, they will be estimated using plane fitting. The plane fitting method uses scipy nearest neighbor detection if scipy is available. Otherwise it uses a spatial grid. The process is as follows: - If ``estimation_radius`` is provided, then it will use neighbors within this range. For a spatial grid, this is the grid size. - If ``estimation_knn`` is provided, then planes will be fit to these number of neighbors. - If neither is provided, then estimation_radius is set to 3 * max dimension of the point cloud / sqrt(N). - If not enough points are within a neighborhood (either 4 or ``estimation_knn``, whichever is larger), then the normal is set to 0. - If ``estimation_viewpoint`` is provided, this must be a 3-list. The normals are oriented such that they point toward the viewpoint. Returns: A list of N 3-lists, or an N x 3 numpy array if numpy is available. If ``add=True``, estimated normals will be added to the point cloud under the ``normal_x, normal_y, normal_z`` properties. """ geom = None if isinstance(pc,Geometry3D): assert pc.type() == 'PointCloud',"Must provide a point cloud to point_cloud_normals" geom = pc pc = pc.getPointCloud() assert isinstance(pc,PointCloud) inds = [-1,-1,-1] props = ['normal_x','normal_y','normal_z'] for i in range(pc.numProperties()): try: ind = props.index(pc.propertyNames[i]) inds[ind] = i except ValueError: pass if all(i>=0 for i in inds): #has the properties! normal_x = pc.getProperties(inds[0]) normal_y = pc.getProperties(inds[1]) normal_z = pc.getProperties(inds[2]) if _has_numpy: return np.array([normal_x,normal_y,normal_z]).T else: return list(zip(normal_x,normal_y,normal_z)) if not all(i < 0 for i in inds): raise ValueError("Point cloud has some normal components but not all of them?") #need to estimate normals _try_numpy_import() _try_scipy_import() N = len(pc.vertices)//3 if not _has_numpy: raise RuntimeError("Need numpy to perform plane fitting") positions = np.array(pc.vertices) positions = positions.reshape((N,3)) if estimation_radius is None and estimation_knn is None: R = max(positions.max(axis=0)-positions.min(axis=0)) estimation_radius = 3*R/math.sqrt(N) if estimation_knn is None or estimation_knn < 4: estimation_knn = 4 normals = [] if _has_scipy: import scipy.spatial tree = scipy.spatial.cKDTree(positions) if estimation_radius is not None: neighbors = tree.query_ball_point(positions,estimation_radius) for n in neighbors: if len(n) < estimation_knn: normals.append([0,0,0]) else: #fit a plane to neighbors normals.append(fit_plane([positions[i] for i in n])[:3]) else: d,neighbors = tree.query(positions,estimation_knn) for n in neighbors: normals.append(fit_plane([positions[i] for i in n])[:3]) else: if estimation_radius is None: raise ValueError("Without scipy, can't do a k-NN plane estimation") #do a spatial hash normals = np.zeros((N,3)) indices = (positions * (1.0/estimation_radius)).astype(int) from collections import defaultdict pt_hash = defaultdict(list) for i,(ind,p) in enumerate(zip(indices,positions)): pt_hash[ind].append((i,p)) successful = 0 for (ind,iplist) in pt_hash.items(): if len(iplist) < estimation_knn: pass else: pindices = [ip[0] for ip in iplist] pts = [ip[1] for ip in iplist] n = fit_plane(pts)[:3] normals[pindices,:] = n successful += len(pindices) normals = np.asarray(normals) if estimation_viewpoint is not None: #flip back-facing normals disp = positions - estimation_viewpoint for i,(n,d) in enumerate(zip(normals,disp)): if np.dot(n,d) < 0: normals[i,:] = -n else: #flip back-facing normals assuming centroid is interior centroid = np.average(positions,axis=0) for i,(n,p) in enumerate(zip(normals,positions)): if np.dot(n,p-centroid) < 0: normals[i,:] = -n if add: normal_x = normals[:,0].tolist() normal_y = normals[:,1].tolist() normal_z = normals[:,2].tolist() pc.addProperty('normal_x',normal_x) pc.addProperty('normal_y',normal_y) pc.addProperty('normal_z',normal_z) if geom is not None: geom.setPointCloud(pc) return normals def fit_plane3(point1,point2,point3): """Returns a 3D plane equation fitting the 3 points. The result is (a,b,c,d) with the plane equation ax+by+cz+d=0 """ _try_numpy_import() normal = np.cross(point2-point1,point3-point1) nlen = np.linalg.norm(normal) if nlen < 1e-4: #degenerate raise ValueError("Points are degenerate") normal = normal / nlen offset = -np.dot(normal,point1) return (normal[0],normal[1],normal[2],offset) def fit_plane(points): """Returns a 3D plane equation that is a least squares fit through the points (len(points) >= 3).""" centroid,normal = fit_plane_centroid(points) return normal[0],normal[1],normal[2],-vectorops.dot(centroid,normal) def fit_plane_centroid(points): """Similar to :func:`fit_plane`, but returns a (centroid,normal) pair.""" if len(points)<3: raise ValueError("Need to have at least 3 points to fit a plane") #if len(points)==3: # return fit_plane3(points[0],points[1],points[2]) _try_numpy_import() points = np.asarray(points) centroid = np.average(points,axis=0) U,W,Vt = np.linalg.svd(points-[centroid]*len(points),full_matrices=False) if np.sum(W<1e-6) > 1: raise ValueError("Point set is degenerate") normal = Vt[2,:] return centroid.tolist(),normal.tolist() def _color_format_from_uint8_channels(format,r,g,b,a=None): import numpy as np if a is None: a = 0xff if format == 'rgb': return np.bitwise_or.reduce((np.left_shift(r,16),np.left_shift(g,8),b)).tolist() elif format == 'bgr': return np.bitwise_or.reduce((np.left_shift(b,16),np.left_shift(g,8),r)).tolist() elif format=='rgba': return np.bitwise_or.reduce((np.left_shift(r,24),np.left_shift(g,16),np.left_shift(b,8),a)).tolist() elif format=='bgra': return np.bitwise_or.reduce((np.left_shift(g,24),np.left_shift(g,16),np.left_shift(r,8),a)).tolist() elif format=='argb': return np.bitwise_or.reduce((np.left_shift(a,24),np.left_shift(r,16),np.left_shift(g,8),b)).tolist() elif format=='abgr': return np.bitwise_or.reduce((np.left_shift(a,24),np.left_shift(b,16),np.left_shift(g,8),r)).tolist() elif format=='channels': one_255 = 1.0/255.0 if not hasattr(a,'__iter__'): return (r*one_255).tolist(),(g*one_255).tolist(),(b*one_255).tolist() else: return (r*one_255).tolist(),(g*one_255).tolist(),(b*one_255).tolist(),(a*one_255).tolist() elif format=='opacity': one_255 = 1.0/255.0 if not hasattr(a,'__iter__'): return np.ones(len(r)) return (a*one_255).tolist() elif tuple(format)==('r','g','b'): one_255 = 1.0/255.0 return np.column_stack((r*one_255,g*one_255,b*one_255)).tolist() elif tuple(format)==('r','g','b','a'): one_255 = 1.0/255.0 if not hasattr(a,'__iter__'): a = np.full(len(r),a) return np.column_stack((r*one_255,g*one_255,b*one_255,a*one_255)).tolist() else: raise ValueError("Invalid format specifier "+str(format)) def _color_format_to_uint8_channels(format,colors): import numpy as np if format=='channels': return tuple((np.asarray(c)*255).astype(np.uint8).tolist() for c in colors) colors = np.asarray(colors) if format == 'rgb': r,g,b = np.right_shift(np.bitwise_and(colors,0xff0000),16),np.right_shift(np.bitwise_and(colors,0xff00),8),np.bitwise_and(colors,0xff) return r.tolist(),g.tolist(),b.tolist() elif format == 'bgr': b,g,r = np.right_shift(np.bitwise_and(colors,0xff0000),16),np.right_shift(np.bitwise_and(colors,0xff00),8),np.bitwise_and(colors,0xff) return r.tolist(),g.tolist(),b.tolist() elif format=='rgba': r,g,b,a = np.right_shift(np.bitwise_and(colors,0xff000000),24),np.right_shift(np.bitwise_and(colors,0xff0000),16),np.right_shift(np.bitwise_and(colors,0xff00),8),np.bitwise_and(colors,0xff) return r.tolist(),g.tolist(),b.tolist(),a.tolist() elif format=='bgra': b,g,r,a = np.right_shift(np.bitwise_and(colors,0xff000000),24),np.right_shift(np.bitwise_and(colors,0xff0000),16),np.right_shift(np.bitwise_and(colors,0xff00),8),np.bitwise_and(colors,0xff) return r.tolist(),g.tolist(),b.tolist(),a.tolist() elif format=='argb': a,r,g,b = np.right_shift(np.bitwise_and(colors,0xff000000),24),np.right_shift(np.bitwise_and(colors,0xff0000),16),np.right_shift(np.bitwise_and(colors,0xff00),8),np.bitwise_and(colors,0xff) return r.tolist(),g.tolist(),b.tolist(),a.tolist() elif format=='abgr': a,b,g,r = np.right_shift(np.bitwise_and(colors,0xff000000),24),np.right_shift(np.bitwise_and(colors,0xff0000),16),np.right_shift(np.bitwise_and(colors,0xff00),8),np.bitwise_and(colors,0xff) return r.tolist(),g.tolist(),b.tolist(),a.tolist() elif format=='opacity': r = [0xff]*len(colors) return r,r,r,(colors*255).astype(np.uint8).tolist() elif tuple(format)==('r','g','b'): colors = (colors*255).astype(np.uint8) r = colors[:,0] g = colors[:,1] b = colors[:,2] return r.tolist(),g.tolist(),b.tolist() elif tuple(format)==('r','g','b','a'): colors = (colors*255).astype(np.uint8) r = colors[:,0] g = colors[:,1] b = colors[:,2] a = colors[:,3] return r.tolist(),g.tolist(),b.tolist(),a.tolist() else: raise ValueError("Invalid format specifier "+str(format)) def point_cloud_colors(pc,format='rgb'): """Returns the colors of the point cloud in the given format. If the point cloud has no colors, this returns None. If the point cloud has no colors but has opacity, this returns white colors. Args: pc (PointCloud): the point cloud format: describes the output color format, either: - 'rgb': packed 24bit int, with the hex format 0xrrggbb, - 'bgr': packed 24bit int, with the hex format 0xbbggrr, - 'rgba': packed 32bit int, with the hex format 0xrrggbbaa, - 'bgra': packed 32bit int, with the hex format 0xbbggrraa, - 'argb': packed 32bit int, with the hex format 0xaarrggbb, - 'abgr': packed 32bit int, with the hex format 0xaabbggrr, - ('r','g','b'): triple with each channel in range [0,1] - ('r','g','b','a'): tuple with each channel in range [0,1] - 'channels': returns a list of channels, in the form (r,g,b) or (r,g,b,a), where each value in the channel has range [0,1]. - 'opacity': returns opacity only, in the range [0,1]. Returns: list: A list of pc.numPoints() colors corresponding to the points in the point cloud. If format='channels', the return value is a tuple (r,g,b) or (r,g,b,a). """ rgbchannels = [] alphachannel = None for i,prop in enumerate(pc.propertyNames): if prop in ['r','g','b','rgb']: rgbchannels.append((prop,i)) elif prop == 'rgba': rgbchannels.append((prop,i)) if alphachannel is not None: alphachannel = (prop,i) elif prop in ['opacity','a','c']: if alphachannel is not None: alphachannel = (prop,i) if len(rgbchannels)==0 and alphachannel is None: return if len(rgbchannels)==1: rgb = pc.getProperties(rgbchannels[0][1]) if format == rgbchannels[0][0]: return rgb import numpy as np rgb = np.array(rgb,dtype=int) r = np.right_shift(np.bitwise_and(rgb,0xff0000),16) g = np.right_shift(np.bitwise_and(rgb,0xff00),8) b = np.bitwise_and(rgb,0xff) if alphachannel is not None: #rgba if alphachannel[0] == 'rgba': a = np.right_shift(np.bitwise_and(rgb,0xff000000),24) elif alphachannel[0] == 'opacity': a = pc.getProperties(alphachannel[0][1]) a = (np.array(a)*255).astype(np.uint32) elif alphachannel[0] == 'c': a = pc.getProperties(alphachannel[0][1]) else: raise ValueError("Weird type of alpha channel? "+alphachannel[0]) return _color_format_from_uint8_channels(format,r,g,b,a) else: return _color_format_from_uint8_channels(format,r,g,b) elif len(rgbchannels) == 3: r=None g=None b=None for (name,index) in rgbchannels: if name=='r': r = pc.getProperties(index) elif name=='g': g = pc.getProperties(index) elif name=='b': b = pc.getProperties(index) else: raise ValueError("Strange, have some subset of r,g,b and other channels in point cloud? "+name) if r is None or g is None or b is None: raise ValueError("Strange, point cloud has some weird subset of r,g,b channels? "+','.join(v[0] for v in rgbchannels)) if alphachannel is None: a = 1.0 elif alphachannel[0] == 'opacity': a = pc.getProperties(alphachannel[0][1]) elif alphachannel[0] == 'c': import numpy as np one_255 = 1.0/255.0 a = (np.array(pc.getProperties(alphachannel[0][1]))*one_255).tolist() else: raise ValueError("Weird type of alpha channel? "+alphachannel[0]) if format=='channels': if alphachannel is None: return r,g,b else: return r,g,b,a elif isinstance(format,(list,tuple)) and tuple(format)==('r','g','b'): return list(zip(r,g,b)) elif isinstance(format,(list,tuple)) and tuple(format)==('r','g','b','a'): if alphachannel is None: a = [1.0]*pc.numPoints() return list(zip(r,g,b,a)) import numpy as np r = (np.array(r)*255.0).astype(np.uint32) g = (np.array(g)*255.0).astype(np.uint32) b = (np.array(b)*255.0).astype(np.uint32) if alphachannel is not None: a = (np.array(a)*255.0).astype(np.uint32) return _color_format_from_uint8_channels(format,r,g,b,a) else: return _color_format_from_uint8_channels(format,r,g,b) elif len(rgbchannels)==0 and alphachannel is not None: if alphachannel[0] == 'opacity': import numpy as np a = pc.getProperties(alphachannel[0][1]) a = (np.array(a)*255).astype(np.uint32) elif alphachannel[0] == 'c': import numpy as np a = pc.getProperties(alphachannel[0][1]) else: raise ValueError("Weird type of alpha channel? "+alphachannel[0]) r = [0xff]*pc.numPoints() return _color_format_from_uint8_channels(format,r,r,r,a) else: raise ValueError("Invalid colors in point cloud? found "+str(len(rgbchannels))+" color channels") def point_cloud_set_colors(pc,colors,color_format='rgb',pc_property='auto'): """Sets the colors of a point cloud. Args: pc (PointCloud): the point cloud colors (list): the list of colors, which can be either ints, tuples, or channels, depending on color_format. color_format: describes the format of each element of ``colors``, and can be: - 'rgb': packed 24bit int, with the hex format 0xrrggbb, - 'bgr': packed 24bit int, with the hex format 0xbbggrr, - 'rgba': packed 32bit int, with the hex format 0xrrggbbaa, - 'bgra': packed 32bit int, with the hex format 0xbbggrraa, - 'argb': packed 32bit int, with the hex format 0xaarrggbb, - 'abgr': packed 32bit int, with the hex format 0xaabbggrr, - ('r','g','b'): triple with each channel in range [0,1] - ('r','g','b','a'): tuple with each channel in range [0,1] - 'channels': ``colors`` is a list of channels, in the form (r,g,b) or (r,g,b,a), where each value in the channel has range [0,1]. - 'opacity': opacity only, in the range [0,1]. pc_property (str): describes to which property the colors should be set. 'auto' determines chooses the property from the point cloud if it's already colored, or color_format if not. 'channels' sets the 'r', 'g', 'b', and optionally 'a' properties. Returns: None """ rgbchannels = [] alphachannel = None for i,prop in enumerate(pc.propertyNames): if prop in ['r','g','b','rgb']: rgbchannels.append((prop,i)) elif prop == 'rgba': rgbchannels.append((prop,i)) if alphachannel is not None: alphachannel = (prop,i) elif prop in ['opacity','a','c']: if alphachannel is not None: alphachannel = (prop,i) rgbdict = dict(rgbchannels) if pc_property == 'auto': if len(rgbchannels) == 0 and alphachannel is None: if color_format=='channels' or isinstance(color_format,(list,tuple)): pc_property = 'channels' else: if 'a' in color_format: pc_property = 'rgba' else: pc_property = 'rgb' elif len(rgbchannels) == 3: pc_property = 'channels' elif len(rgbchannels) == 1: if alphachannel is not None: pc_property = 'rgba' else: pc_property = rgbchannels[0][0] if color_format == pc_property: if color_format == 'channels': assert len(colors)==3 or len(colors)==4,'Channels must give a 3-tuple or 4-tuple' for c,values in zip('rgb',colors): if c in rgbdict: pc.setProperties(rgbdict[c],values) else: pc.addProperty(c,values) if len(colors)==4: if alphachannel[0] == 'a': pc.setProperties(alphachannel[1],colors[3]) else: pc.addProperty('a',colors[3]) else: if color_format in rgbdict: pc.setProperties(rgbdict[color_format],colors) else: pc.addProperty(color_format,colors) else: channels = _color_format_to_uint8_channels(color_format,colors) packed = _color_format_from_uint8_channels(pc_property,*channels) if pc_property in rgbdict: pc.setProperties(rgbdict[pc_property],packed) elif alphachannel is not None and pc_property == alphachannel[0]: pc.setProperties(alphachannel[1],packed) else: pc.addProperty(pc_property,packed)
[ "numpy.cross", "numpy.linalg.eig", "numpy.average", "numpy.left_shift", "numpy.asarray", "math.sqrt", "numpy.column_stack", "numpy.bitwise_and", "numpy.array", "numpy.dot", "numpy.zeros", "collections.defaultdict", "numpy.sum", "numpy.outer", "numpy.linalg.norm", "numpy.argmin", "war...
[((8307, 8328), 'numpy.array', 'np.array', (['pc.vertices'], {}), '(pc.vertices)\n', (8315, 8328), True, 'import numpy as np\n'), ((10118, 10137), 'numpy.asarray', 'np.asarray', (['normals'], {}), '(normals)\n', (10128, 10137), True, 'import numpy as np\n'), ((11197, 11239), 'numpy.cross', 'np.cross', (['(point2 - point1)', '(point3 - point1)'], {}), '(point2 - point1, point3 - point1)\n', (11205, 11239), True, 'import numpy as np\n'), ((11246, 11268), 'numpy.linalg.norm', 'np.linalg.norm', (['normal'], {}), '(normal)\n', (11260, 11268), True, 'import numpy as np\n'), ((12055, 12073), 'numpy.asarray', 'np.asarray', (['points'], {}), '(points)\n', (12065, 12073), True, 'import numpy as np\n'), ((12089, 12115), 'numpy.average', 'np.average', (['points'], {'axis': '(0)'}), '(points, axis=0)\n', (12099, 12115), True, 'import numpy as np\n'), ((14324, 14342), 'numpy.asarray', 'np.asarray', (['colors'], {}), '(colors)\n', (14334, 14342), True, 'import numpy as np\n'), ((3065, 3099), 'numpy.dot', 'np.dot', (['self.centroid', 'self.normal'], {}), '(self.centroid, self.normal)\n', (3071, 3099), True, 'import numpy as np\n'), ((3316, 3367), 'math.sqrt', 'math.sqrt', (['(self.sse * self.count / (self.count - 3))'], {}), '(self.sse * self.count / (self.count - 3))\n', (3325, 3367), False, 'import math\n'), ((5010, 5033), 'numpy.linalg.eig', 'np.linalg.eig', (['self.cov'], {}), '(self.cov)\n', (5023, 5033), True, 'import numpy as np\n'), ((5050, 5062), 'numpy.argmin', 'np.argmin', (['w'], {}), '(w)\n', (5059, 5062), True, 'import numpy as np\n'), ((9467, 9483), 'numpy.zeros', 'np.zeros', (['(N, 3)'], {}), '((N, 3))\n', (9475, 9483), True, 'import numpy as np\n'), ((9613, 9630), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (9624, 9630), False, 'from collections import defaultdict\n'), ((10474, 10503), 'numpy.average', 'np.average', (['positions'], {'axis': '(0)'}), '(positions, axis=0)\n', (10484, 10503), True, 'import numpy as np\n'), ((11400, 11422), 'numpy.dot', 'np.dot', (['normal', 'point1'], {}), '(normal, point1)\n', (11406, 11422), True, 'import numpy as np\n'), ((12200, 12217), 'numpy.sum', 'np.sum', (['(W < 1e-06)'], {}), '(W < 1e-06)\n', (12206, 12217), True, 'import numpy as np\n'), ((18608, 18632), 'numpy.array', 'np.array', (['rgb'], {'dtype': 'int'}), '(rgb, dtype=int)\n', (18616, 18632), True, 'import numpy as np\n'), ((18761, 18785), 'numpy.bitwise_and', 'np.bitwise_and', (['rgb', '(255)'], {}), '(rgb, 255)\n', (18775, 18785), True, 'import numpy as np\n'), ((1518, 1596), 'warnings.warn', 'warnings.warn', (['"""klampt.model.geometry.py: numpy not available."""', 'ImportWarning'], {}), "('klampt.model.geometry.py: numpy not available.', ImportWarning)\n", (1531, 1596), False, 'import warnings\n'), ((1968, 2046), 'warnings.warn', 'warnings.warn', (['"""klampt.model.geometry.py: scipy not available."""', 'ImportWarning'], {}), "('klampt.model.geometry.py: scipy not available.', ImportWarning)\n", (1981, 2046), False, 'import warnings\n'), ((2571, 2582), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (2579, 2582), True, 'import numpy as np\n'), ((2606, 2622), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {}), '((3, 3))\n', (2614, 2622), True, 'import numpy as np\n'), ((2648, 2667), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (2656, 2667), True, 'import numpy as np\n'), ((2770, 2796), 'numpy.average', 'np.average', (['points'], {'axis': '(0)'}), '(points, axis=0)\n', (2780, 2796), True, 'import numpy as np\n'), ((3657, 3673), 'numpy.outer', 'np.outer', (['pt', 'pt'], {}), '(pt, pt)\n', (3665, 3673), True, 'import numpy as np\n'), ((3711, 3747), 'numpy.outer', 'np.outer', (['new_centroid', 'new_centroid'], {}), '(new_centroid, new_centroid)\n', (3719, 3747), True, 'import numpy as np\n'), ((4631, 4667), 'numpy.outer', 'np.outer', (['new_centroid', 'new_centroid'], {}), '(new_centroid, new_centroid)\n', (4639, 4667), True, 'import numpy as np\n'), ((4908, 4931), 'numpy.dot', 'np.dot', (['self.normal', 'pt'], {}), '(self.normal, pt)\n', (4914, 4931), True, 'import numpy as np\n'), ((4931, 4965), 'numpy.dot', 'np.dot', (['self.normal', 'self.centroid'], {}), '(self.normal, self.centroid)\n', (4937, 4965), True, 'import numpy as np\n'), ((8524, 8536), 'math.sqrt', 'math.sqrt', (['N'], {}), '(N)\n', (8533, 8536), False, 'import math\n'), ((14482, 14509), 'numpy.bitwise_and', 'np.bitwise_and', (['colors', '(255)'], {}), '(colors, 255)\n', (14496, 14509), True, 'import numpy as np\n'), ((18659, 18688), 'numpy.bitwise_and', 'np.bitwise_and', (['rgb', '(16711680)'], {}), '(rgb, 16711680)\n', (18673, 18688), True, 'import numpy as np\n'), ((18719, 18745), 'numpy.bitwise_and', 'np.bitwise_and', (['rgb', '(65280)'], {}), '(rgb, 65280)\n', (18733, 18745), True, 'import numpy as np\n'), ((2877, 2901), 'numpy.dot', 'np.dot', (['pprime.T', 'pprime'], {}), '(pprime.T, pprime)\n', (2883, 2901), True, 'import numpy as np\n'), ((3579, 3617), 'numpy.outer', 'np.outer', (['self.centroid', 'self.centroid'], {}), '(self.centroid, self.centroid)\n', (3587, 3617), True, 'import numpy as np\n'), ((4413, 4451), 'numpy.outer', 'np.outer', (['self.centroid', 'self.centroid'], {}), '(self.centroid, self.centroid)\n', (4421, 4451), True, 'import numpy as np\n'), ((4498, 4540), 'numpy.outer', 'np.outer', (['fitter.centroid', 'fitter.centroid'], {}), '(fitter.centroid, fitter.centroid)\n', (4506, 4540), True, 'import numpy as np\n'), ((5147, 5176), 'numpy.dot', 'np.dot', (['self.cov', 'self.normal'], {}), '(self.cov, self.normal)\n', (5153, 5176), True, 'import numpy as np\n'), ((7858, 7898), 'numpy.array', 'np.array', (['[normal_x, normal_y, normal_z]'], {}), '([normal_x, normal_y, normal_z])\n', (7866, 7898), True, 'import numpy as np\n'), ((10330, 10342), 'numpy.dot', 'np.dot', (['n', 'd'], {}), '(n, d)\n', (10336, 10342), True, 'import numpy as np\n'), ((10576, 10599), 'numpy.dot', 'np.dot', (['n', '(p - centroid)'], {}), '(n, p - centroid)\n', (10582, 10599), True, 'import numpy as np\n'), ((14398, 14430), 'numpy.bitwise_and', 'np.bitwise_and', (['colors', '(16711680)'], {}), '(colors, 16711680)\n', (14412, 14430), True, 'import numpy as np\n'), ((14449, 14478), 'numpy.bitwise_and', 'np.bitwise_and', (['colors', '(65280)'], {}), '(colors, 65280)\n', (14463, 14478), True, 'import numpy as np\n'), ((14699, 14726), 'numpy.bitwise_and', 'np.bitwise_and', (['colors', '(255)'], {}), '(colors, 255)\n', (14713, 14726), True, 'import numpy as np\n'), ((14615, 14647), 'numpy.bitwise_and', 'np.bitwise_and', (['colors', '(16711680)'], {}), '(colors, 16711680)\n', (14629, 14647), True, 'import numpy as np\n'), ((14666, 14695), 'numpy.bitwise_and', 'np.bitwise_and', (['colors', '(65280)'], {}), '(colors, 65280)\n', (14680, 14695), True, 'import numpy as np\n'), ((14970, 14997), 'numpy.bitwise_and', 'np.bitwise_and', (['colors', '(255)'], {}), '(colors, 255)\n', (14984, 14997), True, 'import numpy as np\n'), ((18907, 18938), 'numpy.bitwise_and', 'np.bitwise_and', (['rgb', '(4278190080)'], {}), '(rgb, 4278190080)\n', (18921, 18938), True, 'import numpy as np\n'), ((12519, 12539), 'numpy.left_shift', 'np.left_shift', (['r', '(16)'], {}), '(r, 16)\n', (12532, 12539), True, 'import numpy as np\n'), ((12539, 12558), 'numpy.left_shift', 'np.left_shift', (['g', '(8)'], {}), '(g, 8)\n', (12552, 12558), True, 'import numpy as np\n'), ((14833, 14867), 'numpy.bitwise_and', 'np.bitwise_and', (['colors', '(4278190080)'], {}), '(colors, 4278190080)\n', (14847, 14867), True, 'import numpy as np\n'), ((14886, 14918), 'numpy.bitwise_and', 'np.bitwise_and', (['colors', '(16711680)'], {}), '(colors, 16711680)\n', (14900, 14918), True, 'import numpy as np\n'), ((14937, 14966), 'numpy.bitwise_and', 'np.bitwise_and', (['colors', '(65280)'], {}), '(colors, 65280)\n', (14951, 14966), True, 'import numpy as np\n'), ((15252, 15279), 'numpy.bitwise_and', 'np.bitwise_and', (['colors', '(255)'], {}), '(colors, 255)\n', (15266, 15279), True, 'import numpy as np\n'), ((21023, 21034), 'numpy.array', 'np.array', (['r'], {}), '(r)\n', (21031, 21034), True, 'import numpy as np\n'), ((21073, 21084), 'numpy.array', 'np.array', (['g'], {}), '(g)\n', (21081, 21084), True, 'import numpy as np\n'), ((21123, 21134), 'numpy.array', 'np.array', (['b'], {}), '(b)\n', (21131, 21134), True, 'import numpy as np\n'), ((12634, 12654), 'numpy.left_shift', 'np.left_shift', (['b', '(16)'], {}), '(b, 16)\n', (12647, 12654), True, 'import numpy as np\n'), ((12654, 12673), 'numpy.left_shift', 'np.left_shift', (['g', '(8)'], {}), '(g, 8)\n', (12667, 12673), True, 'import numpy as np\n'), ((15115, 15149), 'numpy.bitwise_and', 'np.bitwise_and', (['colors', '(4278190080)'], {}), '(colors, 4278190080)\n', (15129, 15149), True, 'import numpy as np\n'), ((15168, 15200), 'numpy.bitwise_and', 'np.bitwise_and', (['colors', '(16711680)'], {}), '(colors, 16711680)\n', (15182, 15200), True, 'import numpy as np\n'), ((15219, 15248), 'numpy.bitwise_and', 'np.bitwise_and', (['colors', '(65280)'], {}), '(colors, 65280)\n', (15233, 15248), True, 'import numpy as np\n'), ((15534, 15561), 'numpy.bitwise_and', 'np.bitwise_and', (['colors', '(255)'], {}), '(colors, 255)\n', (15548, 15561), True, 'import numpy as np\n'), ((21214, 21225), 'numpy.array', 'np.array', (['a'], {}), '(a)\n', (21222, 21225), True, 'import numpy as np\n'), ((12748, 12768), 'numpy.left_shift', 'np.left_shift', (['r', '(24)'], {}), '(r, 24)\n', (12761, 12768), True, 'import numpy as np\n'), ((12768, 12788), 'numpy.left_shift', 'np.left_shift', (['g', '(16)'], {}), '(g, 16)\n', (12781, 12788), True, 'import numpy as np\n'), ((12788, 12807), 'numpy.left_shift', 'np.left_shift', (['b', '(8)'], {}), '(b, 8)\n', (12801, 12807), True, 'import numpy as np\n'), ((15397, 15431), 'numpy.bitwise_and', 'np.bitwise_and', (['colors', '(4278190080)'], {}), '(colors, 4278190080)\n', (15411, 15431), True, 'import numpy as np\n'), ((15450, 15482), 'numpy.bitwise_and', 'np.bitwise_and', (['colors', '(16711680)'], {}), '(colors, 16711680)\n', (15464, 15482), True, 'import numpy as np\n'), ((15501, 15530), 'numpy.bitwise_and', 'np.bitwise_and', (['colors', '(65280)'], {}), '(colors, 65280)\n', (15515, 15530), True, 'import numpy as np\n'), ((15816, 15843), 'numpy.bitwise_and', 'np.bitwise_and', (['colors', '(255)'], {}), '(colors, 255)\n', (15830, 15843), True, 'import numpy as np\n'), ((19067, 19078), 'numpy.array', 'np.array', (['a'], {}), '(a)\n', (19075, 19078), True, 'import numpy as np\n'), ((21602, 21613), 'numpy.array', 'np.array', (['a'], {}), '(a)\n', (21610, 21613), True, 'import numpy as np\n'), ((12882, 12902), 'numpy.left_shift', 'np.left_shift', (['g', '(24)'], {}), '(g, 24)\n', (12895, 12902), True, 'import numpy as np\n'), ((12902, 12922), 'numpy.left_shift', 'np.left_shift', (['g', '(16)'], {}), '(g, 16)\n', (12915, 12922), True, 'import numpy as np\n'), ((12922, 12941), 'numpy.left_shift', 'np.left_shift', (['r', '(8)'], {}), '(r, 8)\n', (12935, 12941), True, 'import numpy as np\n'), ((14249, 14262), 'numpy.asarray', 'np.asarray', (['c'], {}), '(c)\n', (14259, 14262), True, 'import numpy as np\n'), ((15679, 15713), 'numpy.bitwise_and', 'np.bitwise_and', (['colors', '(4278190080)'], {}), '(colors, 4278190080)\n', (15693, 15713), True, 'import numpy as np\n'), ((15732, 15764), 'numpy.bitwise_and', 'np.bitwise_and', (['colors', '(16711680)'], {}), '(colors, 16711680)\n', (15746, 15764), True, 'import numpy as np\n'), ((15783, 15812), 'numpy.bitwise_and', 'np.bitwise_and', (['colors', '(65280)'], {}), '(colors, 65280)\n', (15797, 15812), True, 'import numpy as np\n'), ((13016, 13036), 'numpy.left_shift', 'np.left_shift', (['a', '(24)'], {}), '(a, 24)\n', (13029, 13036), True, 'import numpy as np\n'), ((13036, 13056), 'numpy.left_shift', 'np.left_shift', (['r', '(16)'], {}), '(r, 16)\n', (13049, 13056), True, 'import numpy as np\n'), ((13056, 13075), 'numpy.left_shift', 'np.left_shift', (['g', '(8)'], {}), '(g, 8)\n', (13069, 13075), True, 'import numpy as np\n'), ((13150, 13170), 'numpy.left_shift', 'np.left_shift', (['a', '(24)'], {}), '(a, 24)\n', (13163, 13170), True, 'import numpy as np\n'), ((13170, 13190), 'numpy.left_shift', 'np.left_shift', (['b', '(16)'], {}), '(b, 16)\n', (13183, 13190), True, 'import numpy as np\n'), ((13190, 13209), 'numpy.left_shift', 'np.left_shift', (['g', '(8)'], {}), '(g, 8)\n', (13203, 13209), True, 'import numpy as np\n'), ((13763, 13819), 'numpy.column_stack', 'np.column_stack', (['(r * one_255, g * one_255, b * one_255)'], {}), '((r * one_255, g * one_255, b * one_255))\n', (13778, 13819), True, 'import numpy as np\n'), ((13979, 14048), 'numpy.column_stack', 'np.column_stack', (['(r * one_255, g * one_255, b * one_255, a * one_255)'], {}), '((r * one_255, g * one_255, b * one_255, a * one_255))\n', (13994, 14048), True, 'import numpy as np\n')]
import numpy as np from wrappa import WrappaObject, WrappaImage class DSModel: def __init__(self, **kwargs): pass def predict(self, data, **kwargs): _ = kwargs # Data is always an array of WrappaObjects responses = [] for obj in data: img = obj.image.as_ndarray rotated_img = np.rot90(img) resp = WrappaObject(WrappaImage.init_from_ndarray( payload=rotated_img, ext=obj.image.ext, )) responses.append(resp) return responses def predict_180(self, data, **kwargs): _ = kwargs # Data is always an array of WrappaObjects responses = [] for obj in data: img = obj.image.as_ndarray rotated_img = np.rot90(img) rotated_img = np.rot90(rotated_img) resp = WrappaObject(WrappaImage.init_from_ndarray( payload=rotated_img, ext=obj.image.ext, )) responses.append(resp) return responses
[ "wrappa.WrappaImage.init_from_ndarray", "numpy.rot90" ]
[((353, 366), 'numpy.rot90', 'np.rot90', (['img'], {}), '(img)\n', (361, 366), True, 'import numpy as np\n'), ((804, 817), 'numpy.rot90', 'np.rot90', (['img'], {}), '(img)\n', (812, 817), True, 'import numpy as np\n'), ((844, 865), 'numpy.rot90', 'np.rot90', (['rotated_img'], {}), '(rotated_img)\n', (852, 865), True, 'import numpy as np\n'), ((399, 468), 'wrappa.WrappaImage.init_from_ndarray', 'WrappaImage.init_from_ndarray', ([], {'payload': 'rotated_img', 'ext': 'obj.image.ext'}), '(payload=rotated_img, ext=obj.image.ext)\n', (428, 468), False, 'from wrappa import WrappaObject, WrappaImage\n'), ((898, 967), 'wrappa.WrappaImage.init_from_ndarray', 'WrappaImage.init_from_ndarray', ([], {'payload': 'rotated_img', 'ext': 'obj.image.ext'}), '(payload=rotated_img, ext=obj.image.ext)\n', (927, 967), False, 'from wrappa import WrappaObject, WrappaImage\n')]
""" This module defines some plotting functions that are used by the BALTO GUI app. It should be included in the same directory as "balto_gui.py" and the corresponding Jupyter notebook. """ #------------------------------------------------------------------------ # # Copyright (C) 2020. <NAME> # #------------------------------------------------------------------------ import matplotlib.pyplot as plt import numpy as np #------------------------------------------------------------------------ # # plot_data() # for x vs. y plots #----------------- # hist_equal() # power_stretch1() # power_stretch2() # power_stretch3() # log_stretch() # stretch_grid() # show_grid_as_image() (used for balto_gui.show_grid() method) # #------------------------------------------------------------------------ def plot_data( x, y, xmin=None, xmax=None, ymin=None, ymax=None, x_name='x', x_units='', marker=',', y_name='y', y_units='', x_size=8, y_size=4): figure = plt.figure(1, figsize=(x_size, y_size)) # fig, ax = plt.subplots( figsize=(x_size, y_size)) # Set the plot point marker # https://matplotlib.org/3.1.1/api/markers_api.html # marker = ',' # pixel # marker = '.' # point (small circle) # marker = 'o' # circle # marker = '+' # marker = 'x' #if (ymin is None): # ymin = y.min() #if (ymax is None): # ymax = y.max() #if (ymax - ymin < 0.1): # ymin = ymin - 0.5 # ymax = ymin + 0.5 # x_name2 = x_name.replace('_', ' ').title() # y_name2 = y_name.replace('_', ' ').title() plt.plot( x, y, marker=marker) plt.xlabel( x_name + ' [' + x_units + ']' ) plt.ylabel( y_name + ' [' + y_units + ']' ) plt.ylim( ymin, ymax ) plt.xlim( xmin, xmax ) #------------------------------------- # This may be necessary depending on # the data type of ymin, ymax #------------------------------------- ## plt.ylim( np.array([ymin, ymax]) ) ## plt.xlim( np.array([xmin, xmax]) ) plt.show() # plot_data() #------------------------------------------------------------------------ def histogram_equalize( grid, PLOT_NCS=False): # https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html (hist, bin_edges) = np.histogram( grid, bins=256) # hmin = hist.min() # hmax = hist.max() cs = hist.cumsum() ncs = (cs - cs.min()) / (cs.max() - cs.min()) ncs.astype('uint8'); ############## ncs.astype('uint8') # no semi-colon at end ?????????? if (PLOT_NCS): plt.plot( ncs ) flat = grid.flatten() flat2 = np.uint8( 255 * (flat - flat.min()) / (flat.max() - flat.min()) ) grid2 = ncs[ flat2 ].reshape( grid.shape ) return grid2 # histogram_equalize() #------------------------------------------------------------------------ def power_stretch1( grid, p ): return grid**p # power_stretch1() #------------------------------------------------------------------------ def power_stretch2( grid, a=1000, b=0.5): # Note: Try a=1000 and b=0.5 gmin = grid.min() gmax = grid.max() norm = (grid - gmin) / (gmax - gmin) return (1 - (1 + a * norm)**(-b)) # power_stretch2() #------------------------------------------------------------------------ def power_stretch3( grid, a=1, b=2): # Note: Try a=1, b=2 (shape of a quarter circle) gmin = grid.min() gmax = grid.max() norm = (grid - gmin) / (gmax - gmin) return (1 - (1 - norm**a)**b)**(1/b) # power_stretch3() #------------------------------------------------------------------------ def log_stretch( grid, a=1 ): return np.log( (a * grid) + 1 ) # log_stretch() #------------------------------------------------------------------------ def stretch_grid( grid, stretch, a=1, b=2, p=0.5 ): if (stretch == 'power_stretch1'): # Try: p = 0.3 grid2 = power_stretch1( grid, p) elif (stretch == 'power_stretch2'): # Try: a=1000, b=0.5. grid2 = power_stretch2( grid, a=a, b=b ) elif (stretch == 'power_stretch3'): # Try: a=1, b=2. grid2 = power_stretch3( grid, a=a, b=b) elif (stretch == 'log_stretch'): grid2 = log_stretch( grid, a=a ) elif (stretch == 'hist_equal'): grid2 = histogram_equalize( grid, PLOT_NCS=False) else: print('SORRY, Unknown stretch =', stretch) return None return grid2 # stretch_grid() #------------------------------------------------------------------------ def show_grid_as_image( grid, long_name, extent=None, cmap='rainbow', stretch_name='hist_equal', stretch_a = 1.0, stretch_b = 1.0, stretch_p = 1.0, nodata_value=None, NO_SHOW=False, im_file=None, ## stretch='power_stretch3', xsize=8, ysize=8, dpi=None): # Note: extent = [minlon, maxlon, minlat, maxlat] # See get_map_bounds() in balto_gui.py. #------------------------- # Other color map names #-------------------------------------------- # hsv, jet, gist_rainbow (reverse rainbow), # gist_ncar, gist_stern #-------------------------------------------- #------------------------------------------ # Replace nodata value before the stretch #------------------------------------------ grid2 = grid.copy() if (nodata_value is not None): w1 = (grid2 == nodata_value) w2 = np.invert( w1 ) gmin = min(grid2[w2]) grid2[ w1 ] = gmin #--------------------------------------------- # Apply stretch function to enhance contrast #--------------------------------------------- # grid2 = stretch_grid( grid, stretch='power_stretch1', p=0.4) # grid2 = stretch_grid( grid, stretch='power_stretch2', a=1000, b=0.5) # grid2 = stretch_grid( grid, stretch='power_stretch3', a=1, b=2) # grid2 = stretch_grid( grid, stretch='log_stretch', a=1) grid2 = stretch_grid( grid2, stretch=stretch_name, a=stretch_a, b=stretch_b, p=stretch_p) #----------------------------------------------- # Get new min and max, before replacing nodata #----------------------------------------------- gmin = grid2.min() gmax = grid2.max() #------------------------------------------ # Replace the nodata values after stretch #------------------------------------------ if (nodata_value is not None): grid2[ w1 ] = nodata_value #---------------------------- # Set up and show the image #---------------------------- # figure = plt.figure(1, figsize=(xsize, ysize)) fig, ax = plt.subplots( figsize=(xsize, ysize), dpi=dpi) im_title = long_name.replace('_', ' ').title() ax.set_title( im_title ) ax.set_xlabel('Longitude [deg]') ax.set_ylabel('Latitude [deg]') im = ax.imshow(grid2, interpolation='nearest', cmap=cmap, vmin=gmin, vmax=gmax, extent=extent) #-------------------------------------------------------- # NOTE! Must save before "showing" or get blank image. # File format is inferred from extension. # e.g. TMP_Image.png, TMP_Image.jpg. #-------------------------------------------------------- if (im_file is not None): plt.savefig( im_file ) if not(NO_SHOW): plt.show() plt.close() # show_grid_as_image() #------------------------------------------------------------------------
[ "numpy.histogram", "matplotlib.pyplot.savefig", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "numpy.log", "numpy.invert", "matplotlib.pyplot.close", "matplotlib.pyplot.figure", "matplotlib.pyplot.ylim", "matplotlib.pyplot.xlim", "matplotlib.pyplot.subplots"...
[((1016, 1055), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {'figsize': '(x_size, y_size)'}), '(1, figsize=(x_size, y_size))\n', (1026, 1055), True, 'import matplotlib.pyplot as plt\n'), ((1631, 1660), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {'marker': 'marker'}), '(x, y, marker=marker)\n', (1639, 1660), True, 'import matplotlib.pyplot as plt\n'), ((1666, 1707), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (["(x_name + ' [' + x_units + ']')"], {}), "(x_name + ' [' + x_units + ']')\n", (1676, 1707), True, 'import matplotlib.pyplot as plt\n'), ((1714, 1755), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (["(y_name + ' [' + y_units + ']')"], {}), "(y_name + ' [' + y_units + ']')\n", (1724, 1755), True, 'import matplotlib.pyplot as plt\n'), ((1767, 1787), 'matplotlib.pyplot.ylim', 'plt.ylim', (['ymin', 'ymax'], {}), '(ymin, ymax)\n', (1775, 1787), True, 'import matplotlib.pyplot as plt\n'), ((1794, 1814), 'matplotlib.pyplot.xlim', 'plt.xlim', (['xmin', 'xmax'], {}), '(xmin, xmax)\n', (1802, 1814), True, 'import matplotlib.pyplot as plt\n'), ((2066, 2076), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2074, 2076), True, 'import matplotlib.pyplot as plt\n'), ((2321, 2349), 'numpy.histogram', 'np.histogram', (['grid'], {'bins': '(256)'}), '(grid, bins=256)\n', (2333, 2349), True, 'import numpy as np\n'), ((3690, 3710), 'numpy.log', 'np.log', (['(a * grid + 1)'], {}), '(a * grid + 1)\n', (3696, 3710), True, 'import numpy as np\n'), ((6871, 6916), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(xsize, ysize)', 'dpi': 'dpi'}), '(figsize=(xsize, ysize), dpi=dpi)\n', (6883, 6916), True, 'import matplotlib.pyplot as plt\n'), ((7593, 7604), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (7602, 7604), True, 'import matplotlib.pyplot as plt\n'), ((2599, 2612), 'matplotlib.pyplot.plot', 'plt.plot', (['ncs'], {}), '(ncs)\n', (2607, 2612), True, 'import matplotlib.pyplot as plt\n'), ((5653, 5666), 'numpy.invert', 'np.invert', (['w1'], {}), '(w1)\n', (5662, 5666), True, 'import numpy as np\n'), ((7524, 7544), 'matplotlib.pyplot.savefig', 'plt.savefig', (['im_file'], {}), '(im_file)\n', (7535, 7544), True, 'import matplotlib.pyplot as plt\n'), ((7576, 7586), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7584, 7586), True, 'import matplotlib.pyplot as plt\n')]
import torch.utils.data as data import os,sys import numpy as np import pickle sys.path.insert(0, '../') def default_loader(path): return pickle.load(open(path, 'rb')) def parse_data(data, cur_num_boxes, w, h, num_boxes): features, boxes, attn_target, use, objs, atts, att_use = [], [], [], [], [], [], [] for i in range(cur_num_boxes): cb, cf, co, ca = data['boxes'][i], data['features'][i], [], [] features.append(np.asarray(cf)) boxes.append(np.asarray([cb[0]*1.0/w, cb[1]*1.0/h, cb[2]*1.0/w, cb[3]*1.0/h, ((cb[2]-cb[0])*(cb[3]-cb[1])*1.0)/(w*h)])) pad_len = num_boxes - cur_num_boxes for i in range(pad_len): features.append(np.asarray([0.0]*2048)) boxes.append(np.asarray([0.0]*5)) return features, boxes class MSCOCOvqa(data.Dataset): def __init__(self, data, path, w2i, num_boxes=36, q_len=14, loader=default_loader): self.data = data self.path = path self.loader = loader self.max_len = q_len self.a_vocab_size = len(w2i[0]) self.q_vocab_size = len(w2i[1]) self.num_boxes = num_boxes def __getitem__(self, index): cur_data = self.data[index] img_id = cur_data['image_id'] question = cur_data['question'][:self.max_len] question_id = -1 if cur_data.has_key('question_id'): question_id = cur_data['question_id'] pad_len = max(0, self.max_len-len(question)) question = question + [self.q_vocab_size]*pad_len answers = cur_data['answers'] data_path = os.path.join(self.path, str(img_id)+'.pkl') try: data = self.loader(data_path) except: print('error in loading pkl from ' + str(data_path)) exit(-1) cur_num_boxes = data['num_boxes'] w = data['image_w'] h = data['image_h'] features, boxes = parse_data(data, cur_num_boxes, w, h, self.num_boxes) label = np.zeros(self.a_vocab_size) for ans in answers: w, c = ans label[w] = float(c) return np.asarray(features, dtype=np.float32), np.asarray(boxes, dtype=np.float32), np.asarray(question), \ label, question_id, data_path def __len__(self): return len(self.data)
[ "numpy.zeros", "sys.path.insert", "numpy.asarray" ]
[((79, 104), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""../"""'], {}), "(0, '../')\n", (94, 104), False, 'import os, sys\n'), ((1988, 2015), 'numpy.zeros', 'np.zeros', (['self.a_vocab_size'], {}), '(self.a_vocab_size)\n', (1996, 2015), True, 'import numpy as np\n'), ((446, 460), 'numpy.asarray', 'np.asarray', (['cf'], {}), '(cf)\n', (456, 460), True, 'import numpy as np\n'), ((483, 618), 'numpy.asarray', 'np.asarray', (['[cb[0] * 1.0 / w, cb[1] * 1.0 / h, cb[2] * 1.0 / w, cb[3] * 1.0 / h, (cb[2] -\n cb[0]) * (cb[3] - cb[1]) * 1.0 / (w * h)]'], {}), '([cb[0] * 1.0 / w, cb[1] * 1.0 / h, cb[2] * 1.0 / w, cb[3] * 1.0 /\n h, (cb[2] - cb[0]) * (cb[3] - cb[1]) * 1.0 / (w * h)])\n', (493, 618), True, 'import numpy as np\n'), ((684, 708), 'numpy.asarray', 'np.asarray', (['([0.0] * 2048)'], {}), '([0.0] * 2048)\n', (694, 708), True, 'import numpy as np\n'), ((729, 750), 'numpy.asarray', 'np.asarray', (['([0.0] * 5)'], {}), '([0.0] * 5)\n', (739, 750), True, 'import numpy as np\n'), ((2115, 2153), 'numpy.asarray', 'np.asarray', (['features'], {'dtype': 'np.float32'}), '(features, dtype=np.float32)\n', (2125, 2153), True, 'import numpy as np\n'), ((2155, 2190), 'numpy.asarray', 'np.asarray', (['boxes'], {'dtype': 'np.float32'}), '(boxes, dtype=np.float32)\n', (2165, 2190), True, 'import numpy as np\n'), ((2192, 2212), 'numpy.asarray', 'np.asarray', (['question'], {}), '(question)\n', (2202, 2212), True, 'import numpy as np\n')]
### NOTE: This final will not run! ### The following functions are not included as our model is proprietary. ### The following (self explanatory) functions would need to be implemented in order for this script to interact with a given structural model. # modify_material_properties_in_structural_FEA_model(Emultiplier) # modify_point_masses_in_structural_FEA_model(point_mass_dict) # frequencies = run_structural_FEA_model_and_return_natural_frequencies() import os import json import numpy as np import scipy.optimize import csv TARGET_FREQS = [5.6492, 29.9699] # computed in STEP3_1 ZETA = [0.0281, 0.0717] # computed in STEP3_1 def modify_masses_and_do_solve(mass): print(">>\n>>\n>>\n>>\n>>\n>>\n") print("Running solve with masses:") if mass[0] < 0: mass[0] = 0.0 mass3 = 0.472-2.0*mass[0] if mass3 < 0: mass3 = 0.0 point_mass_dict = { "servo_1" : mass[0], "servo_2" : mass[0], "pitot_tube" : mass3} print(point_mass_dict) modify_point_masses_in_structural_FEA_model(point_mass_dict) frequencies = run_structural_FEA_model_and_return_natural_frequencies() frequencies = [frequencies[0], frequencies[2]] print("Target frequencies: ", TARGET_FREQS) print("Model frequencies: ", frequencies) error = 0.5*(np.abs(TARGET_FREQS[0] - frequencies[0])/TARGET_FREQS[0] + np.abs(TARGET_FREQS[1] - frequencies[1])/TARGET_FREQS[1]) print("Mean Relative Error: ", error) return error def final_modify_masses_and_do_solve(mass): print(">>\n>>\n>>\n>>\n>>\n>>\n") print("Running solve with masses:") if mass[0] < 0: mass[0] = 0.0 mass3 = 0.472-2.0*mass[0] if mass3 < 0: mass3 = 0.0 point_mass_dict = { "servo_1" : mass[0], "servo_2" : mass[0], "pitot_tube" : mass3} print(point_mass_dict) modify_point_masses_in_structural_FEA_model(point_mass_dict) frequencies = run_structural_FEA_model_and_return_natural_frequencies() frequencies = [frequencies[0], frequencies[2]] return frequencies if __name__ == '__main__': # read in the e samples generated in Step 3_1 and saved in e_samples.csv Emultiplierslist = [] with open('datafiles/step3/e_samples.csv', newline='') as inputfile: for row in csv.reader(inputfile): Emultiplierslist.append(row[0]) # loop over the e samples and run the mass optimization routine for i in range(100): print("\n") print("Starting iteration ", i) # get the Young's modulus scale factor from the data saved in e_samples.csv Emultiplier = Emultiplierslist[i] print("E multiplier= ", Emultiplier) print("\n") # modify Young's modulus and hg commit+push modify_material_properties_in_structural_FEA_model(Emultiplier) mass_opt = scipy.optimize.fmin(func=modify_masses_and_do_solve, x0=[0.169], xtol=0.001) # scipy.optimize.fmin returns optimal masses, but has not necessarily computed the corresponding frequencies. do that here f_opt = final_modify_masses_and_do_solve(mass_opt) mass3 = 0.472-2.0*mass_opt[0]; # write data to file with open('datafiles/step3/massoptimizationresults_new.csv', 'a') as the_file: the_file.write(str(Emultiplier)+","+str(TARGET_FREQS[0])+","+str(TARGET_FREQS[1])+","+str(ZETA[0])+","+str(ZETA[1])+","+str(mass_opt[0])+","+str(mass_opt[0])+","+str(mass3)+","+str(f_opt[0])+","+str(f_opt[1])+'\n') print("Optimized masses:") point_mass_dict_opt = { "servo_1" : mass_opt[0], "servo_2" : mass_opt[0], "pitot_tube" : mass3} print(point_mass_dict_opt) print("\n") print("Optimized frequency mode 1: ", f_opt[0]) print("Optimized frequency mode 2: ", f_opt[0]) print("\n") print("End iteration ",i)
[ "numpy.abs", "csv.reader" ]
[((2353, 2374), 'csv.reader', 'csv.reader', (['inputfile'], {}), '(inputfile)\n', (2363, 2374), False, 'import csv\n'), ((1336, 1376), 'numpy.abs', 'np.abs', (['(TARGET_FREQS[0] - frequencies[0])'], {}), '(TARGET_FREQS[0] - frequencies[0])\n', (1342, 1376), True, 'import numpy as np\n'), ((1395, 1435), 'numpy.abs', 'np.abs', (['(TARGET_FREQS[1] - frequencies[1])'], {}), '(TARGET_FREQS[1] - frequencies[1])\n', (1401, 1435), True, 'import numpy as np\n')]
import copy, os import tensorflow as tf import numpy as np from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between from lib.util import load_numpy from .renderer import Renderer from .transform import GridTransform from .vector import GridShape, Vector3 import logging LOG = logging.getLogger("Structs") # --- DATA Structs --- def get_coord_field(shape, offset=[0,0,0], lod=0.0, concat=True): ''' shape: z,y,x offset: x,y,z returns: 1,z,y,x,c with c=x,z,y,lod ''' coord_z, coord_y, coord_x = tf.meshgrid(tf.range(shape[0], dtype=tf.float32), tf.range(shape[1], dtype=tf.float32), tf.range(shape[2], dtype=tf.float32), indexing='ij') #z,y,x coord_data = [tf.reshape(coord_x + offset[0], [1]+shape+[1]), tf.reshape(coord_y + offset[1], [1]+shape+[1]), tf.reshape(coord_z + offset[2], [1]+shape+[1])] #3 x 1DHW1 if lod is not None: lod_data = tf.constant(lod, shape=[1]+shape+[1], dtype=tf.float32) #tf.ones([1]+shape+[1])*lod coord_data.append(lod_data)#4 x 1DHW1 if concat: coord_data = tf.concat(coord_data, axis=-1) return coord_data class Zeroset: def __init__(self, initial_value, shape=None, as_var=True, outer_bounds="OPEN", device=None, var_name="zeroset", trainable=True): self.outer_bounds = outer_bounds self.is_var = as_var self._device = device self._name = var_name self._is_trainable = trainable with tf.device(self._device): if shape is not None: assert isinstance(shape, GridShape) initial_value = tf.constant(initial_value, shape=shape.value, dtype=tf.float32) if as_var: self._levelset = tf.Variable(initial_value=initial_value, name=var_name, trainable=trainable) else: self._levelset = tf.identity(initial_value) @property def grid_shape(self): return GridShape.from_tensor(self._levelset) def _hull_staggered_lerp_weight(self, a, b): a_leq = tf.less_equal(a,0) return tf.where( tf.logical_xor(a_leq, tf.less_equal(b,0)), #sign change along iterpolation tf.abs( tf.divide( tf.minimum(a,b), tf.subtract(a,b) ) ), tf.cast(a_leq, dtype=a.dtype) ) def _hull_simple_staggered_component(self, axis): assert axis in [1,2,3,-2,-3,-4] axis = axis%5 pad = [(0,0),(0,0),(0,0),(0,0),(0,0)] pad[axis]=(1,1) shape = self.grid_shape.value shape[axis] -= 1 offset = np.zeros((5,), dtype=np.int32) cells_prev = tf.slice(self._levelset, offset, shape) #self._levelset[:,:,:,:-1,:] offset[axis] += 1 cells_next = tf.slice(self._levelset, offset, shape) #self._levelset[:,:,:, 1:,:] hull = self._hull_staggered_lerp_weight(cells_prev,cells_next) hull = tf.pad(hull, pad, constant_values=1 if self.outer_bounds=="OPEN" else 0) return hull def to_hull_simple_staggered(self): return self._hull_simple_staggered_component(-2), self._hull_simple_staggered_component(-3), self._hull_simple_staggered_component(-4) def to_hull_simple_centered(self): raise NotImplementedError() def to_denstiy_simple_centered(self): return tf.where(tf.greater(self._levelset, 0), 250, 0) def resize(self, shape): assert shape_list(shape)==[3] new_shape = GridShape(shape) if new_shape==self.grid_shape: return raise NotImplementedError("Zeroset.resize() not implemented.") def assign(levelset): raise NotImplementedError() class DensityGrid: def __init__(self, shape, constant=0.1, as_var=True, d=None, scale_renderer=None, hull=None, inflow=None, inflow_offset=None, inflow_mask=None, device=None, var_name="denstiy", trainable=True, restrict_to_hull=True): self.shape = shape if d is not None: d_shape = shape_list(d) if not len(d_shape)==5 or not d_shape[-1]==1 or not self.shape==spacial_shape_list(d): raise ValueError("Invalid shape of density on assignment: %s"%d_shape) self.is_var = as_var self._device = device self._name = var_name self._is_trainable = trainable if as_var: rand_init = tf.constant_initializer(constant) with tf.device(self._device): self._d = tf.Variable(initial_value=d if d is not None else rand_init(shape=[1]+self.shape+[1], dtype=tf.float32), name=var_name+'_dens', trainable=True) else: with tf.device(self._device): if d is not None: self._d = tf.constant(d, dtype=tf.float32) else: self._d = tf.constant(constant, shape=[1]+self.shape+[1], dtype=tf.float32) self.scale_renderer = scale_renderer with tf.device(self._device): self.hull = tf.constant(hull, dtype=tf.float32) if hull is not None else None self.restrict_to_hull = restrict_to_hull if inflow is not None: with tf.device(self._device): if isinstance(inflow, str) and inflow=='CONST': assert isinstance(inflow_mask, (tf.Tensor, np.ndarray)) inflow = rand_init(shape=shape_list(inflow_mask), dtype=tf.float32) if as_var: self._inflow = tf.Variable(initial_value=inflow, name=var_name+'_inflow', trainable=True) else: self._inflow = tf.constant(inflow, dtype=tf.float32) self.inflow_mask = tf.constant(inflow_mask, dtype=tf.float32) if inflow_mask is not None else None inflow_shape = spacial_shape_list(self._inflow) #.get_shape().as_list()[-4:-1] self._inflow_padding = [[0,0]]+[[inflow_offset[_],self.shape[_]-inflow_offset[_]-inflow_shape[_]] for _ in range(3)]+[[0,0]] self.inflow_offset = inflow_offset else: self._inflow = None @property def trainable(self): return self._is_trainable and self.is_var @property def d(self): if self.restrict_to_hull: return self.with_hull() else: return tf.identity(self._d) def with_hull(self): if self.hull is not None: return self._d * self.hull # hull is a (smooth) binary mask else: return tf.identity(self._d) @property def inflow(self): if self._inflow is None: return tf.zeros_like(self._d, dtype=tf.float32) elif self.inflow_mask is not None: #hasattr(self, 'inflow_mask') and return tf.pad(self._inflow*self.inflow_mask, self._inflow_padding) else: return tf.pad(self._inflow, self._inflow_padding) def with_inflow(self): density = self.d if self._inflow is not None: density = tf.maximum(density+self.inflow, 0) return density @classmethod def from_file(cls, path, as_var=True, scale_renderer=None, hull=None, inflow=None, inflow_offset=None, inflow_mask=None, device=None, var_name="denstiy", trainable=True, restrict_to_hull=True): try: with np.load(path) as np_data: d = np_data['arr_0'] shape =spacial_shape_list(d) if 'hull' in np_data and hull is None: hull = np_data['hull'] if 'inflow' in np_data and inflow is None: inflow=np_data['inflow'] if 'inflow_mask' in np_data and inflow_mask is None: inflow_mask=np_data['inflow_mask'] if 'inflow_offset' in np_data and inflow_offset is None: inflow_offset=np_data['inflow_offset'].tolist() grid = cls(shape, d=d, as_var=as_var, scale_renderer=scale_renderer, hull=hull, inflow=inflow, inflow_offset=inflow_offset, inflow_mask=inflow_mask, \ device=device, var_name=var_name, trainable=trainable, restrict_to_hull=restrict_to_hull) except: LOG.warning("Failed to load density from '%s':", path, exc_info=True) return None else: return grid @classmethod def from_scalarFlow_file(cls, path, as_var=True, shape=None, scale_renderer=None, hull=None, inflow=None, inflow_offset=None, inflow_mask=None, device=None, var_name="sF_denstiy", trainable=True, restrict_to_hull=True): # if shape is set the loaded grid will be reshaped if necessary density = load_numpy(path).astype(np.float32)[::-1] density = density.reshape([1] + list(density.shape)) # density = tf.constant(density, dtype=tf.float32) d_shape = spacial_shape_list(density) if shape is not None and shape!=d_shape: if scale_renderer is None: raise ValueError("No renderer provided to scale density.") LOG.debug("scaling scalarFlow density from %s to %s", d_shape, shape) density = scale_renderer.resample_grid3D_aligned(density, shape) d_shape = shape else: # cut of SF inflow region and set as inflow. or is it already cut off in SF dataset? it is, but not in the synth dataset or my own sF runs. # lower 15 cells... inflow, density= tf.split(density, [15, d_shape[1]-15], axis=-3) inflow_mask = tf.ones_like(inflow, dtype=tf.float32) inflow_offset = [0,0,0] density = tf.concat([tf.zeros_like(inflow, dtype=tf.float32), density], axis=-3) return cls(d_shape, d=density, as_var=as_var, scale_renderer=scale_renderer, hull=hull, inflow=inflow, inflow_offset=inflow_offset, inflow_mask=inflow_mask, \ device=device, var_name=var_name, trainable=trainable, restrict_to_hull=restrict_to_hull) def copy(self, as_var=None, device=None, var_name=None, trainable=None, restrict_to_hull=None): if as_var is None: as_var = self.is_var if as_var and var_name is None: var_name = self._name + '_cpy' if trainable is None: trainable = self._is_trainable if restrict_to_hull is None: restrict_to_hull = self.restrict_to_hull if self._inflow is not None: grid = DensityGrid(self.shape, d=tf.identity(self._d), as_var=as_var, scale_renderer=self.scale_renderer, hull=self.hull, \ inflow=tf.identity(self._inflow), inflow_offset=self.inflow_offset, inflow_mask=self.inflow_mask, \ device=device, var_name=var_name, trainable=trainable, restrict_to_hull=restrict_to_hull) else: grid = DensityGrid(self.shape, d=tf.identity(self._d), as_var=as_var, scale_renderer=self.scale_renderer, hull=self.hull, \ device=device, var_name=var_name, trainable=trainable, restrict_to_hull=restrict_to_hull) return grid def scaled(self, new_shape, with_inflow=False): if not (isinstance(new_shape, list) and len(new_shape)==3): raise ValueError("Invalid shape") density = self.d if not with_inflow else self.with_inflow() if new_shape!=self.shape: LOG.debug("Scaling density from %s to %s", self.shape, new_shape) with self.scale_renderer.profiler.sample("scale density"): d_scaled = self.scale_renderer.resample_grid3D_aligned(density, new_shape) else: LOG.debug("No need to scale density to same shape %s", self.shape) d_scaled = tf.identity(density) return d_scaled def copy_scaled(self, new_shape, as_var=None, device=None, var_name=None, trainable=None, restrict_to_hull=None): '''Does not copy inflow and hull, TODO''' if as_var is None: as_var = self.is_var if as_var and var_name is None: var_name = self._name + '_scaled' if trainable is None: trainable = self._is_trainable if restrict_to_hull is None: restrict_to_hull = self.restrict_to_hull d_scaled = self.scaled(new_shape) grid = DensityGrid(new_shape, d=d_scaled, as_var=as_var, scale_renderer=self.scale_renderer, device=device, var_name=var_name, trainable=trainable, restrict_to_hull=restrict_to_hull) return grid def warped(self, vel_grid, order=1, dt=1.0, clamp="NONE"): if not (isinstance(vel_grid, VelocityGrid)): raise ValueError("Invalid velocity grid") return vel_grid.warp(self.with_inflow(), order=order, dt=dt, clamp=clamp) def copy_warped(self, vel_grid, as_var=None, order=1, dt=1.0, device=None, var_name=None, clamp="NONE", trainable=None, restrict_to_hull=None): '''Does not copy inflow and hull, TODO''' if as_var is None: as_var = self.is_var if as_var and var_name is None: var_name = self._name + '_warped' if trainable is None: trainable = self._is_trainable if restrict_to_hull is None: restrict_to_hull = self.restrict_to_hull d_warped = self.warped(vel_grid, order=order, dt=dt, clamp=clamp) grid = DensityGrid(self.shape, d=d_warped, as_var=as_var, scale_renderer=self.scale_renderer, device=device, var_name=var_name, trainable=trainable, restrict_to_hull=restrict_to_hull) return grid def scale(self, scale): self.assign(self._d*scale) def apply_clamp(self, vmin, vmax): vmin = tf.maximum(vmin, 0) d = tf.clip_by_value(self._d, vmin, vmax) inflow = None if self._inflow is not None: # use already clamped density for consistency denstiy_shape = shape_list(d) density_cropped = d[self._inflow_padding[0][0] : denstiy_shape[0]-self._inflow_padding[0][1], self._inflow_padding[1][0] : denstiy_shape[1]-self._inflow_padding[1][1], self._inflow_padding[2][0] : denstiy_shape[2]-self._inflow_padding[2][1], self._inflow_padding[3][0] : denstiy_shape[3]-self._inflow_padding[3][1], self._inflow_padding[4][0] : denstiy_shape[4]-self._inflow_padding[4][1]] inflow = tf.clip_by_value(self._inflow, vmin - density_cropped, vmax - density_cropped) self.assign(d, inflow) def assign(self, d, inflow=None): shape = shape_list(d) if not len(shape)==5 or not shape[-1]==1 or not shape[-4:-1]==self.shape: raise ValueError("Invalid or incompatible shape of density on assignment: is {}, required: NDHW1 with DHW={}".format(shape, self.shape)) if self.is_var: self._d.assign(d) if self._inflow is not None and inflow is not None: self._inflow.assign(inflow) else: with tf.device(self._device): self._d = tf.identity(d) if self._inflow is not None and inflow is not None: self._inflow = tf.identity(inflow) def var_list(self): if self.is_var: if self._inflow is not None: return [self._d, self._inflow] return [self._d] else: raise TypeError("This DensityGrid is not a variable.") def get_variables(self): if self.is_var: var_dict = {'density': self._d} if self._inflow is not None: var_dict['inflow'] = self._inflow return var_dict else: raise TypeError("This DensityGrid is not a variable.") def save(self, path): density = self._d if isinstance(density, (tf.Tensor, tf.Variable)): density = density.numpy() save = {} if self.hull is not None: hull = self.hull if isinstance(hull, (tf.Tensor, tf.Variable)): hull = hull.numpy() save['hull']=hull if self._inflow is not None: inflow = self._inflow if isinstance(inflow, (tf.Tensor, tf.Variable)): inflow = inflow.numpy() save['inflow']=inflow if self.inflow_mask is not None: inflow_mask = self.inflow_mask if isinstance(inflow_mask, (tf.Tensor, tf.Variable)): inflow_mask = inflow_mask.numpy() save['inflow_mask']=inflow_mask save['inflow_offset']=np.asarray(self.inflow_offset) np.savez_compressed(path, density, **save) def mean(self): return tf.reduce_mean(self.d) def stats(self, mask=None, state=None, **warp_kwargs): ''' mask: optional binary float mask, stats only consider cells>0.5 ''' d = self.d if mask is not None: mask = mask if mask.dtype==tf.bool else tf.greater(mask, 0.5) d = tf.boolean_mask(d, mask) stats = { 'density': tf_tensor_stats(d, as_dict=True), 'shape':self.shape, } if state is not None and state.prev is not None and state.prev.density is not None and state.prev.velocity is not None: warp_SE = tf.squared_difference(state.prev.density_advected(**warp_kwargs), self.d) if mask is not None: warp_SE = tf.boolean_mask(warp_SE, mask) stats["warp_SE"] = tf_tensor_stats(warp_SE, as_dict=True) else: stats["warp_SE"] = tf_tensor_stats(tf.zeros([1,1,1,1,1], dtype=tf.float32), as_dict=True) return stats class VelocityGrid: @staticmethod def component_shapes(centered_shape): x_shape = copy.copy(centered_shape) x_shape[2] +=1 y_shape = copy.copy(centered_shape) y_shape[1] +=1 z_shape = copy.copy(centered_shape) z_shape[0] +=1 return x_shape, y_shape, z_shape def __init__(self, centered_shape, std=0.1, as_var=True, x=None, y=None, z=None, boundary=None, scale_renderer=None, warp_renderer=None, *, coords=None, lod=None, device=None, var_name="velocity", trainable=True): self.centered_shape = centered_shape.tolist() if isinstance(centered_shape, np.ndarray) else centered_shape self.x_shape, self.y_shape, self.z_shape = VelocityGrid.component_shapes(self.centered_shape) self.set_boundary(boundary) self.is_var = as_var self._device = device self._name = var_name self._is_trainable = trainable if as_var: if x is not None: x_shape = shape_list(x) if not len(x_shape)==5 or not x_shape[-1]==1 or not x_shape[-4:-1]==self.x_shape: raise ValueError("Invalid shape of velocity x component on assignment") if y is not None: y_shape = shape_list(y) if not len(y_shape)==5 or not y_shape[-1]==1 or not y_shape[-4:-1]==self.y_shape: raise ValueError("Invalid shape of velocity y component on assignment") if z is not None: z_shape = shape_list(z) if not len(z_shape)==5 or not z_shape[-1]==1 or not z_shape[-4:-1]==self.z_shape: raise ValueError("Invalid shape of velocity z component on assignment") # in a box #rand_init = tf.random_normal_initializer(0.0, std) std = tf.abs(std) rand_init = tf.random_uniform_initializer(-std, std) # maybe even uniformly in space and in a sphere?: http://6degreesoffreedom.co/circle-random-sampling/ with tf.device(self._device): self._x = tf.Variable(initial_value=x if x is not None else rand_init(shape=[1]+self.x_shape+[1], dtype=tf.float32), name=var_name + '_x', trainable=True) self._y = tf.Variable(initial_value=y if y is not None else rand_init(shape=[1]+self.y_shape+[1], dtype=tf.float32), name=var_name + '_y', trainable=True) self._z = tf.Variable(initial_value=z if z is not None else rand_init(shape=[1]+self.z_shape+[1], dtype=tf.float32), name=var_name + '_z', trainable=True) else: if x is None: x = tf.constant(tf.random.uniform([1]+self.x_shape+[1], -std, std, dtype=tf.float32)) if y is None: y = tf.constant(tf.random.uniform([1]+self.y_shape+[1], -std, std, dtype=tf.float32)) if z is None: z = tf.constant(tf.random.uniform([1]+self.z_shape+[1], -std, std, dtype=tf.float32)) self.assign(x,y,z) if lod is None: lod = tf.zeros([1]+self.centered_shape+[1]) with tf.device(self._device): self.lod_pad = tf.identity(lod) self.scale_renderer = scale_renderer if self.scale_renderer is not None: if (self.outer_bounds=='CLOSED' and self.scale_renderer.boundary_mode!='BORDER') \ or (self.outer_bounds=='OPEN' and self.scale_renderer.boundary_mode!='CLAMP'): LOG.warning("Velocity outer boundary %s does not match scale renderer boundary mode %s", self.outer_bounds, self.scale_renderer.boundary_mode) self.warp_renderer = warp_renderer if self.warp_renderer is not None: if (self.outer_bounds=='CLOSED' and self.warp_renderer.boundary_mode!='BORDER') \ or (self.outer_bounds=='OPEN' and self.warp_renderer.boundary_mode!='CLAMP'): LOG.warning("Velocity outer boundary %s does not match scale renderer boundary mode %s", self.outer_bounds, self.warp_renderer.boundary_mode) def set_boundary(self, boundary): assert (boundary is None) or isinstance(boundary, Zeroset) self.boundary = boundary self.outer_bounds = self.boundary.outer_bounds if self.boundary is not None else "OPEN" @property def trainable(self): return self._is_trainable and self.is_var @property def x(self): v = self._x if self.boundary is not None: v*= self.boundary._hull_simple_staggered_component(-2) return v @property def y(self): v = self._y if self.boundary is not None: v*= self.boundary._hull_simple_staggered_component(-3) return v @property def z(self): v = self._z if self.boundary is not None: v*= self.boundary._hull_simple_staggered_component(-4) return v @classmethod def from_centered(cls, centered_grid, as_var=True, boundary=None, scale_renderer=None, warp_renderer=None, device=None, var_name="velocity", trainable=True): centered_shape = shape_list(centered_grid) assert len(centered_shape)==5 assert centered_shape[-1]==3 assert centered_shape[0]==1 centered_shape = centered_shape[-4:-1] vel_grid = cls(centered_shape, as_var=as_var, boundary=boundary, scale_renderer=scale_renderer, warp_renderer=warp_renderer, device=device, var_name=var_name, trainable=trainable) x,y,z = vel_grid._centered_to_staggered(centered_grid) vel_grid.assign(x,y,z) return vel_grid @classmethod def from_file(cls, path, as_var=True, boundary=None, scale_renderer=None, warp_renderer=None, device=None, var_name="velocity", trainable=True): try: with np.load(path) as vel: if 'centered_shape' not in vel:#legacy shape = shape_list(vel["vel_x"]) LOG.debug("%s", shape) shape[-2] -=1 shape = shape[1:-1] else: shape = vel['centered_shape'].tolist() vel_grid = cls(shape, x=vel["vel_x"].astype(np.float32), y=vel["vel_y"].astype(np.float32), z=vel["vel_z"].astype(np.float32), \ as_var=as_var, boundary=boundary, scale_renderer=scale_renderer, warp_renderer=warp_renderer, device=device, var_name=var_name, trainable=trainable) except: LOG.warning("Failed to load velocity from '%s':", path, exc_info=True) return None else: return vel_grid @classmethod def from_scalarFlow_file(cls, path, as_var=True, shape=None, boundary=None, scale_renderer=None, warp_renderer=None, device=None, var_name="sF_velocity", trainable=True): # sF velocities are stored as combined staggered grid with upper cells missing, DHWC with C=3 velocity = load_numpy(path).astype(np.float32)[::-1] v_shape = GridShape.from_tensor(velocity) velocity = v_shape.normalize_tensor_shape(velocity) #.reshape([1] + list(velocity.shape)) # NDHWC velocity = tf.constant(velocity, dtype=tf.float32) v_shape = v_shape.zyx.value v_x, v_y, v_z = tf.split(velocity, 3, axis=-1) p0 = (0,0) # extend missing upper cell v_x = tf.pad(v_x, [p0,p0,p0,(0,1),p0], "SYMMETRIC") v_y = tf.pad(v_y, [p0,p0,(0,1),p0,p0], "SYMMETRIC") v_z = tf.pad(-v_z, [p0,(1,0),p0,p0,p0], "SYMMETRIC") #z value/direction reversed, pad lower value as axis is reversed (?) #v_shape = spacial_shape_list(velocity) if shape is not None and v_shape!=shape: assert len(shape)==3 if scale_renderer is None: raise ValueError("No renderer provided to scale velocity.") # shape = GridShape(shape).zyx # vel_scale = shape/v_shape #[o/i for i,o in zip(v_shape, shape)] #z,y,x LOG.debug("scaling scalarFlow velocity from %s to %s with magnitude scale %s", v_shape, shape) v_tmp = cls(v_shape, x=v_x, y=v_y, z=v_z, as_var=False, boundary=boundary, scale_renderer=scale_renderer, warp_renderer=warp_renderer, device=device, var_name="sF_tmp", trainable=False) v_x, v_y, v_z = v_tmp.scaled(shape, scale_magnitude=True) # can only scale 1 and 4 channel grids # v_x = scale_renderer.resample_grid3D_aligned(v_x, shape.value)*vel_scale.x#[2] # v_y = scale_renderer.resample_grid3D_aligned(v_y, shape.value)*vel_scale.y#[1] # v_z = scale_renderer.resample_grid3D_aligned(v_z, shape.value)*vel_scale.z#[0] # velocity = tf.concat([v_x, v_y, v_z], axis=-1) v_shape = shape #return cls.from_centered(velocity,as_var=as_var, boundary=boundary, scale_renderer=scale_renderer, warp_renderer=warp_renderer, device=device, var_name=var_name) return cls(v_shape, x=v_x, y=v_y, z=v_z,as_var=as_var, boundary=boundary, scale_renderer=scale_renderer, warp_renderer=warp_renderer, device=device, var_name=var_name, trainable=trainable) def copy(self, as_var=None, device=None, var_name=None, trainable=None): if as_var is None: as_var = self.is_var if as_var and var_name is None: var_name = self._name + '_cpy' if trainable is None: trainable = self._is_trainable grid = VelocityGrid(self.centered_shape, x=tf.identity(self._x), y=tf.identity(self._y), z=tf.identity(self._z), as_var=as_var, \ boundary=self.boundary, scale_renderer=self.scale_renderer, warp_renderer=self.warp_renderer, device=device, var_name=var_name, trainable=trainable) return grid def scaled(self, centered_shape, scale_magnitude=True): if not (isinstance(centered_shape, list) and len(centered_shape)==3): raise ValueError("Invalid shape") #resample velocity if centered_shape!=self.centered_shape: with self.scale_renderer.profiler.sample("scale velocity"): x_shape, y_shape, z_shape = VelocityGrid.component_shapes(centered_shape) LOG.debug("Scaling velocity from %s to %s", self.centered_shape, centered_shape) x_scaled = self.scale_renderer.resample_grid3D_aligned(self.x, x_shape, align_x='center') y_scaled = self.scale_renderer.resample_grid3D_aligned(self.y, y_shape, align_y='center') z_scaled = self.scale_renderer.resample_grid3D_aligned(self.z, z_shape, align_z='center') if scale_magnitude: vel_scale = [o/i for i,o in zip(self.centered_shape, centered_shape)] #z,y,x LOG.debug("Scaling velocity magnitude with %s", vel_scale) x_scaled *= vel_scale[2] y_scaled *= vel_scale[1] z_scaled *= vel_scale[0] else: LOG.debug("No need to scale velocity to same shape %s", self.centered_shape) x_scaled = tf.identity(self.x) y_scaled = tf.identity(self.y) z_scaled = tf.identity(self.z) return x_scaled, y_scaled, z_scaled def copy_scaled(self, centered_shape, scale_magnitude=True, as_var=None, device=None, var_name=None, trainable=None): if as_var is None: as_var = self.is_var if as_var and var_name is None: var_name = self._name + '_scaled' if trainable is None: trainable = self._is_trainable x_scaled, y_scaled, z_scaled = self.scaled(centered_shape, scale_magnitude) grid = VelocityGrid(centered_shape, x=x_scaled, y=y_scaled, z=z_scaled, as_var=as_var, \ boundary=self.boundary, scale_renderer=self.scale_renderer, warp_renderer=self.warp_renderer, device=device, var_name=var_name, trainable=trainable) return grid def _lut_warp_vel(self, shape, dt=1.0): # use to get lookup positions to warp velocity components vel = self._sampled_to_shape(shape) #3 x 1DHW1 vel_lut = [- vel[i]*dt for i in range(len(vel))] #3 x 1DHW1 vel_lut = tf.concat(vel_lut, axis = -1) #1DHW3 return vel_lut def _warp_vel_component(self, data, lut, order=1, dt=1.0, clamp="NONE"): if order<1 or order>2: raise ValueError("Unsupported warp order '{}'".format(order)) warped = self.warp_renderer._sample_LuT(data, lut, True, relative=True) clamp = clamp.upper() if order==2: #MacCormack warped_back = self.warp_renderer._sample_LuT(warped, -lut, True, relative=True) corrected = warped + 0.5*(data-warped_back) if clamp=="MC" or clamp=="MC_SMOOTH": #raise NotImplementedError("MacCormack clamping has not been implemented.") fm = self.warp_renderer.filter_mode self.warp_renderer.filter_mode = "MIN" data_min = self.warp_renderer._sample_LuT(data, lut, True, relative=True) self.warp_renderer.filter_mode = "MAX" data_max = self.warp_renderer._sample_LuT(data, lut, True, relative=True) self.warp_renderer.filter_mode = fm if clamp=='MC': #LOG.warning("Experimental clamp for MacCormack velocity advection.") raise NotImplementedError("MIM and MAX warp sampling have wrong gradients.") corrected = tf.clip_by_value(corrected, data_min, data_max) if clamp=='MC_SMOOTH': #LOG.warning("Experimental 'revert' clamp for MacCormack velocity advection.") clamp_OOB = tf.logical_or(tf.less(corrected, data_min), tf.greater(corrected, data_max)) corrected = tf.where(clamp_OOB, warped, corrected) warped = corrected return warped def warped(self, vel_grid=None, order=1, dt=1.0, clamp="NONE"): if vel_grid is None: #vel_grid = self pass elif not isinstance(vel_grid, VelocityGrid): raise TypeError("Invalid VelocityGrid") with self.warp_renderer.profiler.sample("warp velocity"): LOG.debug("Warping velocity grid") #TODO will cause errors if grid shapes do not match, resample if necessary? if vel_grid is None: lut_x = tf.concat([-vel*dt for vel in self._sampled_to_component_shape('X', concat=False)], axis=-1) else: lut_x = vel_grid._lut_warp_vel(self.x_shape, dt) x_warped = self._warp_vel_component(self.x, lut_x, order=order, dt=dt, clamp=clamp) del lut_x if vel_grid is None: lut_y = tf.concat([-vel*dt for vel in self._sampled_to_component_shape('Y', concat=False)], axis=-1) else: lut_y = vel_grid._lut_warp_vel(self.y_shape, dt) y_warped = self._warp_vel_component(self.y, lut_y, order=order, dt=dt, clamp=clamp) del lut_y if vel_grid is None: lut_z = tf.concat([-vel*dt for vel in self._sampled_to_component_shape('Z', concat=False)], axis=-1) else: lut_z = vel_grid._lut_warp_vel(self.z_shape, dt) z_warped = self._warp_vel_component(self.z, lut_z, order=order, dt=dt, clamp=clamp) del lut_z return x_warped, y_warped, z_warped def copy_warped(self, vel_grid=None, as_var=None, order=1, dt=1.0, device=None, var_name=None, clamp="NONE", trainable=None): if as_var is None: as_var = self.is_var if as_var and var_name is None: var_name = self._name + '_warped' if trainable is None: trainable = self._is_trainable x_warped, y_warped, z_warped = self.warped(vel_grid, order, dt, clamp=clamp) grid = VelocityGrid(self.centered_shape, x=x_warped, y=y_warped, z=z_warped, as_var=as_var, \ boundary=self.boundary, scale_renderer=self.scale_renderer, warp_renderer=self.warp_renderer, device=device, var_name=var_name, trainable=trainable) return grid def divergence_free(self, residual=1e-5): raise NotImplementedError def var_list(self): if self.is_var: return [self._x, self._y, self._z] else: raise TypeError("This VelocityGrid is not a variable.") def get_variables(self): if self.is_var: return {'velocity_x': self._x, 'velocity_y': self._y, 'velocity_z': self._z} else: raise TypeError("This VelocityGrid is not a variable.") def save(self, path): np.savez_compressed(path, centered_shape=self.centered_shape, vel_x=self.x.numpy(), vel_y=self.y.numpy(), vel_z=self.z.numpy()) def assign(self, x,y,z): x_shape = shape_list(x) if not len(x_shape)==5 or not x_shape[-1]==1 or not x_shape[-4:-1]==self.x_shape: raise ValueError("Invalid or incompatible shape of velocity x component on assignment: is {}, required: NDHW1 with DHW={}".format(x_shape, self.x_shape)) y_shape = shape_list(y) if not len(y_shape)==5 or not y_shape[-1]==1 or not y_shape[-4:-1]==self.y_shape: raise ValueError("Invalid or incompatible shape of velocity y component on assignment: is {}, required: NDHW1 with DHW={}".format(y_shape, self.y_shape)) z_shape = shape_list(z) if not len(z_shape)==5 or not z_shape[-1]==1 or not z_shape[-4:-1]==self.z_shape: raise ValueError("Invalid or incompatible shape of velocity z component on assignment: is {}, required: NDHW1 with DHW={}".format(z_shape, self.z_shape)) if self.is_var: self._x.assign(x) self._y.assign(y) self._z.assign(z) else: with tf.device(self._device): self._x = tf.identity(x) self._y = tf.identity(y) self._z = tf.identity(z) def assign_add(self, x,y,z): x_shape = shape_list(x) if not len(x_shape)==5 or not x_shape[-1]==1 or not x_shape[-4:-1]==self.x_shape: raise ValueError("Invalid or incompatible shape of velocity x component on assignment: is {}, required: NDHW1 with DHW={}".format(x_shape, self.x_shape)) y_shape = shape_list(y) if not len(y_shape)==5 or not y_shape[-1]==1 or not y_shape[-4:-1]==self.y_shape: raise ValueError("Invalid or incompatible shape of velocity y component on assignment: is {}, required: NDHW1 with DHW={}".format(y_shape, self.y_shape)) z_shape = shape_list(z) if not len(z_shape)==5 or not z_shape[-1]==1 or not z_shape[-4:-1]==self.z_shape: raise ValueError("Invalid or incompatible shape of velocity z component on assignment: is {}, required: NDHW1 with DHW={}".format(z_shape, self.z_shape)) if self.is_var: self._x.assign_add(x) self._y.assign_add(y) self._z.assign_add(z) else: with tf.device(self._device): self._x = tf.identity(self._x+x) self._y = tf.identity(self._y+y) self._z = tf.identity(self._z+z) def assign_sub(self, x,y,z): x_shape = shape_list(x) if not len(x_shape)==5 or not x_shape[-1]==1 or not x_shape[-4:-1]==self.x_shape: raise ValueError("Invalid or incompatible shape of velocity x component on assignment: is {}, required: NDHW1 with DHW={}".format(x_shape, self.x_shape)) y_shape = shape_list(y) if not len(y_shape)==5 or not y_shape[-1]==1 or not y_shape[-4:-1]==self.y_shape: raise ValueError("Invalid or incompatible shape of velocity y component on assignment: is {}, required: NDHW1 with DHW={}".format(y_shape, self.y_shape)) z_shape = shape_list(z) if not len(z_shape)==5 or not z_shape[-1]==1 or not z_shape[-4:-1]==self.z_shape: raise ValueError("Invalid or incompatible shape of velocity z component on assignment: is {}, required: NDHW1 with DHW={}".format(z_shape, self.z_shape)) if self.is_var: self._x.assign_sub(x) self._y.assign_sub(y) self._z.assign_sub(z) else: with tf.device(self._device): self._x = tf.identity(self._x-x) self._y = tf.identity(self._y-y) self._z = tf.identity(self._z-z) def scale_magnitude(self, scale): if np.isscalar(scale): scale = [scale]*3 assert len(scale)==3 self.assign(self.x*scale[0],self.y*scale[1], self.z*scale[2]) def _centered_to_staggered(self, centered): centered_shape = shape_list(centered) assert len(centered_shape)==5 assert centered_shape[-1]==3 assert centered_shape[0]==1 assert self.centered_shape==centered_shape[-4:-1] with self.scale_renderer.profiler.sample("centered velocity to staggered"): x,y,z= tf.split(centered, 3, axis=-1) centered_x_transform = GridTransform(self.centered_shape, scale=[2./_ for _ in self.x_shape[::-1]], center=True) centered_y_transform = GridTransform(self.centered_shape, scale=[2./_ for _ in self.y_shape[::-1]], center=True) centered_z_transform = GridTransform(self.centered_shape, scale=[2./_ for _ in self.z_shape[::-1]], center=True) # only shape important here staggered_x_transform = GridTransform(self.x_shape)#,translation=[0.5,0,0]) staggered_y_transform = GridTransform(self.y_shape)#,translation=[0,0.5,0]) staggered_z_transform = GridTransform(self.z_shape)#,translation=[0,0,0.5]) x = tf.squeeze(self.scale_renderer._sample_transform(x, [centered_x_transform], [staggered_x_transform]),1) y = tf.squeeze(self.scale_renderer._sample_transform(y, [centered_y_transform], [staggered_y_transform]),1) z = tf.squeeze(self.scale_renderer._sample_transform(z, [centered_z_transform], [staggered_z_transform]),1) return x,y,z def _staggeredTensor_to_components(self, tensor, reverse=False): tensor_shape = GridShape.from_tensor(tensor) # assert len(tensor_shape)==5 assert tensor_shape.c==3 assert tensor_shape.n==1 assert np.asarray(self.tensor_shape)+np.asarray([1,1,1])== tensor_shape.xyz.as_shape() #tensor_shape[-4:-1] tensor = tensor_shape.normalize_tensor_shape(tensor) components = tf.split(tensor, 3, axis=-1) if reverse: components = components[::-1] x = components[0][:,:-1,:-1,:] y = components[0][:,:-1,:,:-1] z = components[0][:,:,:-1,:-1] return x,y,z def as_staggeredTensor(self, reverse=False): z = (0,0) p = (0,1) components = [ tf.pad(self.x, [z,p,p,z,z]), tf.pad(self.y, [z,p,z,p,z]), tf.pad(self.z, [z,z,p,p,z]), ] if reverse: components = components[::-1] return tf.concat(components, axis=-1) def _sampled_to_shape(self, shape): with self.scale_renderer.profiler.sample("velocity to shape"): # uniform scaling, centered grids #_sample_transform assumes the output grid to be in a centered [-1,1] cube, so scale input accordingly # scale with output shape to get the right 0.5 offset scale = [2./_ for _ in shape[::-1]] staggered_x_transform = GridTransform(self.x_shape, scale=scale, center=True) staggered_y_transform = GridTransform(self.y_shape, scale=scale, center=True) staggered_z_transform = GridTransform(self.z_shape, scale=scale, center=True) # only shape important here sample_transform = GridTransform(shape) #check if shape matches component shape to avoid sampling (e.g. for self warping) vel_sampled = [ tf.squeeze(self.scale_renderer._sample_transform(self.x, [staggered_x_transform], [sample_transform]),1) \ if not shape==self.x_shape else tf.identity(self.x), #1DHW1 tf.squeeze(self.scale_renderer._sample_transform(self.y, [staggered_y_transform], [sample_transform]),1) \ if not shape==self.y_shape else tf.identity(self.y), tf.squeeze(self.scale_renderer._sample_transform(self.z, [staggered_z_transform], [sample_transform]),1) \ if not shape==self.z_shape else tf.identity(self.z), ] return vel_sampled def centered(self, pad_lod=False, concat=True):#, shape=None): shape = self.centered_shape with self.warp_renderer.profiler.sample("velocity to centered"): #vel_centered = self._sampled_to_shape(shape)#3 x 1DHW1 h = tf.constant(0.5, dtype=tf.float32) vel_centered = [ (self.x[:,:,:,1:] + self.x[:,:,:,:-1])*h, (self.y[:,:,1:] + self.y[:,:,:-1])*h, (self.z[:,1:] + self.z[:,:-1])*h, ] if pad_lod: vel_centered.append(self.lod_pad)#4 x 1DHW1 if concat: vel_centered = tf.concat(vel_centered, axis=-1) #1DHW[3|4] return vel_centered def _sampled_to_component_shape(self, component, pad_lod=False, concat=True): # grids have the same spacing/resolution, so global/constant offset component = component.upper() offset_coord_from = 0.5 offset_coord_to = -0.5 with self.warp_renderer.profiler.sample("velocity to component shape"): vel_sampled = [] # sample x vel_sampled.append(tf.identity(self.x) if component=='X' else \ tf.squeeze(self.warp_renderer.resample_grid3D_offset(self.x, \ offsets = [[offset_coord_from,offset_coord_to,0.0] if component=='Y' else [offset_coord_from,0.0,offset_coord_to],], \ target_shape = self.y_shape if component=='Y' else self.z_shape), 1)) # sample y vel_sampled.append(tf.identity(self.y) if component=='Y' else \ tf.squeeze(self.warp_renderer.resample_grid3D_offset(self.y, \ offsets = [[offset_coord_to,offset_coord_from,0.0] if component=='X' else [0.0,offset_coord_from,offset_coord_to],], \ target_shape = self.x_shape if component=='X' else self.z_shape), 1)) # sample z vel_sampled.append(tf.identity(self.z) if component=='Z' else \ tf.squeeze(self.warp_renderer.resample_grid3D_offset(self.z, \ offsets = [[offset_coord_to,0.0,offset_coord_from] if component=='X' else [0.0,offset_coord_to,offset_coord_from],], \ target_shape = self.x_shape if component=='X' else self.y_shape), 1)) if pad_lod: vel_sampled.append(self.lod_pad)#4 x 1DHW1 if concat: vel_sampled = tf.concat(vel_sampled, axis=-1) #1DHW[3|4] return vel_sampled def centered_lut_grid(self, dt=1.0): vel_centered = self.centered() #vel_lut = tf.concat([self.coords - vel_centered * dt, self.lod_pad], axis = -1) vel_lut = vel_centered * (- dt) return vel_lut def warp(self, data, order=1, dt=1.0, clamp="NONE"): with self.warp_renderer.profiler.sample("warp scalar"): v = self.centered_lut_grid(dt) data_shape = spacial_shape_list(data) if data_shape!=self.centered_shape: raise ValueError("Shape mismatch") LOG.debug("Warping density grid") data_warped = self.warp_renderer._sample_LuT(data, v, True, relative=True) clamp = clamp.upper() if order==2: #MacCormack data_warped_back = self.warp_renderer._sample_LuT(data_warped, -v, True, relative=True) data_corr = data_warped + 0.5*(data-data_warped_back) if clamp=='MC' or clamp=='MC_SMOOTH': #smooth clamp fm = self.warp_renderer.filter_mode self.warp_renderer.filter_mode = "MIN" data_min = self.warp_renderer._sample_LuT(data, v, True, relative=True) self.warp_renderer.filter_mode = "MAX" data_max = self.warp_renderer._sample_LuT(data, v, True, relative=True) self.warp_renderer.filter_mode = fm if clamp=='MC': #LOG.warning("Experimental clamp for MacCormack density advection.") raise NotImplementedError("MIM and MAX warp sampling have wrong gradients.") data_corr = tf.clip_by_value(data_corr, data_min, data_max) if clamp=='MC_SMOOTH': #LOG.warning("Experimental 'revert' clamp for MacCormack density advection.") clamp_OOB = tf.logical_or(tf.less(data_corr, data_min), tf.greater(data_corr, data_max)) data_corr = tf.where(clamp_OOB, data_warped, data_corr) data_warped = data_corr elif order>2: raise ValueError("Unsupported warp order '{}'".format(order)) if clamp=='NEGATIVE': data_warped = tf.maximum(data_warped, 0) return data_warped def with_buoyancy(self, value, scale_grid): # value: [x,y,z] # scale_grid: density 1DHW1 if isinstance(scale_grid, DensityGrid): scale_grid = scale_grid.with_inflow() #.d assert len(shape_list(value))==1 if not isinstance(value, (tf.Tensor, tf.Variable)): value = tf.constant(value, dtype=tf.float32) value = tf.reshape(value, [1,1,1,1,shape_list(value)[0]]) buoyancy = value*scale_grid # 1DHW3 return self + buoyancy """ def apply_buoyancy(self, value, scale_grid): # value: [x,y,z] # scale_grid: density 1DHW1 assert len(shape_list(value))==1 value = tf.reshape(tf.constant(value, dtype=tf.float32), [1,1,1,1,shape_list(value)[0]]) buoyancy = value*scale_grid # 1DHW3 self += buoyancy """ #centered def divergence(self, world_scale=[1,1,1]): #out - in per cell, per axis x_div = self.x[:,:,:,1:,:] - self.x[:,:,:,:-1,:] y_div = self.y[:,:,1:,:,:] - self.y[:,:,:-1,:,:] z_div = self.z[:,1:,:,:,:] - self.z[:,:-1,:,:,:] # sum to get total divergence per cell div = x_div*world_scale[0]+y_div*world_scale[1]+z_div*world_scale[2] return div #centered def magnitude(self, world_scale=[1,1,1]): with self.warp_renderer.profiler.sample("magnitude"): v = self.centered(pad_lod=False)*tf.constant(world_scale, dtype=tf.float32) return tf_norm2(v, axis=-1, keepdims=True) def stats(self, world_scale=[1,1,1], mask=None, state=None, **warp_kwargs): ''' mask: optional binary float mask, stats only consider cells>0.5 ''' x = self.x if mask is not None: mask_x = tf.greater(self.scale_renderer.resample_grid3D_aligned(mask, self.x_shape, align_x='stagger_output'), 0.5) x = tf.boolean_mask(x, mask_x) y = self.y if mask is not None: mask_y = tf.greater(self.scale_renderer.resample_grid3D_aligned(mask, self.y_shape, align_y='stagger_output'), 0.5) y = tf.boolean_mask(y, mask_y) z = self.z if mask is not None: mask_z = tf.greater(self.scale_renderer.resample_grid3D_aligned(mask, self.z_shape, align_z='stagger_output'), 0.5) z = tf.boolean_mask(z, mask_z) if mask is not None and mask.dtype!=tf.bool: mask = tf.greater(mask, 0.5) divergence = self.divergence(world_scale) if mask is not None: divergence = tf.boolean_mask(divergence, mask) magnitude = self.magnitude(world_scale) if mask is not None: magnitude = tf.boolean_mask(magnitude, mask) stats = { 'divergence': tf_tensor_stats(divergence, as_dict=True), 'magnitude': tf_tensor_stats(magnitude, as_dict=True), 'velocity_x': tf_tensor_stats(x, as_dict=True), 'velocity_y': tf_tensor_stats(y, as_dict=True), 'velocity_z': tf_tensor_stats(z, as_dict=True), 'shape':self.centered_shape, 'bounds':self.outer_bounds, } if state is not None and state.prev is not None and state.prev.velocity is not None: prev_warped = state.prev.velocity_advected(**warp_kwargs) def vel_warp_SE_stats(prev, curr, mask): warp_SE = tf.squared_difference(prev, curr) if mask is not None: warp_SE = tf.boolean_mask(warp_SE, mask) return tf_tensor_stats(warp_SE, as_dict=True) stats["warp_x_SE"] = vel_warp_SE_stats(prev_warped.x, self.x, mask_x if mask is not None else None) stats["warp_y_SE"] = vel_warp_SE_stats(prev_warped.y, self.y, mask_y if mask is not None else None) stats["warp_z_SE"] = vel_warp_SE_stats(prev_warped.z, self.z, mask_z if mask is not None else None) warp_vdiff_mag = (prev_warped-self).magnitude() if mask is not None: warp_vdiff_mag = tf.boolean_mask(warp_vdiff_mag, mask) stats["warp_vdiff_mag"] = tf_tensor_stats(warp_vdiff_mag, as_dict=True) del warp_vdiff_mag vel_CangleRad_mask = tf.greater(state.prev.velocity.magnitude() * self.magnitude(), 1e-8) if mask is not None: vel_CangleRad_mask = tf.logical_and(mask, vel_CangleRad_mask) warp_CangleRad = tf_angle_between(state.prev.velocity.centered(), self.centered(), axis=-1, keepdims=True) stats["warp_angleCM_rad"] = tf_tensor_stats(tf.boolean_mask(warp_CangleRad, vel_CangleRad_mask), as_dict=True) del warp_CangleRad else: stats["warp_x_SE"] = tf_tensor_stats(tf.zeros([1,1,1,1,1], dtype=tf.float32), as_dict=True) stats["warp_y_SE"] = tf_tensor_stats(tf.zeros([1,1,1,1,1], dtype=tf.float32), as_dict=True) stats["warp_z_SE"] = tf_tensor_stats(tf.zeros([1,1,1,1,1], dtype=tf.float32), as_dict=True) stats["warp_vdiff_mag"] = tf_tensor_stats(tf.zeros([1,1,1,1,1], dtype=tf.float32), as_dict=True) stats["warp_angleCM_rad"] = tf_tensor_stats(tf.zeros([1,1,1,1,1], dtype=tf.float32), as_dict=True) return stats def __add__(self, other): if isinstance(other, VelocityGrid): if self.centered_shape!=other.centered_shape: raise ValueError("VelocityGrids of shape %s and %s are not compatible"%(self.centered_shape, other.centered_shape)) return VelocityGrid(self.centered_shape, x=self.x+other.x, y=self.y+other.y, z=self.z+other.z, as_var=False, \ boundary=self.boundary, scale_renderer=self.scale_renderer, warp_renderer=self.warp_renderer, device=None) if isinstance(other, (np.ndarray, tf.Tensor, tf.Variable)): other_shape = shape_list(other) if self.centered_shape!=spacial_shape_list(other) or other_shape[0]!=1 or other_shape[-1]!=3: raise ValueError("VelocityGrid of shape %s is not compatible with tensor of shape %s are not compatible"%(self.centered_shape, spacial_shape_list(other))) x,y,z = self._centered_to_staggered(other) return VelocityGrid(self.centered_shape, x=self.x+x, y=self.y+y, z=self.z+z, as_var=False, \ boundary=self.boundary, scale_renderer=self.scale_renderer, warp_renderer=self.warp_renderer, device=None) else: return NotImplemented def __iadd__(self, other): if isinstance(other, VelocityGrid): if self.centered_shape!=other.centered_shape: raise ValueError("VelocityGrids of shape %s and %s are not compatible"%(self.centered_shape, other.centered_shape)) self.assign_add(other.x, other.y, other.z) return self if isinstance(other, (np.ndarray, tf.Tensor, tf.Variable)): other_shape = shape_list(other) if self.centered_shape!=spacial_shape_list(other) or other_shape[0]!=1 or other_shape[-1]!=3: raise ValueError("VelocityGrid of shape %s is not compatible with tensor of shape %s are not compatible"%(self.centered_shape, spacial_shape_list(other))) x,y,z = self._centered_to_staggered(other) self.assign_add(x, y, z) return self else: return NotImplemented def __sub__(self, other): if isinstance(other, VelocityGrid): if self.centered_shape!=other.centered_shape: raise ValueError("VelocityGrids of shape %s and %s are not compatible"%(self.centered_shape, other.centered_shape)) return VelocityGrid(self.centered_shape, x=self.x-other.x, y=self.y-other.y, z=self.z-other.z, as_var=False, \ boundary=self.boundary, scale_renderer=self.scale_renderer, warp_renderer=self.warp_renderer, device=None) if isinstance(other, (np.ndarray, tf.Tensor, tf.Variable)): other_shape = shape_list(other) if self.centered_shape!=spacial_shape_list(other) or other_shape[0]!=1 or other_shape[-1]!=3: raise ValueError("VelocityGrid of shape %s is not compatible with tensor of shape %s are not compatible"%(self.centered_shape, spacial_shape_list(other))) x,y,z = self._centered_to_staggered(other) return VelocityGrid(self.centered_shape, x=self.x-x, y=self.y-y, z=self.z-z, as_var=False, \ boundary=self.boundary, scale_renderer=self.scale_renderer, warp_renderer=self.warp_renderer, device=None) else: return NotImplemented def __isub__(self, other): if isinstance(other, VelocityGrid): if self.centered_shape!=other.centered_shape: raise ValueError("VelocityGrids of shape %s and %s are not compatible"%(self.centered_shape, other.centered_shape)) self.assign_sub(other.x, other.y, other.z) return self if isinstance(other, (np.ndarray, tf.Tensor, tf.Variable)): other_shape = shape_list(other) if self.centered_shape!=spacial_shape_list(other) or other_shape[0]!=1 or other_shape[-1]!=3: raise ValueError("VelocityGrid of shape %s is not compatible with tensor of shape %s are not compatible"%(self.centered_shape, spacial_shape_list(other))) x,y,z = self._centered_to_staggered(other) self.assign_sub(x, y, z) return self else: return NotImplemented class State: def __init__(self, density, velocity, frame, prev=None, next=None, transform=None, targets=None, targets_raw=None, bkgs=None): self._density = None if density is not None: assert isinstance(density, DensityGrid) self._density = density self._velocity = None if velocity is not None: assert isinstance(velocity, VelocityGrid) self._velocity = velocity self.frame = frame self.prev = prev self.next = next self.transform = transform self.targets = targets self.targets_raw = targets_raw self.bkgs = bkgs self.target_cameras = None self.images = None self.t = None class StateIterator: def __init__(self, state): self.curr_state = state def __next__(self): if self.curr_state is not None: state = self.curr_state self.curr_state = state.next return state raise StopIteration def __iter__(self): return self.StateIterator(self) @property def density(self): if self._density is not None: return self._density else: raise AttributeError("State for frame {} does not contain density".format(self.frame)) @property def velocity(self): if self._velocity is not None: return self._velocity else: raise AttributeError("State for frame {} does not contain velocity".format(self.frame)) @classmethod def from_file(cls, path, frame, transform=None, as_var=True, boundary=None, scale_renderer=None, warp_renderer=None, device=None, density_filename="density.npz", velocity_filename="velocity.npz"): density = DensityGrid.from_file(os.path.join(path, density_filename), as_var=as_var, scale_renderer=scale_renderer, device=device) velocity = VelocityGrid.from_file(os.path.join(path, velocity_filename), as_var=as_var, \ boundary=boundary, scale_renderer=scale_renderer, warp_renderer=warp_renderer, device=device) state = cls(density, velocity, frame, transform=transform) return state @classmethod def from_scalarFlow_file(cls, density_path, velocity_path, frame, transform=None, as_var=True, boundary=None, scale_renderer=None, warp_renderer=None, device=None): density = DensityGrid.from_scalarFlow_file(density_path, as_var=as_var, scale_renderer=scale_renderer, device=device) velocity = VelocityGrid.from_scalarFlow_file(velocity_path, as_var=as_var, \ boundary=boundary, scale_renderer=scale_renderer, warp_renderer=warp_renderer, device=device) state = cls(density, velocity, frame, transform=transform) return state def copy(self, as_var=None, device=None): s = State(self.density.copy(as_var=as_var, device=device), self.velocity.copy(as_var=as_var, device=device), self.frame) m = copy.copy(self.__dict__) del m["_velocity"] del m["_density"] del m["prev"] del m["next"] for k,v in m.items(): setattr(s,k,v) return s def copy_warped(self, order=1, dt=1.0, frame=None, as_var=None, targets=None, targets_raw=None, bkgs=None, device=None, clamp="NONE"): d = self.density.copy_warped(order=order, dt=dt, as_var=as_var, device=device, clamp=clamp) v = self.velocity.copy_warped(order=order, dt=dt, as_var=as_var, device=device, clamp=clamp) return State(d, v, frame, transform=self.transform, targets=targets, targets_raw=targets_raw, bkgs=bkgs) def get_density_transform(self): if isinstance(self.transform, GridTransform): return self.transform.copy_new_data(self.density.d) else: raise TypeError("state.transform is not a GridTransform") def get_velocity_transform(self): if isinstance(self.transform, GridTransform): return self.transform.copy_new_data(self.velocity.lod_pad) else: raise TypeError("state.transform is not a GridTransform") def render_density(self, render_ctx, custom_ops=None): imgs = tf.concat(render_ctx.dens_renderer.render_density(self.get_density_transform(), light_list=render_ctx.lights, camera_list=self.target_cameras, cut_alpha=False, monochrome=render_ctx.monochrome, custom_ops=custom_ops), axis=0) #, background=bkg imgs, d = tf.split(imgs, [3,1], axis=-1) t = tf.exp(-d) self.images = imgs self.t = t def density_advected(self, dt=1.0, order=1, clamp="NONE"): return self.density.warped(self.velocity, order=order, dt=dt, clamp=clamp)#self.velocity.warp(self.density, scale_renderer) def velocity_advected(self, dt=1.0, order=1, clamp="NONE"): return self.velocity.copy_warped(order=order, dt=dt, as_var=False, clamp=clamp) def rescale_density(self, shape, device=None): self._density = self.density.copy_scaled(shape, device=device) def rescale_velocity(self, shape, scale_magnitude=True, device=None): self._velocity = self.velocity.copy_scaled(shape, scale_magnitude=scale_magnitude, device=device) def rescale(self, dens_shape, vel_shape, device=None): rescale_density(self, dens_shape, device=device) rescale_velocity(self, vel_shape, device=device) def var_list(self): var_list = [] if self._density is not None: var_list += self.density.var_list() if self._velocity is not None: var_list += self.velocity.var_list() return var_list def get_variables(self): var_dict = {} if self._density is not None: var_dict.update(self.density.get_variables()) if self._velocity is not None: var_dict.update(self.velocity.get_variables()) return var_dict def stats(self, vel_scale=[1,1,1], mask=None, render_ctx=None, **warp_kwargs): target_stats = None if render_ctx is not None and getattr(self, "target_cameras", None) is not None: target_stats = {} self.render_density(render_ctx) if getattr(self, "targets_raw") is not None and getattr(self, "bkgs") is not None: target_stats["SE_raw"] = tf_tensor_stats(tf.math.squared_difference(self.images + self.bkgs*self.t, self.targets_raw), as_dict=True) if getattr(self, "targets") is not None: target_stats["SE"] = tf_tensor_stats(tf.math.squared_difference(self.images, self.targets), as_dict=True) return self.density.stats(mask=mask, state=self, **warp_kwargs), self.velocity.stats(vel_scale, mask=mask, state=self, **warp_kwargs), target_stats def save(self, path, suffix=None): self.density.save(os.path.join(path, 'density.npz' if suffix is None else 'density_'+suffix+'.npz')) self.velocity.save(os.path.join(path, 'velocity.npz' if suffix is None else 'velocity_'+suffix+'.npz')) class Sequence: def __init__(self, states): self.sequence = [state for state in states] class SequenceIterator: def __init__(self, sequence): self.seq = sequence self.idx = 0 def __next__(self): if self.idx<len(self.seq): idx = self.idx self.idx +=1 return self.seq[idx] raise StopIteration def __iter__(self): return self.SequenceIterator(self) def __getitem__(self, idx): return self.sequence[idx] def __len__(self): return len(self.sequence) @classmethod def from_file(cls, load_path, frames, transform=None, as_var=True, base_path=None, boundary=None, scale_renderer=None, warp_renderer=None, device=None, density_filename="density.npz", velocity_filename="velocity.npz", frame_callback=lambda idx, frame: None): sequence = [] prev = None for idx, frame in enumerate(frames): frame_callback(idx, frame) sub_dir = 'frame_{:06d}'.format(frame) data_path = os.path.join(load_path, sub_dir) state = State.from_file(data_path, frame, transform=transform, as_var=as_var, boundary=boundary, scale_renderer=scale_renderer, warp_renderer=warp_renderer, \ device=device, density_filename=density_filename, velocity_filename=velocity_filename) if base_path is not None: state.data_path = os.path.join(base_path, sub_dir) os.makedirs(state.data_path, exist_ok=True) state.prev = prev prev = state sequence.append(state) for i in range(len(sequence)-1): sequence[i].next = sequence[i+1] return cls(sequence) @classmethod def from_scalarFlow_file(cls, density_path_mask, velocity_path_mask, frames, transform=None, as_var=True, base_path=None, boundary=None, scale_renderer=None, warp_renderer=None, device=None, vel_frame_offset=1, frame_callback=lambda idx, frame: None): sequence = [] prev = None for idx, frame in enumerate(frames): frame_callback(idx, frame) sub_dir = 'frame_{:06d}'.format(frame) density_path = density_path_mask.format(frame=frame) velocity_path = velocity_path_mask.format(frame=frame+vel_frame_offset) state = State.from_scalarFlow_file(density_path, velocity_path, frame=frame, transform=transform, as_var=as_var, boundary=boundary, scale_renderer=scale_renderer, warp_renderer=warp_renderer, device=device) if base_path is not None: state.data_path = os.path.join(base_path, sub_dir) os.makedirs(state.data_path, exist_ok=True) state.prev = prev prev = state sequence.append(state) for i in range(len(sequence)-1): sequence[i].next = sequence[i+1] return cls(sequence) def copy(self, as_var=None, device=None): s = [_.copy(as_var=as_var, device=device) for _ in self] for i in range(len(s)): if i>0: s[i].prev = s[i-1] if i<(len(s)-1): s[i].next = s[i+1] return Sequence(s) def insert_state(self, state, idx): self.sequence.insert(state, idx) def append_state(self, state): self.sequence.append(state) def start_iteration(self, iteration): for state in self: ctx.start_iteration(iteration) def stats(self, vel_scale=[1,1,1], mask=None, **warp_kwargs): return [_.stats(vel_scale, mask=mask, state=_, **warp_kwargs) for _ in self] def save(self, path=None, suffix=None): for state in self: if path is None and hasattr(state, 'data_path'): state.save(state.data_path, suffix) else: state.save(os.path.join(path, 'frame_{:06d}'.format(state.frame)), suffix) def densities_advect_fwd(self, dt=1.0, order=1, clamp='NONE'): if clamp is None or clamp.upper()not in ['LOCAL', 'GLOBAL']: for i in range(1, len(self)): self[i].density.assign(self[i-1].density_advected(order=order, dt=dt, clamp=clamp)) elif clamp.upper()=='LOCAL': #clamp after each step, before the next warp for i in range(1, len(self)): self[i].density.assign(tf.maximum(self[i-1].density_advected(order=order, dt=dt), 0)) elif clamp.upper()=='GLOBAL': #clamp after all warping for i in range(1, len(self)): self[i].density.assign(self[i-1].density_advected(order=order, dt=dt)) for i in range(1, len(self)): self[i].density.assign(tf.maximum(self[i].density._d, 0)) def velocities_advect_fwd(self, dt=1.0, order=1, clamp='NONE'): for i in range(1, len(self)): self[i].velocity.assign(*self[i-1].velocity.warped(order=order, dt=dt, clamp=clamp))
[ "logging.getLogger", "tensorflow.pad", "tensorflow.boolean_mask", "lib.tf_ops.tf_tensor_stats", "tensorflow.split", "lib.tf_ops.spacial_shape_list", "lib.tf_ops.tf_norm2", "tensorflow.ones_like", "tensorflow.reduce_mean", "copy.copy", "tensorflow.cast", "numpy.load", "lib.util.load_numpy", ...
[((329, 357), 'logging.getLogger', 'logging.getLogger', (['"""Structs"""'], {}), "('Structs')\n", (346, 357), False, 'import logging\n'), ((576, 612), 'tensorflow.range', 'tf.range', (['shape[0]'], {'dtype': 'tf.float32'}), '(shape[0], dtype=tf.float32)\n', (584, 612), True, 'import tensorflow as tf\n'), ((614, 650), 'tensorflow.range', 'tf.range', (['shape[1]'], {'dtype': 'tf.float32'}), '(shape[1], dtype=tf.float32)\n', (622, 650), True, 'import tensorflow as tf\n'), ((652, 688), 'tensorflow.range', 'tf.range', (['shape[2]'], {'dtype': 'tf.float32'}), '(shape[2], dtype=tf.float32)\n', (660, 688), True, 'import tensorflow as tf\n'), ((728, 778), 'tensorflow.reshape', 'tf.reshape', (['(coord_x + offset[0])', '([1] + shape + [1])'], {}), '(coord_x + offset[0], [1] + shape + [1])\n', (738, 778), True, 'import tensorflow as tf\n'), ((779, 829), 'tensorflow.reshape', 'tf.reshape', (['(coord_y + offset[1])', '([1] + shape + [1])'], {}), '(coord_y + offset[1], [1] + shape + [1])\n', (789, 829), True, 'import tensorflow as tf\n'), ((830, 880), 'tensorflow.reshape', 'tf.reshape', (['(coord_z + offset[2])', '([1] + shape + [1])'], {}), '(coord_z + offset[2], [1] + shape + [1])\n', (840, 880), True, 'import tensorflow as tf\n'), ((925, 984), 'tensorflow.constant', 'tf.constant', (['lod'], {'shape': '([1] + shape + [1])', 'dtype': 'tf.float32'}), '(lod, shape=[1] + shape + [1], dtype=tf.float32)\n', (936, 984), True, 'import tensorflow as tf\n'), ((1079, 1109), 'tensorflow.concat', 'tf.concat', (['coord_data'], {'axis': '(-1)'}), '(coord_data, axis=-1)\n', (1088, 1109), True, 'import tensorflow as tf\n'), ((1939, 1958), 'tensorflow.less_equal', 'tf.less_equal', (['a', '(0)'], {}), '(a, 0)\n', (1952, 1958), True, 'import tensorflow as tf\n'), ((2389, 2419), 'numpy.zeros', 'np.zeros', (['(5,)'], {'dtype': 'np.int32'}), '((5,), dtype=np.int32)\n', (2397, 2419), True, 'import numpy as np\n'), ((2436, 2475), 'tensorflow.slice', 'tf.slice', (['self._levelset', 'offset', 'shape'], {}), '(self._levelset, offset, shape)\n', (2444, 2475), True, 'import tensorflow as tf\n'), ((2542, 2581), 'tensorflow.slice', 'tf.slice', (['self._levelset', 'offset', 'shape'], {}), '(self._levelset, offset, shape)\n', (2550, 2581), True, 'import tensorflow as tf\n'), ((2687, 2761), 'tensorflow.pad', 'tf.pad', (['hull', 'pad'], {'constant_values': "(1 if self.outer_bounds == 'OPEN' else 0)"}), "(hull, pad, constant_values=1 if self.outer_bounds == 'OPEN' else 0)\n", (2693, 2761), True, 'import tensorflow as tf\n'), ((7819, 7857), 'tensorflow.constant', 'tf.constant', (['density'], {'dtype': 'tf.float32'}), '(density, dtype=tf.float32)\n', (7830, 7857), True, 'import tensorflow as tf\n'), ((7871, 7898), 'lib.tf_ops.spacial_shape_list', 'spacial_shape_list', (['density'], {}), '(density)\n', (7889, 7898), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((12154, 12173), 'tensorflow.maximum', 'tf.maximum', (['vmin', '(0)'], {}), '(vmin, 0)\n', (12164, 12173), True, 'import tensorflow as tf\n'), ((12181, 12218), 'tensorflow.clip_by_value', 'tf.clip_by_value', (['self._d', 'vmin', 'vmax'], {}), '(self._d, vmin, vmax)\n', (12197, 12218), True, 'import tensorflow as tf\n'), ((12938, 12951), 'lib.tf_ops.shape_list', 'shape_list', (['d'], {}), '(d)\n', (12948, 12951), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((14649, 14691), 'numpy.savez_compressed', 'np.savez_compressed', (['path', 'density'], {}), '(path, density, **save)\n', (14668, 14691), True, 'import numpy as np\n'), ((14723, 14745), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['self.d'], {}), '(self.d)\n', (14737, 14745), True, 'import tensorflow as tf\n'), ((15676, 15701), 'copy.copy', 'copy.copy', (['centered_shape'], {}), '(centered_shape)\n', (15685, 15701), False, 'import copy, os\n'), ((15733, 15758), 'copy.copy', 'copy.copy', (['centered_shape'], {}), '(centered_shape)\n', (15742, 15758), False, 'import copy, os\n'), ((15790, 15815), 'copy.copy', 'copy.copy', (['centered_shape'], {}), '(centered_shape)\n', (15799, 15815), False, 'import copy, os\n'), ((20104, 20129), 'lib.tf_ops.shape_list', 'shape_list', (['centered_grid'], {}), '(centered_grid)\n', (20114, 20129), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((21897, 21936), 'tensorflow.constant', 'tf.constant', (['velocity'], {'dtype': 'tf.float32'}), '(velocity, dtype=tf.float32)\n', (21908, 21936), True, 'import tensorflow as tf\n'), ((21987, 22017), 'tensorflow.split', 'tf.split', (['velocity', '(3)'], {'axis': '(-1)'}), '(velocity, 3, axis=-1)\n', (21995, 22017), True, 'import tensorflow as tf\n'), ((22072, 22122), 'tensorflow.pad', 'tf.pad', (['v_x', '[p0, p0, p0, (0, 1), p0]', '"""SYMMETRIC"""'], {}), "(v_x, [p0, p0, p0, (0, 1), p0], 'SYMMETRIC')\n", (22078, 22122), True, 'import tensorflow as tf\n'), ((22127, 22177), 'tensorflow.pad', 'tf.pad', (['v_y', '[p0, p0, (0, 1), p0, p0]', '"""SYMMETRIC"""'], {}), "(v_y, [p0, p0, (0, 1), p0, p0], 'SYMMETRIC')\n", (22133, 22177), True, 'import tensorflow as tf\n'), ((22182, 22233), 'tensorflow.pad', 'tf.pad', (['(-v_z)', '[p0, (1, 0), p0, p0, p0]', '"""SYMMETRIC"""'], {}), "(-v_z, [p0, (1, 0), p0, p0, p0], 'SYMMETRIC')\n", (22188, 22233), True, 'import tensorflow as tf\n'), ((26381, 26408), 'tensorflow.concat', 'tf.concat', (['vel_lut'], {'axis': '(-1)'}), '(vel_lut, axis=-1)\n', (26390, 26408), True, 'import tensorflow as tf\n'), ((30495, 30508), 'lib.tf_ops.shape_list', 'shape_list', (['x'], {}), '(x)\n', (30505, 30508), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((30765, 30778), 'lib.tf_ops.shape_list', 'shape_list', (['y'], {}), '(y)\n', (30775, 30778), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((31035, 31048), 'lib.tf_ops.shape_list', 'shape_list', (['z'], {}), '(z)\n', (31045, 31048), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((31557, 31570), 'lib.tf_ops.shape_list', 'shape_list', (['x'], {}), '(x)\n', (31567, 31570), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((31827, 31840), 'lib.tf_ops.shape_list', 'shape_list', (['y'], {}), '(y)\n', (31837, 31840), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((32097, 32110), 'lib.tf_ops.shape_list', 'shape_list', (['z'], {}), '(z)\n', (32107, 32110), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((32655, 32668), 'lib.tf_ops.shape_list', 'shape_list', (['x'], {}), '(x)\n', (32665, 32668), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((32925, 32938), 'lib.tf_ops.shape_list', 'shape_list', (['y'], {}), '(y)\n', (32935, 32938), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((33195, 33208), 'lib.tf_ops.shape_list', 'shape_list', (['z'], {}), '(z)\n', (33205, 33208), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((33751, 33769), 'numpy.isscalar', 'np.isscalar', (['scale'], {}), '(scale)\n', (33762, 33769), True, 'import numpy as np\n'), ((33951, 33971), 'lib.tf_ops.shape_list', 'shape_list', (['centered'], {}), '(centered)\n', (33961, 33971), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((35606, 35634), 'tensorflow.split', 'tf.split', (['tensor', '(3)'], {'axis': '(-1)'}), '(tensor, 3, axis=-1)\n', (35614, 35634), True, 'import tensorflow as tf\n'), ((36060, 36090), 'tensorflow.concat', 'tf.concat', (['components'], {'axis': '(-1)'}), '(components, axis=-1)\n', (36069, 36090), True, 'import tensorflow as tf\n'), ((52702, 52726), 'copy.copy', 'copy.copy', (['self.__dict__'], {}), '(self.__dict__)\n', (52711, 52726), False, 'import copy, os\n'), ((54062, 54093), 'tensorflow.split', 'tf.split', (['imgs', '[3, 1]'], {'axis': '(-1)'}), '(imgs, [3, 1], axis=-1)\n', (54070, 54093), True, 'import tensorflow as tf\n'), ((54100, 54110), 'tensorflow.exp', 'tf.exp', (['(-d)'], {}), '(-d)\n', (54106, 54110), True, 'import tensorflow as tf\n'), ((1441, 1464), 'tensorflow.device', 'tf.device', (['self._device'], {}), '(self._device)\n', (1450, 1464), True, 'import tensorflow as tf\n'), ((2121, 2150), 'tensorflow.cast', 'tf.cast', (['a_leq'], {'dtype': 'a.dtype'}), '(a_leq, dtype=a.dtype)\n', (2128, 2150), True, 'import tensorflow as tf\n'), ((3087, 3116), 'tensorflow.greater', 'tf.greater', (['self._levelset', '(0)'], {}), '(self._levelset, 0)\n', (3097, 3116), True, 'import tensorflow as tf\n'), ((3166, 3183), 'lib.tf_ops.shape_list', 'shape_list', (['shape'], {}), '(shape)\n', (3176, 3183), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((3692, 3705), 'lib.tf_ops.shape_list', 'shape_list', (['d'], {}), '(d)\n', (3702, 3705), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((4011, 4044), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['constant'], {}), '(constant)\n', (4034, 4044), True, 'import tensorflow as tf\n'), ((4504, 4527), 'tensorflow.device', 'tf.device', (['self._device'], {}), '(self._device)\n', (4513, 4527), True, 'import tensorflow as tf\n'), ((5213, 5245), 'lib.tf_ops.spacial_shape_list', 'spacial_shape_list', (['self._inflow'], {}), '(self._inflow)\n', (5231, 5245), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((5668, 5688), 'tensorflow.identity', 'tf.identity', (['self._d'], {}), '(self._d)\n', (5679, 5688), True, 'import tensorflow as tf\n'), ((5828, 5848), 'tensorflow.identity', 'tf.identity', (['self._d'], {}), '(self._d)\n', (5839, 5848), True, 'import tensorflow as tf\n'), ((5923, 5963), 'tensorflow.zeros_like', 'tf.zeros_like', (['self._d'], {'dtype': 'tf.float32'}), '(self._d, dtype=tf.float32)\n', (5936, 5963), True, 'import tensorflow as tf\n'), ((6265, 6301), 'tensorflow.maximum', 'tf.maximum', (['(density + self.inflow)', '(0)'], {}), '(density + self.inflow, 0)\n', (6275, 6301), True, 'import tensorflow as tf\n'), ((8399, 8448), 'tensorflow.split', 'tf.split', (['density', '[15, d_shape[1] - 15]'], {'axis': '(-3)'}), '(density, [15, d_shape[1] - 15], axis=-3)\n', (8407, 8448), True, 'import tensorflow as tf\n'), ((8465, 8503), 'tensorflow.ones_like', 'tf.ones_like', (['inflow'], {'dtype': 'tf.float32'}), '(inflow, dtype=tf.float32)\n', (8477, 8503), True, 'import tensorflow as tf\n'), ((10389, 10409), 'tensorflow.identity', 'tf.identity', (['density'], {}), '(density)\n', (10400, 10409), True, 'import tensorflow as tf\n'), ((12338, 12351), 'lib.tf_ops.shape_list', 'shape_list', (['d'], {}), '(d)\n', (12348, 12351), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((12783, 12861), 'tensorflow.clip_by_value', 'tf.clip_by_value', (['self._inflow', '(vmin - density_cropped)', '(vmax - density_cropped)'], {}), '(self._inflow, vmin - density_cropped, vmax - density_cropped)\n', (12799, 12861), True, 'import tensorflow as tf\n'), ((14615, 14645), 'numpy.asarray', 'np.asarray', (['self.inflow_offset'], {}), '(self.inflow_offset)\n', (14625, 14645), True, 'import numpy as np\n'), ((15001, 15025), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['d', 'mask'], {}), '(d, mask)\n', (15016, 15025), True, 'import tensorflow as tf\n'), ((15058, 15090), 'lib.tf_ops.tf_tensor_stats', 'tf_tensor_stats', (['d'], {'as_dict': '(True)'}), '(d, as_dict=True)\n', (15073, 15090), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((15426, 15464), 'lib.tf_ops.tf_tensor_stats', 'tf_tensor_stats', (['warp_SE'], {'as_dict': '(True)'}), '(warp_SE, as_dict=True)\n', (15441, 15464), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((17180, 17191), 'tensorflow.abs', 'tf.abs', (['std'], {}), '(std)\n', (17186, 17191), True, 'import tensorflow as tf\n'), ((17208, 17248), 'tensorflow.random_uniform_initializer', 'tf.random_uniform_initializer', (['(-std)', 'std'], {}), '(-std, std)\n', (17237, 17248), True, 'import tensorflow as tf\n'), ((18261, 18302), 'tensorflow.zeros', 'tf.zeros', (['([1] + self.centered_shape + [1])'], {}), '([1] + self.centered_shape + [1])\n', (18269, 18302), True, 'import tensorflow as tf\n'), ((18307, 18330), 'tensorflow.device', 'tf.device', (['self._device'], {}), '(self._device)\n', (18316, 18330), True, 'import tensorflow as tf\n'), ((18351, 18367), 'tensorflow.identity', 'tf.identity', (['lod'], {}), '(lod)\n', (18362, 18367), True, 'import tensorflow as tf\n'), ((25378, 25397), 'tensorflow.identity', 'tf.identity', (['self.x'], {}), '(self.x)\n', (25389, 25397), True, 'import tensorflow as tf\n'), ((25413, 25432), 'tensorflow.identity', 'tf.identity', (['self.y'], {}), '(self.y)\n', (25424, 25432), True, 'import tensorflow as tf\n'), ((25448, 25467), 'tensorflow.identity', 'tf.identity', (['self.z'], {}), '(self.z)\n', (25459, 25467), True, 'import tensorflow as tf\n'), ((34211, 34241), 'tensorflow.split', 'tf.split', (['centered', '(3)'], {'axis': '(-1)'}), '(centered, 3, axis=-1)\n', (34219, 34241), True, 'import tensorflow as tf\n'), ((35901, 35932), 'tensorflow.pad', 'tf.pad', (['self.x', '[z, p, p, z, z]'], {}), '(self.x, [z, p, p, z, z])\n', (35907, 35932), True, 'import tensorflow as tf\n'), ((35934, 35965), 'tensorflow.pad', 'tf.pad', (['self.y', '[z, p, z, p, z]'], {}), '(self.y, [z, p, z, p, z])\n', (35940, 35965), True, 'import tensorflow as tf\n'), ((35967, 35998), 'tensorflow.pad', 'tf.pad', (['self.z', '[z, z, p, p, z]'], {}), '(self.z, [z, z, p, p, z])\n', (35973, 35998), True, 'import tensorflow as tf\n'), ((37652, 37686), 'tensorflow.constant', 'tf.constant', (['(0.5)'], {'dtype': 'tf.float32'}), '(0.5, dtype=tf.float32)\n', (37663, 37686), True, 'import tensorflow as tf\n'), ((39952, 39976), 'lib.tf_ops.spacial_shape_list', 'spacial_shape_list', (['data'], {}), '(data)\n', (39970, 39976), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((41806, 41842), 'tensorflow.constant', 'tf.constant', (['value'], {'dtype': 'tf.float32'}), '(value, dtype=tf.float32)\n', (41817, 41842), True, 'import tensorflow as tf\n'), ((42846, 42881), 'lib.tf_ops.tf_norm2', 'tf_norm2', (['v'], {'axis': '(-1)', 'keepdims': '(True)'}), '(v, axis=-1, keepdims=True)\n', (42854, 42881), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((43211, 43237), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['x', 'mask_x'], {}), '(x, mask_x)\n', (43226, 43237), True, 'import tensorflow as tf\n'), ((43404, 43430), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['y', 'mask_y'], {}), '(y, mask_y)\n', (43419, 43430), True, 'import tensorflow as tf\n'), ((43597, 43623), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['z', 'mask_z'], {}), '(z, mask_z)\n', (43612, 43623), True, 'import tensorflow as tf\n'), ((43683, 43704), 'tensorflow.greater', 'tf.greater', (['mask', '(0.5)'], {}), '(mask, 0.5)\n', (43693, 43704), True, 'import tensorflow as tf\n'), ((43791, 43824), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['divergence', 'mask'], {}), '(divergence, mask)\n', (43806, 43824), True, 'import tensorflow as tf\n'), ((43904, 43936), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['magnitude', 'mask'], {}), '(magnitude, mask)\n', (43919, 43936), True, 'import tensorflow as tf\n'), ((43972, 44013), 'lib.tf_ops.tf_tensor_stats', 'tf_tensor_stats', (['divergence'], {'as_dict': '(True)'}), '(divergence, as_dict=True)\n', (43987, 44013), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((44032, 44072), 'lib.tf_ops.tf_tensor_stats', 'tf_tensor_stats', (['magnitude'], {'as_dict': '(True)'}), '(magnitude, as_dict=True)\n', (44047, 44072), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((44092, 44124), 'lib.tf_ops.tf_tensor_stats', 'tf_tensor_stats', (['x'], {'as_dict': '(True)'}), '(x, as_dict=True)\n', (44107, 44124), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((44144, 44176), 'lib.tf_ops.tf_tensor_stats', 'tf_tensor_stats', (['y'], {'as_dict': '(True)'}), '(y, as_dict=True)\n', (44159, 44176), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((44196, 44228), 'lib.tf_ops.tf_tensor_stats', 'tf_tensor_stats', (['z'], {'as_dict': '(True)'}), '(z, as_dict=True)\n', (44211, 44228), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((45157, 45202), 'lib.tf_ops.tf_tensor_stats', 'tf_tensor_stats', (['warp_vdiff_mag'], {'as_dict': '(True)'}), '(warp_vdiff_mag, as_dict=True)\n', (45172, 45202), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((46741, 46758), 'lib.tf_ops.shape_list', 'shape_list', (['other'], {}), '(other)\n', (46751, 46758), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((47694, 47711), 'lib.tf_ops.shape_list', 'shape_list', (['other'], {}), '(other)\n', (47704, 47711), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((48646, 48663), 'lib.tf_ops.shape_list', 'shape_list', (['other'], {}), '(other)\n', (48656, 48663), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((49599, 49616), 'lib.tf_ops.shape_list', 'shape_list', (['other'], {}), '(other)\n', (49609, 49616), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((51594, 51630), 'os.path.join', 'os.path.join', (['path', 'density_filename'], {}), '(path, density_filename)\n', (51606, 51630), False, 'import copy, os\n'), ((51730, 51767), 'os.path.join', 'os.path.join', (['path', 'velocity_filename'], {}), '(path, velocity_filename)\n', (51742, 51767), False, 'import copy, os\n'), ((56220, 56309), 'os.path.join', 'os.path.join', (['path', "('density.npz' if suffix is None else 'density_' + suffix + '.npz')"], {}), "(path, 'density.npz' if suffix is None else 'density_' + suffix +\n '.npz')\n", (56232, 56309), False, 'import copy, os\n'), ((56325, 56416), 'os.path.join', 'os.path.join', (['path', "('velocity.npz' if suffix is None else 'velocity_' + suffix + '.npz')"], {}), "(path, 'velocity.npz' if suffix is None else 'velocity_' +\n suffix + '.npz')\n", (56337, 56416), False, 'import copy, os\n'), ((57367, 57399), 'os.path.join', 'os.path.join', (['load_path', 'sub_dir'], {}), '(load_path, sub_dir)\n', (57379, 57399), False, 'import copy, os\n'), ((1554, 1617), 'tensorflow.constant', 'tf.constant', (['initial_value'], {'shape': 'shape.value', 'dtype': 'tf.float32'}), '(initial_value, shape=shape.value, dtype=tf.float32)\n', (1565, 1617), True, 'import tensorflow as tf\n'), ((1655, 1731), 'tensorflow.Variable', 'tf.Variable', ([], {'initial_value': 'initial_value', 'name': 'var_name', 'trainable': 'trainable'}), '(initial_value=initial_value, name=var_name, trainable=trainable)\n', (1666, 1731), True, 'import tensorflow as tf\n'), ((1764, 1790), 'tensorflow.identity', 'tf.identity', (['initial_value'], {}), '(initial_value)\n', (1775, 1790), True, 'import tensorflow as tf\n'), ((2000, 2019), 'tensorflow.less_equal', 'tf.less_equal', (['b', '(0)'], {}), '(b, 0)\n', (2013, 2019), True, 'import tensorflow as tf\n'), ((4054, 4077), 'tensorflow.device', 'tf.device', (['self._device'], {}), '(self._device)\n', (4063, 4077), True, 'import tensorflow as tf\n'), ((4261, 4284), 'tensorflow.device', 'tf.device', (['self._device'], {}), '(self._device)\n', (4270, 4284), True, 'import tensorflow as tf\n'), ((4545, 4580), 'tensorflow.constant', 'tf.constant', (['hull'], {'dtype': 'tf.float32'}), '(hull, dtype=tf.float32)\n', (4556, 4580), True, 'import tensorflow as tf\n'), ((4694, 4717), 'tensorflow.device', 'tf.device', (['self._device'], {}), '(self._device)\n', (4703, 4717), True, 'import tensorflow as tf\n'), ((6048, 6109), 'tensorflow.pad', 'tf.pad', (['(self._inflow * self.inflow_mask)', 'self._inflow_padding'], {}), '(self._inflow * self.inflow_mask, self._inflow_padding)\n', (6054, 6109), True, 'import tensorflow as tf\n'), ((6128, 6170), 'tensorflow.pad', 'tf.pad', (['self._inflow', 'self._inflow_padding'], {}), '(self._inflow, self._inflow_padding)\n', (6134, 6170), True, 'import tensorflow as tf\n'), ((6549, 6562), 'numpy.load', 'np.load', (['path'], {}), '(path)\n', (6556, 6562), True, 'import numpy as np\n'), ((6613, 6634), 'lib.tf_ops.spacial_shape_list', 'spacial_shape_list', (['d'], {}), '(d)\n', (6631, 6634), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((13318, 13341), 'tensorflow.device', 'tf.device', (['self._device'], {}), '(self._device)\n', (13327, 13341), True, 'import tensorflow as tf\n'), ((13358, 13372), 'tensorflow.identity', 'tf.identity', (['d'], {}), '(d)\n', (13369, 13372), True, 'import tensorflow as tf\n'), ((14971, 14992), 'tensorflow.greater', 'tf.greater', (['mask', '(0.5)'], {}), '(mask, 0.5)\n', (14981, 14992), True, 'import tensorflow as tf\n'), ((15372, 15402), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['warp_SE', 'mask'], {}), '(warp_SE, mask)\n', (15387, 15402), True, 'import tensorflow as tf\n'), ((15513, 15556), 'tensorflow.zeros', 'tf.zeros', (['[1, 1, 1, 1, 1]'], {'dtype': 'tf.float32'}), '([1, 1, 1, 1, 1], dtype=tf.float32)\n', (15521, 15556), True, 'import tensorflow as tf\n'), ((16488, 16501), 'lib.tf_ops.shape_list', 'shape_list', (['x'], {}), '(x)\n', (16498, 16501), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((16704, 16717), 'lib.tf_ops.shape_list', 'shape_list', (['y'], {}), '(y)\n', (16714, 16717), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((16920, 16933), 'lib.tf_ops.shape_list', 'shape_list', (['z'], {}), '(z)\n', (16930, 16933), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((17364, 17387), 'tensorflow.device', 'tf.device', (['self._device'], {}), '(self._device)\n', (17373, 17387), True, 'import tensorflow as tf\n'), ((20737, 20750), 'numpy.load', 'np.load', (['path'], {}), '(path)\n', (20744, 20750), True, 'import numpy as np\n'), ((23997, 24017), 'tensorflow.identity', 'tf.identity', (['self._x'], {}), '(self._x)\n', (24008, 24017), True, 'import tensorflow as tf\n'), ((24021, 24041), 'tensorflow.identity', 'tf.identity', (['self._y'], {}), '(self._y)\n', (24032, 24041), True, 'import tensorflow as tf\n'), ((24045, 24065), 'tensorflow.identity', 'tf.identity', (['self._z'], {}), '(self._z)\n', (24056, 24065), True, 'import tensorflow as tf\n'), ((31395, 31418), 'tensorflow.device', 'tf.device', (['self._device'], {}), '(self._device)\n', (31404, 31418), True, 'import tensorflow as tf\n'), ((31435, 31449), 'tensorflow.identity', 'tf.identity', (['x'], {}), '(x)\n', (31446, 31449), True, 'import tensorflow as tf\n'), ((31465, 31479), 'tensorflow.identity', 'tf.identity', (['y'], {}), '(y)\n', (31476, 31479), True, 'import tensorflow as tf\n'), ((31495, 31509), 'tensorflow.identity', 'tf.identity', (['z'], {}), '(z)\n', (31506, 31509), True, 'import tensorflow as tf\n'), ((32469, 32492), 'tensorflow.device', 'tf.device', (['self._device'], {}), '(self._device)\n', (32478, 32492), True, 'import tensorflow as tf\n'), ((32509, 32533), 'tensorflow.identity', 'tf.identity', (['(self._x + x)'], {}), '(self._x + x)\n', (32520, 32533), True, 'import tensorflow as tf\n'), ((32547, 32571), 'tensorflow.identity', 'tf.identity', (['(self._y + y)'], {}), '(self._y + y)\n', (32558, 32571), True, 'import tensorflow as tf\n'), ((32585, 32609), 'tensorflow.identity', 'tf.identity', (['(self._z + z)'], {}), '(self._z + z)\n', (32596, 32609), True, 'import tensorflow as tf\n'), ((33567, 33590), 'tensorflow.device', 'tf.device', (['self._device'], {}), '(self._device)\n', (33576, 33590), True, 'import tensorflow as tf\n'), ((33607, 33631), 'tensorflow.identity', 'tf.identity', (['(self._x - x)'], {}), '(self._x - x)\n', (33618, 33631), True, 'import tensorflow as tf\n'), ((33645, 33669), 'tensorflow.identity', 'tf.identity', (['(self._y - y)'], {}), '(self._y - y)\n', (33656, 33669), True, 'import tensorflow as tf\n'), ((33683, 33707), 'tensorflow.identity', 'tf.identity', (['(self._z - z)'], {}), '(self._z - z)\n', (33694, 33707), True, 'import tensorflow as tf\n'), ((35433, 35462), 'numpy.asarray', 'np.asarray', (['self.tensor_shape'], {}), '(self.tensor_shape)\n', (35443, 35462), True, 'import numpy as np\n'), ((35463, 35484), 'numpy.asarray', 'np.asarray', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (35473, 35484), True, 'import numpy as np\n'), ((37943, 37975), 'tensorflow.concat', 'tf.concat', (['vel_centered'], {'axis': '(-1)'}), '(vel_centered, axis=-1)\n', (37952, 37975), True, 'import tensorflow as tf\n'), ((39505, 39536), 'tensorflow.concat', 'tf.concat', (['vel_sampled'], {'axis': '(-1)'}), '(vel_sampled, axis=-1)\n', (39514, 39536), True, 'import tensorflow as tf\n'), ((41459, 41485), 'tensorflow.maximum', 'tf.maximum', (['data_warped', '(0)'], {}), '(data_warped, 0)\n', (41469, 41485), True, 'import tensorflow as tf\n'), ((41717, 41734), 'lib.tf_ops.shape_list', 'shape_list', (['value'], {}), '(value)\n', (41727, 41734), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((42792, 42834), 'tensorflow.constant', 'tf.constant', (['world_scale'], {'dtype': 'tf.float32'}), '(world_scale, dtype=tf.float32)\n', (42803, 42834), True, 'import tensorflow as tf\n'), ((44515, 44548), 'tensorflow.squared_difference', 'tf.squared_difference', (['prev', 'curr'], {}), '(prev, curr)\n', (44536, 44548), True, 'import tensorflow as tf\n'), ((44634, 44672), 'lib.tf_ops.tf_tensor_stats', 'tf_tensor_stats', (['warp_SE'], {'as_dict': '(True)'}), '(warp_SE, as_dict=True)\n', (44649, 44672), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((45089, 45126), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['warp_vdiff_mag', 'mask'], {}), '(warp_vdiff_mag, mask)\n', (45104, 45126), True, 'import tensorflow as tf\n'), ((45376, 45416), 'tensorflow.logical_and', 'tf.logical_and', (['mask', 'vel_CangleRad_mask'], {}), '(mask, vel_CangleRad_mask)\n', (45390, 45416), True, 'import tensorflow as tf\n'), ((45576, 45627), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['warp_CangleRad', 'vel_CangleRad_mask'], {}), '(warp_CangleRad, vel_CangleRad_mask)\n', (45591, 45627), True, 'import tensorflow as tf\n'), ((45721, 45764), 'tensorflow.zeros', 'tf.zeros', (['[1, 1, 1, 1, 1]'], {'dtype': 'tf.float32'}), '([1, 1, 1, 1, 1], dtype=tf.float32)\n', (45729, 45764), True, 'import tensorflow as tf\n'), ((45817, 45860), 'tensorflow.zeros', 'tf.zeros', (['[1, 1, 1, 1, 1]'], {'dtype': 'tf.float32'}), '([1, 1, 1, 1, 1], dtype=tf.float32)\n', (45825, 45860), True, 'import tensorflow as tf\n'), ((45913, 45956), 'tensorflow.zeros', 'tf.zeros', (['[1, 1, 1, 1, 1]'], {'dtype': 'tf.float32'}), '([1, 1, 1, 1, 1], dtype=tf.float32)\n', (45921, 45956), True, 'import tensorflow as tf\n'), ((46014, 46057), 'tensorflow.zeros', 'tf.zeros', (['[1, 1, 1, 1, 1]'], {'dtype': 'tf.float32'}), '([1, 1, 1, 1, 1], dtype=tf.float32)\n', (46022, 46057), True, 'import tensorflow as tf\n'), ((46117, 46160), 'tensorflow.zeros', 'tf.zeros', (['[1, 1, 1, 1, 1]'], {'dtype': 'tf.float32'}), '([1, 1, 1, 1, 1], dtype=tf.float32)\n', (46125, 46160), True, 'import tensorflow as tf\n'), ((57708, 57740), 'os.path.join', 'os.path.join', (['base_path', 'sub_dir'], {}), '(base_path, sub_dir)\n', (57720, 57740), False, 'import copy, os\n'), ((57746, 57789), 'os.makedirs', 'os.makedirs', (['state.data_path'], {'exist_ok': '(True)'}), '(state.data_path, exist_ok=True)\n', (57757, 57789), False, 'import copy, os\n'), ((58768, 58800), 'os.path.join', 'os.path.join', (['base_path', 'sub_dir'], {}), '(base_path, sub_dir)\n', (58780, 58800), False, 'import copy, os\n'), ((58806, 58849), 'os.makedirs', 'os.makedirs', (['state.data_path'], {'exist_ok': '(True)'}), '(state.data_path, exist_ok=True)\n', (58817, 58849), False, 'import copy, os\n'), ((2077, 2093), 'tensorflow.minimum', 'tf.minimum', (['a', 'b'], {}), '(a, b)\n', (2087, 2093), True, 'import tensorflow as tf\n'), ((2094, 2111), 'tensorflow.subtract', 'tf.subtract', (['a', 'b'], {}), '(a, b)\n', (2105, 2111), True, 'import tensorflow as tf\n'), ((4325, 4357), 'tensorflow.constant', 'tf.constant', (['d'], {'dtype': 'tf.float32'}), '(d, dtype=tf.float32)\n', (4336, 4357), True, 'import tensorflow as tf\n'), ((4385, 4454), 'tensorflow.constant', 'tf.constant', (['constant'], {'shape': '([1] + self.shape + [1])', 'dtype': 'tf.float32'}), '(constant, shape=[1] + self.shape + [1], dtype=tf.float32)\n', (4396, 4454), True, 'import tensorflow as tf\n'), ((4945, 5021), 'tensorflow.Variable', 'tf.Variable', ([], {'initial_value': 'inflow', 'name': "(var_name + '_inflow')", 'trainable': '(True)'}), "(initial_value=inflow, name=var_name + '_inflow', trainable=True)\n", (4956, 5021), True, 'import tensorflow as tf\n'), ((5052, 5089), 'tensorflow.constant', 'tf.constant', (['inflow'], {'dtype': 'tf.float32'}), '(inflow, dtype=tf.float32)\n', (5063, 5089), True, 'import tensorflow as tf\n'), ((5114, 5156), 'tensorflow.constant', 'tf.constant', (['inflow_mask'], {'dtype': 'tf.float32'}), '(inflow_mask, dtype=tf.float32)\n', (5125, 5156), True, 'import tensorflow as tf\n'), ((7705, 7721), 'lib.util.load_numpy', 'load_numpy', (['path'], {}), '(path)\n', (7715, 7721), False, 'from lib.util import load_numpy\n'), ((8557, 8596), 'tensorflow.zeros_like', 'tf.zeros_like', (['inflow'], {'dtype': 'tf.float32'}), '(inflow, dtype=tf.float32)\n', (8570, 8596), True, 'import tensorflow as tf\n'), ((9297, 9317), 'tensorflow.identity', 'tf.identity', (['self._d'], {}), '(self._d)\n', (9308, 9317), True, 'import tensorflow as tf\n'), ((9400, 9425), 'tensorflow.identity', 'tf.identity', (['self._inflow'], {}), '(self._inflow)\n', (9411, 9425), True, 'import tensorflow as tf\n'), ((9634, 9654), 'tensorflow.identity', 'tf.identity', (['self._d'], {}), '(self._d)\n', (9645, 9654), True, 'import tensorflow as tf\n'), ((13451, 13470), 'tensorflow.identity', 'tf.identity', (['inflow'], {}), '(inflow)\n', (13462, 13470), True, 'import tensorflow as tf\n'), ((17917, 17989), 'tensorflow.random.uniform', 'tf.random.uniform', (['([1] + self.x_shape + [1])', '(-std)', 'std'], {'dtype': 'tf.float32'}), '([1] + self.x_shape + [1], -std, std, dtype=tf.float32)\n', (17934, 17989), True, 'import tensorflow as tf\n'), ((18026, 18098), 'tensorflow.random.uniform', 'tf.random.uniform', (['([1] + self.y_shape + [1])', '(-std)', 'std'], {'dtype': 'tf.float32'}), '([1] + self.y_shape + [1], -std, std, dtype=tf.float32)\n', (18043, 18098), True, 'import tensorflow as tf\n'), ((18135, 18207), 'tensorflow.random.uniform', 'tf.random.uniform', (['([1] + self.z_shape + [1])', '(-std)', 'std'], {'dtype': 'tf.float32'}), '([1] + self.z_shape + [1], -std, std, dtype=tf.float32)\n', (18152, 18207), True, 'import tensorflow as tf\n'), ((20817, 20841), 'lib.tf_ops.shape_list', 'shape_list', (["vel['vel_x']"], {}), "(vel['vel_x'])\n", (20827, 20841), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((21695, 21711), 'lib.util.load_numpy', 'load_numpy', (['path'], {}), '(path)\n', (21705, 21711), False, 'from lib.util import load_numpy\n'), ((27515, 27562), 'tensorflow.clip_by_value', 'tf.clip_by_value', (['corrected', 'data_min', 'data_max'], {}), '(corrected, data_min, data_max)\n', (27531, 27562), True, 'import tensorflow as tf\n'), ((27789, 27827), 'tensorflow.where', 'tf.where', (['clamp_OOB', 'warped', 'corrected'], {}), '(clamp_OOB, warped, corrected)\n', (27797, 27827), True, 'import tensorflow as tf\n'), ((37019, 37038), 'tensorflow.identity', 'tf.identity', (['self.x'], {}), '(self.x)\n', (37030, 37038), True, 'import tensorflow as tf\n'), ((37197, 37216), 'tensorflow.identity', 'tf.identity', (['self.y'], {}), '(self.y)\n', (37208, 37216), True, 'import tensorflow as tf\n'), ((37368, 37387), 'tensorflow.identity', 'tf.identity', (['self.z'], {}), '(self.z)\n', (37379, 37387), True, 'import tensorflow as tf\n'), ((38384, 38403), 'tensorflow.identity', 'tf.identity', (['self.x'], {}), '(self.x)\n', (38395, 38403), True, 'import tensorflow as tf\n'), ((38736, 38755), 'tensorflow.identity', 'tf.identity', (['self.y'], {}), '(self.y)\n', (38747, 38755), True, 'import tensorflow as tf\n'), ((39088, 39107), 'tensorflow.identity', 'tf.identity', (['self.z'], {}), '(self.z)\n', (39099, 39107), True, 'import tensorflow as tf\n'), ((41881, 41898), 'lib.tf_ops.shape_list', 'shape_list', (['value'], {}), '(value)\n', (41891, 41898), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((44591, 44621), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['warp_SE', 'mask'], {}), '(warp_SE, mask)\n', (44606, 44621), True, 'import tensorflow as tf\n'), ((46787, 46812), 'lib.tf_ops.spacial_shape_list', 'spacial_shape_list', (['other'], {}), '(other)\n', (46805, 46812), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((47740, 47765), 'lib.tf_ops.spacial_shape_list', 'spacial_shape_list', (['other'], {}), '(other)\n', (47758, 47765), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((48692, 48717), 'lib.tf_ops.spacial_shape_list', 'spacial_shape_list', (['other'], {}), '(other)\n', (48710, 48717), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((49645, 49670), 'lib.tf_ops.spacial_shape_list', 'spacial_shape_list', (['other'], {}), '(other)\n', (49663, 49670), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((55760, 55838), 'tensorflow.math.squared_difference', 'tf.math.squared_difference', (['(self.images + self.bkgs * self.t)', 'self.targets_raw'], {}), '(self.images + self.bkgs * self.t, self.targets_raw)\n', (55786, 55838), True, 'import tensorflow as tf\n'), ((55939, 55992), 'tensorflow.math.squared_difference', 'tf.math.squared_difference', (['self.images', 'self.targets'], {}), '(self.images, self.targets)\n', (55965, 55992), True, 'import tensorflow as tf\n'), ((3774, 3795), 'lib.tf_ops.spacial_shape_list', 'spacial_shape_list', (['d'], {}), '(d)\n', (3792, 3795), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((27708, 27736), 'tensorflow.less', 'tf.less', (['corrected', 'data_min'], {}), '(corrected, data_min)\n', (27715, 27736), True, 'import tensorflow as tf\n'), ((27738, 27769), 'tensorflow.greater', 'tf.greater', (['corrected', 'data_max'], {}), '(corrected, data_max)\n', (27748, 27769), True, 'import tensorflow as tf\n'), ((40974, 41021), 'tensorflow.clip_by_value', 'tf.clip_by_value', (['data_corr', 'data_min', 'data_max'], {}), '(data_corr, data_min, data_max)\n', (40990, 41021), True, 'import tensorflow as tf\n'), ((41251, 41294), 'tensorflow.where', 'tf.where', (['clamp_OOB', 'data_warped', 'data_corr'], {}), '(clamp_OOB, data_warped, data_corr)\n', (41259, 41294), True, 'import tensorflow as tf\n'), ((4865, 4888), 'lib.tf_ops.shape_list', 'shape_list', (['inflow_mask'], {}), '(inflow_mask)\n', (4875, 4888), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((41169, 41197), 'tensorflow.less', 'tf.less', (['data_corr', 'data_min'], {}), '(data_corr, data_min)\n', (41176, 41197), True, 'import tensorflow as tf\n'), ((41199, 41230), 'tensorflow.greater', 'tf.greater', (['data_corr', 'data_max'], {}), '(data_corr, data_max)\n', (41209, 41230), True, 'import tensorflow as tf\n'), ((46989, 47014), 'lib.tf_ops.spacial_shape_list', 'spacial_shape_list', (['other'], {}), '(other)\n', (47007, 47014), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((47942, 47967), 'lib.tf_ops.spacial_shape_list', 'spacial_shape_list', (['other'], {}), '(other)\n', (47960, 47967), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((48894, 48919), 'lib.tf_ops.spacial_shape_list', 'spacial_shape_list', (['other'], {}), '(other)\n', (48912, 48919), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((49847, 49872), 'lib.tf_ops.spacial_shape_list', 'spacial_shape_list', (['other'], {}), '(other)\n', (49865, 49872), False, 'from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between\n'), ((60579, 60612), 'tensorflow.maximum', 'tf.maximum', (['self[i].density._d', '(0)'], {}), '(self[i].density._d, 0)\n', (60589, 60612), True, 'import tensorflow as tf\n')]
#!/usr/bin/python # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. # # LASER Language-Agnostic SEntence Representations # is a toolkit to calculate multilingual sentence embeddings # and to use them for document classification, bitext filtering # and mining # # -------------------------------------------------------- # # Python tool to search for paraphrases in FAISS index import re import sys import os.path import tempfile import argparse import faiss import time import pdb import numpy as np from collections import namedtuple # get environment assert os.environ.get('LASER'), 'Please set the enviornment variable LASER' LASER = os.environ['LASER'] sys.path.append(LASER + '/source/lib') from indexing import IndexLoad, IndexTextOpen, IndexTextQuery, SplitOpen, SplitAccess from embed import SentenceEncoder, EncodeLoad, EncodeFile, EncodeTime from text_processing import Token, BPEfastApply SPACE_NORMALIZER = re.compile("\s+") Batch = namedtuple('Batch', 'srcs tokens lengths') # calculate L2 distance between [x] # and the vectors referenced in idxs # x should be already normalized def IndexDistL2(X, E, D, I, thresh=1.0, dtype=np.float32, sort=True): nb, nK = I.shape dim = X.shape[1] dist_l2 = np.empty((nb, nK), dtype=np.float32) y = np.empty((1, dim), dtype=dtype) for i in range(nb): for k in range(nK): if D[i, k] <= thresh: # get embedding from disk np.copyto(y, SplitAccess(E, I[i, k])) faiss.normalize_L2(y) dist_l2[i, k] = 1.0 - np.dot(X[i], y[0]) else: # exclude sentences which already have a huge FAISS distance # (getting embeddings from disk is very time consumming) dist_l2[i, k] = 1.0 if sort: # re-sort according to L2 idxs = np.argsort(dist_l2[i], axis=0) dist_l2[i] = dist_l2[i][idxs] I[i] = I[i][idxs] return dist_l2, I ############################################################################### # # Apply an absolute threshold on the distance # ############################################################################### def MarginAbs(em, ofp, params, args, stats): D, I = params.idx.search(em, args.kmax) thresh = args.threshold_faiss if args.embed: D, I = IndexDistL2(em, params.E, D, I, args.threshold_faiss) thresh = args.threshold_L2 for n in range(D.shape[0]): prev = {} # for deduplication for i in range(args.kmax): txt = IndexTextQuery(params.T, params.R, I[n, i]) if (args.dedup and txt not in prev) and D[n, i] <= thresh: prev[txt] = 1 ofp.write('{:d}\t{:7.5f}\t{}\n' .format(stats.nbs, D[n, i], txt)) stats.nbp += 1 # display source sentece if requested if (args.include_source == 'matches' and len(prev) > 0): ofp.write('{:d}\t{:6.1f}\t{}\n' .format(stats.nbs, 0.0, sentences[n].replace('@@ ', ''))) if args.include_source == 'always': ofp.write('{:d}\t{:6.1f}\t{}\n' .format(stats.nbs, 0.0, sentences[n].replace('@@ ', ''))) stats.nbs += 1 ############################################################################### # # Apply an threshold on the ratio between distance and average # ############################################################################### def MarginRatio(em, ofp, params, args, stats): D, I = params.idx.search(em, args.margin_k) thresh = args.threshold if args.embed: D, I = IndexDistL2(em, params.E, D, I, args.threshold_faiss) thresh = args.threshold_L2 Mean = D.mean(axis=1) for n in range(D.shape[0]): if D[n, 0] / Mean[n] <= args.threshold: if args.include_source == 'matches': ofp.write('{:d}\t{:6.1f}\t{}\n' .format(stats.nbs, 0.0, sentences[n].replace('@@ ', ''))) txt = IndexTextQuery(params.T, params.R, I[n, 0]) ofp.write('{:d}\t{:7.5f}\t{}\n'.format(stats.nbs, D[n, 0], txt)) stats.nbp += 1 stats.nbs += 1 if args.include_source == 'always': ofp.write('{:d}\t{:6.1f}\t{}\n' .format(stats.nbs, 0.0, sentences[n].replace('@@ ', ''))) ############################################################################### def MarginDist(em, ofp, params, args, stats): print('ERROR: MarginAbs not implemented') sys.exit(1) ############################################################################### def buffered_read(fp, buffer_size): buffer = [] for src_str in fp: buffer.append(src_str.strip()) if len(buffer) >= buffer_size: yield buffer buffer = [] if len(buffer) > 0: yield buffer ############################################################################### parser = argparse.ArgumentParser('LASER: paraphrase tool') parser.add_argument('--encoder', type=str, required=True, help='encoder to be used') parser.add_argument('--encoding', default='utf-8', help='Character encoding for input/output') parser.add_argument('--token-lang', type=str, default='--', help="Language of tokenizer ('--' for no tokenization)") parser.add_argument('--bpe-codes', type=str, default=None, required=True, help='BPE codes') parser.add_argument('--buffer-size', type=int, default=100, help='Buffer size (sentences)') parser.add_argument('--max-tokens', type=int, default=12000, help='Maximum number of tokens to process in a batch') parser.add_argument('--max-sentences', type=int, default=None, help='Maximum number of sentences to process in a batch') parser.add_argument('--cpu', action='store_true', help='Use CPU instead of GPU') parser.add_argument('--index', type=str, required=True, help='FAISS index') parser.add_argument('--nprobe', type=int, default=128, help='FAISS: value of nprobe') parser.add_argument('--text', type=str, required=True, help='File with indexed texts') parser.add_argument( '--dim', type=int, default=1024, help='Dimension of specified sentence embeddings') parser.add_argument( '--embed', type=str, default=None, help='Sentence embeddings, true L2 distance will be calculated when specified') parser.add_argument('-i', '--input', type=str, required=True, help='Input text file') parser.add_argument('-p', '--output', type=str, default='--', help='Output paraphrases') parser.add_argument('--kmax', type=int, default=10, help='Max value of distance or margin of each paraphrase') parser.add_argument('--dedup', type=int, default=1, help='Deduplicate list of paraphrases') parser.add_argument('--include-source', default='never', choices=['never', 'matches', 'always'], help='Include source sentence in the list of paraphrases') parser.add_argument('--margin', choices=['absolute', 'distance', 'ratio'], default='ratio', help='Margin function') parser.add_argument('-T', '--threshold-margin', type=float, default=0.9, help='Threshold on margin') parser.add_argument('--threshold-faiss', type=float, default=0.4, help='Threshold on FAISS distance') parser.add_argument('--threshold-L2', type=float, default=0.2, help='Threshold on L2 distance') parser.add_argument('--margin-k', type=int, default=4, help='Number of nearest neighbors for margin calculation') parser.add_argument('--verbose', action='store_true', help='Detailed output') print('\nLASER: paraphrase tool') args = parser.parse_args() # index, # memory mapped texts, references and word counts # encoder params = namedtuple('params', 'idx T R W M E enc') # open text and reference file params.T, params.R, params.W, params.M = IndexTextOpen(args.text) # Open on-disk embeddings for L2 distances if args.embed: params.E = SplitOpen(args.embed, ['en'], args.dim, np.float32, verbose=False) # load FAISS index params.idx = IndexLoad(args.index, args.nprobe) # load sentence encoder params.enc = EncodeLoad(args) margin_methods = {'absolute': MarginAbs, 'distance': MarginDist, 'ratio': MarginRatio} with tempfile.TemporaryDirectory() as tmpdir: ifile = args.input if args.token_lang != '--': ifile = os.path.join(tmpdir, 'tok') Token(args.input, ifile, lang=args.token_lang, romanize=True if args.token_lang == 'el' else False, lower_case=True, gzip=False, verbose=args.verbose, over_write=False) if args.bpe_codes: bpe_file = os.path.join(tmpdir, 'bpe') BPEfastApply(ifile, bpe_file, args.bpe_codes, verbose=args.verbose, over_write=False) ifile = bpe_file print(' - processing (batch size is {:d})'.format(args.buffer_size)) ifp = open(ifile, 'r', encoding=args.encoding, errors='surrogateescape') if args.output == '--': ofp = sys.stdout else: ofp = open(args.output, 'w', encoding=args.encoding, errors='surrogateescape') stats = namedtuple('stats', 'ns np') stats.nbs = 0 stats.nbp = 0 t = time.time() for sentences in buffered_read(ifp, args.buffer_size): embed = params.enc.encode_sentences(sentences) faiss.normalize_L2(embed) # call function for selected margin method margin_methods.get(args.margin)(embed, ofp, params, args, stats) if stats.nbs % 1000 == 0: print('\r - {:d} sentences {:d} paraphrases' .format(stats.nbs, stats.nbp), end='') ifp.close() if args.output != '--': ofp.close() print('\r - {:d} sentences {:d} paraphrases' .format(stats.nbs, stats.nbp), end='') EncodeTime(t)
[ "indexing.SplitOpen", "re.compile", "numpy.argsort", "indexing.IndexTextQuery", "embed.EncodeTime", "sys.exit", "sys.path.append", "embed.EncodeLoad", "faiss.normalize_L2", "argparse.ArgumentParser", "indexing.IndexLoad", "numpy.dot", "numpy.empty", "indexing.IndexTextOpen", "collections...
[((817, 855), 'sys.path.append', 'sys.path.append', (["(LASER + '/source/lib')"], {}), "(LASER + '/source/lib')\n", (832, 855), False, 'import sys\n'), ((1080, 1098), 're.compile', 're.compile', (['"""\\\\s+"""'], {}), "('\\\\s+')\n", (1090, 1098), False, 'import re\n'), ((1106, 1148), 'collections.namedtuple', 'namedtuple', (['"""Batch"""', '"""srcs tokens lengths"""'], {}), "('Batch', 'srcs tokens lengths')\n", (1116, 1148), False, 'from collections import namedtuple\n'), ((5162, 5211), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""LASER: paraphrase tool"""'], {}), "('LASER: paraphrase tool')\n", (5185, 5211), False, 'import argparse\n'), ((7900, 7941), 'collections.namedtuple', 'namedtuple', (['"""params"""', '"""idx T R W M E enc"""'], {}), "('params', 'idx T R W M E enc')\n", (7910, 7941), False, 'from collections import namedtuple\n'), ((8015, 8039), 'indexing.IndexTextOpen', 'IndexTextOpen', (['args.text'], {}), '(args.text)\n', (8028, 8039), False, 'from indexing import IndexLoad, IndexTextOpen, IndexTextQuery, SplitOpen, SplitAccess\n'), ((8246, 8280), 'indexing.IndexLoad', 'IndexLoad', (['args.index', 'args.nprobe'], {}), '(args.index, args.nprobe)\n', (8255, 8280), False, 'from indexing import IndexLoad, IndexTextOpen, IndexTextQuery, SplitOpen, SplitAccess\n'), ((8319, 8335), 'embed.EncodeLoad', 'EncodeLoad', (['args'], {}), '(args)\n', (8329, 8335), False, 'from embed import SentenceEncoder, EncodeLoad, EncodeFile, EncodeTime\n'), ((1382, 1418), 'numpy.empty', 'np.empty', (['(nb, nK)'], {'dtype': 'np.float32'}), '((nb, nK), dtype=np.float32)\n', (1390, 1418), True, 'import numpy as np\n'), ((1427, 1458), 'numpy.empty', 'np.empty', (['(1, dim)'], {'dtype': 'dtype'}), '((1, dim), dtype=dtype)\n', (1435, 1458), True, 'import numpy as np\n'), ((4727, 4738), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (4735, 4738), False, 'import sys\n'), ((8114, 8180), 'indexing.SplitOpen', 'SplitOpen', (['args.embed', "['en']", 'args.dim', 'np.float32'], {'verbose': '(False)'}), "(args.embed, ['en'], args.dim, np.float32, verbose=False)\n", (8123, 8180), False, 'from indexing import IndexLoad, IndexTextOpen, IndexTextQuery, SplitOpen, SplitAccess\n'), ((8467, 8496), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (8494, 8496), False, 'import tempfile\n'), ((9420, 9448), 'collections.namedtuple', 'namedtuple', (['"""stats"""', '"""ns np"""'], {}), "('stats', 'ns np')\n", (9430, 9448), False, 'from collections import namedtuple\n'), ((9493, 9504), 'time.time', 'time.time', ([], {}), '()\n', (9502, 9504), False, 'import time\n'), ((10092, 10105), 'embed.EncodeTime', 'EncodeTime', (['t'], {}), '(t)\n', (10102, 10105), False, 'from embed import SentenceEncoder, EncodeLoad, EncodeFile, EncodeTime\n'), ((8615, 8793), 'text_processing.Token', 'Token', (['args.input', 'ifile'], {'lang': 'args.token_lang', 'romanize': "(True if args.token_lang == 'el' else False)", 'lower_case': '(True)', 'gzip': '(False)', 'verbose': 'args.verbose', 'over_write': '(False)'}), "(args.input, ifile, lang=args.token_lang, romanize=True if args.\n token_lang == 'el' else False, lower_case=True, gzip=False, verbose=\n args.verbose, over_write=False)\n", (8620, 8793), False, 'from text_processing import Token, BPEfastApply\n'), ((8933, 9022), 'text_processing.BPEfastApply', 'BPEfastApply', (['ifile', 'bpe_file', 'args.bpe_codes'], {'verbose': 'args.verbose', 'over_write': '(False)'}), '(ifile, bpe_file, args.bpe_codes, verbose=args.verbose,\n over_write=False)\n', (8945, 9022), False, 'from text_processing import Token, BPEfastApply\n'), ((9627, 9652), 'faiss.normalize_L2', 'faiss.normalize_L2', (['embed'], {}), '(embed)\n', (9645, 9652), False, 'import faiss\n'), ((2015, 2045), 'numpy.argsort', 'np.argsort', (['dist_l2[i]'], {'axis': '(0)'}), '(dist_l2[i], axis=0)\n', (2025, 2045), True, 'import numpy as np\n'), ((2725, 2768), 'indexing.IndexTextQuery', 'IndexTextQuery', (['params.T', 'params.R', 'I[n, i]'], {}), '(params.T, params.R, I[n, i])\n', (2739, 2768), False, 'from indexing import IndexLoad, IndexTextOpen, IndexTextQuery, SplitOpen, SplitAccess\n'), ((4219, 4262), 'indexing.IndexTextQuery', 'IndexTextQuery', (['params.T', 'params.R', 'I[n, 0]'], {}), '(params.T, params.R, I[n, 0])\n', (4233, 4262), False, 'from indexing import IndexLoad, IndexTextOpen, IndexTextQuery, SplitOpen, SplitAccess\n'), ((1657, 1678), 'faiss.normalize_L2', 'faiss.normalize_L2', (['y'], {}), '(y)\n', (1675, 1678), False, 'import faiss\n'), ((1616, 1639), 'indexing.SplitAccess', 'SplitAccess', (['E', 'I[i, k]'], {}), '(E, I[i, k])\n', (1627, 1639), False, 'from indexing import IndexLoad, IndexTextOpen, IndexTextQuery, SplitOpen, SplitAccess\n'), ((1717, 1735), 'numpy.dot', 'np.dot', (['X[i]', 'y[0]'], {}), '(X[i], y[0])\n', (1723, 1735), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from typing import List import numpy as np import torch from pytext.models.representations.transformer import ( TransformerLayer, MultiheadSelfAttention, ) from pytext.models.roberta import RoBERTaEncoder from torch import nn, Tensor torch.ops.load_library("//pytorch/FasterTransformers3.1:faster_transformers") @torch.jit.script def sequence_mask(neg_padding_mask: Tensor) -> Tensor: neg_padding_mask = neg_padding_mask.half() mask = neg_padding_mask.view( neg_padding_mask.size(0), 1, 1, neg_padding_mask.size(1) ) m2 = mask.transpose(2, 3) return mask * m2 def to_fast_transformer_weights(layer): attn_qw, attn_kw, attn_vw = layer.attention.input_projection.weight.chunk(3, dim=0) attn_qb, attn_kb, attn_vb = layer.attention.input_projection.bias.chunk(3, dim=0) attn_ow = layer.attention.output_projection.weight attn_ob = layer.attention.output_projection.bias attn_nw = layer.attention_layer_norm.weight attn_nb = layer.attention_layer_norm.bias inter_w = layer.residual_mlp.mlp.__getattr__("0").weight inter_b = layer.residual_mlp.mlp.__getattr__("0").bias output_w = layer.residual_mlp.mlp.__getattr__("3").weight output_b = layer.residual_mlp.mlp.__getattr__("3").bias norm_w = layer.final_layer_norm.weight norm_b = layer.final_layer_norm.bias fast_transformer_weights = [ attn_qw.transpose(-1, -2).contiguous(), attn_qb, attn_kw.transpose(-1, -2).contiguous(), attn_kb, attn_vw.transpose(-1, -2).contiguous(), attn_vb, attn_ow.transpose(-1, -2).contiguous(), attn_ob, attn_nw, attn_nb, inter_w.transpose(-1, -2).contiguous(), inter_b, output_w.transpose(-1, -2).contiguous(), output_b, norm_w, norm_b, torch.tensor(0), ] return [t.half().cuda() for t in fast_transformer_weights] # Hide custom class behind torch.jit.script as jit.trace doesn't support custom classes. class NVTransformerStack(nn.Module): def __init__(self, layers): super().__init__() self.layers = layers self.layer_num = len(layers) def forward(self, encoded: Tensor, neg_padding_mask: Tensor) -> List[Tensor]: # seq_lengths: [B,] sequence_lengths = neg_padding_mask.sum(dim=1, dtype=torch.int32) # Note - this does a HtoD copy/stream synchronization # Necessary because our implementation does not handle the zero-token case. if sequence_lengths.sum().item() == 0: return [encoded.transpose(0, 1)] + [ torch.zeros_like(encoded.transpose(0, 1)) for _ in range(self.layer_num) ] # Note - this also does a HtoD copy/stream synchronization. ( hidden_states, sequence_id_offset, ) = torch.ops.fastertransformer.build_mask_remove_padding( encoded, sequence_lengths ) # attention_mask: [B, 1, T, T] attention_mask = sequence_mask(neg_padding_mask).half() # trt_seq_len: [B + 1,] trt_seq_len = torch.cumsum( torch.cat( [ torch.zeros( 1, device=sequence_lengths.device, dtype=sequence_lengths.dtype ), sequence_lengths, ], dim=0, ), dim=0, dtype=torch.int32, ) all_hidden_states = [hidden_states] for i in range(self.layer_num): hidden_states = self.layers[i].forward( hidden_states, attention_mask, trt_seq_len, sequence_id_offset ) all_hidden_states.append(hidden_states) # Remap back to padded [B, T, D] representation, and transpose to [T, B, D]. states = [] for hidden_states in all_hidden_states: # Ideally jit.tracer will eliminate unncessary ones as the corresponding # output tensor would be unused. It doesn't seem to currently, though. state = torch.ops.fastertransformer.rebuild_padding( hidden_states, sequence_id_offset, attention_mask, 0 ) # Convert to [T, B, D] representation. states.append(state.transpose(1, 0)) return states class NVFasterTransformerEncoder(nn.Module): def __init__(self, old_transformer): super().__init__() remove_padding = True use_trt_kernel = True allow_gemm_test = False int8_mode = 0 self.layer_num = len(old_transformer.layers) self.int8_mode = int8_mode self.token_embedding = old_transformer.token_embedding self.positional_embedding = old_transformer.positional_embedding self.embedding_layer_norm = old_transformer.embedding_layer_norm self.dropout = old_transformer.dropout self.padding_idx = old_transformer.padding_idx num_headss, scalings, embed_dims = set(), set(), set() for layer in old_transformer.layers: assert isinstance(layer, TransformerLayer) att = layer.attention assert isinstance(att, MultiheadSelfAttention) num_headss.add(att.num_heads) scalings.add(att.scaling) embed_dims.add(att.embed_dim) # TODO: ResidualMLP check. # ensure values match. (num_heads,) = num_headss (scaling,) = scalings (embed_dims,) = embed_dims head_dim = embed_dims // num_heads np.testing.assert_allclose(scaling, 1.0 / np.sqrt(head_dim)) encoders = [] for i in range(self.layer_num): encoders.append( torch.classes.FasterTransformer.Encoder( *to_fast_transformer_weights(old_transformer.layers[i]), num_heads, head_dim, remove_padding, int8_mode, self.layer_num, i, allow_gemm_test, use_trt_kernel ) ) self.encoder = torch.jit.script(NVTransformerStack(encoders)) def forward(self, tokens: Tensor) -> List[Tensor]: # Vanilla transformer prelude neg_padding_mask = tokens.ne(self.padding_idx) embedded = self.token_embedding(tokens) embedded_positions = self.positional_embedding(tokens) normed = self.embedding_layer_norm(embedded + embedded_positions) normed = self.dropout(normed) padded_normed = normed * neg_padding_mask.unsqueeze(-1) # encoded: [B, T, C] encoded = padded_normed.half() states = self.encoder(encoded, neg_padding_mask) # commonly you can retrieve a single "sentence representation" as # states[-1].transpose(0, 1) return states # Swap a transformer for only RoBERTaEncoder encoders def swap_modules_for_faster_transformer(model): if hasattr(model, "encoder") and isinstance(model.encoder, RoBERTaEncoder): old_transformer = model.encoder.encoder.transformer model.encoder.encoder.transformer = NVFasterTransformerEncoder(old_transformer) return model else: return model
[ "torch.ops.load_library", "numpy.sqrt", "torch.tensor", "torch.ops.fastertransformer.rebuild_padding", "torch.ops.fastertransformer.build_mask_remove_padding", "torch.zeros" ]
[((340, 417), 'torch.ops.load_library', 'torch.ops.load_library', (['"""//pytorch/FasterTransformers3.1:faster_transformers"""'], {}), "('//pytorch/FasterTransformers3.1:faster_transformers')\n", (362, 417), False, 'import torch\n'), ((1939, 1954), 'torch.tensor', 'torch.tensor', (['(0)'], {}), '(0)\n', (1951, 1954), False, 'import torch\n'), ((2958, 3043), 'torch.ops.fastertransformer.build_mask_remove_padding', 'torch.ops.fastertransformer.build_mask_remove_padding', (['encoded', 'sequence_lengths'], {}), '(encoded, sequence_lengths\n )\n', (3011, 3043), False, 'import torch\n'), ((4197, 4298), 'torch.ops.fastertransformer.rebuild_padding', 'torch.ops.fastertransformer.rebuild_padding', (['hidden_states', 'sequence_id_offset', 'attention_mask', '(0)'], {}), '(hidden_states,\n sequence_id_offset, attention_mask, 0)\n', (4240, 4298), False, 'import torch\n'), ((5716, 5733), 'numpy.sqrt', 'np.sqrt', (['head_dim'], {}), '(head_dim)\n', (5723, 5733), True, 'import numpy as np\n'), ((3294, 3370), 'torch.zeros', 'torch.zeros', (['(1)'], {'device': 'sequence_lengths.device', 'dtype': 'sequence_lengths.dtype'}), '(1, device=sequence_lengths.device, dtype=sequence_lengths.dtype)\n', (3305, 3370), False, 'import torch\n')]
import numpy as np from ._base import LinearModel from ._regularization import REGULARIZE, Regularizer from utils import batch class LinearRegression(LinearModel): """Linear regression model.""" def __init__(self, regular: REGULARIZE = None): super().__init__() if REGULARIZE is not None: self._regular = Regularizer(regular) else: self._regular = None def fit(self, x: np.ndarray, y: np.ndarray, **kwargs) -> float: assert x.shape[0] == y.shape[0] n, p = x.shape if self._w is None or self._b is None or self._w.shape[0] != p: # Initialize weights using random values self._init_model(p) if kwargs is not None: # Update parameters of training self._update_params(kwargs) iters, loss = 0, 0. # Iterates till converge or iterating times exceed bound while iters < self._iter_bound: iters += 1 # Update weights using mini-batch gradient desent for batch_x, batch_y in batch(x, y, self._batch_size): pred_val = self._predict_value(batch_x, self._w, self._b) loss += self._loss(pred_val, batch_y) * batch_x.shape[0] grad_w, grad_b = self._grad(batch_x, pred_val, batch_y) self._w -= grad_w self._b -= grad_b loss /= n # Break if model converges. if loss <= self._loss_tol: break # Update model with current weight and bias self._update_model(loss) return loss def fit_norm_eq(self, x: np.ndarray, y: np.ndarray) -> float: # Fit x using normal equation assert x.shape[0] == y.shape[0] n, p = x.shape if self._w is None or self._b is None or self._w.shape[0] != p: # Initialize weights using random values self._init_model(p) x_ext = np.hstack((np.ones((n, 1)), x)) w_ext = np.linalg.pinv(np.matmul(x_ext.T, x_ext)) w_ext = np.matmul(np.matmul(w_ext, x_ext.T), y) self._w, self._b = w_ext[1:], w_ext[0] # Calculate training loss pred_val = self._predict_value(x, self._w, self._b) loss = self._loss(pred_val, y) self._update_model(loss) return loss def predict(self, x: np.ndarray, **kwargs) -> np.ndarray: assert not np.isinf(self._optimum['loss']) assert self._optimum['w'].shape[0] == x.shape[1] pred_val = self._predict_value(x, self._optimum['w'], self._optimum['b']) return pred_val def evaluate(self, x: np.ndarray, y: np.ndarray, **kwargs) -> tuple: assert x.shape[0] == y.shape[0] assert not np.isinf(self._optimum['loss']) assert self._optimum['w'].shape[0] == x.shape[1] pred_val = self._predict_value(x, self._optimum['w'], self._optimum['b']) # The precision part of regression is None precision = None loss = self._loss(pred_val, y) return precision, loss @staticmethod def _predict_value(x: np.ndarray, w: np.ndarray, b: float) -> np.ndarray: pred_val = np.matmul(x, w) + b return pred_val @staticmethod def _predict_label(pred_val: np.ndarray) -> np.ndarray: # NO labeling in regression. pass def _loss(self, pred_val: np.ndarray, true_val: np.ndarray) -> float: # Use MSE loss loss = float(np.sum(np.power(pred_val - true_val, 2))) loss /= 2 * true_val.shape[0] # Add regularized loss if self._regular is not None: loss += self._regular[self._w] return loss def _grad(self, x: np.ndarray, pred_val: np.ndarray, true_val: np.ndarray) -> tuple: # Use MSE loss grad_w = (x * (pred_val - true_val).reshape((-1, 1))).mean(axis=0) grad_b = (pred_val - true_val).mean() # Use simple gradient by multiplying learning rate and grad. grad_w *= self._learn_rate grad_b *= self._learn_rate # Add regularized grad if self._regular is not None: grad_w += self._regular.grad(self._w) return grad_w, grad_b
[ "numpy.ones", "utils.batch", "numpy.power", "numpy.matmul", "numpy.isinf" ]
[((1070, 1099), 'utils.batch', 'batch', (['x', 'y', 'self._batch_size'], {}), '(x, y, self._batch_size)\n', (1075, 1099), False, 'from utils import batch\n'), ((2020, 2045), 'numpy.matmul', 'np.matmul', (['x_ext.T', 'x_ext'], {}), '(x_ext.T, x_ext)\n', (2029, 2045), True, 'import numpy as np\n'), ((2073, 2098), 'numpy.matmul', 'np.matmul', (['w_ext', 'x_ext.T'], {}), '(w_ext, x_ext.T)\n', (2082, 2098), True, 'import numpy as np\n'), ((2418, 2449), 'numpy.isinf', 'np.isinf', (["self._optimum['loss']"], {}), "(self._optimum['loss'])\n", (2426, 2449), True, 'import numpy as np\n'), ((2785, 2816), 'numpy.isinf', 'np.isinf', (["self._optimum['loss']"], {}), "(self._optimum['loss'])\n", (2793, 2816), True, 'import numpy as np\n'), ((3280, 3295), 'numpy.matmul', 'np.matmul', (['x', 'w'], {}), '(x, w)\n', (3289, 3295), True, 'import numpy as np\n'), ((1968, 1983), 'numpy.ones', 'np.ones', (['(n, 1)'], {}), '((n, 1))\n', (1975, 1983), True, 'import numpy as np\n'), ((3579, 3611), 'numpy.power', 'np.power', (['(pred_val - true_val)', '(2)'], {}), '(pred_val - true_val, 2)\n', (3587, 3611), True, 'import numpy as np\n')]
"""Test gates defined in `qibo/core/gates.py`.""" import pytest import numpy as np from qibo import gates, K from qibo.config import raise_error from qibo.tests.utils import random_state, random_density_matrix def apply_gates(gatelist, nqubits=None, initial_state=None): if initial_state is None: state = K.qnp.zeros(2 ** nqubits) state[0] = 1 elif isinstance(initial_state, np.ndarray): state = np.copy(initial_state) if nqubits is None: nqubits = int(np.log2(len(state))) else: # pragma: no cover assert nqubits == int(np.log2(len(state))) else: # pragma: no cover raise_error(TypeError, "Invalid initial state type {}." "".format(type(initial_state))) state = K.cast(state) for gate in gatelist: state = gate(state) return state def test__control_unitary(backend): matrix = K.cast(np.random.random((2, 2))) gate = gates.Unitary(matrix, 0) unitary = gate._control_unitary(matrix) target_unitary = np.eye(4, dtype=K._dtypes.get('DTYPECPX')) target_unitary[2:, 2:] = K.to_numpy(matrix) K.assert_allclose(unitary, target_unitary) with pytest.raises(ValueError): unitary = gate._control_unitary(np.random.random((16, 16))) def test_h(backend): final_state = apply_gates([gates.H(0), gates.H(1)], nqubits=2) target_state = np.ones_like(final_state) / 2 K.assert_allclose(final_state, target_state) def test_x(backend): final_state = apply_gates([gates.X(0)], nqubits=2) target_state = np.zeros_like(final_state) target_state[2] = 1.0 K.assert_allclose(final_state, target_state) def test_y(backend): final_state = apply_gates([gates.Y(1)], nqubits=2) target_state = np.zeros_like(final_state) target_state[1] = 1j K.assert_allclose(final_state, target_state) def test_z(backend): final_state = apply_gates([gates.H(0), gates.H(1), gates.Z(0)], nqubits=2) target_state = np.ones_like(final_state) / 2.0 target_state[2] *= -1.0 target_state[3] *= -1.0 K.assert_allclose(final_state, target_state) def test_s(backend): final_state = apply_gates([gates.H(0), gates.H(1), gates.S(1)], nqubits=2) target_state = np.array([0.5, 0.5j, 0.5, 0.5j]) K.assert_allclose(final_state, target_state) def test_sdg(backend): final_state = apply_gates([gates.H(0), gates.H(1), gates.SDG(1)], nqubits=2) target_state = np.array([0.5, -0.5j, 0.5, -0.5j]) K.assert_allclose(final_state, target_state) def test_t(backend): final_state = apply_gates([gates.H(0), gates.H(1), gates.T(1)], nqubits=2) target_state = np.array([0.5, (1 + 1j) / np.sqrt(8), 0.5, (1 + 1j) / np.sqrt(8)]) K.assert_allclose(final_state, target_state) def test_tdg(backend): final_state = apply_gates([gates.H(0), gates.H(1), gates.TDG(1)], nqubits=2) target_state = np.array([0.5, (1 - 1j) / np.sqrt(8), 0.5, (1 - 1j) / np.sqrt(8)]) K.assert_allclose(final_state, target_state) def test_identity(backend): gatelist = [gates.H(0), gates.H(1), gates.I(0), gates.I(1)] final_state = apply_gates(gatelist, nqubits=2) target_state = np.ones_like(final_state) / 2.0 K.assert_allclose(final_state, target_state) gatelist = [gates.H(0), gates.H(1), gates.I(0, 1)] final_state = apply_gates(gatelist, nqubits=2) K.assert_allclose(final_state, target_state) def test_align(backend): gate = gates.Align(0, 1) gatelist = [gates.H(0), gates.H(1), gate] final_state = apply_gates(gatelist, nqubits=2) target_state = np.ones_like(final_state) / 2.0 K.assert_allclose(final_state, target_state) gate_matrix = gate._construct_unitary() K.assert_allclose(gate_matrix, np.eye(4)) # :class:`qibo.core.cgates.M` is tested seperately in `test_measurement_gate.py` def test_rx(backend): theta = 0.1234 final_state = apply_gates([gates.H(0), gates.RX(0, theta=theta)], nqubits=1) phase = np.exp(1j * theta / 2.0) gate = np.array([[phase.real, -1j * phase.imag], [-1j * phase.imag, phase.real]]) target_state = gate.dot(np.ones(2)) / np.sqrt(2) K.assert_allclose(final_state, target_state) def test_ry(backend): theta = 0.1234 final_state = apply_gates([gates.H(0), gates.RY(0, theta=theta)], nqubits=1) phase = np.exp(1j * theta / 2.0) gate = np.array([[phase.real, -phase.imag], [phase.imag, phase.real]]) target_state = gate.dot(np.ones(2)) / np.sqrt(2) K.assert_allclose(final_state, target_state) @pytest.mark.parametrize("applyx", [True, False]) def test_rz(backend, applyx): theta = 0.1234 if applyx: gatelist = [gates.X(0)] else: gatelist = [] gatelist.append(gates.RZ(0, theta)) final_state = apply_gates(gatelist, nqubits=1) target_state = np.zeros_like(final_state) p = int(applyx) target_state[p] = np.exp((2 * p - 1) * 1j * theta / 2.0) K.assert_allclose(final_state, target_state) def test_u1(backend): theta = 0.1234 final_state = apply_gates([gates.X(0), gates.U1(0, theta)], nqubits=1) target_state = np.zeros_like(final_state) target_state[1] = np.exp(1j * theta) K.assert_allclose(final_state, target_state) def test_u2(backend): phi = 0.1234 lam = 0.4321 initial_state = random_state(1) final_state = apply_gates([gates.U2(0, phi, lam)], initial_state=initial_state) matrix = np.array([[np.exp(-1j * (phi + lam) / 2), -np.exp(-1j * (phi - lam) / 2)], [np.exp(1j * (phi - lam) / 2), np.exp(1j * (phi + lam) / 2)]]) target_state = matrix.dot(initial_state) / np.sqrt(2) K.assert_allclose(final_state, target_state) def test_u3(backend): theta = 0.1111 phi = 0.1234 lam = 0.4321 initial_state = random_state(1) final_state = apply_gates([gates.U3(0, theta, phi, lam)], initial_state=initial_state) cost, sint = np.cos(theta / 2), np.sin(theta / 2) ep = np.exp(1j * (phi + lam) / 2) em = np.exp(1j * (phi - lam) / 2) matrix = np.array([[ep.conj() * cost, - em.conj() * sint], [em * sint, ep * cost]]) target_state = matrix.dot(initial_state) K.assert_allclose(final_state, target_state) @pytest.mark.parametrize("applyx", [False, True]) def test_cnot(backend, applyx): if applyx: gatelist = [gates.X(0)] else: gatelist = [] gatelist.append(gates.CNOT(0, 1)) final_state = apply_gates(gatelist, nqubits=2) target_state = np.zeros_like(final_state) target_state[3 * int(applyx)] = 1.0 K.assert_allclose(final_state, target_state) @pytest.mark.parametrize("controlled_by", [False, True]) def test_cz(backend, controlled_by): initial_state = random_state(2) matrix = np.eye(4) matrix[3, 3] = -1 target_state = matrix.dot(initial_state) if controlled_by: gate = gates.Z(1).controlled_by(0) else: gate = gates.CZ(0, 1) final_state = apply_gates([gate], initial_state=initial_state) assert gate.name == "cz" K.assert_allclose(final_state, target_state) @pytest.mark.parametrize("name,params", [("CRX", {"theta": 0.1}), ("CRY", {"theta": 0.2}), ("CRZ", {"theta": 0.3}), ("CU1", {"theta": 0.1}), ("CU2", {"phi": 0.1, "lam": 0.2}), ("CU3", {"theta": 0.1, "phi": 0.2, "lam": 0.3})]) def test_cun(backend, name, params): initial_state = random_state(2) gate = getattr(gates, name)(0, 1, **params) final_state = apply_gates([gate], initial_state=initial_state) target_state = np.dot(K.to_numpy(gate.matrix), initial_state) K.assert_allclose(final_state, target_state) def test_swap(backend): final_state = apply_gates([gates.X(1), gates.SWAP(0, 1)], nqubits=2) target_state = np.zeros_like(final_state) target_state[2] = 1.0 K.assert_allclose(final_state, target_state) def test_multiple_swap(backend): gatelist = [gates.X(0), gates.X(2), gates.SWAP(0, 1), gates.SWAP(2, 3)] final_state = apply_gates(gatelist, nqubits=4) gatelist = [gates.X(1), gates.X(3)] target_state = apply_gates(gatelist, nqubits=4) K.assert_allclose(final_state, target_state) def test_fsim(backend): theta = 0.1234 phi = 0.4321 gatelist = [gates.H(0), gates.H(1), gates.fSim(0, 1, theta, phi)] final_state = apply_gates(gatelist, nqubits=2) target_state = np.ones_like(K.to_numpy(final_state)) / 2.0 rotation = np.array([[np.cos(theta), -1j * np.sin(theta)], [-1j * np.sin(theta), np.cos(theta)]]) matrix = np.eye(4, dtype=target_state.dtype) matrix[1:3, 1:3] = rotation matrix[3, 3] = np.exp(-1j * phi) target_state = matrix.dot(target_state) K.assert_allclose(final_state, target_state) def test_generalized_fsim(backend): phi = np.random.random() rotation = np.random.random((2, 2)) + 1j * np.random.random((2, 2)) gatelist = [gates.H(0), gates.H(1), gates.H(2)] gatelist.append(gates.GeneralizedfSim(1, 2, rotation, phi)) final_state = apply_gates(gatelist, nqubits=3) target_state = np.ones_like(K.to_numpy(final_state)) / np.sqrt(8) matrix = np.eye(4, dtype=target_state.dtype) matrix[1:3, 1:3] = rotation matrix[3, 3] = np.exp(-1j * phi) target_state[:4] = matrix.dot(target_state[:4]) target_state[4:] = matrix.dot(target_state[4:]) K.assert_allclose(final_state, target_state) def test_generalized_fsim_parameter_setter(backend): phi = np.random.random() matrix = np.random.random((2, 2)) gate = gates.GeneralizedfSim(0, 1, matrix, phi) K.assert_allclose(gate.parameters[0], matrix) assert gate.parameters[1] == phi matrix = np.random.random((4, 4)) with pytest.raises(ValueError): gate = gates.GeneralizedfSim(0, 1, matrix, phi) @pytest.mark.parametrize("applyx", [False, True]) def test_toffoli(backend, applyx): if applyx: gatelist = [gates.X(0), gates.X(1), gates.TOFFOLI(0, 1, 2)] else: gatelist = [gates.X(1), gates.TOFFOLI(0, 1, 2)] final_state = apply_gates(gatelist, nqubits=3) target_state = np.zeros_like(final_state) if applyx: target_state[-1] = 1 else: target_state[2] = 1 K.assert_allclose(final_state, target_state) @pytest.mark.parametrize("nqubits", [2, 3]) def test_unitary(backend, nqubits): initial_state = np.ones(2 ** nqubits) / np.sqrt(2 ** nqubits) matrix = np.random.random(2 * (2 ** (nqubits - 1),)) target_state = np.kron(np.eye(2), matrix).dot(initial_state) gatelist = [gates.H(i) for i in range(nqubits)] gatelist.append(gates.Unitary(matrix, *range(1, nqubits), name="random")) final_state = apply_gates(gatelist, nqubits=nqubits) K.assert_allclose(final_state, target_state) def test_unitary_initialization(backend): matrix = np.random.random((4, 4)) gate = gates.Unitary(matrix, 0, 1) K.assert_allclose(gate.parameters, matrix) matrix = np.random.random((8, 8)) with pytest.raises(ValueError): gate = gates.Unitary(matrix, 0, 1) with pytest.raises(TypeError): gate = gates.Unitary("abc", 0, 1) def test_unitary_common_gates(backend): target_state = apply_gates([gates.X(0), gates.H(1)], nqubits=2) gatelist = [gates.Unitary(np.array([[0, 1], [1, 0]]), 0), gates.Unitary(np.array([[1, 1], [1, -1]]) / np.sqrt(2), 1)] final_state = apply_gates(gatelist, nqubits=2) K.assert_allclose(final_state, target_state) thetax = 0.1234 thetay = 0.4321 gatelist = [gates.RX(0, theta=thetax), gates.RY(1, theta=thetay), gates.CNOT(0, 1)] target_state = apply_gates(gatelist, nqubits=2) rx = np.array([[np.cos(thetax / 2), -1j * np.sin(thetax / 2)], [-1j * np.sin(thetax / 2), np.cos(thetax / 2)]]) ry = np.array([[np.cos(thetay / 2), -np.sin(thetay / 2)], [np.sin(thetay / 2), np.cos(thetay / 2)]]) cnot = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]) gatelist = [gates.Unitary(rx, 0), gates.Unitary(ry, 1), gates.Unitary(cnot, 0, 1)] final_state = apply_gates(gatelist, nqubits=2) K.assert_allclose(final_state, target_state) def test_unitary_multiqubit(backend): gatelist = [gates.H(i) for i in range(4)] gatelist.append(gates.CNOT(0, 1)) gatelist.append(gates.CNOT(2, 3)) gatelist.extend(gates.X(i) for i in range(4)) h = np.array([[1, 1], [1, -1]]) / np.sqrt(2) x = np.array([[0, 1], [1, 0]]) cnot = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]) matrix = np.kron(np.kron(x, x), np.kron(x, x)) matrix = matrix @ np.kron(cnot, cnot) matrix = matrix @ np.kron(np.kron(h, h), np.kron(h, h)) unitary = gates.Unitary(matrix, 0, 1, 2, 3) if K.name == "qibotf": with pytest.raises(NotImplementedError): final_state = apply_gates([unitary], nqubits=4) else: final_state = apply_gates([unitary], nqubits=4) target_state = apply_gates(gatelist, nqubits=4) K.assert_allclose(final_state, target_state) @pytest.mark.parametrize("nqubits", [5, 6]) def test_variational_layer(backend, nqubits): theta = 2 * np.pi * np.random.random(nqubits) gatelist = [gates.RY(i, t) for i, t in enumerate(theta)] gatelist.extend(gates.CZ(i, i + 1) for i in range(0, nqubits - 1, 2)) target_state = apply_gates(gatelist, nqubits=nqubits) pairs = list((i, i + 1) for i in range(0, nqubits - 1, 2)) gate = gates.VariationalLayer(range(nqubits), pairs, gates.RY, gates.CZ, theta) final_state = apply_gates([gate], nqubits=nqubits) K.assert_allclose(target_state, final_state) def test_variational_layer__construct_unitary(backend): pairs = list((i, i + 1) for i in range(0, 5, 2)) theta = 2 * np.pi * np.random.random(6) gate = gates.VariationalLayer(range(6), pairs, gates.RY, gates.CZ, theta) with pytest.raises(ValueError): gate._construct_unitary() def test_flatten(backend): target_state = np.ones(4) / 2.0 final_state = apply_gates([gates.Flatten(target_state)], nqubits=2) K.assert_allclose(final_state, target_state) target_state = np.ones(4) / 2.0 gate = gates.Flatten(target_state) with pytest.raises(ValueError): gate._construct_unitary() def test_callback_gate_errors(): from qibo import callbacks entropy = callbacks.EntanglementEntropy([0]) gate = gates.CallbackGate(entropy) with pytest.raises(ValueError): gate._construct_unitary() def test_general_channel(backend): a1 = np.sqrt(0.4) * np.array([[0, 1], [1, 0]]) a2 = np.sqrt(0.6) * np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]) a1, a2 = K.cast(a1), K.cast(a2) initial_rho = random_density_matrix(2) gate = gates.KrausChannel([((1,), a1), ((0, 1), a2)]) assert gate.target_qubits == (0, 1) final_rho = gate(np.copy(initial_rho)) m1 = np.kron(np.eye(2), K.to_numpy(a1)) m2 = K.to_numpy(a2) target_rho = (m1.dot(initial_rho).dot(m1.conj().T) + m2.dot(initial_rho).dot(m2.conj().T)) K.assert_allclose(final_rho, target_rho) def test_krauss_channel_errors(backend): # bad Kraus matrix shape a1 = np.sqrt(0.4) * np.array([[0, 1], [1, 0]]) with pytest.raises(ValueError): gate = gates.KrausChannel([((0, 1), a1)]) # Using KrausChannel on state vectors channel = gates.KrausChannel([((0,), np.eye(2))]) with pytest.raises(ValueError): channel._state_vector_call(np.random.random(4)) # Attempt to construct unitary for KrausChannel with pytest.raises(ValueError): channel._construct_unitary() def test_controlled_by_channel_error(): with pytest.raises(ValueError): gates.PauliNoiseChannel(0, px=0.5).controlled_by(1) a1 = np.sqrt(0.4) * np.array([[0, 1], [1, 0]]) a2 = np.sqrt(0.6) * np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]) config = [((1,), a1), ((0, 1), a2)] with pytest.raises(ValueError): gates.KrausChannel(config).controlled_by(1) def test_unitary_channel(backend): a1 = np.array([[0, 1], [1, 0]]) a2 = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]) probs = [0.4, 0.3] matrices = [((0,), a1), ((2, 3), a2)] initial_state = random_density_matrix(4) gate = gates.UnitaryChannel(probs, matrices) gate.density_matrix = True final_state = gate(K.cast(np.copy(initial_state))) eye = np.eye(2) ma1 = np.kron(np.kron(a1, eye), np.kron(eye, eye)) ma2 = np.kron(np.kron(eye, eye), a2) target_state = (0.3 * initial_state + 0.4 * ma1.dot(initial_state.dot(ma1)) + 0.3 * ma2.dot(initial_state.dot(ma2))) K.assert_allclose(final_state, target_state) def test_unitary_channel_errors(): """Check errors raised by ``gates.UnitaryChannel``.""" a1 = np.array([[0, 1], [1, 0]]) a2 = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]) probs = [0.4, 0.3] matrices = [((0,), a1), ((2, 3), a2)] # Invalid probability length with pytest.raises(ValueError): gate = gates.UnitaryChannel([0.1, 0.3, 0.2], matrices) # Probability > 1 with pytest.raises(ValueError): gate = gates.UnitaryChannel([1.1, 0.2], matrices) # Probability sum = 0 with pytest.raises(ValueError): gate = gates.UnitaryChannel([0.0, 0.0], matrices) def test_pauli_noise_channel(backend): initial_rho = random_density_matrix(2) gate = gates.PauliNoiseChannel(1, px=0.3) gate.density_matrix = True final_rho = gate(K.cast(np.copy(initial_rho))) gate = gates.X(1) gate.density_matrix = True initial_rho = K.cast(initial_rho) target_rho = 0.3 * gate(K.copy(initial_rho)) target_rho += 0.7 * initial_rho K.assert_allclose(final_rho, target_rho) def test_reset_channel(backend): initial_rho = random_density_matrix(3) gate = gates.ResetChannel(0, p0=0.2, p1=0.2) gate.density_matrix = True final_rho = gate(K.cast(np.copy(initial_rho))) dtype = initial_rho.dtype collapsed_rho = np.copy(initial_rho).reshape(6 * (2,)) collapsed_rho[0, :, :, 1, :, :] = np.zeros(4 * (2,), dtype=dtype) collapsed_rho[1, :, :, 0, :, :] = np.zeros(4 * (2,), dtype=dtype) collapsed_rho[1, :, :, 1, :, :] = np.zeros(4 * (2,), dtype=dtype) collapsed_rho = collapsed_rho.reshape((8, 8)) collapsed_rho /= np.trace(collapsed_rho) mx = np.kron(np.array([[0, 1], [1, 0]]), np.eye(4)) flipped_rho = mx.dot(collapsed_rho.dot(mx)) target_rho = 0.6 * initial_rho + 0.2 * (collapsed_rho + flipped_rho) K.assert_allclose(final_rho, target_rho) @pytest.mark.parametrize("t1,t2,time,excpop", [(0.8, 0.5, 1.0, 0.4), (0.5, 0.8, 1.0, 0.4)]) def test_thermal_relaxation_channel(backend, t1, t2, time, excpop): """Check ``gates.ThermalRelaxationChannel`` on a 3-qubit random density matrix.""" initial_rho = random_density_matrix(3) gate = gates.ThermalRelaxationChannel(0, t1, t2, time=time, excited_population=excpop) gate.density_matrix = True final_rho = gate(K.cast(np.copy(initial_rho))) # pylint: disable=E1102 exp, p0, p1 = gate.calculate_probabilities(t1, t2, time, excpop) if t2 > t1: matrix = np.diag([1 - p1, p0, p1, 1 - p0]) matrix[0, -1], matrix[-1, 0] = exp, exp matrix = matrix.reshape(4 * (2,)) # Apply matrix using Eq. (3.28) from arXiv:1111.6950 target_rho = np.copy(initial_rho).reshape(6 * (2,)) target_rho = np.einsum("abcd,aJKcjk->bJKdjk", matrix, target_rho) target_rho = target_rho.reshape(initial_rho.shape) else: pz = exp pi = 1 - pz - p0 - p1 dtype = initial_rho.dtype collapsed_rho = np.copy(initial_rho).reshape(6 * (2,)) collapsed_rho[0, :, :, 1, :, :] = np.zeros(4 * (2,), dtype=dtype) collapsed_rho[1, :, :, 0, :, :] = np.zeros(4 * (2,), dtype=dtype) collapsed_rho[1, :, :, 1, :, :] = np.zeros(4 * (2,), dtype=dtype) collapsed_rho = collapsed_rho.reshape((8, 8)) collapsed_rho /= np.trace(collapsed_rho) mx = np.kron(np.array([[0, 1], [1, 0]]), np.eye(4)) mz = np.kron(np.array([[1, 0], [0, -1]]), np.eye(4)) z_rho = mz.dot(initial_rho.dot(mz)) flipped_rho = mx.dot(collapsed_rho.dot(mx)) target_rho = (pi * initial_rho + pz * z_rho + p0 * collapsed_rho + p1 * flipped_rho) K.assert_allclose(final_rho, target_rho) # Try to apply to state vector if t1 < t2 if t1 < t2: with pytest.raises(ValueError): gate._state_vector_call(initial_rho) # pylint: disable=no-member @pytest.mark.parametrize("t1,t2,time,excpop", [(1.0, 0.5, 1.5, 1.5), (1.0, 0.5, -0.5, 0.5), (1.0, -0.5, 1.5, 0.5), (-1.0, 0.5, 1.5, 0.5), (1.0, 3.0, 1.5, 0.5)]) def test_thermal_relaxation_channel_errors(backend, t1, t2, time, excpop): with pytest.raises(ValueError): gate = gates.ThermalRelaxationChannel( 0, t1, t2, time, excited_population=excpop) def test_fused_gate_init(backend): gate = gates.FusedGate(0) gate = gates.FusedGate(0, 1) if K.is_custom: with pytest.raises(NotImplementedError): gate = gates.FusedGate(0, 1, 2) def test_fused_gate_construct_unitary(backend): gate = gates.FusedGate(0, 1) gate.add(gates.H(0)) gate.add(gates.H(1)) gate.add(gates.CZ(0, 1)) hmatrix = np.array([[1, 1], [1, -1]]) / np.sqrt(2) czmatrix = np.diag([1, 1, 1, -1]) target_matrix = czmatrix @ np.kron(hmatrix, hmatrix) K.assert_allclose(gate.matrix, target_matrix)
[ "qibo.gates.Unitary", "numpy.trace", "qibo.K.to_numpy", "numpy.sqrt", "qibo.gates.CZ", "qibo.gates.CallbackGate", "qibo.K.qnp.zeros", "qibo.gates.KrausChannel", "qibo.gates.CNOT", "qibo.gates.U2", "qibo.tests.utils.random_state", "qibo.gates.U1", "qibo.gates.RZ", "numpy.array", "qibo.gat...
[((4644, 4692), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""applyx"""', '[True, False]'], {}), "('applyx', [True, False])\n", (4667, 4692), False, 'import pytest\n'), ((6373, 6421), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""applyx"""', '[False, True]'], {}), "('applyx', [False, True])\n", (6396, 6421), False, 'import pytest\n'), ((6760, 6815), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""controlled_by"""', '[False, True]'], {}), "('controlled_by', [False, True])\n", (6783, 6815), False, 'import pytest\n'), ((7232, 7470), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""name,params"""', "[('CRX', {'theta': 0.1}), ('CRY', {'theta': 0.2}), ('CRZ', {'theta': 0.3}),\n ('CU1', {'theta': 0.1}), ('CU2', {'phi': 0.1, 'lam': 0.2}), ('CU3', {\n 'theta': 0.1, 'phi': 0.2, 'lam': 0.3})]"], {}), "('name,params', [('CRX', {'theta': 0.1}), ('CRY', {\n 'theta': 0.2}), ('CRZ', {'theta': 0.3}), ('CU1', {'theta': 0.1}), (\n 'CU2', {'phi': 0.1, 'lam': 0.2}), ('CU3', {'theta': 0.1, 'phi': 0.2,\n 'lam': 0.3})])\n", (7255, 7470), False, 'import pytest\n'), ((10063, 10111), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""applyx"""', '[False, True]'], {}), "('applyx', [False, True])\n", (10086, 10111), False, 'import pytest\n'), ((10527, 10569), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""nqubits"""', '[2, 3]'], {}), "('nqubits', [2, 3])\n", (10550, 10569), False, 'import pytest\n'), ((13368, 13410), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""nqubits"""', '[5, 6]'], {}), "('nqubits', [5, 6])\n", (13391, 13410), False, 'import pytest\n'), ((19127, 19222), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""t1,t2,time,excpop"""', '[(0.8, 0.5, 1.0, 0.4), (0.5, 0.8, 1.0, 0.4)]'], {}), "('t1,t2,time,excpop', [(0.8, 0.5, 1.0, 0.4), (0.5, \n 0.8, 1.0, 0.4)])\n", (19150, 19222), False, 'import pytest\n'), ((21165, 21334), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""t1,t2,time,excpop"""', '[(1.0, 0.5, 1.5, 1.5), (1.0, 0.5, -0.5, 0.5), (1.0, -0.5, 1.5, 0.5), (-1.0,\n 0.5, 1.5, 0.5), (1.0, 3.0, 1.5, 0.5)]'], {}), "('t1,t2,time,excpop', [(1.0, 0.5, 1.5, 1.5), (1.0, \n 0.5, -0.5, 0.5), (1.0, -0.5, 1.5, 0.5), (-1.0, 0.5, 1.5, 0.5), (1.0, \n 3.0, 1.5, 0.5)])\n", (21188, 21334), False, 'import pytest\n'), ((785, 798), 'qibo.K.cast', 'K.cast', (['state'], {}), '(state)\n', (791, 798), False, 'from qibo import gates, K\n'), ((965, 989), 'qibo.gates.Unitary', 'gates.Unitary', (['matrix', '(0)'], {}), '(matrix, 0)\n', (978, 989), False, 'from qibo import gates, K\n'), ((1127, 1145), 'qibo.K.to_numpy', 'K.to_numpy', (['matrix'], {}), '(matrix)\n', (1137, 1145), False, 'from qibo import gates, K\n'), ((1150, 1192), 'qibo.K.assert_allclose', 'K.assert_allclose', (['unitary', 'target_unitary'], {}), '(unitary, target_unitary)\n', (1167, 1192), False, 'from qibo import gates, K\n'), ((1440, 1484), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (1457, 1484), False, 'from qibo import gates, K\n'), ((1582, 1608), 'numpy.zeros_like', 'np.zeros_like', (['final_state'], {}), '(final_state)\n', (1595, 1608), True, 'import numpy as np\n'), ((1639, 1683), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (1656, 1683), False, 'from qibo import gates, K\n'), ((1781, 1807), 'numpy.zeros_like', 'np.zeros_like', (['final_state'], {}), '(final_state)\n', (1794, 1807), True, 'import numpy as np\n'), ((1837, 1881), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (1854, 1881), False, 'from qibo import gates, K\n'), ((2095, 2139), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (2112, 2139), False, 'from qibo import gates, K\n'), ((2261, 2293), 'numpy.array', 'np.array', (['[0.5, 0.5j, 0.5, 0.5j]'], {}), '([0.5, 0.5j, 0.5, 0.5j])\n', (2269, 2293), True, 'import numpy as np\n'), ((2298, 2342), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (2315, 2342), False, 'from qibo import gates, K\n'), ((2468, 2502), 'numpy.array', 'np.array', (['[0.5, -0.5j, 0.5, -0.5j]'], {}), '([0.5, -0.5j, 0.5, -0.5j])\n', (2476, 2502), True, 'import numpy as np\n'), ((2507, 2551), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (2524, 2551), False, 'from qibo import gates, K\n'), ((2773, 2817), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (2790, 2817), False, 'from qibo import gates, K\n'), ((3043, 3087), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (3060, 3087), False, 'from qibo import gates, K\n'), ((3288, 3332), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (3305, 3332), False, 'from qibo import gates, K\n'), ((3443, 3487), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (3460, 3487), False, 'from qibo import gates, K\n'), ((3526, 3543), 'qibo.gates.Align', 'gates.Align', (['(0)', '(1)'], {}), '(0, 1)\n', (3537, 3543), False, 'from qibo import gates, K\n'), ((3696, 3740), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (3713, 3740), False, 'from qibo import gates, K\n'), ((4049, 4075), 'numpy.exp', 'np.exp', (['(1.0j * theta / 2.0)'], {}), '(1.0j * theta / 2.0)\n', (4055, 4075), True, 'import numpy as np\n'), ((4085, 4163), 'numpy.array', 'np.array', (['[[phase.real, -1.0j * phase.imag], [-1.0j * phase.imag, phase.real]]'], {}), '([[phase.real, -1.0j * phase.imag], [-1.0j * phase.imag, phase.real]])\n', (4093, 4163), True, 'import numpy as np\n'), ((4237, 4281), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (4254, 4281), False, 'from qibo import gates, K\n'), ((4418, 4444), 'numpy.exp', 'np.exp', (['(1.0j * theta / 2.0)'], {}), '(1.0j * theta / 2.0)\n', (4424, 4444), True, 'import numpy as np\n'), ((4454, 4517), 'numpy.array', 'np.array', (['[[phase.real, -phase.imag], [phase.imag, phase.real]]'], {}), '([[phase.real, -phase.imag], [phase.imag, phase.real]])\n', (4462, 4517), True, 'import numpy as np\n'), ((4596, 4640), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (4613, 4640), False, 'from qibo import gates, K\n'), ((4931, 4957), 'numpy.zeros_like', 'np.zeros_like', (['final_state'], {}), '(final_state)\n', (4944, 4957), True, 'import numpy as np\n'), ((5000, 5040), 'numpy.exp', 'np.exp', (['((2 * p - 1) * 1.0j * theta / 2.0)'], {}), '((2 * p - 1) * 1.0j * theta / 2.0)\n', (5006, 5040), True, 'import numpy as np\n'), ((5043, 5087), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (5060, 5087), False, 'from qibo import gates, K\n'), ((5225, 5251), 'numpy.zeros_like', 'np.zeros_like', (['final_state'], {}), '(final_state)\n', (5238, 5251), True, 'import numpy as np\n'), ((5274, 5294), 'numpy.exp', 'np.exp', (['(1.0j * theta)'], {}), '(1.0j * theta)\n', (5280, 5294), True, 'import numpy as np\n'), ((5297, 5341), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (5314, 5341), False, 'from qibo import gates, K\n'), ((5420, 5435), 'qibo.tests.utils.random_state', 'random_state', (['(1)'], {}), '(1)\n', (5432, 5435), False, 'from qibo.tests.utils import random_state, random_density_matrix\n'), ((5756, 5800), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (5773, 5800), False, 'from qibo import gates, K\n'), ((5898, 5913), 'qibo.tests.utils.random_state', 'random_state', (['(1)'], {}), '(1)\n', (5910, 5913), False, 'from qibo.tests.utils import random_state, random_density_matrix\n'), ((6098, 6128), 'numpy.exp', 'np.exp', (['(1.0j * (phi + lam) / 2)'], {}), '(1.0j * (phi + lam) / 2)\n', (6104, 6128), True, 'import numpy as np\n'), ((6136, 6166), 'numpy.exp', 'np.exp', (['(1.0j * (phi - lam) / 2)'], {}), '(1.0j * (phi - lam) / 2)\n', (6142, 6166), True, 'import numpy as np\n'), ((6325, 6369), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (6342, 6369), False, 'from qibo import gates, K\n'), ((6641, 6667), 'numpy.zeros_like', 'np.zeros_like', (['final_state'], {}), '(final_state)\n', (6654, 6667), True, 'import numpy as np\n'), ((6712, 6756), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (6729, 6756), False, 'from qibo import gates, K\n'), ((6873, 6888), 'qibo.tests.utils.random_state', 'random_state', (['(2)'], {}), '(2)\n', (6885, 6888), False, 'from qibo.tests.utils import random_state, random_density_matrix\n'), ((6902, 6911), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (6908, 6911), True, 'import numpy as np\n'), ((7184, 7228), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (7201, 7228), False, 'from qibo import gates, K\n'), ((7669, 7684), 'qibo.tests.utils.random_state', 'random_state', (['(2)'], {}), '(2)\n', (7681, 7684), False, 'from qibo.tests.utils import random_state, random_density_matrix\n'), ((7870, 7914), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (7887, 7914), False, 'from qibo import gates, K\n'), ((8033, 8059), 'numpy.zeros_like', 'np.zeros_like', (['final_state'], {}), '(final_state)\n', (8046, 8059), True, 'import numpy as np\n'), ((8090, 8134), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (8107, 8134), False, 'from qibo import gates, K\n'), ((8393, 8437), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (8410, 8437), False, 'from qibo import gates, K\n'), ((8824, 8859), 'numpy.eye', 'np.eye', (['(4)'], {'dtype': 'target_state.dtype'}), '(4, dtype=target_state.dtype)\n', (8830, 8859), True, 'import numpy as np\n'), ((8911, 8930), 'numpy.exp', 'np.exp', (['(-1.0j * phi)'], {}), '(-1.0j * phi)\n', (8917, 8930), True, 'import numpy as np\n'), ((8977, 9021), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (8994, 9021), False, 'from qibo import gates, K\n'), ((9070, 9088), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (9086, 9088), True, 'import numpy as np\n'), ((9411, 9446), 'numpy.eye', 'np.eye', (['(4)'], {'dtype': 'target_state.dtype'}), '(4, dtype=target_state.dtype)\n', (9417, 9446), True, 'import numpy as np\n'), ((9498, 9517), 'numpy.exp', 'np.exp', (['(-1.0j * phi)'], {}), '(-1.0j * phi)\n', (9504, 9517), True, 'import numpy as np\n'), ((9624, 9668), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (9641, 9668), False, 'from qibo import gates, K\n'), ((9734, 9752), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (9750, 9752), True, 'import numpy as np\n'), ((9766, 9790), 'numpy.random.random', 'np.random.random', (['(2, 2)'], {}), '((2, 2))\n', (9782, 9790), True, 'import numpy as np\n'), ((9802, 9842), 'qibo.gates.GeneralizedfSim', 'gates.GeneralizedfSim', (['(0)', '(1)', 'matrix', 'phi'], {}), '(0, 1, matrix, phi)\n', (9823, 9842), False, 'from qibo import gates, K\n'), ((9847, 9892), 'qibo.K.assert_allclose', 'K.assert_allclose', (['gate.parameters[0]', 'matrix'], {}), '(gate.parameters[0], matrix)\n', (9864, 9892), False, 'from qibo import gates, K\n'), ((9943, 9967), 'numpy.random.random', 'np.random.random', (['(4, 4)'], {}), '((4, 4))\n', (9959, 9967), True, 'import numpy as np\n'), ((10366, 10392), 'numpy.zeros_like', 'np.zeros_like', (['final_state'], {}), '(final_state)\n', (10379, 10392), True, 'import numpy as np\n'), ((10479, 10523), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (10496, 10523), False, 'from qibo import gates, K\n'), ((10685, 10728), 'numpy.random.random', 'np.random.random', (['(2 * (2 ** (nqubits - 1),))'], {}), '(2 * (2 ** (nqubits - 1),))\n', (10701, 10728), True, 'import numpy as np\n'), ((10985, 11029), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (11002, 11029), False, 'from qibo import gates, K\n'), ((11087, 11111), 'numpy.random.random', 'np.random.random', (['(4, 4)'], {}), '((4, 4))\n', (11103, 11111), True, 'import numpy as np\n'), ((11123, 11150), 'qibo.gates.Unitary', 'gates.Unitary', (['matrix', '(0)', '(1)'], {}), '(matrix, 0, 1)\n', (11136, 11150), False, 'from qibo import gates, K\n'), ((11155, 11197), 'qibo.K.assert_allclose', 'K.assert_allclose', (['gate.parameters', 'matrix'], {}), '(gate.parameters, matrix)\n', (11172, 11197), False, 'from qibo import gates, K\n'), ((11211, 11235), 'numpy.random.random', 'np.random.random', (['(8, 8)'], {}), '((8, 8))\n', (11227, 11235), True, 'import numpy as np\n'), ((11695, 11739), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (11712, 11739), False, 'from qibo import gates, K\n'), ((12208, 12274), 'numpy.array', 'np.array', (['[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]'], {}), '([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])\n', (12216, 12274), True, 'import numpy as np\n'), ((12433, 12477), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (12450, 12477), False, 'from qibo import gates, K\n'), ((12748, 12774), 'numpy.array', 'np.array', (['[[0, 1], [1, 0]]'], {}), '([[0, 1], [1, 0]])\n', (12756, 12774), True, 'import numpy as np\n'), ((12786, 12852), 'numpy.array', 'np.array', (['[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]'], {}), '([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])\n', (12794, 12852), True, 'import numpy as np\n'), ((13020, 13053), 'qibo.gates.Unitary', 'gates.Unitary', (['matrix', '(0)', '(1)', '(2)', '(3)'], {}), '(matrix, 0, 1, 2, 3)\n', (13033, 13053), False, 'from qibo import gates, K\n'), ((13975, 14019), 'qibo.K.assert_allclose', 'K.assert_allclose', (['target_state', 'final_state'], {}), '(target_state, final_state)\n', (13992, 14019), False, 'from qibo import gates, K\n'), ((14464, 14508), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (14481, 14508), False, 'from qibo import gates, K\n'), ((14557, 14584), 'qibo.gates.Flatten', 'gates.Flatten', (['target_state'], {}), '(target_state)\n', (14570, 14584), False, 'from qibo import gates, K\n'), ((14735, 14769), 'qibo.callbacks.EntanglementEntropy', 'callbacks.EntanglementEntropy', (['[0]'], {}), '([0])\n', (14764, 14769), False, 'from qibo import callbacks\n'), ((14781, 14808), 'qibo.gates.CallbackGate', 'gates.CallbackGate', (['entropy'], {}), '(entropy)\n', (14799, 14808), False, 'from qibo import gates, K\n'), ((15146, 15170), 'qibo.tests.utils.random_density_matrix', 'random_density_matrix', (['(2)'], {}), '(2)\n', (15167, 15170), False, 'from qibo.tests.utils import random_state, random_density_matrix\n'), ((15182, 15228), 'qibo.gates.KrausChannel', 'gates.KrausChannel', (['[((1,), a1), ((0, 1), a2)]'], {}), '([((1,), a1), ((0, 1), a2)])\n', (15200, 15228), False, 'from qibo import gates, K\n'), ((15365, 15379), 'qibo.K.to_numpy', 'K.to_numpy', (['a2'], {}), '(a2)\n', (15375, 15379), False, 'from qibo import gates, K\n'), ((15497, 15537), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_rho', 'target_rho'], {}), '(final_rho, target_rho)\n', (15514, 15537), False, 'from qibo import gates, K\n'), ((16549, 16575), 'numpy.array', 'np.array', (['[[0, 1], [1, 0]]'], {}), '([[0, 1], [1, 0]])\n', (16557, 16575), True, 'import numpy as np\n'), ((16585, 16651), 'numpy.array', 'np.array', (['[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]'], {}), '([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])\n', (16593, 16651), True, 'import numpy as np\n'), ((16737, 16761), 'qibo.tests.utils.random_density_matrix', 'random_density_matrix', (['(4)'], {}), '(4)\n', (16758, 16761), False, 'from qibo.tests.utils import random_state, random_density_matrix\n'), ((16773, 16810), 'qibo.gates.UnitaryChannel', 'gates.UnitaryChannel', (['probs', 'matrices'], {}), '(probs, matrices)\n', (16793, 16810), False, 'from qibo import gates, K\n'), ((16908, 16917), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (16914, 16917), True, 'import numpy as np\n'), ((17179, 17223), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (17196, 17223), False, 'from qibo import gates, K\n'), ((17329, 17355), 'numpy.array', 'np.array', (['[[0, 1], [1, 0]]'], {}), '([[0, 1], [1, 0]])\n', (17337, 17355), True, 'import numpy as np\n'), ((17365, 17431), 'numpy.array', 'np.array', (['[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]'], {}), '([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])\n', (17373, 17431), True, 'import numpy as np\n'), ((17924, 17948), 'qibo.tests.utils.random_density_matrix', 'random_density_matrix', (['(2)'], {}), '(2)\n', (17945, 17948), False, 'from qibo.tests.utils import random_state, random_density_matrix\n'), ((17960, 17994), 'qibo.gates.PauliNoiseChannel', 'gates.PauliNoiseChannel', (['(1)'], {'px': '(0.3)'}), '(1, px=0.3)\n', (17983, 17994), False, 'from qibo import gates, K\n'), ((18088, 18098), 'qibo.gates.X', 'gates.X', (['(1)'], {}), '(1)\n', (18095, 18098), False, 'from qibo import gates, K\n'), ((18148, 18167), 'qibo.K.cast', 'K.cast', (['initial_rho'], {}), '(initial_rho)\n', (18154, 18167), False, 'from qibo import gates, K\n'), ((18257, 18297), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_rho', 'target_rho'], {}), '(final_rho, target_rho)\n', (18274, 18297), False, 'from qibo import gates, K\n'), ((18351, 18375), 'qibo.tests.utils.random_density_matrix', 'random_density_matrix', (['(3)'], {}), '(3)\n', (18372, 18375), False, 'from qibo.tests.utils import random_state, random_density_matrix\n'), ((18387, 18424), 'qibo.gates.ResetChannel', 'gates.ResetChannel', (['(0)'], {'p0': '(0.2)', 'p1': '(0.2)'}), '(0, p0=0.2, p1=0.2)\n', (18405, 18424), False, 'from qibo import gates, K\n'), ((18635, 18666), 'numpy.zeros', 'np.zeros', (['(4 * (2,))'], {'dtype': 'dtype'}), '(4 * (2,), dtype=dtype)\n', (18643, 18666), True, 'import numpy as np\n'), ((18705, 18736), 'numpy.zeros', 'np.zeros', (['(4 * (2,))'], {'dtype': 'dtype'}), '(4 * (2,), dtype=dtype)\n', (18713, 18736), True, 'import numpy as np\n'), ((18775, 18806), 'numpy.zeros', 'np.zeros', (['(4 * (2,))'], {'dtype': 'dtype'}), '(4 * (2,), dtype=dtype)\n', (18783, 18806), True, 'import numpy as np\n'), ((18878, 18901), 'numpy.trace', 'np.trace', (['collapsed_rho'], {}), '(collapsed_rho)\n', (18886, 18901), True, 'import numpy as np\n'), ((19083, 19123), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_rho', 'target_rho'], {}), '(final_rho, target_rho)\n', (19100, 19123), False, 'from qibo import gates, K\n'), ((19416, 19440), 'qibo.tests.utils.random_density_matrix', 'random_density_matrix', (['(3)'], {}), '(3)\n', (19437, 19440), False, 'from qibo.tests.utils import random_state, random_density_matrix\n'), ((19452, 19531), 'qibo.gates.ThermalRelaxationChannel', 'gates.ThermalRelaxationChannel', (['(0)', 't1', 't2'], {'time': 'time', 'excited_population': 'excpop'}), '(0, t1, t2, time=time, excited_population=excpop)\n', (19482, 19531), False, 'from qibo import gates, K\n'), ((20942, 20982), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_rho', 'target_rho'], {}), '(final_rho, target_rho)\n', (20959, 20982), False, 'from qibo import gates, K\n'), ((21664, 21682), 'qibo.gates.FusedGate', 'gates.FusedGate', (['(0)'], {}), '(0)\n', (21679, 21682), False, 'from qibo import gates, K\n'), ((21694, 21715), 'qibo.gates.FusedGate', 'gates.FusedGate', (['(0)', '(1)'], {}), '(0, 1)\n', (21709, 21715), False, 'from qibo import gates, K\n'), ((21890, 21911), 'qibo.gates.FusedGate', 'gates.FusedGate', (['(0)', '(1)'], {}), '(0, 1)\n', (21905, 21911), False, 'from qibo import gates, K\n'), ((22061, 22083), 'numpy.diag', 'np.diag', (['[1, 1, 1, -1]'], {}), '([1, 1, 1, -1])\n', (22068, 22083), True, 'import numpy as np\n'), ((22145, 22190), 'qibo.K.assert_allclose', 'K.assert_allclose', (['gate.matrix', 'target_matrix'], {}), '(gate.matrix, target_matrix)\n', (22162, 22190), False, 'from qibo import gates, K\n'), ((319, 344), 'qibo.K.qnp.zeros', 'K.qnp.zeros', (['(2 ** nqubits)'], {}), '(2 ** nqubits)\n', (330, 344), False, 'from qibo import gates, K\n'), ((928, 952), 'numpy.random.random', 'np.random.random', (['(2, 2)'], {}), '((2, 2))\n', (944, 952), True, 'import numpy as np\n'), ((1202, 1227), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1215, 1227), False, 'import pytest\n'), ((1406, 1431), 'numpy.ones_like', 'np.ones_like', (['final_state'], {}), '(final_state)\n', (1418, 1431), True, 'import numpy as np\n'), ((2003, 2028), 'numpy.ones_like', 'np.ones_like', (['final_state'], {}), '(final_state)\n', (2015, 2028), True, 'import numpy as np\n'), ((3134, 3144), 'qibo.gates.H', 'gates.H', (['(0)'], {}), '(0)\n', (3141, 3144), False, 'from qibo import gates, K\n'), ((3146, 3156), 'qibo.gates.H', 'gates.H', (['(1)'], {}), '(1)\n', (3153, 3156), False, 'from qibo import gates, K\n'), ((3158, 3168), 'qibo.gates.I', 'gates.I', (['(0)'], {}), '(0)\n', (3165, 3168), False, 'from qibo import gates, K\n'), ((3170, 3180), 'qibo.gates.I', 'gates.I', (['(1)'], {}), '(1)\n', (3177, 3180), False, 'from qibo import gates, K\n'), ((3252, 3277), 'numpy.ones_like', 'np.ones_like', (['final_state'], {}), '(final_state)\n', (3264, 3277), True, 'import numpy as np\n'), ((3349, 3359), 'qibo.gates.H', 'gates.H', (['(0)'], {}), '(0)\n', (3356, 3359), False, 'from qibo import gates, K\n'), ((3361, 3371), 'qibo.gates.H', 'gates.H', (['(1)'], {}), '(1)\n', (3368, 3371), False, 'from qibo import gates, K\n'), ((3373, 3386), 'qibo.gates.I', 'gates.I', (['(0)', '(1)'], {}), '(0, 1)\n', (3380, 3386), False, 'from qibo import gates, K\n'), ((3560, 3570), 'qibo.gates.H', 'gates.H', (['(0)'], {}), '(0)\n', (3567, 3570), False, 'from qibo import gates, K\n'), ((3572, 3582), 'qibo.gates.H', 'gates.H', (['(1)'], {}), '(1)\n', (3579, 3582), False, 'from qibo import gates, K\n'), ((3660, 3685), 'numpy.ones_like', 'np.ones_like', (['final_state'], {}), '(final_state)\n', (3672, 3685), True, 'import numpy as np\n'), ((3820, 3829), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (3826, 3829), True, 'import numpy as np\n'), ((4222, 4232), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (4229, 4232), True, 'import numpy as np\n'), ((4581, 4591), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (4588, 4591), True, 'import numpy as np\n'), ((4841, 4859), 'qibo.gates.RZ', 'gates.RZ', (['(0)', 'theta'], {}), '(0, theta)\n', (4849, 4859), False, 'from qibo import gates, K\n'), ((5741, 5751), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (5748, 5751), True, 'import numpy as np\n'), ((6052, 6069), 'numpy.cos', 'np.cos', (['(theta / 2)'], {}), '(theta / 2)\n', (6058, 6069), True, 'import numpy as np\n'), ((6071, 6088), 'numpy.sin', 'np.sin', (['(theta / 2)'], {}), '(theta / 2)\n', (6077, 6088), True, 'import numpy as np\n'), ((6553, 6569), 'qibo.gates.CNOT', 'gates.CNOT', (['(0)', '(1)'], {}), '(0, 1)\n', (6563, 6569), False, 'from qibo import gates, K\n'), ((7069, 7083), 'qibo.gates.CZ', 'gates.CZ', (['(0)', '(1)'], {}), '(0, 1)\n', (7077, 7083), False, 'from qibo import gates, K\n'), ((7826, 7849), 'qibo.K.to_numpy', 'K.to_numpy', (['gate.matrix'], {}), '(gate.matrix)\n', (7836, 7849), False, 'from qibo import gates, K\n'), ((8186, 8196), 'qibo.gates.X', 'gates.X', (['(0)'], {}), '(0)\n', (8193, 8196), False, 'from qibo import gates, K\n'), ((8198, 8208), 'qibo.gates.X', 'gates.X', (['(2)'], {}), '(2)\n', (8205, 8208), False, 'from qibo import gates, K\n'), ((8210, 8226), 'qibo.gates.SWAP', 'gates.SWAP', (['(0)', '(1)'], {}), '(0, 1)\n', (8220, 8226), False, 'from qibo import gates, K\n'), ((8228, 8244), 'qibo.gates.SWAP', 'gates.SWAP', (['(2)', '(3)'], {}), '(2, 3)\n', (8238, 8244), False, 'from qibo import gates, K\n'), ((8313, 8323), 'qibo.gates.X', 'gates.X', (['(1)'], {}), '(1)\n', (8320, 8323), False, 'from qibo import gates, K\n'), ((8325, 8335), 'qibo.gates.X', 'gates.X', (['(3)'], {}), '(3)\n', (8332, 8335), False, 'from qibo import gates, K\n'), ((8516, 8526), 'qibo.gates.H', 'gates.H', (['(0)'], {}), '(0)\n', (8523, 8526), False, 'from qibo import gates, K\n'), ((8528, 8538), 'qibo.gates.H', 'gates.H', (['(1)'], {}), '(1)\n', (8535, 8538), False, 'from qibo import gates, K\n'), ((8540, 8568), 'qibo.gates.fSim', 'gates.fSim', (['(0)', '(1)', 'theta', 'phi'], {}), '(0, 1, theta, phi)\n', (8550, 8568), False, 'from qibo import gates, K\n'), ((9104, 9128), 'numpy.random.random', 'np.random.random', (['(2, 2)'], {}), '((2, 2))\n', (9120, 9128), True, 'import numpy as np\n'), ((9177, 9187), 'qibo.gates.H', 'gates.H', (['(0)'], {}), '(0)\n', (9184, 9187), False, 'from qibo import gates, K\n'), ((9189, 9199), 'qibo.gates.H', 'gates.H', (['(1)'], {}), '(1)\n', (9196, 9199), False, 'from qibo import gates, K\n'), ((9201, 9211), 'qibo.gates.H', 'gates.H', (['(2)'], {}), '(2)\n', (9208, 9211), False, 'from qibo import gates, K\n'), ((9233, 9275), 'qibo.gates.GeneralizedfSim', 'gates.GeneralizedfSim', (['(1)', '(2)', 'rotation', 'phi'], {}), '(1, 2, rotation, phi)\n', (9254, 9275), False, 'from qibo import gates, K\n'), ((9387, 9397), 'numpy.sqrt', 'np.sqrt', (['(8)'], {}), '(8)\n', (9394, 9397), True, 'import numpy as np\n'), ((9977, 10002), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (9990, 10002), False, 'import pytest\n'), ((10019, 10059), 'qibo.gates.GeneralizedfSim', 'gates.GeneralizedfSim', (['(0)', '(1)', 'matrix', 'phi'], {}), '(0, 1, matrix, phi)\n', (10040, 10059), False, 'from qibo import gates, K\n'), ((10626, 10647), 'numpy.ones', 'np.ones', (['(2 ** nqubits)'], {}), '(2 ** nqubits)\n', (10633, 10647), True, 'import numpy as np\n'), ((10650, 10671), 'numpy.sqrt', 'np.sqrt', (['(2 ** nqubits)'], {}), '(2 ** nqubits)\n', (10657, 10671), True, 'import numpy as np\n'), ((10810, 10820), 'qibo.gates.H', 'gates.H', (['i'], {}), '(i)\n', (10817, 10820), False, 'from qibo import gates, K\n'), ((11245, 11270), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (11258, 11270), False, 'import pytest\n'), ((11287, 11314), 'qibo.gates.Unitary', 'gates.Unitary', (['matrix', '(0)', '(1)'], {}), '(matrix, 0, 1)\n', (11300, 11314), False, 'from qibo import gates, K\n'), ((11324, 11348), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (11337, 11348), False, 'import pytest\n'), ((11365, 11391), 'qibo.gates.Unitary', 'gates.Unitary', (['"""abc"""', '(0)', '(1)'], {}), "('abc', 0, 1)\n", (11378, 11391), False, 'from qibo import gates, K\n'), ((11797, 11822), 'qibo.gates.RX', 'gates.RX', (['(0)'], {'theta': 'thetax'}), '(0, theta=thetax)\n', (11805, 11822), False, 'from qibo import gates, K\n'), ((11824, 11849), 'qibo.gates.RY', 'gates.RY', (['(1)'], {'theta': 'thetay'}), '(1, theta=thetay)\n', (11832, 11849), False, 'from qibo import gates, K\n'), ((11867, 11883), 'qibo.gates.CNOT', 'gates.CNOT', (['(0)', '(1)'], {}), '(0, 1)\n', (11877, 11883), False, 'from qibo import gates, K\n'), ((12291, 12311), 'qibo.gates.Unitary', 'gates.Unitary', (['rx', '(0)'], {}), '(rx, 0)\n', (12304, 12311), False, 'from qibo import gates, K\n'), ((12313, 12333), 'qibo.gates.Unitary', 'gates.Unitary', (['ry', '(1)'], {}), '(ry, 1)\n', (12326, 12333), False, 'from qibo import gates, K\n'), ((12351, 12376), 'qibo.gates.Unitary', 'gates.Unitary', (['cnot', '(0)', '(1)'], {}), '(cnot, 0, 1)\n', (12364, 12376), False, 'from qibo import gates, K\n'), ((12534, 12544), 'qibo.gates.H', 'gates.H', (['i'], {}), '(i)\n', (12541, 12544), False, 'from qibo import gates, K\n'), ((12584, 12600), 'qibo.gates.CNOT', 'gates.CNOT', (['(0)', '(1)'], {}), '(0, 1)\n', (12594, 12600), False, 'from qibo import gates, K\n'), ((12622, 12638), 'qibo.gates.CNOT', 'gates.CNOT', (['(2)', '(3)'], {}), '(2, 3)\n', (12632, 12638), False, 'from qibo import gates, K\n'), ((12699, 12726), 'numpy.array', 'np.array', (['[[1, 1], [1, -1]]'], {}), '([[1, 1], [1, -1]])\n', (12707, 12726), True, 'import numpy as np\n'), ((12729, 12739), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (12736, 12739), True, 'import numpy as np\n'), ((12874, 12887), 'numpy.kron', 'np.kron', (['x', 'x'], {}), '(x, x)\n', (12881, 12887), True, 'import numpy as np\n'), ((12889, 12902), 'numpy.kron', 'np.kron', (['x', 'x'], {}), '(x, x)\n', (12896, 12902), True, 'import numpy as np\n'), ((12926, 12945), 'numpy.kron', 'np.kron', (['cnot', 'cnot'], {}), '(cnot, cnot)\n', (12933, 12945), True, 'import numpy as np\n'), ((13320, 13364), 'qibo.K.assert_allclose', 'K.assert_allclose', (['final_state', 'target_state'], {}), '(final_state, target_state)\n', (13337, 13364), False, 'from qibo import gates, K\n'), ((13481, 13506), 'numpy.random.random', 'np.random.random', (['nqubits'], {}), '(nqubits)\n', (13497, 13506), True, 'import numpy as np\n'), ((13523, 13537), 'qibo.gates.RY', 'gates.RY', (['i', 't'], {}), '(i, t)\n', (13531, 13537), False, 'from qibo import gates, K\n'), ((14155, 14174), 'numpy.random.random', 'np.random.random', (['(6)'], {}), '(6)\n', (14171, 14174), True, 'import numpy as np\n'), ((14262, 14287), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (14275, 14287), False, 'import pytest\n'), ((14371, 14381), 'numpy.ones', 'np.ones', (['(4)'], {}), '(4)\n', (14378, 14381), True, 'import numpy as np\n'), ((14529, 14539), 'numpy.ones', 'np.ones', (['(4)'], {}), '(4)\n', (14536, 14539), True, 'import numpy as np\n'), ((14594, 14619), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (14607, 14619), False, 'import pytest\n'), ((14818, 14843), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (14831, 14843), False, 'import pytest\n'), ((14925, 14937), 'numpy.sqrt', 'np.sqrt', (['(0.4)'], {}), '(0.4)\n', (14932, 14937), True, 'import numpy as np\n'), ((14940, 14966), 'numpy.array', 'np.array', (['[[0, 1], [1, 0]]'], {}), '([[0, 1], [1, 0]])\n', (14948, 14966), True, 'import numpy as np\n'), ((14976, 14988), 'numpy.sqrt', 'np.sqrt', (['(0.6)'], {}), '(0.6)\n', (14983, 14988), True, 'import numpy as np\n'), ((14991, 15057), 'numpy.array', 'np.array', (['[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]'], {}), '([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])\n', (14999, 15057), True, 'import numpy as np\n'), ((15105, 15115), 'qibo.K.cast', 'K.cast', (['a1'], {}), '(a1)\n', (15111, 15115), False, 'from qibo import gates, K\n'), ((15117, 15127), 'qibo.K.cast', 'K.cast', (['a2'], {}), '(a2)\n', (15123, 15127), False, 'from qibo import gates, K\n'), ((15290, 15310), 'numpy.copy', 'np.copy', (['initial_rho'], {}), '(initial_rho)\n', (15297, 15310), True, 'import numpy as np\n'), ((15329, 15338), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (15335, 15338), True, 'import numpy as np\n'), ((15340, 15354), 'qibo.K.to_numpy', 'K.to_numpy', (['a1'], {}), '(a1)\n', (15350, 15354), False, 'from qibo import gates, K\n'), ((15619, 15631), 'numpy.sqrt', 'np.sqrt', (['(0.4)'], {}), '(0.4)\n', (15626, 15631), True, 'import numpy as np\n'), ((15634, 15660), 'numpy.array', 'np.array', (['[[0, 1], [1, 0]]'], {}), '([[0, 1], [1, 0]])\n', (15642, 15660), True, 'import numpy as np\n'), ((15670, 15695), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (15683, 15695), False, 'import pytest\n'), ((15712, 15746), 'qibo.gates.KrausChannel', 'gates.KrausChannel', (['[((0, 1), a1)]'], {}), '([((0, 1), a1)])\n', (15730, 15746), False, 'from qibo import gates, K\n'), ((15852, 15877), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (15865, 15877), False, 'import pytest\n'), ((15996, 16021), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (16009, 16021), False, 'import pytest\n'), ((16111, 16136), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (16124, 16136), False, 'import pytest\n'), ((16208, 16220), 'numpy.sqrt', 'np.sqrt', (['(0.4)'], {}), '(0.4)\n', (16215, 16220), True, 'import numpy as np\n'), ((16223, 16249), 'numpy.array', 'np.array', (['[[0, 1], [1, 0]]'], {}), '([[0, 1], [1, 0]])\n', (16231, 16249), True, 'import numpy as np\n'), ((16259, 16271), 'numpy.sqrt', 'np.sqrt', (['(0.6)'], {}), '(0.6)\n', (16266, 16271), True, 'import numpy as np\n'), ((16274, 16340), 'numpy.array', 'np.array', (['[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]'], {}), '([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])\n', (16282, 16340), True, 'import numpy as np\n'), ((16424, 16449), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (16437, 16449), False, 'import pytest\n'), ((16936, 16952), 'numpy.kron', 'np.kron', (['a1', 'eye'], {}), '(a1, eye)\n', (16943, 16952), True, 'import numpy as np\n'), ((16954, 16971), 'numpy.kron', 'np.kron', (['eye', 'eye'], {}), '(eye, eye)\n', (16961, 16971), True, 'import numpy as np\n'), ((16991, 17008), 'numpy.kron', 'np.kron', (['eye', 'eye'], {}), '(eye, eye)\n', (16998, 17008), True, 'import numpy as np\n'), ((17539, 17564), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (17552, 17564), False, 'import pytest\n'), ((17581, 17628), 'qibo.gates.UnitaryChannel', 'gates.UnitaryChannel', (['[0.1, 0.3, 0.2]', 'matrices'], {}), '([0.1, 0.3, 0.2], matrices)\n', (17601, 17628), False, 'from qibo import gates, K\n'), ((17660, 17685), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (17673, 17685), False, 'import pytest\n'), ((17702, 17744), 'qibo.gates.UnitaryChannel', 'gates.UnitaryChannel', (['[1.1, 0.2]', 'matrices'], {}), '([1.1, 0.2], matrices)\n', (17722, 17744), False, 'from qibo import gates, K\n'), ((17780, 17805), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (17793, 17805), False, 'import pytest\n'), ((17822, 17864), 'qibo.gates.UnitaryChannel', 'gates.UnitaryChannel', (['[0.0, 0.0]', 'matrices'], {}), '([0.0, 0.0], matrices)\n', (17842, 17864), False, 'from qibo import gates, K\n'), ((18919, 18945), 'numpy.array', 'np.array', (['[[0, 1], [1, 0]]'], {}), '([[0, 1], [1, 0]])\n', (18927, 18945), True, 'import numpy as np\n'), ((18947, 18956), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (18953, 18956), True, 'import numpy as np\n'), ((19749, 19782), 'numpy.diag', 'np.diag', (['[1 - p1, p0, p1, 1 - p0]'], {}), '([1 - p1, p0, p1, 1 - p0])\n', (19756, 19782), True, 'import numpy as np\n'), ((20015, 20067), 'numpy.einsum', 'np.einsum', (['"""abcd,aJKcjk->bJKdjk"""', 'matrix', 'target_rho'], {}), "('abcd,aJKcjk->bJKdjk', matrix, target_rho)\n", (20024, 20067), True, 'import numpy as np\n'), ((20323, 20354), 'numpy.zeros', 'np.zeros', (['(4 * (2,))'], {'dtype': 'dtype'}), '(4 * (2,), dtype=dtype)\n', (20331, 20354), True, 'import numpy as np\n'), ((20397, 20428), 'numpy.zeros', 'np.zeros', (['(4 * (2,))'], {'dtype': 'dtype'}), '(4 * (2,), dtype=dtype)\n', (20405, 20428), True, 'import numpy as np\n'), ((20471, 20502), 'numpy.zeros', 'np.zeros', (['(4 * (2,))'], {'dtype': 'dtype'}), '(4 * (2,), dtype=dtype)\n', (20479, 20502), True, 'import numpy as np\n'), ((20582, 20605), 'numpy.trace', 'np.trace', (['collapsed_rho'], {}), '(collapsed_rho)\n', (20590, 20605), True, 'import numpy as np\n'), ((21486, 21511), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (21499, 21511), False, 'import pytest\n'), ((21528, 21602), 'qibo.gates.ThermalRelaxationChannel', 'gates.ThermalRelaxationChannel', (['(0)', 't1', 't2', 'time'], {'excited_population': 'excpop'}), '(0, t1, t2, time, excited_population=excpop)\n', (21558, 21602), False, 'from qibo import gates, K\n'), ((21925, 21935), 'qibo.gates.H', 'gates.H', (['(0)'], {}), '(0)\n', (21932, 21935), False, 'from qibo import gates, K\n'), ((21950, 21960), 'qibo.gates.H', 'gates.H', (['(1)'], {}), '(1)\n', (21957, 21960), False, 'from qibo import gates, K\n'), ((21975, 21989), 'qibo.gates.CZ', 'gates.CZ', (['(0)', '(1)'], {}), '(0, 1)\n', (21983, 21989), False, 'from qibo import gates, K\n'), ((22005, 22032), 'numpy.array', 'np.array', (['[[1, 1], [1, -1]]'], {}), '([[1, 1], [1, -1]])\n', (22013, 22032), True, 'import numpy as np\n'), ((22035, 22045), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (22042, 22045), True, 'import numpy as np\n'), ((22115, 22140), 'numpy.kron', 'np.kron', (['hmatrix', 'hmatrix'], {}), '(hmatrix, hmatrix)\n', (22122, 22140), True, 'import numpy as np\n'), ((430, 452), 'numpy.copy', 'np.copy', (['initial_state'], {}), '(initial_state)\n', (437, 452), True, 'import numpy as np\n'), ((1071, 1096), 'qibo.K._dtypes.get', 'K._dtypes.get', (['"""DTYPECPX"""'], {}), "('DTYPECPX')\n", (1084, 1096), False, 'from qibo import gates, K\n'), ((1269, 1295), 'numpy.random.random', 'np.random.random', (['(16, 16)'], {}), '((16, 16))\n', (1285, 1295), True, 'import numpy as np\n'), ((1351, 1361), 'qibo.gates.H', 'gates.H', (['(0)'], {}), '(0)\n', (1358, 1361), False, 'from qibo import gates, K\n'), ((1363, 1373), 'qibo.gates.H', 'gates.H', (['(1)'], {}), '(1)\n', (1370, 1373), False, 'from qibo import gates, K\n'), ((1539, 1549), 'qibo.gates.X', 'gates.X', (['(0)'], {}), '(0)\n', (1546, 1549), False, 'from qibo import gates, K\n'), ((1738, 1748), 'qibo.gates.Y', 'gates.Y', (['(1)'], {}), '(1)\n', (1745, 1748), False, 'from qibo import gates, K\n'), ((1936, 1946), 'qibo.gates.H', 'gates.H', (['(0)'], {}), '(0)\n', (1943, 1946), False, 'from qibo import gates, K\n'), ((1948, 1958), 'qibo.gates.H', 'gates.H', (['(1)'], {}), '(1)\n', (1955, 1958), False, 'from qibo import gates, K\n'), ((1960, 1970), 'qibo.gates.Z', 'gates.Z', (['(0)'], {}), '(0)\n', (1967, 1970), False, 'from qibo import gates, K\n'), ((2194, 2204), 'qibo.gates.H', 'gates.H', (['(0)'], {}), '(0)\n', (2201, 2204), False, 'from qibo import gates, K\n'), ((2206, 2216), 'qibo.gates.H', 'gates.H', (['(1)'], {}), '(1)\n', (2213, 2216), False, 'from qibo import gates, K\n'), ((2218, 2228), 'qibo.gates.S', 'gates.S', (['(1)'], {}), '(1)\n', (2225, 2228), False, 'from qibo import gates, K\n'), ((2399, 2409), 'qibo.gates.H', 'gates.H', (['(0)'], {}), '(0)\n', (2406, 2409), False, 'from qibo import gates, K\n'), ((2411, 2421), 'qibo.gates.H', 'gates.H', (['(1)'], {}), '(1)\n', (2418, 2421), False, 'from qibo import gates, K\n'), ((2423, 2435), 'qibo.gates.SDG', 'gates.SDG', (['(1)'], {}), '(1)\n', (2432, 2435), False, 'from qibo import gates, K\n'), ((2606, 2616), 'qibo.gates.H', 'gates.H', (['(0)'], {}), '(0)\n', (2613, 2616), False, 'from qibo import gates, K\n'), ((2618, 2628), 'qibo.gates.H', 'gates.H', (['(1)'], {}), '(1)\n', (2625, 2628), False, 'from qibo import gates, K\n'), ((2630, 2640), 'qibo.gates.T', 'gates.T', (['(1)'], {}), '(1)\n', (2637, 2640), False, 'from qibo import gates, K\n'), ((2874, 2884), 'qibo.gates.H', 'gates.H', (['(0)'], {}), '(0)\n', (2881, 2884), False, 'from qibo import gates, K\n'), ((2886, 2896), 'qibo.gates.H', 'gates.H', (['(1)'], {}), '(1)\n', (2893, 2896), False, 'from qibo import gates, K\n'), ((2898, 2910), 'qibo.gates.TDG', 'gates.TDG', (['(1)'], {}), '(1)\n', (2907, 2910), False, 'from qibo import gates, K\n'), ((3987, 3997), 'qibo.gates.H', 'gates.H', (['(0)'], {}), '(0)\n', (3994, 3997), False, 'from qibo import gates, K\n'), ((3999, 4023), 'qibo.gates.RX', 'gates.RX', (['(0)'], {'theta': 'theta'}), '(0, theta=theta)\n', (4007, 4023), False, 'from qibo import gates, K\n'), ((4208, 4218), 'numpy.ones', 'np.ones', (['(2)'], {}), '(2)\n', (4215, 4218), True, 'import numpy as np\n'), ((4356, 4366), 'qibo.gates.H', 'gates.H', (['(0)'], {}), '(0)\n', (4363, 4366), False, 'from qibo import gates, K\n'), ((4368, 4392), 'qibo.gates.RY', 'gates.RY', (['(0)'], {'theta': 'theta'}), '(0, theta=theta)\n', (4376, 4392), False, 'from qibo import gates, K\n'), ((4567, 4577), 'numpy.ones', 'np.ones', (['(2)'], {}), '(2)\n', (4574, 4577), True, 'import numpy as np\n'), ((4777, 4787), 'qibo.gates.X', 'gates.X', (['(0)'], {}), '(0)\n', (4784, 4787), False, 'from qibo import gates, K\n'), ((5162, 5172), 'qibo.gates.X', 'gates.X', (['(0)'], {}), '(0)\n', (5169, 5172), False, 'from qibo import gates, K\n'), ((5174, 5192), 'qibo.gates.U1', 'gates.U1', (['(0)', 'theta'], {}), '(0, theta)\n', (5182, 5192), False, 'from qibo import gates, K\n'), ((5467, 5488), 'qibo.gates.U2', 'gates.U2', (['(0)', 'phi', 'lam'], {}), '(0, phi, lam)\n', (5475, 5488), False, 'from qibo import gates, K\n'), ((5945, 5973), 'qibo.gates.U3', 'gates.U3', (['(0)', 'theta', 'phi', 'lam'], {}), '(0, theta, phi, lam)\n', (5953, 5973), False, 'from qibo import gates, K\n'), ((6489, 6499), 'qibo.gates.X', 'gates.X', (['(0)'], {}), '(0)\n', (6496, 6499), False, 'from qibo import gates, K\n'), ((7972, 7982), 'qibo.gates.X', 'gates.X', (['(1)'], {}), '(1)\n', (7979, 7982), False, 'from qibo import gates, K\n'), ((7984, 8000), 'qibo.gates.SWAP', 'gates.SWAP', (['(0)', '(1)'], {}), '(0, 1)\n', (7994, 8000), False, 'from qibo import gates, K\n'), ((8653, 8676), 'qibo.K.to_numpy', 'K.to_numpy', (['final_state'], {}), '(final_state)\n', (8663, 8676), False, 'from qibo import gates, K\n'), ((9136, 9160), 'numpy.random.random', 'np.random.random', (['(2, 2)'], {}), '((2, 2))\n', (9152, 9160), True, 'import numpy as np\n'), ((9360, 9383), 'qibo.K.to_numpy', 'K.to_numpy', (['final_state'], {}), '(final_state)\n', (9370, 9383), False, 'from qibo import gates, K\n'), ((10182, 10192), 'qibo.gates.X', 'gates.X', (['(0)'], {}), '(0)\n', (10189, 10192), False, 'from qibo import gates, K\n'), ((10194, 10204), 'qibo.gates.X', 'gates.X', (['(1)'], {}), '(1)\n', (10201, 10204), False, 'from qibo import gates, K\n'), ((10206, 10228), 'qibo.gates.TOFFOLI', 'gates.TOFFOLI', (['(0)', '(1)', '(2)'], {}), '(0, 1, 2)\n', (10219, 10228), False, 'from qibo import gates, K\n'), ((10260, 10270), 'qibo.gates.X', 'gates.X', (['(1)'], {}), '(1)\n', (10267, 10270), False, 'from qibo import gates, K\n'), ((10272, 10294), 'qibo.gates.TOFFOLI', 'gates.TOFFOLI', (['(0)', '(1)', '(2)'], {}), '(0, 1, 2)\n', (10285, 10294), False, 'from qibo import gates, K\n'), ((11466, 11476), 'qibo.gates.X', 'gates.X', (['(0)'], {}), '(0)\n', (11473, 11476), False, 'from qibo import gates, K\n'), ((11478, 11488), 'qibo.gates.H', 'gates.H', (['(1)'], {}), '(1)\n', (11485, 11488), False, 'from qibo import gates, K\n'), ((11532, 11558), 'numpy.array', 'np.array', (['[[0, 1], [1, 0]]'], {}), '([[0, 1], [1, 0]])\n', (11540, 11558), True, 'import numpy as np\n'), ((12660, 12670), 'qibo.gates.X', 'gates.X', (['i'], {}), '(i)\n', (12667, 12670), False, 'from qibo import gates, K\n'), ((12976, 12989), 'numpy.kron', 'np.kron', (['h', 'h'], {}), '(h, h)\n', (12983, 12989), True, 'import numpy as np\n'), ((12991, 13004), 'numpy.kron', 'np.kron', (['h', 'h'], {}), '(h, h)\n', (12998, 13004), True, 'import numpy as np\n'), ((13094, 13128), 'pytest.raises', 'pytest.raises', (['NotImplementedError'], {}), '(NotImplementedError)\n', (13107, 13128), False, 'import pytest\n'), ((13588, 13606), 'qibo.gates.CZ', 'gates.CZ', (['i', '(i + 1)'], {}), '(i, i + 1)\n', (13596, 13606), False, 'from qibo import gates, K\n'), ((14419, 14446), 'qibo.gates.Flatten', 'gates.Flatten', (['target_state'], {}), '(target_state)\n', (14432, 14446), False, 'from qibo import gates, K\n'), ((15914, 15933), 'numpy.random.random', 'np.random.random', (['(4)'], {}), '(4)\n', (15930, 15933), True, 'import numpy as np\n'), ((16872, 16894), 'numpy.copy', 'np.copy', (['initial_state'], {}), '(initial_state)\n', (16879, 16894), True, 'import numpy as np\n'), ((18054, 18074), 'numpy.copy', 'np.copy', (['initial_rho'], {}), '(initial_rho)\n', (18061, 18074), True, 'import numpy as np\n'), ((18196, 18215), 'qibo.K.copy', 'K.copy', (['initial_rho'], {}), '(initial_rho)\n', (18202, 18215), False, 'from qibo import gates, K\n'), ((18484, 18504), 'numpy.copy', 'np.copy', (['initial_rho'], {}), '(initial_rho)\n', (18491, 18504), True, 'import numpy as np\n'), ((18558, 18578), 'numpy.copy', 'np.copy', (['initial_rho'], {}), '(initial_rho)\n', (18565, 18578), True, 'import numpy as np\n'), ((19599, 19619), 'numpy.copy', 'np.copy', (['initial_rho'], {}), '(initial_rho)\n', (19606, 19619), True, 'import numpy as np\n'), ((20627, 20653), 'numpy.array', 'np.array', (['[[0, 1], [1, 0]]'], {}), '([[0, 1], [1, 0]])\n', (20635, 20653), True, 'import numpy as np\n'), ((20655, 20664), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (20661, 20664), True, 'import numpy as np\n'), ((20687, 20714), 'numpy.array', 'np.array', (['[[1, 0], [0, -1]]'], {}), '([[1, 0], [0, -1]])\n', (20695, 20714), True, 'import numpy as np\n'), ((20716, 20725), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (20722, 20725), True, 'import numpy as np\n'), ((21058, 21083), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (21071, 21083), False, 'import pytest\n'), ((21749, 21783), 'pytest.raises', 'pytest.raises', (['NotImplementedError'], {}), '(NotImplementedError)\n', (21762, 21783), False, 'import pytest\n'), ((21804, 21828), 'qibo.gates.FusedGate', 'gates.FusedGate', (['(0)', '(1)', '(2)'], {}), '(0, 1, 2)\n', (21819, 21828), False, 'from qibo import gates, K\n'), ((2699, 2709), 'numpy.sqrt', 'np.sqrt', (['(8)'], {}), '(8)\n', (2706, 2709), True, 'import numpy as np\n'), ((2756, 2766), 'numpy.sqrt', 'np.sqrt', (['(8)'], {}), '(8)\n', (2763, 2766), True, 'import numpy as np\n'), ((2969, 2979), 'numpy.sqrt', 'np.sqrt', (['(8)'], {}), '(8)\n', (2976, 2979), True, 'import numpy as np\n'), ((3026, 3036), 'numpy.sqrt', 'np.sqrt', (['(8)'], {}), '(8)\n', (3033, 3036), True, 'import numpy as np\n'), ((5544, 5575), 'numpy.exp', 'np.exp', (['(-1.0j * (phi + lam) / 2)'], {}), '(-1.0j * (phi + lam) / 2)\n', (5550, 5575), True, 'import numpy as np\n'), ((5632, 5662), 'numpy.exp', 'np.exp', (['(1.0j * (phi - lam) / 2)'], {}), '(1.0j * (phi - lam) / 2)\n', (5638, 5662), True, 'import numpy as np\n'), ((5662, 5692), 'numpy.exp', 'np.exp', (['(1.0j * (phi + lam) / 2)'], {}), '(1.0j * (phi + lam) / 2)\n', (5668, 5692), True, 'import numpy as np\n'), ((7016, 7026), 'qibo.gates.Z', 'gates.Z', (['(1)'], {}), '(1)\n', (7023, 7026), False, 'from qibo import gates, K\n'), ((8710, 8723), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (8716, 8723), True, 'import numpy as np\n'), ((8794, 8807), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (8800, 8807), True, 'import numpy as np\n'), ((10756, 10765), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (10762, 10765), True, 'import numpy as np\n'), ((11594, 11621), 'numpy.array', 'np.array', (['[[1, 1], [1, -1]]'], {}), '([[1, 1], [1, -1]])\n', (11602, 11621), True, 'import numpy as np\n'), ((11624, 11634), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (11631, 11634), True, 'import numpy as np\n'), ((11958, 11976), 'numpy.cos', 'np.cos', (['(thetax / 2)'], {}), '(thetax / 2)\n', (11964, 11976), True, 'import numpy as np\n'), ((12051, 12069), 'numpy.cos', 'np.cos', (['(thetax / 2)'], {}), '(thetax / 2)\n', (12057, 12069), True, 'import numpy as np\n'), ((12093, 12111), 'numpy.cos', 'np.cos', (['(thetay / 2)'], {}), '(thetay / 2)\n', (12099, 12111), True, 'import numpy as np\n'), ((12155, 12173), 'numpy.sin', 'np.sin', (['(thetay / 2)'], {}), '(thetay / 2)\n', (12161, 12173), True, 'import numpy as np\n'), ((12175, 12193), 'numpy.cos', 'np.cos', (['(thetay / 2)'], {}), '(thetay / 2)\n', (12181, 12193), True, 'import numpy as np\n'), ((15830, 15839), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (15836, 15839), True, 'import numpy as np\n'), ((16146, 16180), 'qibo.gates.PauliNoiseChannel', 'gates.PauliNoiseChannel', (['(0)'], {'px': '(0.5)'}), '(0, px=0.5)\n', (16169, 16180), False, 'from qibo import gates, K\n'), ((16459, 16485), 'qibo.gates.KrausChannel', 'gates.KrausChannel', (['config'], {}), '(config)\n', (16477, 16485), False, 'from qibo import gates, K\n'), ((19955, 19975), 'numpy.copy', 'np.copy', (['initial_rho'], {}), '(initial_rho)\n', (19962, 19975), True, 'import numpy as np\n'), ((20242, 20262), 'numpy.copy', 'np.copy', (['initial_rho'], {}), '(initial_rho)\n', (20249, 20262), True, 'import numpy as np\n'), ((5576, 5607), 'numpy.exp', 'np.exp', (['(-1.0j * (phi - lam) / 2)'], {}), '(-1.0j * (phi - lam) / 2)\n', (5582, 5607), True, 'import numpy as np\n'), ((8731, 8744), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (8737, 8744), True, 'import numpy as np\n'), ((8779, 8792), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (8785, 8792), True, 'import numpy as np\n'), ((11984, 12002), 'numpy.sin', 'np.sin', (['(thetax / 2)'], {}), '(thetax / 2)\n', (11990, 12002), True, 'import numpy as np\n'), ((12031, 12049), 'numpy.sin', 'np.sin', (['(thetax / 2)'], {}), '(thetax / 2)\n', (12037, 12049), True, 'import numpy as np\n'), ((12114, 12132), 'numpy.sin', 'np.sin', (['(thetay / 2)'], {}), '(thetay / 2)\n', (12120, 12132), True, 'import numpy as np\n')]
""" Experiment for NN4(RI) Aim: To find the best max_epochs for NN4(*, 1024, 1024, 1024) + RI(k = 3, m = 200) max_epochs: [22, 24, ... ,98, 140] Averaging 20 models Summary epochs 88 , loss 0.421860471364 Time:3:40:30 on i7-4790k 32G MEM GTX660 I got a different result, epochs 112 loss 0.422868, before I reinstalled ubuntu 14.04 LTS. So I chose max_epochs = 112. """ import numpy as np import scipy as sp import pandas as pd from pylearn2.models import mlp from pylearn2.models.mlp import RectifiedLinear, Softmax, MLP from pylearn2.costs.mlp.dropout import Dropout from pylearn2.training_algorithms import sgd, learning_rule from pylearn2.termination_criteria import EpochCounter from pylearn2.datasets import DenseDesignMatrix from pylearn2.train import Train from theano.compat.python2x import OrderedDict import theano.tensor as T from theano import function import pickle import sklearn.preprocessing as pp from sklearn import cross_validation from sklearn.cross_validation import StratifiedKFold from sklearn.preprocessing import scale from sklearn.metrics import log_loss from sklearn.grid_search import ParameterGrid from datetime import datetime import os from utility import * from predict import predict import pylab path = os.getcwd() + '/' path_log = path + 'logs/' file_train = path + 'train.csv' training = pd.read_csv(file_train, index_col = 0) num_train = training.shape[0] y = training['target'].values yMat = pd.get_dummies(training['target']).values X = training.iloc[:,:93].values scaler = pp.StandardScaler() X2 = scaler.fit_transform(X ** .6) kf = cross_validation.StratifiedKFold(y, n_folds=5, shuffle = True, random_state = 345) for train_idx, valid_idx in kf: break y_train = yMat[train_idx] y_valid = yMat[valid_idx] training = DenseDesignMatrix(X = X2[train_idx], y = y_train) valid = DenseDesignMatrix(X = X2[valid_idx], y = y_valid) # [l1, l2, l3, l4, output] nIter = 20 # Params for RI m = 200 k = 3 # Params for NN epochs = 20 epochs_add = 2 n_add = 60 bs = 64 mm = .97 lr = .01 dim2 = 1024 ir1 = .01 ir2 = .05 ip = .8 ir_out = .05 mcn_out = 2.5 scores = [] t0 = datetime.now() predAll = [np.zeros(y_valid.shape) for s in range(n_add)] for i in range(nIter): seed = i + 3819 R = RImatrix(X.shape[1], m, k, rm_dup_cols = True, seed = seed) R = np.abs(R.todense().astype(np.float32)) dim1 = R.shape[1] l1 = RectifiedLinear(layer_name='l1', irange = ir1, dim = dim1, mask_weights = R) l2 = RectifiedLinear(layer_name='l2', irange = ir2, dim = dim2, max_col_norm = 1.) l3 = RectifiedLinear(layer_name='l3', irange = ir2, dim = dim2, max_col_norm = 1.) l4 = RectifiedLinear(layer_name='l4', irange = ir2, dim = dim2, max_col_norm = 1.) output = Softmax(layer_name='y', n_classes = 9, irange = ir_out, max_col_norm = mcn_out) mdl = MLP([l1, l2, l3, l4, output], nvis = X2.shape[1]) trainer = sgd.SGD(learning_rate=lr, batch_size=bs, learning_rule=learning_rule.Momentum(mm), cost=Dropout(input_include_probs = {'l1':1.}, input_scales = {'l1':1.}, default_input_include_prob=ip, default_input_scale=1/ip), termination_criterion=EpochCounter(epochs),seed = seed) decay = sgd.LinearDecayOverEpoch(start=2, saturate=20, decay_factor= .1) experiment = Train(dataset = training, model=mdl, algorithm=trainer, extensions=[decay]) experiment.main_loop() epochs_current = epochs for s in range(n_add): del mdl.monitor trainer = sgd.SGD(learning_rate=lr * .1, batch_size=bs, learning_rule=learning_rule.Momentum(mm), cost=Dropout(input_include_probs = {'l1':1.}, input_scales = {'l1':1.}, default_input_include_prob=ip, default_input_scale=1/ip), termination_criterion=EpochCounter(epochs_add),seed = seed) experiment = Train(dataset = training, model=mdl, algorithm=trainer) experiment.main_loop() epochs_current += epochs_add pred_train = predict(mdl, X2[train_idx].astype(np.float32)) pred_valid = predict(mdl, X2[valid_idx].astype(np.float32)) predAll[s] += pred_valid scores.append({'epochs':epochs_current, 'nModels':i + 1, 'seed':seed, 'train':log_loss(y_train, pred_train), 'valid':log_loss(y_valid, pred_valid), 'valid_avg':log_loss(y_valid, predAll[s] / (i + 1))}) print(scores[-1], datetime.now() - t0) df = pd.DataFrame(scores) if os.path.exists(path_log) is False: print('mkdir', path_log) os.mkdir(path_log) df.to_csv(path_log + 'exp_NN4_RI_max_epochs.csv') keys = ['epochs'] grouped = df.groupby(keys) print('epochs',grouped['valid_avg'].last().idxmin(),', loss',grouped['valid_avg'].last().min()) # epochs 88 , loss 0.421860471364 g = grouped[['train', 'valid']].mean() g['valid_avg'] = grouped['valid_avg'].last() print(g.iloc[[0,1,32,33,34,58,59],:]) # train valid valid_avg # epochs # 22 0.319737 0.468458 0.436766 # 24 0.313538 0.468300 0.435694 # 86 0.193640 0.486078 0.422321 # 88 0.190694 0.487625 0.421860 # 90 0.187374 0.487897 0.421998 # 138 0.134388 0.512527 0.423662 # 140 0.132642 0.514666 0.425003 ax = g.plot() ax.set_title('NN4(RI) m=200, k=3') ax.set_ylabel('Logloss') fig = ax.get_figure() fig.savefig(path_log + 'exp_NN4_RI_max_epochs.png')
[ "pandas.read_csv", "pylearn2.models.mlp.MLP", "pylearn2.train.Train", "sklearn.metrics.log_loss", "pylearn2.models.mlp.RectifiedLinear", "pylearn2.models.mlp.Softmax", "pylearn2.training_algorithms.learning_rule.Momentum", "pylearn2.datasets.DenseDesignMatrix", "os.path.exists", "os.mkdir", "pan...
[((1384, 1420), 'pandas.read_csv', 'pd.read_csv', (['file_train'], {'index_col': '(0)'}), '(file_train, index_col=0)\n', (1395, 1420), True, 'import pandas as pd\n'), ((1578, 1597), 'sklearn.preprocessing.StandardScaler', 'pp.StandardScaler', ([], {}), '()\n', (1595, 1597), True, 'import sklearn.preprocessing as pp\n'), ((1644, 1722), 'sklearn.cross_validation.StratifiedKFold', 'cross_validation.StratifiedKFold', (['y'], {'n_folds': '(5)', 'shuffle': '(True)', 'random_state': '(345)'}), '(y, n_folds=5, shuffle=True, random_state=345)\n', (1676, 1722), False, 'from sklearn import cross_validation\n'), ((1839, 1884), 'pylearn2.datasets.DenseDesignMatrix', 'DenseDesignMatrix', ([], {'X': 'X2[train_idx]', 'y': 'y_train'}), '(X=X2[train_idx], y=y_train)\n', (1856, 1884), False, 'from pylearn2.datasets import DenseDesignMatrix\n'), ((1898, 1943), 'pylearn2.datasets.DenseDesignMatrix', 'DenseDesignMatrix', ([], {'X': 'X2[valid_idx]', 'y': 'y_valid'}), '(X=X2[valid_idx], y=y_valid)\n', (1915, 1943), False, 'from pylearn2.datasets import DenseDesignMatrix\n'), ((2210, 2224), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (2222, 2224), False, 'from datetime import datetime\n'), ((4947, 4967), 'pandas.DataFrame', 'pd.DataFrame', (['scores'], {}), '(scores)\n', (4959, 4967), True, 'import pandas as pd\n'), ((1292, 1303), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1301, 1303), False, 'import os\n'), ((1493, 1527), 'pandas.get_dummies', 'pd.get_dummies', (["training['target']"], {}), "(training['target'])\n", (1507, 1527), True, 'import pandas as pd\n'), ((2237, 2260), 'numpy.zeros', 'np.zeros', (['y_valid.shape'], {}), '(y_valid.shape)\n', (2245, 2260), True, 'import numpy as np\n'), ((2479, 2549), 'pylearn2.models.mlp.RectifiedLinear', 'RectifiedLinear', ([], {'layer_name': '"""l1"""', 'irange': 'ir1', 'dim': 'dim1', 'mask_weights': 'R'}), "(layer_name='l1', irange=ir1, dim=dim1, mask_weights=R)\n", (2494, 2549), False, 'from pylearn2.models.mlp import RectifiedLinear, Softmax, MLP\n'), ((2566, 2638), 'pylearn2.models.mlp.RectifiedLinear', 'RectifiedLinear', ([], {'layer_name': '"""l2"""', 'irange': 'ir2', 'dim': 'dim2', 'max_col_norm': '(1.0)'}), "(layer_name='l2', irange=ir2, dim=dim2, max_col_norm=1.0)\n", (2581, 2638), False, 'from pylearn2.models.mlp import RectifiedLinear, Softmax, MLP\n'), ((2654, 2726), 'pylearn2.models.mlp.RectifiedLinear', 'RectifiedLinear', ([], {'layer_name': '"""l3"""', 'irange': 'ir2', 'dim': 'dim2', 'max_col_norm': '(1.0)'}), "(layer_name='l3', irange=ir2, dim=dim2, max_col_norm=1.0)\n", (2669, 2726), False, 'from pylearn2.models.mlp import RectifiedLinear, Softmax, MLP\n'), ((2742, 2814), 'pylearn2.models.mlp.RectifiedLinear', 'RectifiedLinear', ([], {'layer_name': '"""l4"""', 'irange': 'ir2', 'dim': 'dim2', 'max_col_norm': '(1.0)'}), "(layer_name='l4', irange=ir2, dim=dim2, max_col_norm=1.0)\n", (2757, 2814), False, 'from pylearn2.models.mlp import RectifiedLinear, Softmax, MLP\n'), ((2834, 2907), 'pylearn2.models.mlp.Softmax', 'Softmax', ([], {'layer_name': '"""y"""', 'n_classes': '(9)', 'irange': 'ir_out', 'max_col_norm': 'mcn_out'}), "(layer_name='y', n_classes=9, irange=ir_out, max_col_norm=mcn_out)\n", (2841, 2907), False, 'from pylearn2.models.mlp import RectifiedLinear, Softmax, MLP\n'), ((2947, 2994), 'pylearn2.models.mlp.MLP', 'MLP', (['[l1, l2, l3, l4, output]'], {'nvis': 'X2.shape[1]'}), '([l1, l2, l3, l4, output], nvis=X2.shape[1])\n', (2950, 2994), False, 'from pylearn2.models.mlp import RectifiedLinear, Softmax, MLP\n'), ((3494, 3558), 'pylearn2.training_algorithms.sgd.LinearDecayOverEpoch', 'sgd.LinearDecayOverEpoch', ([], {'start': '(2)', 'saturate': '(20)', 'decay_factor': '(0.1)'}), '(start=2, saturate=20, decay_factor=0.1)\n', (3518, 3558), False, 'from pylearn2.training_algorithms import sgd, learning_rule\n'), ((3577, 3650), 'pylearn2.train.Train', 'Train', ([], {'dataset': 'training', 'model': 'mdl', 'algorithm': 'trainer', 'extensions': '[decay]'}), '(dataset=training, model=mdl, algorithm=trainer, extensions=[decay])\n', (3582, 3650), False, 'from pylearn2.train import Train\n'), ((4974, 4998), 'os.path.exists', 'os.path.exists', (['path_log'], {}), '(path_log)\n', (4988, 4998), False, 'import os\n'), ((5044, 5062), 'os.mkdir', 'os.mkdir', (['path_log'], {}), '(path_log)\n', (5052, 5062), False, 'import os\n'), ((4310, 4363), 'pylearn2.train.Train', 'Train', ([], {'dataset': 'training', 'model': 'mdl', 'algorithm': 'trainer'}), '(dataset=training, model=mdl, algorithm=trainer)\n', (4315, 4363), False, 'from pylearn2.train import Train\n'), ((3113, 3139), 'pylearn2.training_algorithms.learning_rule.Momentum', 'learning_rule.Momentum', (['mm'], {}), '(mm)\n', (3135, 3139), False, 'from pylearn2.training_algorithms import sgd, learning_rule\n'), ((3169, 3298), 'pylearn2.costs.mlp.dropout.Dropout', 'Dropout', ([], {'input_include_probs': "{'l1': 1.0}", 'input_scales': "{'l1': 1.0}", 'default_input_include_prob': 'ip', 'default_input_scale': '(1 / ip)'}), "(input_include_probs={'l1': 1.0}, input_scales={'l1': 1.0},\n default_input_include_prob=ip, default_input_scale=1 / ip)\n", (3176, 3298), False, 'from pylearn2.costs.mlp.dropout import Dropout\n'), ((3447, 3467), 'pylearn2.termination_criteria.EpochCounter', 'EpochCounter', (['epochs'], {}), '(epochs)\n', (3459, 3467), False, 'from pylearn2.termination_criteria import EpochCounter\n'), ((3896, 3922), 'pylearn2.training_algorithms.learning_rule.Momentum', 'learning_rule.Momentum', (['mm'], {}), '(mm)\n', (3918, 3922), False, 'from pylearn2.training_algorithms import sgd, learning_rule\n'), ((3956, 4085), 'pylearn2.costs.mlp.dropout.Dropout', 'Dropout', ([], {'input_include_probs': "{'l1': 1.0}", 'input_scales': "{'l1': 1.0}", 'default_input_include_prob': 'ip', 'default_input_scale': '(1 / ip)'}), "(input_include_probs={'l1': 1.0}, input_scales={'l1': 1.0},\n default_input_include_prob=ip, default_input_scale=1 / ip)\n", (3963, 4085), False, 'from pylearn2.costs.mlp.dropout import Dropout\n'), ((4250, 4274), 'pylearn2.termination_criteria.EpochCounter', 'EpochCounter', (['epochs_add'], {}), '(epochs_add)\n', (4262, 4274), False, 'from pylearn2.termination_criteria import EpochCounter\n'), ((4719, 4748), 'sklearn.metrics.log_loss', 'log_loss', (['y_train', 'pred_train'], {}), '(y_train, pred_train)\n', (4727, 4748), False, 'from sklearn.metrics import log_loss\n'), ((4782, 4811), 'sklearn.metrics.log_loss', 'log_loss', (['y_valid', 'pred_valid'], {}), '(y_valid, pred_valid)\n', (4790, 4811), False, 'from sklearn.metrics import log_loss\n'), ((4849, 4888), 'sklearn.metrics.log_loss', 'log_loss', (['y_valid', '(predAll[s] / (i + 1))'], {}), '(y_valid, predAll[s] / (i + 1))\n', (4857, 4888), False, 'from sklearn.metrics import log_loss\n'), ((4918, 4932), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (4930, 4932), False, 'from datetime import datetime\n')]
import numpy as np import pytest from chainer_chemistry.dataset.preprocessors import wle_util def test_to_index(): values = ['foo', 'bar', 'buz', 'non-exist'] mols = [['foo', 'bar', 'buz'], ['foo', 'foo'], ['buz', 'bar']] actual = wle_util.to_index(mols, values) expect = np.array([np.array([0, 1, 2], np.int32), np.array([0, 0], np.int32), np.array([2, 1], np.int32)]) assert len(actual) == len(expect) for a, e in zip(actual, expect): np.testing.assert_array_equal(a, e) def test_to_index_non_existence(): values = ['foo', 'bar'] mols = [['strange_label']] with pytest.raises(ValueError): wle_util.to_index(mols, values) def test_compress_relation_axis_2_dim(): arr = np.random.uniform(size=(10, 2)) actual = wle_util.compress_relation_axis(arr) np.testing.assert_array_equal(actual, arr) def test_compress_relation_axis_3_dim(): arr = np.array( [ [ [1, 0], [2, 0], ], [ [1, 1], [0, 0] ] ] ) arr = np.swapaxes(arr, 0, 1) ret = wle_util.compress_relation_axis(arr) actual = ret != 0 expect = np.array( [[True, True], [True, False]] ) np.testing.assert_array_equal(actual, expect) def test_compress_relation_axis_invalid_ndim(): arr = np.zeros(3) with pytest.raises(ValueError): wle_util.compress_relation_axis(arr) arr = np.zeros((1, 2, 3, 4)) with pytest.raises(ValueError): wle_util.compress_relation_axis(arr) @pytest.fixture def small_molecule(): # a-b-c d atom_array = ['a', 'b', 'c', 'd'] neighbors = np.array( [ [0, 1, 1, 2], # first end of edges [1, 0, 2, 1] # second end of edges ] ) return atom_array, neighbors def test_get_neighbor_representation_with_focus_atom(small_molecule): atom_array, neighbors = small_molecule expects = ['a-b', 'b-a.c', 'c-b', 'd-'] for i in range(len(expects)): actual = wle_util.get_neighbor_representation( i, atom_array, neighbors, True) assert actual == expects[i] def test_get_neighbor_representation_without_focus_atom(small_molecule): atom_array, neighbors = small_molecule expects = ['b', 'a.c', 'b', ''] for i in range(len(expects)): actual = wle_util.get_neighbor_representation( i, atom_array, neighbors, False) assert actual == expects[i] @pytest.mark.parametrize('label, expect', [ ('a-b', 'a'), ('a-b.c', 'a'), ('aa-b', 'aa'), ('a-', 'a'), ('aa-', 'aa'), ]) def test_get_focus_node_label(label, expect): actual = wle_util.get_focus_node_label(label) assert actual == expect @pytest.mark.parametrize('label', ['aa', 'a-a-a', 'a--']) def test_get_focus_node_label_invalid(label): with pytest.raises(ValueError): wle_util.get_focus_node_label(label)
[ "chainer_chemistry.dataset.preprocessors.wle_util.to_index", "chainer_chemistry.dataset.preprocessors.wle_util.get_neighbor_representation", "numpy.swapaxes", "pytest.mark.parametrize", "numpy.array", "numpy.zeros", "pytest.raises", "chainer_chemistry.dataset.preprocessors.wle_util.get_focus_node_labe...
[((2575, 2696), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""label, expect"""', "[('a-b', 'a'), ('a-b.c', 'a'), ('aa-b', 'aa'), ('a-', 'a'), ('aa-', 'aa')]"], {}), "('label, expect', [('a-b', 'a'), ('a-b.c', 'a'), (\n 'aa-b', 'aa'), ('a-', 'a'), ('aa-', 'aa')])\n", (2598, 2696), False, 'import pytest\n'), ((2842, 2898), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""label"""', "['aa', 'a-a-a', 'a--']"], {}), "('label', ['aa', 'a-a-a', 'a--'])\n", (2865, 2898), False, 'import pytest\n'), ((247, 278), 'chainer_chemistry.dataset.preprocessors.wle_util.to_index', 'wle_util.to_index', (['mols', 'values'], {}), '(mols, values)\n', (264, 278), False, 'from chainer_chemistry.dataset.preprocessors import wle_util\n'), ((781, 812), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(10, 2)'}), '(size=(10, 2))\n', (798, 812), True, 'import numpy as np\n'), ((826, 862), 'chainer_chemistry.dataset.preprocessors.wle_util.compress_relation_axis', 'wle_util.compress_relation_axis', (['arr'], {}), '(arr)\n', (857, 862), False, 'from chainer_chemistry.dataset.preprocessors import wle_util\n'), ((867, 909), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['actual', 'arr'], {}), '(actual, arr)\n', (896, 909), True, 'import numpy as np\n'), ((963, 1009), 'numpy.array', 'np.array', (['[[[1, 0], [2, 0]], [[1, 1], [0, 0]]]'], {}), '([[[1, 0], [2, 0]], [[1, 1], [0, 0]]])\n', (971, 1009), True, 'import numpy as np\n'), ((1161, 1183), 'numpy.swapaxes', 'np.swapaxes', (['arr', '(0)', '(1)'], {}), '(arr, 0, 1)\n', (1172, 1183), True, 'import numpy as np\n'), ((1194, 1230), 'chainer_chemistry.dataset.preprocessors.wle_util.compress_relation_axis', 'wle_util.compress_relation_axis', (['arr'], {}), '(arr)\n', (1225, 1230), False, 'from chainer_chemistry.dataset.preprocessors import wle_util\n'), ((1266, 1305), 'numpy.array', 'np.array', (['[[True, True], [True, False]]'], {}), '([[True, True], [True, False]])\n', (1274, 1305), True, 'import numpy as np\n'), ((1332, 1377), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['actual', 'expect'], {}), '(actual, expect)\n', (1361, 1377), True, 'import numpy as np\n'), ((1438, 1449), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (1446, 1449), True, 'import numpy as np\n'), ((1542, 1564), 'numpy.zeros', 'np.zeros', (['(1, 2, 3, 4)'], {}), '((1, 2, 3, 4))\n', (1550, 1564), True, 'import numpy as np\n'), ((1754, 1792), 'numpy.array', 'np.array', (['[[0, 1, 1, 2], [1, 0, 2, 1]]'], {}), '([[0, 1, 1, 2], [1, 0, 2, 1]])\n', (1762, 1792), True, 'import numpy as np\n'), ((2774, 2810), 'chainer_chemistry.dataset.preprocessors.wle_util.get_focus_node_label', 'wle_util.get_focus_node_label', (['label'], {}), '(label)\n', (2803, 2810), False, 'from chainer_chemistry.dataset.preprocessors import wle_util\n'), ((519, 554), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['a', 'e'], {}), '(a, e)\n', (548, 554), True, 'import numpy as np\n'), ((661, 686), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (674, 686), False, 'import pytest\n'), ((696, 727), 'chainer_chemistry.dataset.preprocessors.wle_util.to_index', 'wle_util.to_index', (['mols', 'values'], {}), '(mols, values)\n', (713, 727), False, 'from chainer_chemistry.dataset.preprocessors import wle_util\n'), ((1459, 1484), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1472, 1484), False, 'import pytest\n'), ((1494, 1530), 'chainer_chemistry.dataset.preprocessors.wle_util.compress_relation_axis', 'wle_util.compress_relation_axis', (['arr'], {}), '(arr)\n', (1525, 1530), False, 'from chainer_chemistry.dataset.preprocessors import wle_util\n'), ((1574, 1599), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1587, 1599), False, 'import pytest\n'), ((1609, 1645), 'chainer_chemistry.dataset.preprocessors.wle_util.compress_relation_axis', 'wle_util.compress_relation_axis', (['arr'], {}), '(arr)\n', (1640, 1645), False, 'from chainer_chemistry.dataset.preprocessors import wle_util\n'), ((2130, 2198), 'chainer_chemistry.dataset.preprocessors.wle_util.get_neighbor_representation', 'wle_util.get_neighbor_representation', (['i', 'atom_array', 'neighbors', '(True)'], {}), '(i, atom_array, neighbors, True)\n', (2166, 2198), False, 'from chainer_chemistry.dataset.preprocessors import wle_util\n'), ((2453, 2522), 'chainer_chemistry.dataset.preprocessors.wle_util.get_neighbor_representation', 'wle_util.get_neighbor_representation', (['i', 'atom_array', 'neighbors', '(False)'], {}), '(i, atom_array, neighbors, False)\n', (2489, 2522), False, 'from chainer_chemistry.dataset.preprocessors import wle_util\n'), ((2954, 2979), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2967, 2979), False, 'import pytest\n'), ((2989, 3025), 'chainer_chemistry.dataset.preprocessors.wle_util.get_focus_node_label', 'wle_util.get_focus_node_label', (['label'], {}), '(label)\n', (3018, 3025), False, 'from chainer_chemistry.dataset.preprocessors import wle_util\n'), ((302, 331), 'numpy.array', 'np.array', (['[0, 1, 2]', 'np.int32'], {}), '([0, 1, 2], np.int32)\n', (310, 331), True, 'import numpy as np\n'), ((356, 382), 'numpy.array', 'np.array', (['[0, 0]', 'np.int32'], {}), '([0, 0], np.int32)\n', (364, 382), True, 'import numpy as np\n'), ((407, 433), 'numpy.array', 'np.array', (['[2, 1]', 'np.int32'], {}), '([2, 1], np.int32)\n', (415, 433), True, 'import numpy as np\n')]
# /////////////////////////////////////////////////////////////// # # BY: <NAME> # PROJECT MADE WITH: Qt Designer and PySide6 # V: 1.0.0 # # This project can be used freely for all uses, as long as they maintain the # respective credits only in the Python scripts, any information in the visual # interface (GUI) can be modified without any implication. # # There are limitations on Qt licenses if you want to use your products # commercially, I recommend reading them on the official website: # https://doc.qt.io/qtforpython/licenses.html # # /////////////////////////////////////////////////////////////// import sys import os import platform import pandas as pd import numpy as np import time # IMPORT / GUI AND MODULES AND WIDGETS # /////////////////////////////////////////////////////////////// from modules import * from widgets import * os.environ["QT_FONT_DPI"] = "96" # FIX Problem for High DPI and Scale above 100% # SET AS GLOBAL WIDGETS # /////////////////////////////////////////////////////////////// widgets = None class AlertWindow(QMessageBox): def __init__(self, text): super().__init__() QMessageBox.about(self, "test",text) class MainWindow(QMainWindow): def __init__(self): self.w = None QMainWindow.__init__(self) # SET AS GLOBAL WIDGETS # /////////////////////////////////////////////////////////////// self.ui = Ui_MainWindow() self.ui.setupUi(self) global widgets widgets = self.ui # USE CUSTOM TITLE BAR | USE AS "False" FOR MAC OR LINUX # /////////////////////////////////////////////////////////////// Settings.ENABLE_CUSTOM_TITLE_BAR = True # APP NAME # /////////////////////////////////////////////////////////////// title = "SEMA-VOC Analysis GUI" description = "SEMA-VOC Analysis GUI tool" # APPLY TEXTS self.setWindowTitle(title) widgets.titleRightInfo.setText(description) # TOGGLE MENU # /////////////////////////////////////////////////////////////// widgets.toggleButton.clicked.connect(lambda: UIFunctions.toggleMenu(self, True)) # SET UI DEFINITIONS # /////////////////////////////////////////////////////////////// UIFunctions.uiDefinitions(self) # QTableWidget PARAMETERS # /////////////////////////////////////////////////////////////// widgets.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) # BUTTONS CLICK # /////////////////////////////////////////////////////////////// # LEFT MENUS widgets.btn_home.clicked.connect(self.buttonClick) widgets.btn_widgets.clicked.connect(self.buttonClick) # widgets.btn_new.clicked.connect(self.buttonClick) widgets.btn_save.clicked.connect(self.buttonClick) widgets.pushButton.clicked.connect(self.buttonClick) # EXTRA LEFT BOX def openCloseLeftBox(): UIFunctions.toggleLeftBox(self, True) # widgets.toggleLeftBox.clicked.connect(openCloseLeftBox) # widgets.extraCloseColumnBtn.clicked.connect(openCloseLeftBox) # EXTRA RIGHT BOX def openCloseRightBox(): UIFunctions.toggleRightBox(self, True) # widgets.settingsTopBtn.clicked.connect(openCloseRightBox) # SHOW APP # /////////////////////////////////////////////////////////////// self.show() # SET CUSTOM THEME # /////////////////////////////////////////////////////////////// useCustomTheme = False themeFile = "themes\py_dracula_light.qss" # SET THEME AND HACKS if useCustomTheme: # LOAD AND APPLY STYLE UIFunctions.theme(self, themeFile, True) # SET HACKS AppFunctions.setThemeHack(self) # SET HOME PAGE AND SELECT MENU # /////////////////////////////////////////////////////////////// widgets.stackedWidget.setCurrentWidget(widgets.home) widgets.btn_home.setStyleSheet(UIFunctions.selectMenu(widgets.btn_home.styleSheet())) widgets.home.setStyleSheet("background-image: url(images/images/sema-back.png);\n" "background-position: center;\n" "background-repeat: no-repeat;\n" "background-color: #1449a2;") # BUTTONS CLICK # Post here your functions for clicked buttons # /////////////////////////////////////////////////////////////// def buttonClick(self): # GET BUTTON CLICKED btn = self.sender() btnName = btn.objectName() # SHOW HOME PAGE if btnName == "btn_home": widgets.stackedWidget.setCurrentWidget(widgets.home) UIFunctions.resetStyle(self, btnName) btn.setStyleSheet(UIFunctions.selectMenu(btn.styleSheet())) # SHOW WIDGETS PAGE if btnName == "btn_widgets": widgets.stackedWidget.setCurrentWidget(widgets.widgets) UIFunctions.resetStyle(self, btnName) btn.setStyleSheet(UIFunctions.selectMenu(btn.styleSheet())) # # SHOW NEW PAGE # if btnName == "btn_new": # widgets.stackedWidget.setCurrentWidget(widgets.new_page) # SET PAGE # UIFunctions.resetStyle(self, btnName) # RESET ANOTHERS BUTTONS SELECTED # btn.setStyleSheet(UIFunctions.selectMenu(btn.styleSheet())) # SELECT MENU if btnName == "btn_save": print("Save BTN clicked!") inference(self.filename) QMessageBox.about(self, "합성", """ 합성 종료 """) if btnName == "pushButton": print("Open BTN clicked!") self.filename = QFileDialog.getOpenFileName(self)[0] UIFunctions.resetStyle(self, btnName) btn.setStyleSheet(UIFunctions.selectMenu(btn.styleSheet())) print(self.filename) widgets.lineEdit.setText(self.filename) df = pd.read_excel(self.filename) columns2show = ['아이디', '조사시작시간', 'VOC1', 'VOC2'] df2fill = np.empty(df[columns2show].shape) df2fill.flags.writeable = True df2show = df[['아이디', '조사시작시간', 'VOC1', 'VOC2']].values.tolist() # df[['아이디','조사시작시간','VOC1','VOC2']] for i in range(df2fill.shape[0]): for j in range(df2fill.shape[1]): # df2fill[i][j] = df2show[i][j] widgets.tableWidget.setItem(i+1,j, QTableWidgetItem(str(df2show[i][j]))) print(str(df2show[i][j])) # PRINT BTN NAME print(f'Button "{btnName}" pressed!') # RESIZE EVENTS # /////////////////////////////////////////////////////////////// def resizeEvent(self, event): # Update Size Grips UIFunctions.resize_grips(self) # MOUSE CLICK EVENTS # /////////////////////////////////////////////////////////////// def mousePressEvent(self, event): # SET DRAG POS WINDOW self.dragPos = event.globalPos() # PRINT MOUSE EVENTS if event.buttons() == Qt.LeftButton: print('Mouse click: LEFT CLICK') if event.buttons() == Qt.RightButton: print('Mouse click: RIGHT CLICK') def inference(file_name): import cli cli.SEMA(file_path=file_name).process_analysis_gui() if __name__ == "__main__": app = QApplication(sys.argv) app.setWindowIcon(QIcon("icon.ico")) window = MainWindow() sys.exit(app.exec_())
[ "cli.SEMA", "numpy.empty", "pandas.read_excel" ]
[((6071, 6099), 'pandas.read_excel', 'pd.read_excel', (['self.filename'], {}), '(self.filename)\n', (6084, 6099), True, 'import pandas as pd\n'), ((6183, 6215), 'numpy.empty', 'np.empty', (['df[columns2show].shape'], {}), '(df[columns2show].shape)\n', (6191, 6215), True, 'import numpy as np\n'), ((7402, 7431), 'cli.SEMA', 'cli.SEMA', ([], {'file_path': 'file_name'}), '(file_path=file_name)\n', (7410, 7431), False, 'import cli\n')]
from unittest import TestCase import numpy as np import math from somnium.lattice import LatticeFactory from scipy.spatial.distance import pdist, squareform from itertools import combinations, product, compress from somnium.tests.util import euclidean_distance class TestRectLattice(TestCase): def test_dimension(self): lat = LatticeFactory.build("rect")(n_rows=2, n_cols=3, distance_metric="euclidean") self.assertEqual(6, len(lat.coordinates)) self.assertEqual(2, lat.n_rows) self.assertEqual(3, lat.n_cols) def test_distances(self): lat = LatticeFactory.build("rect")(n_rows=2, n_cols=3, distance_metric="euclidean") pairs = list(product(lat.coordinates, lat.coordinates)) dist = np.array([euclidean_distance(x=u1, y=u2) for (u1, u2) in pairs]) dist = dist.reshape(6,2,3) self.assertTrue(np.allclose(dist, lat.distances)) def test_ordering(self): lat = LatticeFactory.build("rect")(n_rows=2, n_cols=3, distance_metric="euclidean") self.assertTrue(lat.distances[0, 0, 0] == 0) self.assertTrue(lat.distances[1, 0, 1] == 0) self.assertTrue(lat.distances[2, 0, 2] == 0) self.assertTrue(lat.distances[5, 1, 2] == 0) def test_n_neighbors(self): lat = LatticeFactory.build("rect")(n_rows=4, n_cols=3, distance_metric="euclidean") dist_matrix = squareform(pdist(lat.coordinates)) n_neighbors = set(np.sum(np.isclose(dist_matrix, 1), axis=0)) self.assertEqual({2,3,4}, n_neighbors) def test_neighborhood_method(self): lat = LatticeFactory.build("rect")(n_rows=4, n_cols=7, distance_metric="euclidean") pairs = list(combinations(lat.coordinates, 2)) neighbors = [euclidean_distance(x=u1, y=u2)==1 for (u1, u2) in pairs] neighbor_pairs = list(compress(pairs, neighbors)) not_neighbor_pairs = list(compress(pairs, [not(n) for n in neighbors])) self.assertTrue(all([lat.are_neighbors(*x) for x in neighbor_pairs])) self.assertTrue(not(any([lat.are_neighbors(*x) for x in not_neighbor_pairs]))) def test_neighborhood_method_cherrypick(self): lat = LatticeFactory.build("rect")(n_rows=7, n_cols=8, distance_metric="euclidean") center = 14 neighbors = [6, 13, 15, 22] self.assertTrue(all([lat.are_neighbor_indices(center, n) for n in neighbors])) lat = LatticeFactory.build("rect")(n_rows=6, n_cols=7, distance_metric="euclidean") center = 8 neighbors = [1, 7, 9, 15] self.assertTrue(all([lat.are_neighbor_indices(center, n) for n in neighbors])) center = 15 neighbors = [8 ,14, 16, 22] self.assertTrue(all([lat.are_neighbor_indices(center, n) for n in neighbors])) class TestHexaLattice(TestCase): def test_dimension(self): lat = LatticeFactory.build("hexa")(n_rows=2, n_cols=3, distance_metric="euclidean") self.assertEqual(6, len(lat.coordinates)) self.assertEqual(2, lat.n_rows) self.assertEqual(3, lat.n_cols) def test_distances(self): lat = LatticeFactory.build("hexa")(n_rows=2, n_cols=3, distance_metric="euclidean") pairs = list(product(lat.coordinates, lat.coordinates)) dist = np.array([euclidean_distance(x=u1, y=u2) for (u1, u2) in pairs]) dist = dist.reshape(6, 2, 3) self.assertTrue(np.allclose(dist, lat.distances)) def test_ordering(self): lat = LatticeFactory.build("hexa")(n_rows=2, n_cols=3, distance_metric="euclidean") self.assertTrue(lat.distances[0, 0, 0] == 0) self.assertTrue(lat.distances[1, 0, 1] == 0) self.assertTrue(lat.distances[2, 0, 2] == 0) self.assertTrue(lat.distances[5, 1, 2] == 0) def test_n_neighbors(self): lat = LatticeFactory.build("hexa")(n_rows=4, n_cols=3, distance_metric="euclidean") dist_matrix = squareform(pdist(lat.coordinates)) n_neighbors = set(np.sum(np.isclose(dist_matrix, 1), axis=0)) self.assertEqual({2,3,4,5,6}, n_neighbors) def test_neighborhood_method_in_batch(self): lat = LatticeFactory.build("hexa")(n_rows=4, n_cols=7, distance_metric="euclidean") pairs = list(combinations(lat.coordinates, 2)) neighbors = [math.isclose(a=euclidean_distance(x=u1, y=u2), b=1) for (u1, u2) in pairs] neighbor_pairs = list(compress(pairs, neighbors)) not_neighbor_pairs = list(compress(pairs, [not(n) for n in neighbors])) self.assertTrue(all([lat.are_neighbors(*x) for x in neighbor_pairs])) self.assertTrue(not(any([lat.are_neighbors(*x) for x in not_neighbor_pairs]))) def test_neighborhood_method_cherrypick(self): lat = LatticeFactory.build("hexa")(n_rows=7, n_cols=8, distance_metric="euclidean") center = 14 neighbors = [5, 6, 13, 15, 21, 22] self.assertTrue(all([lat.are_neighbor_indices(center, n) for n in neighbors])) lat = LatticeFactory.build("hexa")(n_rows=6, n_cols=7, distance_metric="euclidean") center = 8 neighbors = [0, 1, 7, 9, 14, 15] self.assertTrue(all([lat.are_neighbor_indices(center, n) for n in neighbors])) center = 15 neighbors = [8, 9, 14, 16, 22, 23] self.assertTrue(all([lat.are_neighbor_indices(center, n) for n in neighbors]))
[ "numpy.allclose", "numpy.isclose", "scipy.spatial.distance.pdist", "somnium.lattice.LatticeFactory.build", "itertools.product", "somnium.tests.util.euclidean_distance", "itertools.combinations", "itertools.compress" ]
[((341, 369), 'somnium.lattice.LatticeFactory.build', 'LatticeFactory.build', (['"""rect"""'], {}), "('rect')\n", (361, 369), False, 'from somnium.lattice import LatticeFactory\n'), ((594, 622), 'somnium.lattice.LatticeFactory.build', 'LatticeFactory.build', (['"""rect"""'], {}), "('rect')\n", (614, 622), False, 'from somnium.lattice import LatticeFactory\n'), ((693, 734), 'itertools.product', 'product', (['lat.coordinates', 'lat.coordinates'], {}), '(lat.coordinates, lat.coordinates)\n', (700, 734), False, 'from itertools import combinations, product, compress\n'), ((875, 907), 'numpy.allclose', 'np.allclose', (['dist', 'lat.distances'], {}), '(dist, lat.distances)\n', (886, 907), True, 'import numpy as np\n'), ((953, 981), 'somnium.lattice.LatticeFactory.build', 'LatticeFactory.build', (['"""rect"""'], {}), "('rect')\n", (973, 981), False, 'from somnium.lattice import LatticeFactory\n'), ((1290, 1318), 'somnium.lattice.LatticeFactory.build', 'LatticeFactory.build', (['"""rect"""'], {}), "('rect')\n", (1310, 1318), False, 'from somnium.lattice import LatticeFactory\n'), ((1401, 1423), 'scipy.spatial.distance.pdist', 'pdist', (['lat.coordinates'], {}), '(lat.coordinates)\n', (1406, 1423), False, 'from scipy.spatial.distance import pdist, squareform\n'), ((1597, 1625), 'somnium.lattice.LatticeFactory.build', 'LatticeFactory.build', (['"""rect"""'], {}), "('rect')\n", (1617, 1625), False, 'from somnium.lattice import LatticeFactory\n'), ((1696, 1728), 'itertools.combinations', 'combinations', (['lat.coordinates', '(2)'], {}), '(lat.coordinates, 2)\n', (1708, 1728), False, 'from itertools import combinations, product, compress\n'), ((1838, 1864), 'itertools.compress', 'compress', (['pairs', 'neighbors'], {}), '(pairs, neighbors)\n', (1846, 1864), False, 'from itertools import combinations, product, compress\n'), ((1900, 1945), 'itertools.compress', 'compress', (['pairs', '[(not n) for n in neighbors]'], {}), '(pairs, [(not n) for n in neighbors])\n', (1908, 1945), False, 'from itertools import combinations, product, compress\n'), ((2177, 2205), 'somnium.lattice.LatticeFactory.build', 'LatticeFactory.build', (['"""rect"""'], {}), "('rect')\n", (2197, 2205), False, 'from somnium.lattice import LatticeFactory\n'), ((2412, 2440), 'somnium.lattice.LatticeFactory.build', 'LatticeFactory.build', (['"""rect"""'], {}), "('rect')\n", (2432, 2440), False, 'from somnium.lattice import LatticeFactory\n'), ((2852, 2880), 'somnium.lattice.LatticeFactory.build', 'LatticeFactory.build', (['"""hexa"""'], {}), "('hexa')\n", (2872, 2880), False, 'from somnium.lattice import LatticeFactory\n'), ((3105, 3133), 'somnium.lattice.LatticeFactory.build', 'LatticeFactory.build', (['"""hexa"""'], {}), "('hexa')\n", (3125, 3133), False, 'from somnium.lattice import LatticeFactory\n'), ((3204, 3245), 'itertools.product', 'product', (['lat.coordinates', 'lat.coordinates'], {}), '(lat.coordinates, lat.coordinates)\n', (3211, 3245), False, 'from itertools import combinations, product, compress\n'), ((3388, 3420), 'numpy.allclose', 'np.allclose', (['dist', 'lat.distances'], {}), '(dist, lat.distances)\n', (3399, 3420), True, 'import numpy as np\n'), ((3466, 3494), 'somnium.lattice.LatticeFactory.build', 'LatticeFactory.build', (['"""hexa"""'], {}), "('hexa')\n", (3486, 3494), False, 'from somnium.lattice import LatticeFactory\n'), ((3803, 3831), 'somnium.lattice.LatticeFactory.build', 'LatticeFactory.build', (['"""hexa"""'], {}), "('hexa')\n", (3823, 3831), False, 'from somnium.lattice import LatticeFactory\n'), ((3914, 3936), 'scipy.spatial.distance.pdist', 'pdist', (['lat.coordinates'], {}), '(lat.coordinates)\n', (3919, 3936), False, 'from scipy.spatial.distance import pdist, squareform\n'), ((4123, 4151), 'somnium.lattice.LatticeFactory.build', 'LatticeFactory.build', (['"""hexa"""'], {}), "('hexa')\n", (4143, 4151), False, 'from somnium.lattice import LatticeFactory\n'), ((4222, 4254), 'itertools.combinations', 'combinations', (['lat.coordinates', '(2)'], {}), '(lat.coordinates, 2)\n', (4234, 4254), False, 'from itertools import combinations, product, compress\n'), ((4382, 4408), 'itertools.compress', 'compress', (['pairs', 'neighbors'], {}), '(pairs, neighbors)\n', (4390, 4408), False, 'from itertools import combinations, product, compress\n'), ((4444, 4489), 'itertools.compress', 'compress', (['pairs', '[(not n) for n in neighbors]'], {}), '(pairs, [(not n) for n in neighbors])\n', (4452, 4489), False, 'from itertools import combinations, product, compress\n'), ((4721, 4749), 'somnium.lattice.LatticeFactory.build', 'LatticeFactory.build', (['"""hexa"""'], {}), "('hexa')\n", (4741, 4749), False, 'from somnium.lattice import LatticeFactory\n'), ((4963, 4991), 'somnium.lattice.LatticeFactory.build', 'LatticeFactory.build', (['"""hexa"""'], {}), "('hexa')\n", (4983, 4991), False, 'from somnium.lattice import LatticeFactory\n'), ((761, 791), 'somnium.tests.util.euclidean_distance', 'euclidean_distance', ([], {'x': 'u1', 'y': 'u2'}), '(x=u1, y=u2)\n', (779, 791), False, 'from somnium.tests.util import euclidean_distance\n'), ((1458, 1484), 'numpy.isclose', 'np.isclose', (['dist_matrix', '(1)'], {}), '(dist_matrix, 1)\n', (1468, 1484), True, 'import numpy as np\n'), ((1751, 1781), 'somnium.tests.util.euclidean_distance', 'euclidean_distance', ([], {'x': 'u1', 'y': 'u2'}), '(x=u1, y=u2)\n', (1769, 1781), False, 'from somnium.tests.util import euclidean_distance\n'), ((3272, 3302), 'somnium.tests.util.euclidean_distance', 'euclidean_distance', ([], {'x': 'u1', 'y': 'u2'}), '(x=u1, y=u2)\n', (3290, 3302), False, 'from somnium.tests.util import euclidean_distance\n'), ((3971, 3997), 'numpy.isclose', 'np.isclose', (['dist_matrix', '(1)'], {}), '(dist_matrix, 1)\n', (3981, 3997), True, 'import numpy as np\n'), ((4292, 4322), 'somnium.tests.util.euclidean_distance', 'euclidean_distance', ([], {'x': 'u1', 'y': 'u2'}), '(x=u1, y=u2)\n', (4310, 4322), False, 'from somnium.tests.util import euclidean_distance\n')]
from __future__ import print_function import numpy as np import sys import mesh.patch as patch from util import msg def init_data(my_data, rp): """ initialize the HSE problem """ msg.bold("initializing the HSE problem...") # make sure that we are passed a valid patch object if not isinstance(my_data, patch.CellCenterData2d): print("ERROR: patch invalid in hse.py") print(my_data.__class__) sys.exit() # get the density, momenta, and energy as separate variables dens = my_data.get_var("density") xmom = my_data.get_var("x-momentum") ymom = my_data.get_var("y-momentum") ener = my_data.get_var("energy") gamma = rp.get_param("eos.gamma") grav = rp.get_param("compressible.grav") dens0 = rp.get_param("hse.dens0") print("dens0 = ", dens0) H = rp.get_param("hse.h") # isothermal sound speed (squared) cs2 = H*abs(grav) # initialize the components, remember, that ener here is # rho*eint + 0.5*rho*v**2, where eint is the specific # internal energy (erg/g) xmom[:, :] = 0.0 ymom[:, :] = 0.0 dens[:, :] = 0.0 # set the density to be stratified in the y-direction myg = my_data.grid p = myg.scratch_array() for j in range(myg.jlo, myg.jhi+1): dens[:, j] = dens0*np.exp(-myg.y[j]/H) if j == myg.jlo: p[:, j] = dens[:, j]*cs2 else: p[:, j] = p[:, j-1] + 0.5*myg.dy*(dens[:, j] + dens[:, j-1])*grav # set the energy ener[:, :] = p[:, :]/(gamma - 1.0) + \ 0.5*(xmom[:, :]**2 + ymom[:, :]**2)/dens[:, :] def finalize(): """ print out any information to the user at the end of the run """ pass
[ "numpy.exp", "util.msg.bold", "sys.exit" ]
[((192, 235), 'util.msg.bold', 'msg.bold', (['"""initializing the HSE problem..."""'], {}), "('initializing the HSE problem...')\n", (200, 235), False, 'from util import msg\n'), ((438, 448), 'sys.exit', 'sys.exit', ([], {}), '()\n', (446, 448), False, 'import sys\n'), ((1309, 1330), 'numpy.exp', 'np.exp', (['(-myg.y[j] / H)'], {}), '(-myg.y[j] / H)\n', (1315, 1330), True, 'import numpy as np\n')]
# Distributed under the MIT License. # See LICENSE.txt for details. import numpy as np from numpy import sqrt, exp, pi def normal_dot_minus_stress(x, n, beam_width): n /= np.linalg.norm(n) r = sqrt(np.linalg.norm(x)**2 - np.dot(x, n)**2) beam_profile = exp(-(r / beam_width)**2) / pi / beam_width**2 return np.tensordot(-n, beam_profile, axes=0) def normal_dot_minus_stress_linearized(x, n, beam_width): return np.zeros(3)
[ "numpy.tensordot", "numpy.exp", "numpy.dot", "numpy.zeros", "numpy.linalg.norm" ]
[((178, 195), 'numpy.linalg.norm', 'np.linalg.norm', (['n'], {}), '(n)\n', (192, 195), True, 'import numpy as np\n'), ((326, 364), 'numpy.tensordot', 'np.tensordot', (['(-n)', 'beam_profile'], {'axes': '(0)'}), '(-n, beam_profile, axes=0)\n', (338, 364), True, 'import numpy as np\n'), ((436, 447), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (444, 447), True, 'import numpy as np\n'), ((268, 295), 'numpy.exp', 'exp', (['(-(r / beam_width) ** 2)'], {}), '(-(r / beam_width) ** 2)\n', (271, 295), False, 'from numpy import sqrt, exp, pi\n'), ((209, 226), 'numpy.linalg.norm', 'np.linalg.norm', (['x'], {}), '(x)\n', (223, 226), True, 'import numpy as np\n'), ((232, 244), 'numpy.dot', 'np.dot', (['x', 'n'], {}), '(x, n)\n', (238, 244), True, 'import numpy as np\n')]
import numpy as np import xarray from numpy.ma.core import default_fill_value from scipy import ndimage from enstools.core import check_arguments from enstools.misc import count_ge from enstools.core.parallelisation import apply_chunkwise @check_arguments(units={"pr": "kg m-2 s-1", "cape": "J kg-1", "return_value": "hour"}, shape={"pr": "cape"}) def convective_adjustment_time_scale(pr, cape, th=1.0, fraction_above_th=0.0015): """ Calculate the convective adjustment time scale from precipitation and CAPE as described in [1]_. A gaussian filter is applied to the input data if at least one dimension has more then 30 grid points. Parameters ---------- pr: xarray.DataArray Hourly or longer accumulated precipitation converted to [kg m-2 s-1]. cape: xarray.DataArray The CAPE of mean surface layer parcel [J kg-1]. For example, mean of start and end value of the period of the accumulation. th: float threshold for the precipitation rate above which the calculation should be performed [kg m-2 h-1]. Grid points with smaller precipitation values will contain missing values. Default: 1 fraction_above_th: float fraction of grid points that must exceed the threshold defined in `th`. Default: 0.0015 (e.g. 15 of 10.000 grid points). Returns ------- tau: masked_array or xarray (depending on type of pr) the convective adjustment time scale [h] Examples -------- >>> if np.__version__ > "1.13.9": np.set_printoptions(legacy="1.13") # numpy version independent printing >>> cape = xarray.DataArray([500.0, 290.44], attrs={"units": "J kg-1"}) >>> pr = xarray.DataArray([0.0, 2.0], attrs={"units": "kg m-2 hour-1"}) >>> np.round(convective_adjustment_time_scale(pr, cape).compute(), 4) # doctest:+ELLIPSIS <xarray.DataArray 'tauc-...' (dim_0: 2)> array([ nan, 1.]) Dimensions without coordinates: dim_0 with not enough values above the defined threshold: >>> np.round(convective_adjustment_time_scale(pr, cape, fraction_above_th=0.6).compute(), 4) # doctest:+ELLIPSIS <xarray.DataArray 'tauc-...' (dim_0: 2)> array([ nan, nan]) Dimensions without coordinates: dim_0 References ---------- .. [1] <NAME>., <NAME>. and <NAME>. (2014), The convective adjustment time-scale as indicator of predictability of convective precipitation. Q.J.R. Meteorol. Soc., 140: 480-490. doi:10.1002/qj.2143 """ # TODO: tauc calculation is not chunkwise but something like layer wise @apply_chunkwise def tauc(pr, cape, th): # create a result array filled with the default fill value for the data type of pr fill_value = np.nan result = np.full_like(pr, fill_value=fill_value) # count values above threshold n_above_th = count_ge(pr, th / 3600.0) if n_above_th < pr.size * fraction_above_th: result = np.ma.masked_equal(result, fill_value) return result # Gaussian filtering sig = 10. # Gaussian goes to zero 3*sig grid points from centre if max(pr.shape) > 3*sig: cape_filtered = ndimage.filters.gaussian_filter(cape, sig, mode='reflect') pr_filtered = ndimage.filters.gaussian_filter(pr, sig, mode='reflect') else: cape_filtered = cape pr_filtered = pr # perform the actual calculation ind = np.where(pr > th / 3600.0) result[ind] = 1.91281e-06 * cape_filtered[ind] / pr_filtered[ind] result = np.ma.masked_equal(result, fill_value) return result result = tauc(pr, cape, th) # convert the result to xarray if the input type is also xarray if type(pr) == xarray.DataArray: result = xarray.DataArray(result, coords=pr.coords, dims=pr.dims, attrs={"units": "hour"}) return result
[ "enstools.core.check_arguments", "enstools.misc.count_ge", "numpy.full_like", "numpy.ma.masked_equal", "scipy.ndimage.filters.gaussian_filter", "numpy.where", "xarray.DataArray" ]
[((242, 353), 'enstools.core.check_arguments', 'check_arguments', ([], {'units': "{'pr': 'kg m-2 s-1', 'cape': 'J kg-1', 'return_value': 'hour'}", 'shape': "{'pr': 'cape'}"}), "(units={'pr': 'kg m-2 s-1', 'cape': 'J kg-1', 'return_value':\n 'hour'}, shape={'pr': 'cape'})\n", (257, 353), False, 'from enstools.core import check_arguments\n'), ((2919, 2958), 'numpy.full_like', 'np.full_like', (['pr'], {'fill_value': 'fill_value'}), '(pr, fill_value=fill_value)\n', (2931, 2958), True, 'import numpy as np\n'), ((3020, 3045), 'enstools.misc.count_ge', 'count_ge', (['pr', '(th / 3600.0)'], {}), '(pr, th / 3600.0)\n', (3028, 3045), False, 'from enstools.misc import count_ge\n'), ((3624, 3650), 'numpy.where', 'np.where', (['(pr > th / 3600.0)'], {}), '(pr > th / 3600.0)\n', (3632, 3650), True, 'import numpy as np\n'), ((3742, 3780), 'numpy.ma.masked_equal', 'np.ma.masked_equal', (['result', 'fill_value'], {}), '(result, fill_value)\n', (3760, 3780), True, 'import numpy as np\n'), ((3958, 4043), 'xarray.DataArray', 'xarray.DataArray', (['result'], {'coords': 'pr.coords', 'dims': 'pr.dims', 'attrs': "{'units': 'hour'}"}), "(result, coords=pr.coords, dims=pr.dims, attrs={'units':\n 'hour'})\n", (3974, 4043), False, 'import xarray\n'), ((3120, 3158), 'numpy.ma.masked_equal', 'np.ma.masked_equal', (['result', 'fill_value'], {}), '(result, fill_value)\n', (3138, 3158), True, 'import numpy as np\n'), ((3350, 3408), 'scipy.ndimage.filters.gaussian_filter', 'ndimage.filters.gaussian_filter', (['cape', 'sig'], {'mode': '"""reflect"""'}), "(cape, sig, mode='reflect')\n", (3381, 3408), False, 'from scipy import ndimage\n'), ((3435, 3491), 'scipy.ndimage.filters.gaussian_filter', 'ndimage.filters.gaussian_filter', (['pr', 'sig'], {'mode': '"""reflect"""'}), "(pr, sig, mode='reflect')\n", (3466, 3491), False, 'from scipy import ndimage\n')]
import numpy as np import pandas as pd from collections import Counter from sklearn.utils import resample from tqdm.notebook import tqdm_notebook import copy from sklearn.base import is_classifier class DSClassifier: """This classifier is designed to handle unbalanced data. The classification is based on an ensemble of sub-sets. Input: base_estimator A base model that the classifier will use to make a prediction on each subset. ratio The ratio of the minority group to the rest of the data. The default is 1. The ratio describes a ratio of 1: ratio. For example: Ratio = 1 Creates a 1: 1 ratio (50% / 50%) between the minority group and the rest of the data. Ratio = 2 Creates a 2: 1 ratio (33% / 66%) between the minority group and the rest of the data. ensemble The method by which the models of each subset will be combined together. The default is mean. For numeric labels you can select max or min to tilt the classifier to a certain side. random_state Seed for the distribution of the majority population in each subset. The default is 42. Attributes: fit(X_train, y_train) predict(X) predict_proba(X) list_of_df List of all created sub-sets. list_models List of all the models that make up the final model. """ def __init__(self, base_estimator, ratio = 1, ensemble = 'mean', random_state = 42): def get_ensemble(ensemble): if ensemble == 'mean': return np.mean if ensemble == 'max': return np.max if ensemble == 'min': return np.min else: raise ValueError("ensemble must be one of these options: 'mean', 'max', 'min' not " + ensemble) if is_classifier(base_estimator): self.base_estimator = base_estimator else: raise ValueError("base_estimator must be a classifier not " + base_estimator) self._estimator_type = 'classifier' self._ratio = ratio self.ensemble = get_ensemble(ensemble) self._random_state = random_state self.classes_ = None self._target = None self.list_of_df = None self.list_models = None def __repr__(self): return self._estimator_type def fit(self, X_train, y_train): def balance(X_train, y_train, ratio, random_state): model_input_data = pd.concat([X_train, y_train], axis=1) counter = Counter(y_train).most_common() minority = counter[-1][0] majority = counter[0][0] row_by_class = {majority: model_input_data[model_input_data[self.target] != minority], \ minority: model_input_data[model_input_data[self.target] == minority],} num_of_samples_minority = int(row_by_class[minority].shape[0]) num_of_samples_majority = int(num_of_samples_minority)*ratio list_of_df = [] while len(row_by_class[majority])>num_of_samples_majority: majority_sample = resample(row_by_class[majority], replace = True, n_samples = num_of_samples_majority, random_state=random_state) row_by_class[majority] = row_by_class[majority].drop(majority_sample.index.values.tolist()) subsets = pd.concat([row_by_class[minority], majority_sample]) list_of_df.append(subsets) old_minority_percent = format(counter[-1][1] / (counter[0][1] + counter[-1][1]) *100, '.2f') new_minority_percent = format(num_of_samples_minority / (num_of_samples_majority + num_of_samples_minority) *100, '.2f') return list_of_df def modeling(list_of_df, base_estimator): list_models = [] for i in tqdm_notebook(range((len(list_of_df)))): x_train = list_of_df[i].drop(self.target, axis=1) y_train = list_of_df[i][self.target] model = copy.deepcopy(base_estimator) model.fit(x_train, y_train) list_models.append(model) return list_models self.target = y_train.name self.classes_ = np.unique(y_train) self.list_of_df = balance(X_train, y_train, self._ratio, self._random_state) self.list_models = modeling(self.list_of_df, self.base_estimator) def predict(self, X): list_of_predict = [] for i in tqdm_notebook(range(len(self.list_models))): list_of_predict.append(self.list_models[i].predict(X)) return self.ensemble(list_of_predict, axis=0).round() def predict_proba(self, X): list_of_predict_proba = [] for i in tqdm_notebook(range(len(self.list_models))): list_of_predict_proba.append(self.list_models[i].predict_proba(X)) return self.ensemble(list_of_predict_proba, axis=0)
[ "numpy.unique", "sklearn.base.is_classifier", "collections.Counter", "sklearn.utils.resample", "copy.deepcopy", "pandas.concat" ]
[((2230, 2259), 'sklearn.base.is_classifier', 'is_classifier', (['base_estimator'], {}), '(base_estimator)\n', (2243, 2259), False, 'from sklearn.base import is_classifier\n'), ((4776, 4794), 'numpy.unique', 'np.unique', (['y_train'], {}), '(y_train)\n', (4785, 4794), True, 'import numpy as np\n'), ((2905, 2942), 'pandas.concat', 'pd.concat', (['[X_train, y_train]'], {'axis': '(1)'}), '([X_train, y_train], axis=1)\n', (2914, 2942), True, 'import pandas as pd\n'), ((3576, 3689), 'sklearn.utils.resample', 'resample', (['row_by_class[majority]'], {'replace': '(True)', 'n_samples': 'num_of_samples_majority', 'random_state': 'random_state'}), '(row_by_class[majority], replace=True, n_samples=\n num_of_samples_majority, random_state=random_state)\n', (3584, 3689), False, 'from sklearn.utils import resample\n'), ((3912, 3964), 'pandas.concat', 'pd.concat', (['[row_by_class[minority], majority_sample]'], {}), '([row_by_class[minority], majority_sample])\n', (3921, 3964), True, 'import pandas as pd\n'), ((4565, 4594), 'copy.deepcopy', 'copy.deepcopy', (['base_estimator'], {}), '(base_estimator)\n', (4578, 4594), False, 'import copy\n'), ((2966, 2982), 'collections.Counter', 'Counter', (['y_train'], {}), '(y_train)\n', (2973, 2982), False, 'from collections import Counter\n')]
# Multiple Linear Regression # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('50_Startups.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, -1].values print(X) """ [[165349.2 136897.8 471784.1 'New York'] [162597.7 151377.59 443898.53 'California'] [153441.51 101145.55 407934.54 'Florida'] [144372.41 118671.85 383199.62 'New York'] [142107.34 91391.77 366168.42 'Florida'] [131876.9 99814.71 362861.36 'New York'] [134615.46 147198.87 127716.82 'California'] [130298.13 145530.06 323876.68 'Florida'] [120542.52 148718.95 311613.29 'New York'] [123334.88 108679.17 304981.62 'California'] [101913.08 110594.11 229160.95 'Florida'] [100671.96 91790.61 249744.55 'California'] [93863.75 127320.38 249839.44 'Florida'] [91992.39 135495.07 252664.93 'California'] [119943.24 156547.42 256512.92 'Florida'] [114523.61 122616.84 261776.23 'New York'] [78013.11 121597.55 264346.06 'California'] [94657.16 145077.58 282574.31 'New York'] [91749.16 114175.79 294919.57 'Florida'] [86419.7 153514.11 0.0 'New York'] [76253.86 113867.3 298664.47 'California'] [78389.47 153773.43 299737.29 'New York'] [73994.56 122782.75 303319.26 'Florida'] [67532.53 105751.03 304768.73 'Florida'] [77044.01 99281.34 140574.81 'New York'] [64664.71 139553.16 137962.62 'California'] [75328.87 144135.98 134050.07 'Florida'] [72107.6 127864.55 353183.81 'New York'] [66051.52 182645.56 118148.2 'Florida'] [65605.48 153032.06 107138.38 'New York'] [61994.48 115641.28 91131.24 'Florida'] [61136.38 152701.92 88218.23 'New York'] [63408.86 129219.61 46085.25 'California'] [55493.95 103057.49 214634.81 'Florida'] [46426.07 157693.92 210797.67 'California'] [46014.02 85047.44 205517.64 'New York'] [28663.76 127056.21 201126.82 'Florida'] [44069.95 51283.14 197029.42 'California'] [20229.59 65947.93 185265.1 'New York'] [38558.51 82982.09 174999.3 'California'] [28754.33 118546.05 172795.67 'California'] [27892.92 84710.77 164470.71 'Florida'] [23640.93 96189.63 148001.11 'California'] [15505.73 127382.3 35534.17 'New York'] [22177.74 154806.14 28334.72 'California'] [1000.23 124153.04 1903.93 'New York'] [1315.46 115816.21 297114.46 'Florida'] [0.0 135426.92 0.0 'California'] [542.05 51743.15 0.0 'New York'] [0.0 116983.8 45173.06 'California']] """ # Encoding categorical data from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder ct = ColumnTransformer(transformers = [('encoder', OneHotEncoder(), [3])], remainder = 'passthrough') X = np.array(ct.fit_transform(X)) print(X) """ [[0.0 0.0 1.0 165349.2 136897.8 471784.1] [1.0 0.0 0.0 162597.7 151377.59 443898.53] [0.0 1.0 0.0 153441.51 101145.55 407934.54] [0.0 0.0 1.0 144372.41 118671.85 383199.62] [0.0 1.0 0.0 142107.34 91391.77 366168.42] [0.0 0.0 1.0 131876.9 99814.71 362861.36] [1.0 0.0 0.0 134615.46 147198.87 127716.82] [0.0 1.0 0.0 130298.13 145530.06 323876.68] [0.0 0.0 1.0 120542.52 148718.95 311613.29] [1.0 0.0 0.0 123334.88 108679.17 304981.62] [0.0 1.0 0.0 101913.08 110594.11 229160.95] [1.0 0.0 0.0 100671.96 91790.61 249744.55] [0.0 1.0 0.0 93863.75 127320.38 249839.44] [1.0 0.0 0.0 91992.39 135495.07 252664.93] [0.0 1.0 0.0 119943.24 156547.42 256512.92] [0.0 0.0 1.0 114523.61 122616.84 261776.23] [1.0 0.0 0.0 78013.11 121597.55 264346.06] [0.0 0.0 1.0 94657.16 145077.58 282574.31] [0.0 1.0 0.0 91749.16 114175.79 294919.57] [0.0 0.0 1.0 86419.7 153514.11 0.0] [1.0 0.0 0.0 76253.86 113867.3 298664.47] [0.0 0.0 1.0 78389.47 153773.43 299737.29] [0.0 1.0 0.0 73994.56 122782.75 303319.26] [0.0 1.0 0.0 67532.53 105751.03 304768.73] [0.0 0.0 1.0 77044.01 99281.34 140574.81] [1.0 0.0 0.0 64664.71 139553.16 137962.62] [0.0 1.0 0.0 75328.87 144135.98 134050.07] [0.0 0.0 1.0 72107.6 127864.55 353183.81] [0.0 1.0 0.0 66051.52 182645.56 118148.2] [0.0 0.0 1.0 65605.48 153032.06 107138.38] [0.0 1.0 0.0 61994.48 115641.28 91131.24] [0.0 0.0 1.0 61136.38 152701.92 88218.23] [1.0 0.0 0.0 63408.86 129219.61 46085.25] [0.0 1.0 0.0 55493.95 103057.49 214634.81] [1.0 0.0 0.0 46426.07 157693.92 210797.67] [0.0 0.0 1.0 46014.02 85047.44 205517.64] [0.0 1.0 0.0 28663.76 127056.21 201126.82] [1.0 0.0 0.0 44069.95 51283.14 197029.42] [0.0 0.0 1.0 20229.59 65947.93 185265.1] [1.0 0.0 0.0 38558.51 82982.09 174999.3] [1.0 0.0 0.0 28754.33 118546.05 172795.67] [0.0 1.0 0.0 27892.92 84710.77 164470.71] [1.0 0.0 0.0 23640.93 96189.63 148001.11] [0.0 0.0 1.0 15505.73 127382.3 35534.17] [1.0 0.0 0.0 22177.74 154806.14 28334.72] [0.0 0.0 1.0 1000.23 124153.04 1903.93] [0.0 1.0 0.0 1315.46 115816.21 297114.46] [1.0 0.0 0.0 0.0 135426.92 0.0] [0.0 0.0 1.0 542.05 51743.15 0.0] [1.0 0.0 0.0 0.0 116983.8 45173.06]] """ # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) # Training the Multiple Linear Regression model on the Training set from sklearn.linear_model import LinearRegression regressor = LinearRegression() ## This line of code will build the Multiple Regression Model. regressor.fit(X_train, y_train) ## This line of code will train the model on the training set. # Predicting the Test set results y_pred = regressor.predict(X_test) np.set_printoptions(precision = 2) print(np.concatenate((y_pred.reshape(len(y_pred), 1), y_test.reshape(len(y_test), 1)), 1)) """ [[103015.2 103282.38] [132582.28 144259.4 ] [132447.74 146121.95] [ 71976.1 77798.83] [178537.48 191050.39] [116161.24 105008.31] [ 67851.69 81229.06] [ 98791.73 97483.56] [113969.44 110352.25] [167921.07 166187.94]] """ """ # Evaluating the Model Performance from sklearn.metrics import r2_score r2_score(y_test, y_pred) """ # Making a single prediction (for example the profit of a startup with R&D Spend = 160000, Administration Spend = 130000, Marketing Spend = 300000 and State = 'California') print(regressor.predict([[1, 0, 0, 160000, 130000, 300000]])) ## [181566.92] """ Therefore, our model predicts that the profit of a Californian startup which spent 160000 in R&D, 130000 in Administration and 300000 in Marketing is $ 181566,92. Important note 1: Notice that the values of the features were all input in a double pair of square brackets. That's because the "predict" method always expects a 2D array as the format of its inputs. And putting our values into a double pair of square brackets makes the input exactly a 2D array. Simply put: 1,0,0,160000,130000,300000 -> scalars [1,0,0,160000,130000,300000] -> 1D array [[1,0,0,160000,130000,300000]] -> 2D array Important note 2: Notice also that the "California" state was not input as a string in the last column but as "1, 0, 0" in the first three columns. That's because of course the predict method expects the one-hot-encoded values of the state, and as we see in the second row of the matrix of features X, "California" was encoded as "1, 0, 0". And be careful to include these values in the first three columns, not the last three ones, because the dummy variables are always created in the first columns. """ # Getting the final linear regression equation with the values of the coefficients print(regressor.coef_) print(regressor.intercept_) """ [ 8.66e+01 -8.73e+02 7.86e+02 7.73e-01 3.29e-02 3.66e-02] 42467.52924853204 """ """ Therefore, the equation of our multiple linear regression model is: Profit=86.6 × Dummy State 1 − 873 × Dummy State 2 + 786 × Dummy State 3 + 0.773 × R&D Spend + 0.0329 × Administration + 0.0366 × Marketing Spend + 42467.53 Important Note: To get these coefficients we called the "coef_" and "intercept_" attributes from our regressor object. Attributes in Python are different than methods and usually return a simple value or an array of values. """
[ "pandas.read_csv", "sklearn.model_selection.train_test_split", "sklearn.preprocessing.OneHotEncoder", "sklearn.linear_model.LinearRegression", "numpy.set_printoptions" ]
[((162, 192), 'pandas.read_csv', 'pd.read_csv', (['"""50_Startups.csv"""'], {}), "('50_Startups.csv')\n", (173, 192), True, 'import pandas as pd\n'), ((4969, 5022), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.2)', 'random_state': '(0)'}), '(X, y, test_size=0.2, random_state=0)\n', (4985, 5022), False, 'from sklearn.model_selection import train_test_split\n'), ((5158, 5176), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (5174, 5176), False, 'from sklearn.linear_model import LinearRegression\n'), ((5405, 5437), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(2)'}), '(precision=2)\n', (5424, 5437), True, 'import numpy as np\n'), ((2567, 2582), 'sklearn.preprocessing.OneHotEncoder', 'OneHotEncoder', ([], {}), '()\n', (2580, 2582), False, 'from sklearn.preprocessing import OneHotEncoder\n')]
import torch import numpy as np import onnx import os from onnx2keras import onnx_to_keras, check_torch_keras_error from relu import LayerReLUTest, FReLUTest from hard_tanh import LayerHardtanhTest, FHardtanhTest from leaky_relu import LayerLeakyReLUTest, FLeakyReLUTest from selu import LayerSELUTest, FSELUTest from sigmoid import LayerSigmoidTest, FSigmoidTest from tanh import LayerTanhTest, FTanhTest from log_sigmoid import LayerLogSigmoidTest, FLogSigmoidTest # from threshold import LayerThresholdTest, FThresholdTest # Not Supported by ONNX from relu6 import LayerReLU6Test, FReLU6Test from softmax import LayerSoftmaxTest, FSoftmaxTest # from log_softmax import LayerLogSoftmaxTest, FLogSoftmaxTest # Not Supported by ONNX # TODO: # Threshold, Softmax2d, LogSoftmax, ELU, CELU, Hardshrink, \ # Softplus, Softshrink, MultiheadAttention, PReLU, Softsign, Softmin, Tanhshrink, RReLU, GLU if __name__ == '__main__': max_error = 0 for act_type in [ # LayerLogSoftmaxTest, FLogSoftmaxTest, # Not Supported by ONNX LayerSoftmaxTest, FSoftmaxTest, LayerReLU6Test, FReLU6Test, # LayerThresholdTest, FThresholdTest, # Not Supported by ONNX LayerLogSigmoidTest, FLogSigmoidTest, LayerTanhTest, FTanhTest, LayerSigmoidTest, FSigmoidTest, LayerSELUTest, FSELUTest, LayerLeakyReLUTest, FLeakyReLUTest, LayerHardtanhTest, FHardtanhTest, LayerReLUTest, FReLUTest,]: for i in range(10): model = act_type() model.eval() input_np = np.random.uniform(0, 1, (1, 3, 224, 224)) input_var = torch.FloatTensor(input_np) torch.onnx.export(model, input_var, "_tmpnet.onnx", verbose=True, input_names=['test_in'], output_names=['test_out']) onnx_model = onnx.load('_tmpnet.onnx') k_model = onnx_to_keras(onnx_model, ['test_in']) os.unlink('_tmpnet.onnx') error = check_torch_keras_error(model, k_model, input_np) print('Error:', error) if max_error < error: max_error = error print('Max error: {0}'.format(max_error))
[ "onnx2keras.check_torch_keras_error", "onnx2keras.onnx_to_keras", "onnx.load", "os.unlink", "numpy.random.uniform", "torch.FloatTensor", "torch.onnx.export" ]
[((1717, 1758), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)', '(1, 3, 224, 224)'], {}), '(0, 1, (1, 3, 224, 224))\n', (1734, 1758), True, 'import numpy as np\n'), ((1783, 1810), 'torch.FloatTensor', 'torch.FloatTensor', (['input_np'], {}), '(input_np)\n', (1800, 1810), False, 'import torch\n'), ((1824, 1945), 'torch.onnx.export', 'torch.onnx.export', (['model', 'input_var', '"""_tmpnet.onnx"""'], {'verbose': '(True)', 'input_names': "['test_in']", 'output_names': "['test_out']"}), "(model, input_var, '_tmpnet.onnx', verbose=True,\n input_names=['test_in'], output_names=['test_out'])\n", (1841, 1945), False, 'import torch\n'), ((1998, 2023), 'onnx.load', 'onnx.load', (['"""_tmpnet.onnx"""'], {}), "('_tmpnet.onnx')\n", (2007, 2023), False, 'import onnx\n'), ((2046, 2084), 'onnx2keras.onnx_to_keras', 'onnx_to_keras', (['onnx_model', "['test_in']"], {}), "(onnx_model, ['test_in'])\n", (2059, 2084), False, 'from onnx2keras import onnx_to_keras, check_torch_keras_error\n'), ((2097, 2122), 'os.unlink', 'os.unlink', (['"""_tmpnet.onnx"""'], {}), "('_tmpnet.onnx')\n", (2106, 2122), False, 'import os\n'), ((2144, 2193), 'onnx2keras.check_torch_keras_error', 'check_torch_keras_error', (['model', 'k_model', 'input_np'], {}), '(model, k_model, input_np)\n', (2167, 2193), False, 'from onnx2keras import onnx_to_keras, check_torch_keras_error\n')]
import numpy as np import matplotlib.pyplot as plt from math import sqrt, copysign from scipy.optimize import brenth from scipy.optimize import fsolve,fmin_l_bfgs_b,fmin_cg,fminbound """ sign of the number """ def sign(x): if x==0: return 0 else: return copysign(1,x) """ if function f can't be computed, return None """ def f_None(f,x): try: return f(x) except: return None """ if the bound was touched returns None L is the level of the function f """ def correct(x,y,f,L): eps=10e-5 if abs(f(x,y)-L)>eps: return None else: return y """ if output can't be produced, return 0, if there's division by zero, then it looks for the limit and returns it """ def _(f,*x): try: out=f(*x) if out is None: return float("inf") else: return out except ZeroDivisionError: l=len(x) eps=abs(f(*[1e-02]*l)-f(*[1e-04]*l)) if abs(f(*[1e-04]*l)-f(*[1e-06]*l))<eps and abs(f(*[1e-06]*l)-f(*[1e-08]*l))<eps: return f(*[1e-10]*l) else: return sign(f(*[1e-10]*l))*float("inf") """ produces the array of the first items of the element of the array """ def fst(X): return list(map(lambda x: x[0],X)) """ produces the array of the second items of the element of the array """ def snd(X): return list(map(lambda x: x[1],X)) """ unpacks [(X_1,Y_1),...,(X_k,Y_k),...,(X_n,Y_n)] into [(X_1,...,X_k,...,X_n),(Y_1,...,Y_k,...,Y_n)] """ def unpack(X): return [fst(X),snd(X)] """ find the root of the function. If the ends of the interval have the same signs, try to make it smaller """ def rootalt(f,a,b): eps=(b-a)/64.0 turn=0 N_iter=10 while abs(a-b)>eps and N_iter > 0: N_iter-=1 try: #return fmin_cg(f,(a+b)/2.0)[0] return brenth(f,a,b) except ValueError: if turn==0: a=a+eps turn=1 else: b=b+eps turn=0 #return root2(f,a,b) return None def root(f,a,b): a_init=a b_init=b eps=(b-a)/16.0 turn=0 N_iter=12 while abs(a-b)>eps and N_iter > 0 and f(a)*f(b)>0: N_iter-=1 if turn==0: a=a+eps turn=1 else: b=b-eps turn=0 try: return brenth(f,a,b) except ValueError: return fminbound(f,a_init,b_init) def root2(f,a,b): return fmin_cg(f,(a+b)/2.0,disp=False)[0] def root3(f,a,b): return fmin_l_bfgs_b(func=f,x0=(a+b)/2,bounds=[a,b]) """ 2-point numerical derivative """ def prime(f,dt=10e-3): return lambda x: (f(x+dt)-f(x-dt))/(2*dt) """ Marginal rate of substitution of a utility function u(.) """ def MRS(u): u_x=lambda x,y: prime(lambda z: u(z,y))(x) u_y=lambda x,y: prime(lambda z: u(x,z))(y) return lambda x,y: u_x(x,y)/u_y(x,y) """ Edgeworth Box parameter determine that to show on the plot """ class EdgeBoxParameter: #def __init__(self,pareto,core,U1,U2,endow,walras,budget,N): #boll_array=[pareto,core,U1,U2,endow,walras,budget] def __init__(self,N,pareto=True,core=True,eq=True,budget=True): self.N=N self.pareto=pareto self.core=core self.eq=eq self.budget=budget defaultEBP=EdgeBoxParameter(100) class EdgeBox(): def __init__(self,u1,u2,IE1,IE2,EBP=defaultEBP): self.core=0 self.pareto=0 self.eq=0 self.p=[None,1] self.p_weighted=[None,None] self.u1=u1 self.u2=u2 self.u2_compl=lambda x,y: u2(self.IE[0]-x,self.IE[1]-y) self.IE1=IE1 self.IE2=IE2 self.IE=[IE1[0]+IE2[0],IE1[1]+IE2[1]] self.EBP=EBP self.dt=min(self.IE)/float(EBP.N) self.X=np.linspace(self.dt,self.IE[0]-self.dt,EBP.N) self.Y=np.linspace(self.dt,self.IE[1]-self.dt,EBP.N) self.calc_init() self.calc() def calc(self): """ calculate all solutions of the box """ self.calc_pareto() self.calc_core() self.calc_eq() self.calc_budget() def calc_init(self): self.u1(*self.IE1) self.UIE1=self.u1(*self.IE1) # utility of the 1-st player at her initial endowment self.UIE2=self.u2(*self.IE2) # utility of the 2-nd player at her initial endowment self.u_ie_1=lambda x: root(lambda y: self.u1(x,y)-self.UIE1,self.Y[0],self.Y[-1]) # utility function at initial endowment of the 1-st participant self.u_ie_2=lambda x: root(lambda y: self.u2(x,y)-self.UIE2,self.Y[0],self.Y[-1]) # utility function at initial endowment of the 2-nd participant self.u_ie_2_compl=lambda x: -self.u_ie_2(self.IE[0]-x)+self.IE[1] # utility function at initial endowment of the 2-nd participant in terms of the 1-st U1 = list(map(lambda x: correct(x,f_None(self.u_ie_1,x),self.u1,self.UIE1),self.X)) U2 = list(map(lambda x: correct(x,f_None(self.u_ie_2_compl,x),self.u2_compl,self.UIE2),self.X)) self.U1 = list(filter(lambda x: x[0] is not None and x[1] is not None,zip(self.X,U1))) self.U2 = list(filter(lambda x: x[0] is not None and x[1] is not None,zip(self.X,U2))) U1_sort = sorted(self.U1,key=lambda x: x[1]) U2_sort = sorted(self.U2,key=lambda x: x[1]) if len(U1_sort)>0: self.U1_min=U1_sort[0] self.U1_max=U1_sort[-1] else: self.U1_min=None self.U1_max=None if len(U2_sort)>0: self.U2_min=U2_sort[0] self.U2_max=U2_sort[-1] else: self.U2_min=None self.U2_max=None self._B=lambda x,y,p: y-(p*(self.IE1[0]-x)+self.IE1[1]) # budget constraint def calc_pareto(self): self.MRS1=MRS(self.u1) # marginal rate of substitution of the 1st participant self.MRS2=MRS(self.u2) # marginal rate of substitution of the 2nd participant self._pareto=lambda x: root(lambda y: _(self.MRS1,x,y)-_(self.MRS2,self.IE[0]-x,self.IE[1]-y),self.Y[0],self.Y[-1]) # Pareto solutions in functional form P = list(map(lambda x: f_None(self._pareto,x),self.X[1:-1])) self.PARETO=list(zip(self.X[1:-1],P)) # set of some Pareto solution points (enough to draw it) self._Bx=lambda x: root(lambda y: self._B(x,y,self.MRS1(x,y)),self.Y[0],self.Y[-1]) #plot_pareto,=plt.plot(X,P,linewidth=2) PU1_X=root(lambda x: _(self._pareto,x)-_(self.u_ie_1,x),self.U1_min[0],self.U1_max[0]) PU2_X=root(lambda x: _(self._pareto,x)-_(self.u_ie_2_compl,x),self.U2_min[0],self.U2_max[0]) PU1_Y=self.u_ie_1(PU1_X) PU2_Y=self.u_ie_2_compl(PU2_X) self.PU1=[PU1_X,PU1_Y] self.PU2=[PU2_X,PU2_Y] self._Bx=lambda x: root(lambda y: _(self._B,x,y,_(self.MRS1,x,y)),self.Y[0],self.Y[-1]) def calc_core(self): CORE_X = list(filter(lambda x: x>=self.PU1[0] and x<=self.PU2[0], self.X)) CORE_Y = list(map(lambda x: self._pareto(x), CORE_X)) self.CORE = list(zip(CORE_X,CORE_Y)) # set of some solutions in the core (could be one, could be many or none) def calc_eq(self): EQ_X1=root(lambda x: _(self._pareto,x)-_(self._Bx,x),self.PU1[0],self.PU2[0]) EQ_Y1=self._pareto(EQ_X1) EQ_X2=self.IE[0]-EQ_X1 EQ_Y2=self.IE[1]-EQ_Y1 self.EQ1=[EQ_X1,EQ_Y1] # equilibrium solution for the 1st participant self.EQ2=[EQ_X2,EQ_Y2] # equilibrium solution for the 2nd participant self.p=self.MRS1(*self.EQ1) # price vector self.p_weighted=[self.p/(self.p+1),1/(self.p+1)] self.UEQ1=self.u1(*self.EQ1) # value of utility function of the 1st participant at her equilibrium point (functional form) self.UEQ2=self.u2(*self.EQ2) # value of utility function of the 2nd participant at her equilibrium point (functional form) self.u_eq_1=lambda x: root(lambda y: self.u1(x,y)-self.UEQ1,self.Y[0],self.Y[-1]) self.u_eq_2=lambda x: root(lambda y: self.u2(x,y)-self.UEQ2,self.Y[0],self.Y[-1]) self.u_eq_2_compl=lambda x: -self.u_eq_2(self.IE[0]-x)+self.IE[1] U1_EQ = list(map(lambda x: correct(x,f_None(self.u_eq_1,x),self.u1,self.UEQ1),self.X)) U2_EQ = list(map(lambda x: correct(x,f_None(self.u_eq_2_compl,x),self.u2_compl,self.UEQ2),self.X)) self.U1_EQ = list(filter(lambda x: x[0] is not None and x[1] is not None,zip(self.X,U1_EQ))) self.U2_EQ = list(filter(lambda x: x[0] is not None and x[1] is not None,zip(self.X,U2_EQ))) def calc_budget(self,price=None): if price is None: price=self.p self.Bp=lambda x: price*self.IE1[0]+self.IE1[1]-price*x # budget line (functional form) Budget = list(map(self.Bp,self.X)) # set of some points from the budget line self.BUDGET = list(zip(self.X,Budget)) def plot(self,fname=None): plot_endow,=plt.plot(self.IE1[0],self.IE1[1],color="white",marker="o") m=max(self.IE[0],self.IE[1]) plt.axis([0,m,0,m],autoscale=False) plot_U1,=plt.plot(*unpack(self.U1),color="blue") plot_U2,=plt.plot(*unpack(self.U2),color="brown") plot_pareto,=plt.plot(*unpack(self.PARETO),linewidth=2,color="red") plot_core,=plt.plot(*unpack(self.CORE),color="black",linewidth=4) plot_U1_EQ,=plt.plot(*unpack(self.U1_EQ),ls='--',color="blue") plot_U2_EQ,=plt.plot(*unpack(self.U2_EQ),ls='--',color="brown") plot_budget,=plt.plot(*unpack(self.BUDGET),color="green") plt.plot(self.PU1[0],self.PU1[1],color="blue",marker="o") plt.plot(self.PU2[0],self.PU2[1],color="brown",marker="o") plot_walras,=plt.plot(self.EQ1[0],self.EQ1[1],color="green",marker="o") # annotation plt.annotate("(%s;%s)"%(round(self.EQ1[0],2),round(self.EQ1[1],2)), xy=self.EQ1, xytext=(self.EQ1[0]+self.dt,self.EQ1[1]-self.dt)) plt.title("Edgeworth Box") plt.legend([plot_pareto,plot_U1,plot_U2,plot_endow,plot_core,plot_walras,plot_budget,plot_U1_EQ,plot_U2_EQ] ,["Pareto","U1 before trade","U2 before trade","Init. endow.","Core","Equilibrium","Budget constraint","U1 at eq.","U2 at eq."]) #Axes Dscription plt.xlabel("Units of 1-st good") plt.ylabel("Units of 2-nd good") if fname is not None: plt.savefig(fname) plt.close() else: plt.show(block=False)
[ "matplotlib.pyplot.title", "matplotlib.pyplot.savefig", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "scipy.optimize.fminbound", "math.copysign", "scipy.optimize.brenth", "numpy.linspace", "matplotlib.pyplot.close", "matplotlib.pyp...
[((2562, 2614), 'scipy.optimize.fmin_l_bfgs_b', 'fmin_l_bfgs_b', ([], {'func': 'f', 'x0': '((a + b) / 2)', 'bounds': '[a, b]'}), '(func=f, x0=(a + b) / 2, bounds=[a, b])\n', (2575, 2614), False, 'from scipy.optimize import fsolve, fmin_l_bfgs_b, fmin_cg, fminbound\n'), ((280, 294), 'math.copysign', 'copysign', (['(1)', 'x'], {}), '(1, x)\n', (288, 294), False, 'from math import sqrt, copysign\n'), ((2376, 2391), 'scipy.optimize.brenth', 'brenth', (['f', 'a', 'b'], {}), '(f, a, b)\n', (2382, 2391), False, 'from scipy.optimize import brenth\n'), ((2497, 2534), 'scipy.optimize.fmin_cg', 'fmin_cg', (['f', '((a + b) / 2.0)'], {'disp': '(False)'}), '(f, (a + b) / 2.0, disp=False)\n', (2504, 2534), False, 'from scipy.optimize import fsolve, fmin_l_bfgs_b, fmin_cg, fminbound\n'), ((3836, 3885), 'numpy.linspace', 'np.linspace', (['self.dt', '(self.IE[0] - self.dt)', 'EBP.N'], {}), '(self.dt, self.IE[0] - self.dt, EBP.N)\n', (3847, 3885), True, 'import numpy as np\n'), ((3897, 3946), 'numpy.linspace', 'np.linspace', (['self.dt', '(self.IE[1] - self.dt)', 'EBP.N'], {}), '(self.dt, self.IE[1] - self.dt, EBP.N)\n', (3908, 3946), True, 'import numpy as np\n'), ((9056, 9117), 'matplotlib.pyplot.plot', 'plt.plot', (['self.IE1[0]', 'self.IE1[1]'], {'color': '"""white"""', 'marker': '"""o"""'}), "(self.IE1[0], self.IE1[1], color='white', marker='o')\n", (9064, 9117), True, 'import matplotlib.pyplot as plt\n'), ((9160, 9199), 'matplotlib.pyplot.axis', 'plt.axis', (['[0, m, 0, m]'], {'autoscale': '(False)'}), '([0, m, 0, m], autoscale=False)\n', (9168, 9199), True, 'import matplotlib.pyplot as plt\n'), ((9696, 9756), 'matplotlib.pyplot.plot', 'plt.plot', (['self.PU1[0]', 'self.PU1[1]'], {'color': '"""blue"""', 'marker': '"""o"""'}), "(self.PU1[0], self.PU1[1], color='blue', marker='o')\n", (9704, 9756), True, 'import matplotlib.pyplot as plt\n'), ((9762, 9823), 'matplotlib.pyplot.plot', 'plt.plot', (['self.PU2[0]', 'self.PU2[1]'], {'color': '"""brown"""', 'marker': '"""o"""'}), "(self.PU2[0], self.PU2[1], color='brown', marker='o')\n", (9770, 9823), True, 'import matplotlib.pyplot as plt\n'), ((9842, 9903), 'matplotlib.pyplot.plot', 'plt.plot', (['self.EQ1[0]', 'self.EQ1[1]'], {'color': '"""green"""', 'marker': '"""o"""'}), "(self.EQ1[0], self.EQ1[1], color='green', marker='o')\n", (9850, 9903), True, 'import matplotlib.pyplot as plt\n'), ((10071, 10097), 'matplotlib.pyplot.title', 'plt.title', (['"""Edgeworth Box"""'], {}), "('Edgeworth Box')\n", (10080, 10097), True, 'import matplotlib.pyplot as plt\n'), ((10106, 10370), 'matplotlib.pyplot.legend', 'plt.legend', (['[plot_pareto, plot_U1, plot_U2, plot_endow, plot_core, plot_walras,\n plot_budget, plot_U1_EQ, plot_U2_EQ]', "['Pareto', 'U1 before trade', 'U2 before trade', 'Init. endow.', 'Core',\n 'Equilibrium', 'Budget constraint', 'U1 at eq.', 'U2 at eq.']"], {}), "([plot_pareto, plot_U1, plot_U2, plot_endow, plot_core,\n plot_walras, plot_budget, plot_U1_EQ, plot_U2_EQ], ['Pareto',\n 'U1 before trade', 'U2 before trade', 'Init. endow.', 'Core',\n 'Equilibrium', 'Budget constraint', 'U1 at eq.', 'U2 at eq.'])\n", (10116, 10370), True, 'import matplotlib.pyplot as plt\n'), ((10395, 10427), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Units of 1-st good"""'], {}), "('Units of 1-st good')\n", (10405, 10427), True, 'import matplotlib.pyplot as plt\n'), ((10436, 10468), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Units of 2-nd good"""'], {}), "('Units of 2-nd good')\n", (10446, 10468), True, 'import matplotlib.pyplot as plt\n'), ((1861, 1876), 'scipy.optimize.brenth', 'brenth', (['f', 'a', 'b'], {}), '(f, a, b)\n', (1867, 1876), False, 'from scipy.optimize import brenth\n'), ((2428, 2456), 'scipy.optimize.fminbound', 'fminbound', (['f', 'a_init', 'b_init'], {}), '(f, a_init, b_init)\n', (2437, 2456), False, 'from scipy.optimize import fsolve, fmin_l_bfgs_b, fmin_cg, fminbound\n'), ((10511, 10529), 'matplotlib.pyplot.savefig', 'plt.savefig', (['fname'], {}), '(fname)\n', (10522, 10529), True, 'import matplotlib.pyplot as plt\n'), ((10542, 10553), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (10551, 10553), True, 'import matplotlib.pyplot as plt\n'), ((10580, 10601), 'matplotlib.pyplot.show', 'plt.show', ([], {'block': '(False)'}), '(block=False)\n', (10588, 10601), True, 'import matplotlib.pyplot as plt\n')]
# -*- coding: utf-8 -*- """ Created on Thu Mar 5 08:14:54 2020 @author: Tom """ import ecm import numpy as np import matplotlib.pyplot as plt import os from sklearn.preprocessing import StandardScaler import scipy import pandas as pd from matplotlib import cm import configparser # Turn off code warnings (this is not recommended for routine use) import warnings warnings.filterwarnings("ignore") root = 'D:\\pybamm_pnm_results\\Chen2020_v3' save_im_path = 'D:\\pybamm_pnm_results\\figures' exp_root = 'D:\\pybamm_pnm_results\\experimental' exp_files = ['MJ1_0.5C.csv', 'MJ1_1.0C.csv', 'MJ1_1.5C.csv'] base = 'pybamm_pnm_case' plt.close('all') savefigs = False tab_1 = [0, 1, 2, 3, 4] tab_2 = [5, 6, 7, 8, 9] tab_5 = [10, 11, 12, 13, 14] tab_2_third = [15, 16, 17, 18, 19] tab_1_2 = [20, 21, 22, 23, 24] amps = ecm.get_amp_cases() d = ecm.load_all_data() cases = ecm.get_cases() #soc_list=[[0.9, 0.8, 0.7],[0.6, 0.5, 0.4],[0.3, 0.2, 0.1]] #mini_soc_list=[[0.99, 0.98, 0.97],[0.96, 0.95, 0.94],[0.93, 0.92, 0.91]] soc_list = [[0.9, 0.5, 0.4], [0.3, 0.2, 0.1]] mini_soc_list = [[0.09, 0.08], [0.07, 0.06]] grp = 'neg' data = d[0][5.25][0]['data'] def load_experimental(): data_list = [] for ef in exp_files: fp = os.path.join(exp_root, ef) data_list.append(pd.read_csv(fp)) return data_list def get_cases(): cases = [ '1_Chen2020', '2_Chen2020', '5_Chen2020', '3_Chen2020', '4_Chen2020', '1_Chen2020c', '2_Chen2020c', '5_Chen2020c', '3_Chen2020c', '4_Chen2020c', '1_Chen2020b', '2_Chen2020b', '5_Chen2020b', '3_Chen2020b', '4_Chen2020b', '1_Chen2020_third', '2_Chen2020_third', '5_Chen2020_third', '3_Chen2020_third', '4_Chen2020_third', ] full = [base + case for case in cases] cases = { 0: {'file': full[0], 'htc': 5, 'tabs': 1}, 1: {'file': full[1], 'htc': 10, 'tabs': 1}, 2: {'file': full[2], 'htc': 28, 'tabs': 1}, 3: {'file': full[3], 'htc': 50, 'tabs': 1}, 4: {'file': full[4], 'htc': 100, 'tabs': 1}, 5: {'file': full[5], 'htc': 5, 'tabs': 2}, 6: {'file': full[6], 'htc': 10, 'tabs': 2}, 7: {'file': full[7], 'htc': 28, 'tabs': 2}, 8: {'file': full[8], 'htc': 50, 'tabs': 2}, 9: {'file': full[9], 'htc': 100, 'tabs': 2}, 10: {'file': full[10], 'htc': 5, 'tabs': 5}, 11: {'file': full[11], 'htc': 10, 'tabs': 5}, 12: {'file': full[12], 'htc': 28, 'tabs': 5}, 13: {'file': full[13], 'htc': 50, 'tabs': 5}, 14: {'file': full[14], 'htc': 100, 'tabs': 5}, 15: {'file': full[15], 'htc': 5, 'tabs': 1}, 16: {'file': full[16], 'htc': 10, 'tabs': 1}, 17: {'file': full[17], 'htc': 28, 'tabs': 1}, 18: {'file': full[18], 'htc': 50, 'tabs': 1}, 19: {'file': full[19], 'htc': 100, 'tabs': 1}, } return cases def get_case_details(key): cases = get_cases() return cases[key]['htc'], cases[key]['tabs'] def abc(x): alphabet = np.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']) return alphabet[x].upper() def format_case(x, a, expanded=False, print_amps=True): htc, tabs = get_case_details(x) if expanded: text = ('Case ' + abc(x) + ': h=' + str(htc) + ' [W.m-2.K-1] #tabs=' + str(tabs).capitalize() + ': I=' + str(a) + ' [A]') else: if print_amps: text = 'Case ' + abc(x) + ': I=' + str(a) + ' [A]' else: text = 'Case ' + abc(x) return text def load_all_data(): config = configparser.ConfigParser() net = ecm.get_net() weights = ecm.get_weights(net) cases = get_cases() amps = ecm.get_amp_cases() variables = ecm.get_saved_var_names() data = {} for ci in range(len(cases.keys())): case_folder = os.path.join(root, cases[ci]['file']) data[ci] = {} config.read(os.path.join(case_folder, 'config.txt')) data[ci]['config'] = ecm.config2dict(config) for amp in amps: amp_folder = os.path.join(case_folder, str(amp) + 'A') data[ci][amp] = {} for vi, v in enumerate(variables): data[ci][amp][vi] = {} temp = ecm.load_and_amalgamate(amp_folder, v) if temp is not None: if vi == 0: check_nans = np.any(np.isnan(temp), axis=1) if np.any(check_nans): print('Nans removed from', amp_folder) if np.any(check_nans): temp = temp[~check_nans, :] data[ci][amp][vi]['data'] = temp means = np.zeros(temp.shape[0]) for t in range(temp.shape[0]): (mean, std_dev) = ecm.weighted_avg_and_std(temp[t, :], weights) means[t] = mean data[ci][amp][vi]['mean'] = means data[ci][amp][vi]['min'] = np.min(temp, axis=1) data[ci][amp][vi]['max'] = np.max(temp, axis=1) if temp is not None: t_hrs = data[ci][amp][10]['data'][:, 0] cap = t_hrs * amp data[ci][amp]['capacity'] = cap return data def jellyroll_one_plot(data, title, dp=3): input_dir = ecm.INPUT_DIR fig, ax = plt.subplots(figsize=(12, 12)) spm_map = np.load(os.path.join(input_dir, 'im_spm_map.npz'))['arr_0'] spm_map_copy = spm_map.copy() spm_map_copy[np.isnan(spm_map_copy)] = -1 spm_map_copy = spm_map_copy.astype(int) mask = np.isnan(spm_map) arr = np.ones_like(spm_map).astype(float) arr[~mask] = data[spm_map_copy][~mask] arr[mask] = np.nan im = ax.imshow(arr, cmap=cm.inferno) ax.set_axis_off() plt.colorbar(im, ax=ax, format='%.' + str(dp) + 'f') ax.set_title(title) return fig def find_best_fit(y, report_results=False): # Set up list of candidate distributions to use # See https://docs.scipy.org/doc/scipy/reference/stats.html for more #y = data_spm.copy() size = len(y) dist_names = ['norm', 'gumbel_l', 'gumbel_r'] # Set up empty lists to stroe results chi_square = [] p_values = [] params = [] sc = StandardScaler() yy = y.reshape(-1, 1) sc.fit(yy) y_std = sc.transform(yy) y_std = y_std.flatten() # Set up 50 bins for chi-square test # Observed data will be approximately evenly distrubuted aross all bins percentile_bins = np.linspace(0, 100, 51) percentile_cutoffs = np.percentile(y_std, percentile_bins) observed_frequency, bins = (np.histogram(y_std, bins=percentile_cutoffs)) cum_observed_frequency = np.cumsum(observed_frequency) # Loop through candidate distributions for distribution in dist_names: # Set up distribution and get fitted distribution parameters dist = getattr(scipy.stats, distribution) param = dist.fit(y_std) params.append(param) # Obtain the KS test P statistic, round it to 5 decimal places p = scipy.stats.kstest(y_std, distribution, args=param)[1] p = np.around(p, 5) p_values.append(p) # Get expected counts in percentile bins # This is based on a 'cumulative distrubution function' (cdf) cdf_fitted = dist.cdf(percentile_cutoffs, *param[:-2], loc=param[-2], scale=param[-1]) expected_frequency = [] for bin in range(len(percentile_bins) - 1): expected_cdf_area = cdf_fitted[bin + 1] - cdf_fitted[bin] expected_frequency.append(expected_cdf_area) # calculate chi-squared expected_frequency = np.array(expected_frequency) * size cum_expected_frequency = np.cumsum(expected_frequency) ss = sum(((cum_expected_frequency - cum_observed_frequency) ** 2) / cum_observed_frequency) chi_square.append(ss) # Collate results and sort by goodness of fit (best at top) results = pd.DataFrame() results['Distribution'] = dist_names results['chi_square'] = chi_square results['p_value'] = p_values results.sort_values(['chi_square'], inplace=True) # Report results if report_results: print('\nDistributions sorted by goodness of fit:') print('----------------------------------------') print(results) best_dist_name = results.values[0][0] best_chi_square = results.values[0][1] dist = getattr(scipy.stats, best_dist_name) args = dist.fit(y) return (best_dist_name, best_chi_square, dist, args, dist.mean(*args), dist.std(*args)) # Base Case 5.25 Amps - HTC 28 - 1 Tab fig1 = ecm.jellyroll_subplot(d, 2, amps[-1], var=0, soc_list=soc_list, global_range=False, dp=1) if savefigs: plt.savefig(os.path.join(save_im_path, 'fig1.png'), dpi=600) # Base Case all Amps - HTC 28 - 2 Tabs fig2 = ecm.multi_var_subplot(d, [0], amps, [2, 0], landscape=False) if savefigs: plt.savefig(os.path.join(save_im_path, 'fig2.png'), dpi=600) # All HTC cases - 1 tabs, 10 A fig3 = ecm.multi_var_subplot(d, tab_1, [amps[-1]], [0, 1]) if savefigs: plt.savefig(os.path.join(save_im_path, 'fig3.png'), dpi=600) # 2nd Case 5.25 Amps - HTC 100 - 2 Tab fig4 = ecm.jellyroll_subplot(d, 7, amps[-1], var=0, soc_list=soc_list, global_range=False, dp=1) if savefigs: plt.savefig(os.path.join(save_im_path, 'fig4.png'), dpi=600) # 3rd Case 5.25 Amps - HTC 100 - 5 Tab fig5 = ecm.jellyroll_subplot(d, 12, amps[-1], var=0, soc_list=soc_list, global_range=False, dp=1) if savefigs: plt.savefig(os.path.join(save_im_path, 'fig5.png'), dpi=600) # All Tabs, all currents HTC 5 fig6 = ecm.spacetime(d, [0, 5, 10], amps, var=0, group=grp, normed=True) if savefigs: plt.savefig(os.path.join(save_im_path, 'fig6.png'), dpi=600) # All Tabs, highest currents HTC 5 fig7 = ecm.multi_var_subplot(d, [0, 5, 10], [amps[-1]], [0, 1]) if savefigs: plt.savefig(os.path.join(save_im_path, 'fig7.png'), dpi=600) # All Tabs, highest currents HTC 100 fig8 = ecm.multi_var_subplot(d, [4, 9, 14], [amps[-1]], [0, 1]) if savefigs: plt.savefig(os.path.join(save_im_path, 'fig8.png'), dpi=600) # All Tabs, all currents HTC 5 fig9a = ecm.spacetime(d, [0, 5, 10], amps, var=0, group=grp, normed=True) if savefigs: plt.savefig(os.path.join(save_im_path, 'fig9a.png'), dpi=600) fig9b = ecm.chargeogram(d, [0, 5, 10], amps, group=grp) if savefigs: plt.savefig(os.path.join(save_im_path, 'fig9b.png'), dpi=600) # All Tabs, all currents HTC 100 fig10a = ecm.spacetime(d, [4, 9, 14], amps, var=0, group=grp, normed=True) if savefigs: plt.savefig(os.path.join(save_im_path, 'fig10a.png'), dpi=600) fig10b = ecm.chargeogram(d, [4, 9, 14], amps, group=grp) if savefigs: plt.savefig(os.path.join(save_im_path, 'fig10b.png'), dpi=600) fig11a = ecm.spacetime(d, [9, 17, 19], amps, var=0, group=grp, normed=True) if savefigs: plt.savefig(os.path.join(save_im_path, 'fig11a.png'), dpi=600) fig11b = ecm.chargeogram(d, [9, 17, 19], amps, group=grp) if savefigs: plt.savefig(os.path.join(save_im_path, 'fig11b.png'), dpi=600) # Third Heating fig12 = ecm.jellyroll_subplot(d, 19, 5.25, var=0, soc_list=soc_list, global_range=False) if savefigs: plt.savefig(os.path.join(save_im_path, 'fig12.png'), dpi=600) fig13 = jellyroll_one_plot(d[19][5.25][1]['data'][-1, :], 'Temperature [K] with uneven cooling\n' + ecm.format_case(19, 5.25, True)) if savefigs: plt.savefig(os.path.join(save_im_path, 'fig13.png'), dpi=600) fig14 = ecm.multi_var_subplot(d, [2, 4, 17, 19], [5.25], [0, 1]) if savefigs: plt.savefig(os.path.join(save_im_path, 'fig14.png'), dpi=600) exp_data = ecm.load_experimental() #sim_data = [d[2][1.75], d[2][3.5], d[2][5.25]] fig, ax = plt.subplots() for i in range(3): ed = exp_data[i] sd = d[2][amps[i]] ax.scatter(ed['Q discharge [mA.h]'].values / 1000, ed['Temperature [K]'].values) ax.plot(sd['capacity'], sd[1]['mean'], label='I=' + str(amps[i]) + ' [A]') ax.set_xlabel('Capacity [Ah]') ax.set_ylabel('Temperature [K]') plt.legend() if savefigs: plt.savefig(os.path.join(save_im_path, 'figX.png'), dpi=600) figY = ecm.jellyroll_subplot(d, 19, 5.25, var=1, soc_list=[[0.9, 0.7], [0.5, 0.3]], global_range=False, dp=1) if savefigs: plt.savefig(os.path.join(save_im_path, 'figY.png'), dpi=600)
[ "configparser.ConfigParser", "pandas.read_csv", "ecm.get_amp_cases", "ecm.get_weights", "numpy.array", "ecm.weighted_avg_and_std", "numpy.cumsum", "ecm.config2dict", "ecm.load_and_amalgamate", "numpy.histogram", "ecm.chargeogram", "ecm.get_net", "ecm.get_cases", "matplotlib.pyplot.close", ...
[((367, 400), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (390, 400), False, 'import warnings\n'), ((660, 676), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (669, 676), True, 'import matplotlib.pyplot as plt\n'), ((848, 867), 'ecm.get_amp_cases', 'ecm.get_amp_cases', ([], {}), '()\n', (865, 867), False, 'import ecm\n'), ((872, 891), 'ecm.load_all_data', 'ecm.load_all_data', ([], {}), '()\n', (889, 891), False, 'import ecm\n'), ((900, 915), 'ecm.get_cases', 'ecm.get_cases', ([], {}), '()\n', (913, 915), False, 'import ecm\n'), ((9147, 9240), 'ecm.jellyroll_subplot', 'ecm.jellyroll_subplot', (['d', '(2)', 'amps[-1]'], {'var': '(0)', 'soc_list': 'soc_list', 'global_range': '(False)', 'dp': '(1)'}), '(d, 2, amps[-1], var=0, soc_list=soc_list,\n global_range=False, dp=1)\n', (9168, 9240), False, 'import ecm\n'), ((9390, 9450), 'ecm.multi_var_subplot', 'ecm.multi_var_subplot', (['d', '[0]', 'amps', '[2, 0]'], {'landscape': '(False)'}), '(d, [0], amps, [2, 0], landscape=False)\n', (9411, 9450), False, 'import ecm\n'), ((9567, 9618), 'ecm.multi_var_subplot', 'ecm.multi_var_subplot', (['d', 'tab_1', '[amps[-1]]', '[0, 1]'], {}), '(d, tab_1, [amps[-1]], [0, 1])\n', (9588, 9618), False, 'import ecm\n'), ((9743, 9836), 'ecm.jellyroll_subplot', 'ecm.jellyroll_subplot', (['d', '(7)', 'amps[-1]'], {'var': '(0)', 'soc_list': 'soc_list', 'global_range': '(False)', 'dp': '(1)'}), '(d, 7, amps[-1], var=0, soc_list=soc_list,\n global_range=False, dp=1)\n', (9764, 9836), False, 'import ecm\n'), ((9986, 10080), 'ecm.jellyroll_subplot', 'ecm.jellyroll_subplot', (['d', '(12)', 'amps[-1]'], {'var': '(0)', 'soc_list': 'soc_list', 'global_range': '(False)', 'dp': '(1)'}), '(d, 12, amps[-1], var=0, soc_list=soc_list,\n global_range=False, dp=1)\n', (10007, 10080), False, 'import ecm\n'), ((10222, 10287), 'ecm.spacetime', 'ecm.spacetime', (['d', '[0, 5, 10]', 'amps'], {'var': '(0)', 'group': 'grp', 'normed': '(True)'}), '(d, [0, 5, 10], amps, var=0, group=grp, normed=True)\n', (10235, 10287), False, 'import ecm\n'), ((10408, 10464), 'ecm.multi_var_subplot', 'ecm.multi_var_subplot', (['d', '[0, 5, 10]', '[amps[-1]]', '[0, 1]'], {}), '(d, [0, 5, 10], [amps[-1]], [0, 1])\n', (10429, 10464), False, 'import ecm\n'), ((10587, 10643), 'ecm.multi_var_subplot', 'ecm.multi_var_subplot', (['d', '[4, 9, 14]', '[amps[-1]]', '[0, 1]'], {}), '(d, [4, 9, 14], [amps[-1]], [0, 1])\n', (10608, 10643), False, 'import ecm\n'), ((10761, 10826), 'ecm.spacetime', 'ecm.spacetime', (['d', '[0, 5, 10]', 'amps'], {'var': '(0)', 'group': 'grp', 'normed': '(True)'}), '(d, [0, 5, 10], amps, var=0, group=grp, normed=True)\n', (10774, 10826), False, 'import ecm\n'), ((10914, 10961), 'ecm.chargeogram', 'ecm.chargeogram', (['d', '[0, 5, 10]', 'amps'], {'group': 'grp'}), '(d, [0, 5, 10], amps, group=grp)\n', (10929, 10961), False, 'import ecm\n'), ((11083, 11148), 'ecm.spacetime', 'ecm.spacetime', (['d', '[4, 9, 14]', 'amps'], {'var': '(0)', 'group': 'grp', 'normed': '(True)'}), '(d, [4, 9, 14], amps, var=0, group=grp, normed=True)\n', (11096, 11148), False, 'import ecm\n'), ((11238, 11285), 'ecm.chargeogram', 'ecm.chargeogram', (['d', '[4, 9, 14]', 'amps'], {'group': 'grp'}), '(d, [4, 9, 14], amps, group=grp)\n', (11253, 11285), False, 'import ecm\n'), ((11375, 11441), 'ecm.spacetime', 'ecm.spacetime', (['d', '[9, 17, 19]', 'amps'], {'var': '(0)', 'group': 'grp', 'normed': '(True)'}), '(d, [9, 17, 19], amps, var=0, group=grp, normed=True)\n', (11388, 11441), False, 'import ecm\n'), ((11531, 11579), 'ecm.chargeogram', 'ecm.chargeogram', (['d', '[9, 17, 19]', 'amps'], {'group': 'grp'}), '(d, [9, 17, 19], amps, group=grp)\n', (11546, 11579), False, 'import ecm\n'), ((11684, 11769), 'ecm.jellyroll_subplot', 'ecm.jellyroll_subplot', (['d', '(19)', '(5.25)'], {'var': '(0)', 'soc_list': 'soc_list', 'global_range': '(False)'}), '(d, 19, 5.25, var=0, soc_list=soc_list, global_range=False\n )\n', (11705, 11769), False, 'import ecm\n'), ((12118, 12174), 'ecm.multi_var_subplot', 'ecm.multi_var_subplot', (['d', '[2, 4, 17, 19]', '[5.25]', '[0, 1]'], {}), '(d, [2, 4, 17, 19], [5.25], [0, 1])\n', (12139, 12174), False, 'import ecm\n'), ((12265, 12288), 'ecm.load_experimental', 'ecm.load_experimental', ([], {}), '()\n', (12286, 12288), False, 'import ecm\n'), ((12347, 12361), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (12359, 12361), True, 'import matplotlib.pyplot as plt\n'), ((12653, 12665), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (12663, 12665), True, 'import matplotlib.pyplot as plt\n'), ((12753, 12859), 'ecm.jellyroll_subplot', 'ecm.jellyroll_subplot', (['d', '(19)', '(5.25)'], {'var': '(1)', 'soc_list': '[[0.9, 0.7], [0.5, 0.3]]', 'global_range': '(False)', 'dp': '(1)'}), '(d, 19, 5.25, var=1, soc_list=[[0.9, 0.7], [0.5, 0.3]],\n global_range=False, dp=1)\n', (12774, 12859), False, 'import ecm\n'), ((3177, 3321), 'numpy.array', 'np.array', (["['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',\n 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']"], {}), "(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',\n 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'])\n", (3185, 3321), True, 'import numpy as np\n'), ((3954, 3981), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (3979, 3981), False, 'import configparser\n'), ((3992, 4005), 'ecm.get_net', 'ecm.get_net', ([], {}), '()\n', (4003, 4005), False, 'import ecm\n'), ((4020, 4040), 'ecm.get_weights', 'ecm.get_weights', (['net'], {}), '(net)\n', (4035, 4040), False, 'import ecm\n'), ((4076, 4095), 'ecm.get_amp_cases', 'ecm.get_amp_cases', ([], {}), '()\n', (4093, 4095), False, 'import ecm\n'), ((4112, 4137), 'ecm.get_saved_var_names', 'ecm.get_saved_var_names', ([], {}), '()\n', (4135, 4137), False, 'import ecm\n'), ((5755, 5785), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(12, 12)'}), '(figsize=(12, 12))\n', (5767, 5785), True, 'import matplotlib.pyplot as plt\n'), ((5995, 6012), 'numpy.isnan', 'np.isnan', (['spm_map'], {}), '(spm_map)\n', (6003, 6012), True, 'import numpy as np\n'), ((6691, 6707), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (6705, 6707), False, 'from sklearn.preprocessing import StandardScaler\n'), ((6946, 6969), 'numpy.linspace', 'np.linspace', (['(0)', '(100)', '(51)'], {}), '(0, 100, 51)\n', (6957, 6969), True, 'import numpy as np\n'), ((6995, 7032), 'numpy.percentile', 'np.percentile', (['y_std', 'percentile_bins'], {}), '(y_std, percentile_bins)\n', (7008, 7032), True, 'import numpy as np\n'), ((7065, 7109), 'numpy.histogram', 'np.histogram', (['y_std'], {'bins': 'percentile_cutoffs'}), '(y_std, bins=percentile_cutoffs)\n', (7077, 7109), True, 'import numpy as np\n'), ((7140, 7169), 'numpy.cumsum', 'np.cumsum', (['observed_frequency'], {}), '(observed_frequency)\n', (7149, 7169), True, 'import numpy as np\n'), ((8470, 8484), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (8482, 8484), True, 'import pandas as pd\n'), ((1296, 1322), 'os.path.join', 'os.path.join', (['exp_root', 'ef'], {}), '(exp_root, ef)\n', (1308, 1322), False, 'import os\n'), ((4214, 4251), 'os.path.join', 'os.path.join', (['root', "cases[ci]['file']"], {}), "(root, cases[ci]['file'])\n", (4226, 4251), False, 'import os\n'), ((4364, 4387), 'ecm.config2dict', 'ecm.config2dict', (['config'], {}), '(config)\n', (4379, 4387), False, 'import ecm\n'), ((5911, 5933), 'numpy.isnan', 'np.isnan', (['spm_map_copy'], {}), '(spm_map_copy)\n', (5919, 5933), True, 'import numpy as np\n'), ((7581, 7596), 'numpy.around', 'np.around', (['p', '(5)'], {}), '(p, 5)\n', (7590, 7596), True, 'import numpy as np\n'), ((8211, 8240), 'numpy.cumsum', 'np.cumsum', (['expected_frequency'], {}), '(expected_frequency)\n', (8220, 8240), True, 'import numpy as np\n'), ((9295, 9333), 'os.path.join', 'os.path.join', (['save_im_path', '"""fig1.png"""'], {}), "(save_im_path, 'fig1.png')\n", (9307, 9333), False, 'import os\n'), ((9480, 9518), 'os.path.join', 'os.path.join', (['save_im_path', '"""fig2.png"""'], {}), "(save_im_path, 'fig2.png')\n", (9492, 9518), False, 'import os\n'), ((9648, 9686), 'os.path.join', 'os.path.join', (['save_im_path', '"""fig3.png"""'], {}), "(save_im_path, 'fig3.png')\n", (9660, 9686), False, 'import os\n'), ((9891, 9929), 'os.path.join', 'os.path.join', (['save_im_path', '"""fig4.png"""'], {}), "(save_im_path, 'fig4.png')\n", (9903, 9929), False, 'import os\n'), ((10135, 10173), 'os.path.join', 'os.path.join', (['save_im_path', '"""fig5.png"""'], {}), "(save_im_path, 'fig5.png')\n", (10147, 10173), False, 'import os\n'), ((10317, 10355), 'os.path.join', 'os.path.join', (['save_im_path', '"""fig6.png"""'], {}), "(save_im_path, 'fig6.png')\n", (10329, 10355), False, 'import os\n'), ((10494, 10532), 'os.path.join', 'os.path.join', (['save_im_path', '"""fig7.png"""'], {}), "(save_im_path, 'fig7.png')\n", (10506, 10532), False, 'import os\n'), ((10673, 10711), 'os.path.join', 'os.path.join', (['save_im_path', '"""fig8.png"""'], {}), "(save_im_path, 'fig8.png')\n", (10685, 10711), False, 'import os\n'), ((10856, 10895), 'os.path.join', 'os.path.join', (['save_im_path', '"""fig9a.png"""'], {}), "(save_im_path, 'fig9a.png')\n", (10868, 10895), False, 'import os\n'), ((10991, 11030), 'os.path.join', 'os.path.join', (['save_im_path', '"""fig9b.png"""'], {}), "(save_im_path, 'fig9b.png')\n", (11003, 11030), False, 'import os\n'), ((11178, 11218), 'os.path.join', 'os.path.join', (['save_im_path', '"""fig10a.png"""'], {}), "(save_im_path, 'fig10a.png')\n", (11190, 11218), False, 'import os\n'), ((11315, 11355), 'os.path.join', 'os.path.join', (['save_im_path', '"""fig10b.png"""'], {}), "(save_im_path, 'fig10b.png')\n", (11327, 11355), False, 'import os\n'), ((11471, 11511), 'os.path.join', 'os.path.join', (['save_im_path', '"""fig11a.png"""'], {}), "(save_im_path, 'fig11a.png')\n", (11483, 11511), False, 'import os\n'), ((11609, 11649), 'os.path.join', 'os.path.join', (['save_im_path', '"""fig11b.png"""'], {}), "(save_im_path, 'fig11b.png')\n", (11621, 11649), False, 'import os\n'), ((11794, 11833), 'os.path.join', 'os.path.join', (['save_im_path', '"""fig12.png"""'], {}), "(save_im_path, 'fig12.png')\n", (11806, 11833), False, 'import os\n'), ((11998, 12029), 'ecm.format_case', 'ecm.format_case', (['(19)', '(5.25)', '(True)'], {}), '(19, 5.25, True)\n', (12013, 12029), False, 'import ecm\n'), ((12060, 12099), 'os.path.join', 'os.path.join', (['save_im_path', '"""fig13.png"""'], {}), "(save_im_path, 'fig13.png')\n", (12072, 12099), False, 'import os\n'), ((12204, 12243), 'os.path.join', 'os.path.join', (['save_im_path', '"""fig14.png"""'], {}), "(save_im_path, 'fig14.png')\n", (12216, 12243), False, 'import os\n'), ((12696, 12734), 'os.path.join', 'os.path.join', (['save_im_path', '"""figX.png"""'], {}), "(save_im_path, 'figX.png')\n", (12708, 12734), False, 'import os\n'), ((12914, 12952), 'os.path.join', 'os.path.join', (['save_im_path', '"""figY.png"""'], {}), "(save_im_path, 'figY.png')\n", (12926, 12952), False, 'import os\n'), ((1348, 1363), 'pandas.read_csv', 'pd.read_csv', (['fp'], {}), '(fp)\n', (1359, 1363), True, 'import pandas as pd\n'), ((4294, 4333), 'os.path.join', 'os.path.join', (['case_folder', '"""config.txt"""'], {}), "(case_folder, 'config.txt')\n", (4306, 4333), False, 'import os\n'), ((5808, 5849), 'os.path.join', 'os.path.join', (['input_dir', '"""im_spm_map.npz"""'], {}), "(input_dir, 'im_spm_map.npz')\n", (5820, 5849), False, 'import os\n'), ((6023, 6044), 'numpy.ones_like', 'np.ones_like', (['spm_map'], {}), '(spm_map)\n', (6035, 6044), True, 'import numpy as np\n'), ((7514, 7565), 'scipy.stats.kstest', 'scipy.stats.kstest', (['y_std', 'distribution'], {'args': 'param'}), '(y_std, distribution, args=param)\n', (7532, 7565), False, 'import scipy\n'), ((8142, 8170), 'numpy.array', 'np.array', (['expected_frequency'], {}), '(expected_frequency)\n', (8150, 8170), True, 'import numpy as np\n'), ((4620, 4658), 'ecm.load_and_amalgamate', 'ecm.load_and_amalgamate', (['amp_folder', 'v'], {}), '(amp_folder, v)\n', (4643, 4658), False, 'import ecm\n'), ((4933, 4951), 'numpy.any', 'np.any', (['check_nans'], {}), '(check_nans)\n', (4939, 4951), True, 'import numpy as np\n'), ((5086, 5109), 'numpy.zeros', 'np.zeros', (['temp.shape[0]'], {}), '(temp.shape[0])\n', (5094, 5109), True, 'import numpy as np\n'), ((5390, 5410), 'numpy.min', 'np.min', (['temp'], {'axis': '(1)'}), '(temp, axis=1)\n', (5396, 5410), True, 'import numpy as np\n'), ((5458, 5478), 'numpy.max', 'np.max', (['temp'], {'axis': '(1)'}), '(temp, axis=1)\n', (5464, 5478), True, 'import numpy as np\n'), ((4823, 4841), 'numpy.any', 'np.any', (['check_nans'], {}), '(check_nans)\n', (4829, 4841), True, 'import numpy as np\n'), ((5203, 5248), 'ecm.weighted_avg_and_std', 'ecm.weighted_avg_and_std', (['temp[t, :]', 'weights'], {}), '(temp[t, :], weights)\n', (5227, 5248), False, 'import ecm\n'), ((4772, 4786), 'numpy.isnan', 'np.isnan', (['temp'], {}), '(temp)\n', (4780, 4786), True, 'import numpy as np\n')]
from typing import Dict, Tuple, Callable import cv2 import numpy as np import albumentations as albu from facial_attributes_parser.dataset import CelebAMaskHQDataset def visualization_transform(image: np.array, masks: Dict[int, np.array]) -> Tuple[np.array, np.array]: shape = 512, 512, 3 result_mask = np.zeros(shape, dtype=np.uint8) for cls_index, mask in masks.items(): result_mask[mask == 255] = CelebAMaskHQDataset.COLORS[cls_index] image = cv2.resize(image, result_mask.shape[:2]) return image, result_mask def inference_transform(image: np.array, masks: Dict[int, np.array]) -> Tuple[np.array, np.array]: image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # indices target (one-hotted in loss and metrics functions) result_mask = np.zeros((512, 512), dtype=np.long) for cls_index, mask in masks.items(): result_mask[mask == 255] = cls_index return image, result_mask def to_tensor(x: np.array, **kwargs) -> np.array: return x.transpose(2, 0, 1).astype(np.float32) def get_preprocessing(preprocessing_fn: Callable) -> albu.Compose: transform = [ albu.Lambda(image=preprocessing_fn), albu.Lambda(image=to_tensor), albu.Lambda(mask=lambda x, **kwargs: x.astype(np.long)), ] return albu.Compose(transform) def get_train_augmentations() -> albu.Compose: train_augs = [ albu.Resize(height=512, width=512, p=1), albu.OneOf( [ albu.CLAHE(p=1), albu.RandomBrightnessContrast(p=1), albu.RandomGamma(p=1), ], p=0.6, ), albu.GaussNoise(p=0.2), albu.OneOf( [ albu.Sharpen(p=1), albu.Blur(blur_limit=3, p=1), albu.MotionBlur(blur_limit=3, p=1), ], p=0.6, ), ] return albu.Compose(train_augs) def get_valid_augmentations() -> albu.Compose: valid_augs = [ albu.Resize(height=512, width=512, p=1), ] return albu.Compose(valid_augs)
[ "albumentations.CLAHE", "albumentations.RandomBrightnessContrast", "albumentations.Blur", "albumentations.GaussNoise", "albumentations.RandomGamma", "numpy.zeros", "albumentations.Compose", "albumentations.Resize", "cv2.cvtColor", "albumentations.MotionBlur", "cv2.resize", "albumentations.Shar...
[((315, 346), 'numpy.zeros', 'np.zeros', (['shape'], {'dtype': 'np.uint8'}), '(shape, dtype=np.uint8)\n', (323, 346), True, 'import numpy as np\n'), ((474, 514), 'cv2.resize', 'cv2.resize', (['image', 'result_mask.shape[:2]'], {}), '(image, result_mask.shape[:2])\n', (484, 514), False, 'import cv2\n'), ((658, 696), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2RGB'], {}), '(image, cv2.COLOR_BGR2RGB)\n', (670, 696), False, 'import cv2\n'), ((780, 815), 'numpy.zeros', 'np.zeros', (['(512, 512)'], {'dtype': 'np.long'}), '((512, 512), dtype=np.long)\n', (788, 815), True, 'import numpy as np\n'), ((1289, 1312), 'albumentations.Compose', 'albu.Compose', (['transform'], {}), '(transform)\n', (1301, 1312), True, 'import albumentations as albu\n'), ((1894, 1918), 'albumentations.Compose', 'albu.Compose', (['train_augs'], {}), '(train_augs)\n', (1906, 1918), True, 'import albumentations as albu\n'), ((2053, 2077), 'albumentations.Compose', 'albu.Compose', (['valid_augs'], {}), '(valid_augs)\n', (2065, 2077), True, 'import albumentations as albu\n'), ((1132, 1167), 'albumentations.Lambda', 'albu.Lambda', ([], {'image': 'preprocessing_fn'}), '(image=preprocessing_fn)\n', (1143, 1167), True, 'import albumentations as albu\n'), ((1177, 1205), 'albumentations.Lambda', 'albu.Lambda', ([], {'image': 'to_tensor'}), '(image=to_tensor)\n', (1188, 1205), True, 'import albumentations as albu\n'), ((1389, 1428), 'albumentations.Resize', 'albu.Resize', ([], {'height': '(512)', 'width': '(512)', 'p': '(1)'}), '(height=512, width=512, p=1)\n', (1400, 1428), True, 'import albumentations as albu\n'), ((1641, 1663), 'albumentations.GaussNoise', 'albu.GaussNoise', ([], {'p': '(0.2)'}), '(p=0.2)\n', (1656, 1663), True, 'import albumentations as albu\n'), ((1995, 2034), 'albumentations.Resize', 'albu.Resize', ([], {'height': '(512)', 'width': '(512)', 'p': '(1)'}), '(height=512, width=512, p=1)\n', (2006, 2034), True, 'import albumentations as albu\n'), ((1480, 1495), 'albumentations.CLAHE', 'albu.CLAHE', ([], {'p': '(1)'}), '(p=1)\n', (1490, 1495), True, 'import albumentations as albu\n'), ((1513, 1547), 'albumentations.RandomBrightnessContrast', 'albu.RandomBrightnessContrast', ([], {'p': '(1)'}), '(p=1)\n', (1542, 1547), True, 'import albumentations as albu\n'), ((1565, 1586), 'albumentations.RandomGamma', 'albu.RandomGamma', ([], {'p': '(1)'}), '(p=1)\n', (1581, 1586), True, 'import albumentations as albu\n'), ((1715, 1732), 'albumentations.Sharpen', 'albu.Sharpen', ([], {'p': '(1)'}), '(p=1)\n', (1727, 1732), True, 'import albumentations as albu\n'), ((1750, 1778), 'albumentations.Blur', 'albu.Blur', ([], {'blur_limit': '(3)', 'p': '(1)'}), '(blur_limit=3, p=1)\n', (1759, 1778), True, 'import albumentations as albu\n'), ((1796, 1830), 'albumentations.MotionBlur', 'albu.MotionBlur', ([], {'blur_limit': '(3)', 'p': '(1)'}), '(blur_limit=3, p=1)\n', (1811, 1830), True, 'import albumentations as albu\n')]
# -*- coding: utf-8 -*- """ Script to perform the harmonic analysis of the sea level This script reads the sea level (corrected) raw data to perform harmonic analysis and filtering of the water level. It saves the tidal reconstruction, the residual and the filtered sea level to a file. Must intall pytide conda install pytide -c conda-forge @author: mduranmatute """ import pandas as pd #%% Function to convert MATLAB's datenum to Python's datetime import datetime as dt def datenum_to_datetime(datenum): """ Convert Matlab datenum into Python datetime. :param datenum: Date in datenum format :return: Datetime object corresponding to datenum. """ days = datenum % 1 return dt.datetime.fromordinal(int(datenum)) \ + dt.timedelta(days=days) \ - dt.timedelta(days=366) # %% Load Data SL = pd.read_csv('data/raw_data/SL_DH_data.csv') time = list(map(datenum_to_datetime,SL.datenum)) level = SL.CorrectedSeaLevel[:]-694.6 years=[element.year for element in time] j2 = 473472 level[j2]=(level[j2-1]+level[j2+1])/2 # %% Perform harmonic analysis #import netCDF4 import pytide import numpy as np wt = pytide.WaveTable() #To test difference with t_tide these are the constituents with snr>10 for 2015 #wt = pytide.WaveTable(["O1", "P1", "K1", "Mu2", "N2", "Nu2", "M2", "L2", "S2", "K2", "MO3", "MN4", "M4", "MS4", "2MK6", "2MN6", "M6", "2MS6", "M8"]) hp = list() for year in np.unique(years): ind = np.nonzero(np.array(years) == year )[0] time_tmp = [time[i] for i in ind] level_tmp = [level[i] for i in ind] f, vu = wt.compute_nodal_modulations(time_tmp) # You can also use a list of datetime.datetime objects # wt.compute_nodal_modulations(list(time)) w = wt.harmonic_analysis(level_tmp, f, vu) time_ms = [element.timestamp()+3600 for element in time_tmp] hp = hp + list(wt.tide_from_tide_series(time_ms, w)+np.mean(level_tmp)) res = level - hp + 694.6 d = {'time': time, 'sea_level_0m': level + 694.6 , 'harmonic_rec': hp, 'residual': res} df = pd.DataFrame(data=d) # %% #import matplotlib.pyplot as plt #plt.plot(time[0:800],level[0:800]) #plt.plot(time[0:800],hp[0:800]) #plt.show() # %% filtering the tide from oceans.filters import lanc freq = 1./40/6 # Hours window_size = 6*(96+1+96) pad = np.zeros(window_size) * np.NaN win = lanc(window_size, freq) res = np.convolve(win, df['sea_level_0m']-694.6, mode='same') df['low'] = res + 694.6 df['high'] = df['sea_level_0m'] - df['low'] df['pandas_l'] = df['sea_level_0m'].rolling(window = 240, center=True, min_periods=1).mean() df['pandas_h'] = df['sea_level_0m'] - df['pandas_l'] # %% This part using iris uses too much memory #import iris #from iris.pandas import as_cube #cube = as_cube(df['sea_level']) #low = cube.rolling_window('index', # iris.analysis.SUM, # len(wt), # weights=wt) #df['iris_l'] = np.r_[pad, low.data, pad] #df['iris_h'] = df['sea_level'] - df['iris_l'] # %% df.to_csv('data/SL_DH_decomposed.csv')
[ "numpy.mean", "numpy.convolve", "numpy.unique", "pandas.read_csv", "numpy.array", "numpy.zeros", "pandas.DataFrame", "datetime.timedelta", "pytide.WaveTable", "oceans.filters.lanc" ]
[((863, 906), 'pandas.read_csv', 'pd.read_csv', (['"""data/raw_data/SL_DH_data.csv"""'], {}), "('data/raw_data/SL_DH_data.csv')\n", (874, 906), True, 'import pandas as pd\n'), ((1182, 1200), 'pytide.WaveTable', 'pytide.WaveTable', ([], {}), '()\n', (1198, 1200), False, 'import pytide\n'), ((1459, 1475), 'numpy.unique', 'np.unique', (['years'], {}), '(years)\n', (1468, 1475), True, 'import numpy as np\n'), ((2082, 2102), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'd'}), '(data=d)\n', (2094, 2102), True, 'import pandas as pd\n'), ((2380, 2403), 'oceans.filters.lanc', 'lanc', (['window_size', 'freq'], {}), '(window_size, freq)\n', (2384, 2403), False, 'from oceans.filters import lanc\n'), ((2410, 2467), 'numpy.convolve', 'np.convolve', (['win', "(df['sea_level_0m'] - 694.6)"], {'mode': '"""same"""'}), "(win, df['sea_level_0m'] - 694.6, mode='same')\n", (2421, 2467), True, 'import numpy as np\n'), ((2342, 2363), 'numpy.zeros', 'np.zeros', (['window_size'], {}), '(window_size)\n', (2350, 2363), True, 'import numpy as np\n'), ((817, 839), 'datetime.timedelta', 'dt.timedelta', ([], {'days': '(366)'}), '(days=366)\n', (829, 839), True, 'import datetime as dt\n'), ((778, 801), 'datetime.timedelta', 'dt.timedelta', ([], {'days': 'days'}), '(days=days)\n', (790, 801), True, 'import datetime as dt\n'), ((1499, 1514), 'numpy.array', 'np.array', (['years'], {}), '(years)\n', (1507, 1514), True, 'import numpy as np\n'), ((1936, 1954), 'numpy.mean', 'np.mean', (['level_tmp'], {}), '(level_tmp)\n', (1943, 1954), True, 'import numpy as np\n')]
# Routine to calibrate the image frames of Halpha for estimation of # absolute flux of net emission line by using line and continuum image # frames of standard objects and program objects. import os.path import numpy as np from scipy import interpolate from scipy.optimize import curve_fit import matplotlib.pyplot as plt from scipy import integrate from scipy.interpolate import InterpolatedUnivariateSpline def readfile(filename): ''' Reads a file. Input: Filename. Returns: x, y, xmin, xmax, number of points, filename. ''' if os.path.isfile(filename) != True: print("File not in this directory!") else: file = np.loadtxt(filename, unpack=True) x = file[0] y = file[1] xmax = np.amax(x) xmin = np.amin(x) npts = len(file[0]) return(x, y, xmin, xmax, npts, filename) def obsWavelength(x, vel): ''' Corrects for systemic velocity. Input: Rest wavelength and velocity in km/s. Output: Observed wavelengh. ''' c = 299792.458 z = vel / c lambda_obs = x * (1 + z) return lambda_obs def interp(x, y): ''' Interpolates a function fitting a spline y = spl(x). Input: x, y (arrays). Output: Interpolated function. ''' f = InterpolatedUnivariateSpline(x, y) return f def integral(func, a, b): ''' Method of InterpolatedUnivariateSpline to calculate the integral of the interpolated function. Input: Function to be integrated and interval. Output: Result of the integral. ''' I = func.integral(a, b) return I if __name__ == "__main__": # Data input Xl = 1.38 print('Line filter air masses (program objects):', Xl) Xsl = 1.50 print('Line filter air masses (standard objects):', Xsl) Xc = 1.34 print('Air masses for the continuum filter (program):', Xc) Xsc = 1.54 print('Air masses for the continuum filter (standard):', Xsc) kpl = 0.14 print('mag/air mass for line:', kpl) kpc = 0.23 print('mag/air mass for continuum:', kpc) fsl = 294.3 print('Raw fluxes of the standard with sky subtracted (line):', fsl) fsc = 2565.5 print('Raw fluxes of the standard with sky subtracted (continuum):', fsc) nline = 1 print('Number of lines found in the line filter range, its rest wavelengths and fractional contribution (sum=1.0):', nline) rfWave = [6563,1] print('Rest wavelength (Angstroms) of each line as well as its fractional contibution (sum = 1.0):', rfWave) vsys = 45 print('Systemic velocity of the galaxy:', vsys) texpl = 2400 print('Exposure times of program frames (line):', texpl) texpc = 600 print('Exposure times of program frames (continuum):', texpc) skyl = 67.9 print('Sky background of the program frames in counts/pixel (line):', skyl) skyc = 123.8 print('Sky background of the program frames in counts/pixel (continuum):', skyc) # Line file path = '/Users/bmiller/src/calibrate' # path = '/Users/tuilaziliotto/Documents/GitHub/calibrate_line/'' line = readfile(os.path.join(path, '6568.dat')) print('Line filter file:', line[5]) linex = line[0] liney = line[1] xlmax = line[3] xlmin = line[2] # Continuum file continuum = readfile(os.path.join(path, '6092.dat')) print('Continuum filter file:', continuum[5]) xcmax = continuum[3] xcmin = continuum[2] contx = continuum[0] conty = continuum[1] # Standard file standard = readfile(os.path.join(path, 'f34f.dat')) print('Standard flux file:', standard[5],'\n') standx = standard[0] standy = standard[1] xmin = standard[2] xmax = standard[3] # Interpolations lineInterp = interp(linex,liney) standInterp = interp(standx,standy) contInterp = interp(contx,conty) # Plotting the data and interpolations #plt.figure() #plt.subplot(121) #linexNew = np.arange(xlmin,xlmax,0.1) #lineyNew = lineInterp(linexNew) #plt.plot(linex, liney, 'o') #plt.plot(linexNew, lineyNew) #plt.title('Interpolation for line filter') #plt.ylabel('Transmission (%)') #plt.xlabel(r'Wavelength ($\AA$)') #plt.subplot(122) #contxNew = np.arange(xcmin,xcmax,0.1) #contyNew = contInterp(contxNew) #plt.plot(contx, conty, 'o') #plt.plot(contxNew, contyNew) #plt.title('Interpolation for continuum filter') #plt.ylabel('Transmission (%)') #plt.xlabel(r'Wavelength ($\AA$)') #plt.subplots_adjust(top = 0.7,bottom = 0.3,left = 0.10,hspace = 0.9,wspace = 0.5) #plt.show() #standxNew = np.arange(xmin,xmax,0.1) #standyNew = standInterp(standxNew) #plt.plot(standx, standy, 'o') #plt.plot(standxNew, standyNew) #plt.title('Interpolation for standard') #plt.ylabel(r'Flux ($erg/s/cm^2/\AA$)') #plt.xlabel(r'Wavelength ($\AA$)') #plt.show() # Continuum filter integration contInt = integral(contInterp, xcmin, xcmax) # Line filter integration lineInt = integral(lineInterp, xlmin, xlmax) # Standard flux file integration standInt = integral(standInterp, xmin, xmax) # Integration of continuum filter * standard flux auxContFunc = lambda x: contInterp(x) * standInterp(x) contFluxInt = integrate.quad(auxContFunc, xcmin, xcmax, epsabs=1.49e-11) # Integration of line filter * standard flux auxLineFunc = lambda x: lineInterp(x) * standInterp(x) lineFluxInt = integrate.quad(auxLineFunc, xlmin, xlmax, epsabs=1.49e-11) # Q factorQ = 10 ** ( 0.4 * ( kpc * ( Xc - Xsc ) ) ) Q = (factorQ / fsc) * contFluxInt[0] * (lineInt / contInt) print('Q =', Q) # P factorP = 10 ** ( 0.4 * ( kpl * ( Xl - Xsl ) ) ) P = (factorP / fsl) * lineFluxInt[0] print('P =', P) # R fwhm = 1. g = fwhm / (2 * np.sqrt(np.log(2))) cte = 1. / ( np.sqrt( np.pi ) * g ) waveobs = obsWavelength(6563., vsys) funcR = lambda x: lineInterp(x) * np.exp(-(( x - waveobs )/g )**2) intR = integrate.quad(funcR, xlmin, xlmax) R = intR[0] * cte print('R =', R,'\n') alpha = P / ( R * texpl ) beta = Q * texpl / ( P * texpc ) gamma = -skyl + ( skyc * texpl * Q / ( texpc * P ) ) print('F = ', alpha, '(I(line) -', beta, 'I(continuum) +', gamma,')')
[ "numpy.sqrt", "numpy.amin", "scipy.integrate.quad", "numpy.log", "numpy.exp", "scipy.interpolate.InterpolatedUnivariateSpline", "numpy.loadtxt", "numpy.amax" ]
[((1265, 1299), 'scipy.interpolate.InterpolatedUnivariateSpline', 'InterpolatedUnivariateSpline', (['x', 'y'], {}), '(x, y)\n', (1293, 1299), False, 'from scipy.interpolate import InterpolatedUnivariateSpline\n'), ((5275, 5333), 'scipy.integrate.quad', 'integrate.quad', (['auxContFunc', 'xcmin', 'xcmax'], {'epsabs': '(1.49e-11)'}), '(auxContFunc, xcmin, xcmax, epsabs=1.49e-11)\n', (5289, 5333), False, 'from scipy import integrate\n'), ((5461, 5519), 'scipy.integrate.quad', 'integrate.quad', (['auxLineFunc', 'xlmin', 'xlmax'], {'epsabs': '(1.49e-11)'}), '(auxLineFunc, xlmin, xlmax, epsabs=1.49e-11)\n', (5475, 5519), False, 'from scipy import integrate\n'), ((6014, 6049), 'scipy.integrate.quad', 'integrate.quad', (['funcR', 'xlmin', 'xlmax'], {}), '(funcR, xlmin, xlmax)\n', (6028, 6049), False, 'from scipy import integrate\n'), ((660, 693), 'numpy.loadtxt', 'np.loadtxt', (['filename'], {'unpack': '(True)'}), '(filename, unpack=True)\n', (670, 693), True, 'import numpy as np\n'), ((749, 759), 'numpy.amax', 'np.amax', (['x'], {}), '(x)\n', (756, 759), True, 'import numpy as np\n'), ((775, 785), 'numpy.amin', 'np.amin', (['x'], {}), '(x)\n', (782, 785), True, 'import numpy as np\n'), ((5868, 5882), 'numpy.sqrt', 'np.sqrt', (['np.pi'], {}), '(np.pi)\n', (5875, 5882), True, 'import numpy as np\n'), ((5970, 6003), 'numpy.exp', 'np.exp', (['(-((x - waveobs) / g) ** 2)'], {}), '(-((x - waveobs) / g) ** 2)\n', (5976, 6003), True, 'import numpy as np\n'), ((5839, 5848), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (5845, 5848), True, 'import numpy as np\n')]
import os.path import numpy as np import random from argparse import ArgumentParser from collections import Counter from utils.data_writer import DataWriter from utils.file_utils import make_dir from utils.constants import TRAIN, VALID, TEST, SAMPLE_ID, INPUTS, OUTPUT WINDOW_SIZE = 20 STRIDE = 4 TRAIN_FRAC = 0.85 VALID_FRAC = 0.15 CHUNK_SIZE = 5000 def write_dataset(data: np.ndarray, output_folder: str, series: str): # Create the data writers if series == TRAIN: writers = { TRAIN: DataWriter(os.path.join(output_folder, TRAIN), file_prefix='data', chunk_size=CHUNK_SIZE, file_suffix='jsonl.gz'), VALID: DataWriter(os.path.join(output_folder, VALID), file_prefix='data', chunk_size=CHUNK_SIZE, file_suffix='jsonl.gz') } label_counters = { TRAIN: Counter(), VALID: Counter() } else: writers = { TEST: DataWriter(os.path.join(output_folder, TEST), file_prefix='data', chunk_size=CHUNK_SIZE, file_suffix='jsonl.gz') } label_counters = { TEST: Counter() } sample_id = 0 for index, features in enumerate(data): label = int(features[0]) input_features = features[1:].reshape(-1, 1).astype(float).tolist() # Get the data partition if series == TRAIN: if random.random() < TRAIN_FRAC: partition = TRAIN else: partition = VALID else: partition = TEST # Create the sample and add to corresponding data writer for i in range(0, len(input_features) - WINDOW_SIZE + 1, STRIDE): sample = { SAMPLE_ID: sample_id, OUTPUT: label, INPUTS: input_features[i:i+WINDOW_SIZE], } writers[partition].add(sample) label_counters[partition][label] += 1 sample_id += 1 if (index + 1) % CHUNK_SIZE == 0: print('Completed {0} sample.'.format(index + 1), end='\r') print() # Close all data writers for writer in writers.values(): writer.close() print(label_counters) if __name__ == '__main__': parser = ArgumentParser() parser.add_argument('--input-folder', type=str, required=True) parser.add_argument('--output-folder', type=str, required=True) args = parser.parse_args() # Set the random seed for reproducible results random.seed(42) train_path = os.path.join(args.input_folder, 'MelbournePedestrian_TRAIN.txt') train_data = np.loadtxt(train_path) # [T, D + 1] array. Element 0 is the label. make_dir(args.output_folder) write_dataset(train_data, output_folder=args.output_folder, series=TRAIN) test_path = os.path.join(args.input_folder, 'MelbournePedestrian_TEST.txt') test_data = np.loadtxt(test_path) write_dataset(test_data, output_folder=args.output_folder, series=TEST)
[ "argparse.ArgumentParser", "random.seed", "collections.Counter", "random.random", "utils.file_utils.make_dir", "numpy.loadtxt" ]
[((2232, 2248), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (2246, 2248), False, 'from argparse import ArgumentParser\n'), ((2471, 2486), 'random.seed', 'random.seed', (['(42)'], {}), '(42)\n', (2482, 2486), False, 'import random\n'), ((2587, 2609), 'numpy.loadtxt', 'np.loadtxt', (['train_path'], {}), '(train_path)\n', (2597, 2609), True, 'import numpy as np\n'), ((2660, 2688), 'utils.file_utils.make_dir', 'make_dir', (['args.output_folder'], {}), '(args.output_folder)\n', (2668, 2688), False, 'from utils.file_utils import make_dir\n'), ((2864, 2885), 'numpy.loadtxt', 'np.loadtxt', (['test_path'], {}), '(test_path)\n', (2874, 2885), True, 'import numpy as np\n'), ((824, 833), 'collections.Counter', 'Counter', ([], {}), '()\n', (831, 833), False, 'from collections import Counter\n'), ((854, 863), 'collections.Counter', 'Counter', ([], {}), '()\n', (861, 863), False, 'from collections import Counter\n'), ((1091, 1100), 'collections.Counter', 'Counter', ([], {}), '()\n', (1098, 1100), False, 'from collections import Counter\n'), ((1360, 1375), 'random.random', 'random.random', ([], {}), '()\n', (1373, 1375), False, 'import random\n')]
# Analyse the AFQMC back propagated RDM. import glob import h5py import numpy try: import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt have_mpl = True except ImportError: have_mpl = False import scipy.stats from afqmctools.analysis.average import average_one_rdm from afqmctools.analysis.extraction import ( extract_observable, get_metadata ) def compute_one_body(filename, hcore, skip, group): energies = [] # weights can be ignored if not using free projection. dm = extract_observable(filename, ix=group).reshape((-1,)+hcore.shape) for d in dm[skip:]: e1b = numpy.einsum('ij,ij->', hcore, d) energies.append(e1b.real) av = numpy.mean(energies) err = scipy.stats.sem(energies) return av, err def plot_convergence(filename): with h5py.File('afqmc.h5', 'r') as fh5: hcore = fh5['Hamiltonian/hcore'][:].view(numpy.complex128)[:,:,0] energies = [] errs = [] tau_bps = [] sym_md = get_metadata(filename) bp_md = get_metadata(filename, 'Observables/BackPropagated/') taus = bp_md['BackPropSteps'] for i, t in enumerate(taus): # skip the first block for equilibration skip = 1 nelec = sym_md['NAEA'] + sym_md['NAEB'] # We can extract the averaged 1RDM. rdm_av, rdm_errs = average_one_rdm(filename, eqlb=skip, ix=i) nelec_rdm = (rdm_av[0].trace()).real assert(nelec_rdm-nelec < 1e-12) # Often it is simpler to compute error bars if we first contract the 1RDM. # For example, we can compute the one-body energy from the averaged RDM as. e1b = numpy.einsum('ij,sij->', hcore, rdm_av).real # Or we can instead compute the average of the one-body energies. e1b_series, err = compute_one_body(filename, hcore, skip, i) energies.append(e1b_series) errs.append(err) # get back propagation time tau_bps.append(t*sym_md['Timestep']) assert(e1b-e1b_series < 1e-12) # Finally plot the one-body energy and check the estimator is converged with # respect to back propagation time. if have_mpl: plt.errorbar(tau_bps, energies, yerr=errs, fmt='o') plt.xlabel(r'$\tau_{BP}$') plt.ylabel(r'$E_{1B}$ (Ha)') plt.savefig('h1e_conv.pdf', fmt='pdf', bbox_inches='tight') if __name__ == '__main__': plot_convergence('qmc.s000.stat.h5')
[ "numpy.mean", "matplotlib.pyplot.savefig", "matplotlib.pyplot.ylabel", "matplotlib.use", "afqmctools.analysis.average.average_one_rdm", "matplotlib.pyplot.xlabel", "h5py.File", "afqmctools.analysis.extraction.get_metadata", "numpy.einsum", "matplotlib.pyplot.errorbar", "afqmctools.analysis.extra...
[((116, 130), 'matplotlib.use', 'mpl.use', (['"""Agg"""'], {}), "('Agg')\n", (123, 130), True, 'import matplotlib as mpl\n'), ((727, 747), 'numpy.mean', 'numpy.mean', (['energies'], {}), '(energies)\n', (737, 747), False, 'import numpy\n'), ((1016, 1038), 'afqmctools.analysis.extraction.get_metadata', 'get_metadata', (['filename'], {}), '(filename)\n', (1028, 1038), False, 'from afqmctools.analysis.extraction import extract_observable, get_metadata\n'), ((1051, 1104), 'afqmctools.analysis.extraction.get_metadata', 'get_metadata', (['filename', '"""Observables/BackPropagated/"""'], {}), "(filename, 'Observables/BackPropagated/')\n", (1063, 1104), False, 'from afqmctools.analysis.extraction import extract_observable, get_metadata\n'), ((650, 683), 'numpy.einsum', 'numpy.einsum', (['"""ij,ij->"""', 'hcore', 'd'], {}), "('ij,ij->', hcore, d)\n", (662, 683), False, 'import numpy\n'), ((845, 871), 'h5py.File', 'h5py.File', (['"""afqmc.h5"""', '"""r"""'], {}), "('afqmc.h5', 'r')\n", (854, 871), False, 'import h5py\n'), ((1357, 1399), 'afqmctools.analysis.average.average_one_rdm', 'average_one_rdm', (['filename'], {'eqlb': 'skip', 'ix': 'i'}), '(filename, eqlb=skip, ix=i)\n', (1372, 1399), False, 'from afqmctools.analysis.average import average_one_rdm\n'), ((2182, 2233), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (['tau_bps', 'energies'], {'yerr': 'errs', 'fmt': '"""o"""'}), "(tau_bps, energies, yerr=errs, fmt='o')\n", (2194, 2233), True, 'import matplotlib.pyplot as plt\n'), ((2242, 2268), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$\\\\tau_{BP}$"""'], {}), "('$\\\\tau_{BP}$')\n", (2252, 2268), True, 'import matplotlib.pyplot as plt\n'), ((2277, 2304), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$E_{1B}$ (Ha)"""'], {}), "('$E_{1B}$ (Ha)')\n", (2287, 2304), True, 'import matplotlib.pyplot as plt\n'), ((2314, 2373), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""h1e_conv.pdf"""'], {'fmt': '"""pdf"""', 'bbox_inches': '"""tight"""'}), "('h1e_conv.pdf', fmt='pdf', bbox_inches='tight')\n", (2325, 2373), True, 'import matplotlib.pyplot as plt\n'), ((546, 584), 'afqmctools.analysis.extraction.extract_observable', 'extract_observable', (['filename'], {'ix': 'group'}), '(filename, ix=group)\n', (564, 584), False, 'from afqmctools.analysis.extraction import extract_observable, get_metadata\n'), ((1666, 1705), 'numpy.einsum', 'numpy.einsum', (['"""ij,sij->"""', 'hcore', 'rdm_av'], {}), "('ij,sij->', hcore, rdm_av)\n", (1678, 1705), False, 'import numpy\n')]
""" script to create pandas Dataframes with all results from multiple runs of the EQL stored inside. """ __author__ = "<NAME> (GMi)" __version__ = "1.2.0" __date__ = "07.09.2020" __email__ = "<EMAIL>" __status__ = "Development" import numpy as np #from matplotlib import pyplot as plt import pandas import sympy import pandas as pd from os import path, walk # import holoviews as hv # import bokeh # from bokeh.io import show # from holoviews import opts # hv.extension('bokeh','matplotlib') from graphviz import Source import matplotlib.pylab as pylab params = {'legend.fontsize': 'xx-large', 'figure.figsize': (15, 15), 'axes.labelsize': 'xx-large', 'axes.titlesize':'xx-large', 'xtick.labelsize':'xx-large', 'ytick.labelsize':'xx-large'} pylab.rcParams.update(params) ################### functions from original EQL - modified ######################## def select_instance(df=None, file=None, use_extrapolation=True): """ Expects a file with one row per network and columns reporting the parameters and complexity and performance First line should be the column names, col1 col2 col3..., then one additional comments line which can be empty. Third line should be the values for each column. :param df: pandas dataframe containing data about model performance :param file: file containing data about model performance, only used if dataframe is none :param use_extrapolation: flag to determine if extrapolation data should be used :return: pandas dataframe containing id and performance data of best model. """ if df is not None and file is not None: raise ValueError('Both results_df and file specified. Only specify one.') if df is None: if file is None: raise ValueError('Either results_df or file have to be specified.') df = pd.read_csv(file) if 'extr_error' in df.keys(): extr_available = not df['extr_error'].isnull().values.any() else: extr_available = False if use_extrapolation and not extr_available: raise ValueError("use_extrapolation flag is set to True but no extrapolation results were found.") if use_extrapolation: df['extr_normed'] = normalize_to_max_one(df['extr_error']) df['val_normed'] = normalize_to_max_one(df['val_error']) df['complexity_normed'] = normalize_to_max_one(df['complexity'], defensive=False) if use_extrapolation: print('Extrapolation data used.') df['score'] = np.sqrt(df['extr_normed'] ** 2 + df['val_normed'] ** 2) else: print('No extrapolation data used, performing model selection based on complexity and validation instead.') df['score'] = np.sqrt(df['complexity_normed'] ** 2 + df['val_normed'] ** 2) return df def normalize_to_max_one(arr, defensive=True): """ Routine that normalizes an array to a maximumum of one. :param arr: array to be normalized :param defensive: flag to determine if behavior is defensive (if all array elements are the same raise exception) or not (if all array elements are the same return an array of same length filled with zeros) """ if np.isclose(np.max(arr), np.min(arr)): if defensive: raise ValueError('All elements in array are the same, no normalization possible.') else: return np.zeros(len(arr)) norm_arr = arr / (np.max(arr)) return norm_arr def aggregate_csv_files_recursively(directory, filename): """ Returns a pandas DF that is a concatenation of csvs with given filename in given directory (recursively).""" return pd.concat(_df_from_csv_recursive_generator(directory, filename)) def _df_from_csv_recursive_generator(directory, filename): """ Returns a generator producing pandas DF for each csv with given filename in given directory (recursively).""" for root, dirs, files in walk(directory): if filename in files: yield pd.read_csv(path.join(root, filename)) ######################## functions from GMi ################################ def list_from_npy(directory, filename): """ Returns a generator producing list for each npy file with given filename in given directory (recursively). Args: directory: path to directory, where npy files are stored (in subfolders), string filename: name of npy file, string Returns: list1: list of all npy files found in the subdirectories, list """ list_npy = [] for root, dirs, files in walk(directory): if filename in files: #print('here: ', root) list_npy.append(np.load(path.join(root, filename), allow_pickle=True)) return list_npy def get_list_of_formula(working_directory, filename='formula_0.npy'): """Returns list of formulas as sympy expression found in a the subfolders of a given directory. Args: working_directory: path to directory, where npy files are stored (in subfolders), string filename: name of npy file, string id1: list of id tags sorted with ascending score, list Returns: formula_sort: list of sympy expression of the formulas found in the subdirectories - sorted, list """ all_formula = list_from_npy(working_directory, filename) #print(len(all_formula)) formula_sort = [] #print(len(all_formula)) for i in range(len(all_formula)): #print(i) #print(all_formula[i]) formula_sort.append(sympy.sympify(all_formula[i])) return formula_sort def graph_from_formula(formula): """returns variable tree from formula expression. Args: formula: list of sympy expressions, list Retruns: graph: list of variable trees of the respected formula expression, Source object """ graph = [] for i in range(len(formula)): #formula = parse_expr(formula[i]) # if input is string if not (formula[i] == np.nan): graph_c = Source(sympy.dotprint(formula[i])) else: print('formula is NaN') graph_c = np.nan graph.append(graph_c) return graph def EQL_df_creation(num_runs, path_results, num_h_layers, reg_percent, use_extrapolation=True, filename_formula='formula_0.npy'): """function to create pandas dataframe from csv file for EQL runs. Ordered by id (ascending). Args: num_runs: number of runs, int path_results: path to working directory, where the results are stored, string num_h_layers: number of hidden layers, list with len=len(num_runs) or singel value reg_percent: regularization strength, list with len=len(num_runs) filename_formula: filename of npy file with formula expression in respected folder, string - e.g.: 'formula_0.npy' Returns: df: pandas dataframe with all info from the runs of EQL runs. nan where something is missing df includes: - 'val_error': prediction error with validation dataset - 'extr_error': prediction error with test dataset - 'complexity': number of active nodes of network - 'id': the results are stored in a folder with this name. Serves as a tag - 'extr_normed': extr_error/max(extr_error) --> normed value for extr_error - 'val_normed': val_error/max(val_error) --> normed value for val_error - 'complexity_normed': complexity/max(complexity) --> normed value for complexity - 'score': root mean squared of extr_normed and val_normed - 'num_h_layers': number of hidden layers, int - 'reg_percent': regularization strength, int - 'formula': sympy formula expression resulting from EQL run - 'graph': variable tree of the respected formula expression, Source object """ aggregated_results = aggregate_csv_files_recursively(path_results, "results.csv") df = select_instance(df=aggregated_results, use_extrapolation=use_extrapolation) # append df with nan, where no results are generated df_nan = pd.DataFrame({'Unnamed: 0': [np.nan], 'val_error': [np.nan], 'complexity': [np.nan], 'extr_error': [np.nan], 'id': [np.nan], 'extr_normed': [np.nan], 'val_normed': [np.nan], 'complexity_normed': [np.nan], 'score': [np.nan], 'formula': [np.nan], }) for i in range(num_runs): if any(df['id'] == i) == False: df_nan['id'] = i df = df.append(df_nan, ignore_index=True) formula = get_list_of_formula(path_results, filename_formula) if not(len(formula) == num_runs): print('ERROR: # formulas in df are not equal to the # runs') # these lines need to be adapted for other input to be saved additionally # list_train_error = list_from_npy(path_results, 'loss_test_all.npy') # list_val_error = list_from_npy(path_results, 'loss_train_all.npy') # list_extr_error = list_from_npy(path_results, 'loss_val_all.npy') # list_complexity = list_from_npy(path_results, 'complexity_all.npy') # list_train_error = [] # list_val_error = [] # list_extr_error = [] # list_complexity = [] # for i in range(num_runs): # list_train_error.append(np.load(path_results+'\\'+str(i)+'\\loss_train_all.npy')) # list_val_error.append(np.load(path_results+'\\'+str(i)+'\\loss_val_all.npy')) # list_extr_error.append(np.load(path_results+'\\'+str(i)+'\\loss_test_all.npy')) # list_complexity.append(np.load(path_results+'\\'+str(i)+'\\complexity_all.npy')) df['num_h_layers'] = num_h_layers df['reg_percent'] = reg_percent df['formula'] = formula df.to_csv(path_or_buf=path_results+'\\df.csv') return df def plot_from_df_reduced(df, title, x, y, details, logx=True, logy=True): """Function for plotting the results from the EQL. Only works in Jupyter Notebook! The plot shows x and y of EQL runs with different parameters: available details that can be displayed for the EQL model selection: - 'val_error': prediction error with validation dataset - 'extr_error': prediction error with test dataset - 'complexity': number of active nodes of network - 'id': the results are stored in a folder with this name. Serves as a tag - 'extr_normed': extr_error/max(extr_error) --> normed value for extr_error - 'val_normed': val_error/max(val_error) --> normed value for val_error - 'complexity_normed': complexity/max(complexity) --> normed value for complexity - 'score': root mean squared of extr_normed and val_normed - 'num_h_layers': number of hidden layers (1,2,3,4), int - 'reg_percent': regularization strength, int - 'formula': sympy formula expression resulting from EQL run Args: df: pandas dataframe with all input - for EQL model selection: expects all details mentioned above fun_name: name of the function - displayed in title, string x: data for x axis - must be inside df, string y: data for y axis - must be inside df, string details: details that should be displayed while hoovering over a point, list of strings logx: boolean if x-axis should be plotted logarithmic, default=True logy: boolean if y-axis should be plotted logarithmic, default=True E.g.: plot_extr_val(df_F1, 'F1', 'extr_error', 'val_error', ['complexity', 'id', 'formula']) """ plot = hv.Scatter(df, [x, y], details) plot.opts(size=4.5, tools=['tap', 'hover']) plot.opts(logx=logx, logy=logy) plot.opts(title=title) plot.opts(xlabel=x, ylabel=y) plot.opts(width=700, height=700) plot.opts(legend_position='top_right') plot.opts(fontsize={'title': 16, 'labels': 14, 'xticks': 12, 'yticks': 12}) figure_bokeh = hv.render(plot, backend='bokeh') show(figure_bokeh) if __name__ == '__main__': #path_data = # add path to directory, where the results are stored #num_h_layers = # number of hidden layers, list with len=len(num_runs) or singel value #rp = # regularization strength, list with len=len(num_runs) ####### if file is missing --> generate npy file with the desired name and add them to the subdirectories to avoid error ######## #np.save(path_data+r'\formula_0.npy', [np.nan]) #np.save(path_data+r'\loss_test_all.npy', [np.nan]) #np.save(path_data+r'\loss_train_all.npy', [np.nan]) #np.save(path_data+r'\loss_val_all.npy', [np.nan]) #np.save(path_data+r'\complexity_all.npy', [np.nan]) df = EQL_df_creation(num_runs=len(rp), path_results=path_data, num_h_layers=num_h_layers, reg_percent=rp, use_extrapolation=False, filename_formula='formula_0.npy')
[ "sympy.dotprint", "numpy.sqrt", "pandas.read_csv", "sympy.sympify", "os.path.join", "numpy.max", "matplotlib.pylab.rcParams.update", "numpy.min", "pandas.DataFrame", "os.walk" ]
[((798, 827), 'matplotlib.pylab.rcParams.update', 'pylab.rcParams.update', (['params'], {}), '(params)\n', (819, 827), True, 'import matplotlib.pylab as pylab\n'), ((3929, 3944), 'os.walk', 'walk', (['directory'], {}), '(directory)\n', (3933, 3944), False, 'from os import path, walk\n'), ((4579, 4594), 'os.walk', 'walk', (['directory'], {}), '(directory)\n', (4583, 4594), False, 'from os import path, walk\n'), ((8226, 8485), 'pandas.DataFrame', 'pd.DataFrame', (["{'Unnamed: 0': [np.nan], 'val_error': [np.nan], 'complexity': [np.nan],\n 'extr_error': [np.nan], 'id': [np.nan], 'extr_normed': [np.nan],\n 'val_normed': [np.nan], 'complexity_normed': [np.nan], 'score': [np.nan\n ], 'formula': [np.nan]}"], {}), "({'Unnamed: 0': [np.nan], 'val_error': [np.nan], 'complexity':\n [np.nan], 'extr_error': [np.nan], 'id': [np.nan], 'extr_normed': [np.\n nan], 'val_normed': [np.nan], 'complexity_normed': [np.nan], 'score': [\n np.nan], 'formula': [np.nan]})\n", (8238, 8485), True, 'import pandas as pd\n'), ((1871, 1888), 'pandas.read_csv', 'pd.read_csv', (['file'], {}), '(file)\n', (1882, 1888), True, 'import pandas as pd\n'), ((2520, 2575), 'numpy.sqrt', 'np.sqrt', (["(df['extr_normed'] ** 2 + df['val_normed'] ** 2)"], {}), "(df['extr_normed'] ** 2 + df['val_normed'] ** 2)\n", (2527, 2575), True, 'import numpy as np\n'), ((2724, 2785), 'numpy.sqrt', 'np.sqrt', (["(df['complexity_normed'] ** 2 + df['val_normed'] ** 2)"], {}), "(df['complexity_normed'] ** 2 + df['val_normed'] ** 2)\n", (2731, 2785), True, 'import numpy as np\n'), ((3216, 3227), 'numpy.max', 'np.max', (['arr'], {}), '(arr)\n', (3222, 3227), True, 'import numpy as np\n'), ((3229, 3240), 'numpy.min', 'np.min', (['arr'], {}), '(arr)\n', (3235, 3240), True, 'import numpy as np\n'), ((3434, 3445), 'numpy.max', 'np.max', (['arr'], {}), '(arr)\n', (3440, 3445), True, 'import numpy as np\n'), ((5582, 5611), 'sympy.sympify', 'sympy.sympify', (['all_formula[i]'], {}), '(all_formula[i])\n', (5595, 5611), False, 'import sympy\n'), ((6118, 6144), 'sympy.dotprint', 'sympy.dotprint', (['formula[i]'], {}), '(formula[i])\n', (6132, 6144), False, 'import sympy\n'), ((4006, 4031), 'os.path.join', 'path.join', (['root', 'filename'], {}), '(root, filename)\n', (4015, 4031), False, 'from os import path, walk\n'), ((4697, 4722), 'os.path.join', 'path.join', (['root', 'filename'], {}), '(root, filename)\n', (4706, 4722), False, 'from os import path, walk\n')]
######################################################### # # Fringe Model Functions # ######################################################### import sys, copy import numpy as np import matplotlib.pyplot as plt import scipy.signal as signal from scipy.optimize import curve_fit import smart def get_peak_fringe_frequency(fringe_object, pixel_start, pixel_end): """ Get the two peak frequencies for the fringe pattern. """ tmp = copy.deepcopy(fringe_object) tmp.flux = tmp.flux[pixel_start: pixel_end] tmp.wave = tmp.wave[pixel_start: pixel_end] f = np.linspace(0.01, 10.0, 10000) pgram = signal.lombscargle(tmp.wave, tmp.flux, f, normalize=True) best_frequency1 = f[np.argmax(pgram)] #print(best_frequency1) best_frequency2 = f[(f>0.5) & (f<1.3)][np.argmax(pgram[(f>0.5) & (f<1.3)])] #print(best_frequency2) return best_frequency1, best_frequency2 def double_sine(wave, a1, k1, a2, k2): """ Double sine function for the fringe pattern that assume wave numnber k times wavekength x with a fringe amplitdue a. The initial guess is determined from the best frequency. """ return (1 + a1**2 + 2 * a1 * np.sin( k1 * wave )) * ( 1 + a2**2 + 2 * a2 * np.sin( k2 * wave )) - 1 def double_sine_fringe(model, data, piecewise_fringe_model, teff, logg, vsini, rv, airmass, pwv, wave_offset, flux_offset, lsf, modelset): # make a model without the fringe model_tmp = smart.makeModel(teff=teff, logg=logg, metal=0.0, vsini=vsini, rv=rv, tell_alpha=1.0, wave_offset=wave_offset, flux_offset=flux_offset, lsf=lsf, order=str(data.order), data=data, modelset=modelset, airmass=airmass, pwv=pwv, output_stellar_model=False) # construct the fringe model residual = copy.deepcopy(data) residual.flux = (data.flux - model_tmp.flux)/model_tmp.flux end = len(piecewise_fringe_model)-1 for i in range(len(piecewise_fringe_model)-1): pixel_start, pixel_end = piecewise_fringe_model[i], piecewise_fringe_model[i+1] tmp = copy.deepcopy(residual) tmp.flux = tmp.flux[pixel_start: pixel_end] tmp.wave = tmp.wave[pixel_start: pixel_end] #best_frequency1, best_frequency2 = get_peak_fringe_frequency(tmp, pixel_start, pixel_end) best_frequency1, best_frequency2 = 2.10, 0.85 #amp = max(tmp.flux) amp = 0.01 p0 = [amp, best_frequency1, amp, best_frequency2] bounds = ( [0.0, 0.0, 0.0, 0.0], [2.0*amp, 100*best_frequency1, 2.0*amp, 100*best_frequency2]) try: popt, pcov = curve_fit(double_sine, tmp.wave, tmp.flux, maxfev=10000, p0=p0, bounds=bounds) # replace the model with the fringe pattern; note that this has to be the model wavelength at the current forward-modeling step before resampling model.flux[(model.wave>residual.wave[pixel_start]) & (model.wave<residual.wave[pixel_end])] *= (1 + double_sine(model.wave[[(model.wave>residual.wave[pixel_start]) & (model.wave<residual.wave[pixel_end])]], *popt)) except: pass return model.flux
[ "scipy.optimize.curve_fit", "numpy.sin", "numpy.argmax", "numpy.linspace", "copy.deepcopy", "scipy.signal.lombscargle" ]
[((435, 463), 'copy.deepcopy', 'copy.deepcopy', (['fringe_object'], {}), '(fringe_object)\n', (448, 463), False, 'import sys, copy\n'), ((561, 591), 'numpy.linspace', 'np.linspace', (['(0.01)', '(10.0)', '(10000)'], {}), '(0.01, 10.0, 10000)\n', (572, 591), True, 'import numpy as np\n'), ((601, 658), 'scipy.signal.lombscargle', 'signal.lombscargle', (['tmp.wave', 'tmp.flux', 'f'], {'normalize': '(True)'}), '(tmp.wave, tmp.flux, f, normalize=True)\n', (619, 658), True, 'import scipy.signal as signal\n'), ((1693, 1712), 'copy.deepcopy', 'copy.deepcopy', (['data'], {}), '(data)\n', (1706, 1712), False, 'import sys, copy\n'), ((682, 698), 'numpy.argmax', 'np.argmax', (['pgram'], {}), '(pgram)\n', (691, 698), True, 'import numpy as np\n'), ((765, 804), 'numpy.argmax', 'np.argmax', (['pgram[(f > 0.5) & (f < 1.3)]'], {}), '(pgram[(f > 0.5) & (f < 1.3)])\n', (774, 804), True, 'import numpy as np\n'), ((1952, 1975), 'copy.deepcopy', 'copy.deepcopy', (['residual'], {}), '(residual)\n', (1965, 1975), False, 'import sys, copy\n'), ((2427, 2505), 'scipy.optimize.curve_fit', 'curve_fit', (['double_sine', 'tmp.wave', 'tmp.flux'], {'maxfev': '(10000)', 'p0': 'p0', 'bounds': 'bounds'}), '(double_sine, tmp.wave, tmp.flux, maxfev=10000, p0=p0, bounds=bounds)\n', (2436, 2505), False, 'from scipy.optimize import curve_fit\n'), ((1128, 1145), 'numpy.sin', 'np.sin', (['(k1 * wave)'], {}), '(k1 * wave)\n', (1134, 1145), True, 'import numpy as np\n'), ((1174, 1191), 'numpy.sin', 'np.sin', (['(k2 * wave)'], {}), '(k2 * wave)\n', (1180, 1191), True, 'import numpy as np\n')]
# Copyright 2022 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """main""" import argparse import os import json import cv2 import numpy as np from api.infer import SdkApi from config.config import config from tqdm import tqdm from shapely.geometry import Polygon def parser_args(): """parser_args""" parser = argparse.ArgumentParser(description="siamRPN inference") parser.add_argument("--img_path", type=str, required=False, default="../data/input/vot2015", help="image directory.") parser.add_argument( "--pipeline_path", type=str, required=False, default="../data/config/siamRPN.pipeline", help="image file path. The default is '../data/config/siamRPN.pipeline'. ") parser.add_argument( "--infer_result_dir", type=str, required=False, default="./result", help="cache dir of inference result. The default is './result'." ) arg = parser.parse_args() return arg def get_instance_image(img, bbox, size_z, size_x, context_amount, img_mean=None): cx, cy, w, h = bbox # float type wc_z = w + context_amount * (w + h) hc_z = h + context_amount * (w + h) s_z = np.sqrt(wc_z * hc_z) # the width of the crop box s_x = s_z * size_x / size_z instance_img, scale_x = crop_and_pad(img, cx, cy, size_x, s_x, img_mean) w_x = w * scale_x h_x = h * scale_x return instance_img, w_x, h_x, scale_x def get_exemplar_image(img, bbox, size_z, context_amount, img_mean=None): cx, cy, w, h = bbox wc_z = w + context_amount * (w + h) hc_z = h + context_amount * (w + h) s_z = np.sqrt(wc_z * hc_z) scale_z = size_z / s_z exemplar_img, _ = crop_and_pad(img, cx, cy, size_z, s_z, img_mean) return exemplar_img, scale_z, s_z def round_up(value): return round(value + 1e-6 + 1000) - 1000 def crop_and_pad(img, cx, cy, model_sz, original_sz, img_mean=None): """change img size :param img:rgb :param cx: center x :param cy: center y :param model_sz: changed size :param original_sz: origin size :param img_mean: mean of img :return: changed img ,scale for origin to changed """ im_h, im_w, _ = img.shape xmin = cx - (original_sz - 1) / 2 xmax = xmin + original_sz - 1 ymin = cy - (original_sz - 1) / 2 ymax = ymin + original_sz - 1 left = int(round_up(max(0., -xmin))) top = int(round_up(max(0., -ymin))) right = int(round_up(max(0., xmax - im_w + 1))) bottom = int(round_up(max(0., ymax - im_h + 1))) xmin = int(round_up(xmin + left)) xmax = int(round_up(xmax + left)) ymin = int(round_up(ymin + top)) ymax = int(round_up(ymax + top)) r, c, k = img.shape if any([top, bottom, left, right]): # 0 is better than 1 initialization te_im = np.zeros((r + top + bottom, c + left + right, k), np.uint8) te_im[top:top + r, left:left + c, :] = img if top: te_im[0:top, left:left + c, :] = img_mean if bottom: te_im[r + top:, left:left + c, :] = img_mean if left: te_im[:, 0:left, :] = img_mean if right: te_im[:, c + left:, :] = img_mean im_patch_original = te_im[int(ymin):int( ymax + 1), int(xmin):int(xmax + 1), :] else: im_patch_original = img[int(ymin):int( ymax + 1), int(xmin):int(xmax + 1), :] if not np.array_equal(model_sz, original_sz): # zzp: use cv to get a better speed im_patch = cv2.resize(im_patch_original, (model_sz, model_sz)) else: im_patch = im_patch_original scale = model_sz / im_patch_original.shape[0] return im_patch, scale def generate_anchors(total_stride, base_size, scales, ratios, score_size): """ anchor generator function""" anchor_num = len(ratios) * len(scales) anchor = np.zeros((anchor_num, 4), dtype=np.float32) size = base_size * base_size count = 0 for ratio in ratios: ws = int(np.sqrt(size / ratio)) hs = int(ws * ratio) for scale in scales: wws = ws * scale hhs = hs * scale anchor[count, 0] = 0 anchor[count, 1] = 0 anchor[count, 2] = wws anchor[count, 3] = hhs count += 1 anchor = np.tile(anchor, score_size * score_size).reshape((-1, 4)) ori = - (score_size // 2) * total_stride xx, yy = np.meshgrid([ori + total_stride * dx for dx in range(score_size)], [ori + total_stride * dy for dy in range(score_size)]) xx, yy = np.tile(xx.flatten(), (anchor_num, 1)).flatten(), \ np.tile(yy.flatten(), (anchor_num, 1)).flatten() anchor[:, 0], anchor[:, 1] = xx.astype(np.float32), yy.astype(np.float32) return anchor def box_transform_inv(anchors, offset): """invert transform box :param anchors: object :param offset: object :return: object """ anchor_xctr = anchors[:, :1] anchor_yctr = anchors[:, 1:2] anchor_w = anchors[:, 2:3] anchor_h = anchors[:, 3:] offset_x, offset_y, offset_w, offset_h = offset[:, :1], offset[:, 1:2], offset[:, 2:3], offset[:, 3:], box_cx = anchor_w * offset_x + anchor_xctr box_cy = anchor_h * offset_y + anchor_yctr box_w = anchor_w * np.exp(offset_w) box_h = anchor_h * np.exp(offset_h) box = np.hstack([box_cx, box_cy, box_w, box_h]) return box def get_axis_aligned_bbox(region): """ convert region to (cx, cy, w, h) that represent by axis aligned box """ nv = len(region) region = np.array(region) if nv == 8: x1 = min(region[0::2]) x2 = max(region[0::2]) y1 = min(region[1::2]) y2 = max(region[1::2]) A1 = np.linalg.norm(region[0:2] - region[2:4]) * \ np.linalg.norm(region[2:4] - region[4:6]) A2 = (x2 - x1) * (y2 - y1) s = np.sqrt(A1 / A2) w = s * (x2 - x1) + 1 h = s * (y2 - y1) + 1 x = x1 y = y1 else: x = region[0] y = region[1] w = region[2] h = region[3] return x, y, w, h def softmax(y): """softmax of numpy""" x = y.copy() if len(x.shape) > 1: tmp = np.max(x, axis=1) x -= tmp.reshape((x.shape[0], 1)) x = np.exp(x) tmp = np.sum(x, axis=1) x /= tmp.reshape((x.shape[0], 1)) else: tmp = np.max(x) x -= tmp x = np.exp(x) tmp = np.sum(x) x /= tmp return x def judge_failures(pred_bbox, gt_bbox, threshold=0): """" judge whether to fail or not """ if len(gt_bbox) == 4: if iou(np.array(pred_bbox).reshape(-1, 4), np.array(gt_bbox).reshape(-1, 4)) > threshold: return False else: poly_pred = Polygon(np.array([[pred_bbox[0], pred_bbox[1]], [pred_bbox[2], pred_bbox[1]], [pred_bbox[2], pred_bbox[3]], [pred_bbox[0], pred_bbox[3]] ])).convex_hull poly_gt = Polygon(np.array(gt_bbox).reshape(4, 2)).convex_hull inter_area = poly_gt.intersection(poly_pred).area overlap = inter_area / (poly_gt.area + poly_pred.area - inter_area) if overlap > threshold: return False return True def calculate_accuracy_failures(pred_trajectory, gt_trajectory, bound=None): ''' args: pred_trajectory:list of bbox gt_trajectory: list of bbox ,shape == pred_trajectory bound :w and h of img return : overlaps:list ,iou value in pred_trajectory acc : mean iou value failures: failures point in pred_trajectory num_failures: number of failres ''' overlaps = [] failures = [] for i, pred_traj in enumerate(pred_trajectory): if len(pred_traj) == 1: if pred_trajectory[i][0] == 2: failures.append(i) overlaps.append(float("nan")) else: if bound is not None: poly_img = Polygon(np.array([[0, 0], [0, bound[1]], [bound[0], bound[1]], [bound[0], 0]])).convex_hull if len(gt_trajectory[i]) == 8: poly_pred = Polygon(np.array([[pred_trajectory[i][0], pred_trajectory[i][1]], [pred_trajectory[i][2], pred_trajectory[i][1]], [pred_trajectory[i][2], pred_trajectory[i][3]], [pred_trajectory[i][0], pred_trajectory[i][3]] ])).convex_hull poly_gt = Polygon( np.array(gt_trajectory[i]).reshape(4, 2)).convex_hull if bound is not None: gt_inter_img = poly_gt.intersection(poly_img) pred_inter_img = poly_pred.intersection(poly_img) inter_area = gt_inter_img.intersection(pred_inter_img).area overlap = inter_area / \ (gt_inter_img.area + pred_inter_img.area - inter_area) else: inter_area = poly_gt.intersection(poly_pred).area overlap = inter_area / \ (poly_gt.area + poly_pred.area - inter_area) elif len(gt_trajectory[i]) == 4: overlap = iou(np.array(pred_trajectory[i]).reshape(-1, 4), np.array(gt_trajectory[i]).reshape(-1, 4)) overlaps.append(overlap) acc = 0 num_failures = len(failures) if overlaps: acc = np.nanmean(overlaps) return acc, overlaps, failures, num_failures def calculate_expected_overlap(fragments, fweights): """ compute expected iou """ max_len = fragments.shape[1] expected_overlaps = np.zeros((max_len), np.float32) expected_overlaps[0] = 1 # TODO Speed Up for i in range(1, max_len): mask = np.logical_not(np.isnan(fragments[:, i])) if np.any(mask): fragment = fragments[mask, 1:i+1] seq_mean = np.sum(fragment, 1) / fragment.shape[1] expected_overlaps[i] = np.sum(seq_mean * fweights[mask]) / np.sum(fweights[mask]) return expected_overlaps def iou(box1, box2): """ compute iou """ box1, box2 = box1.copy(), box2.copy() N = box1.shape[0] K = box2.shape[0] box1 = np.array(box1.reshape((N, 1, 4))) + \ np.zeros((1, K, 4)) # box1=[N,K,4] box2 = np.array(box2.reshape((1, K, 4))) + \ np.zeros((N, 1, 4)) # box1=[N,K,4] x_max = np.max(np.stack((box1[:, :, 0], box2[:, :, 0]), axis=-1), axis=2) x_min = np.min(np.stack((box1[:, :, 2], box2[:, :, 2]), axis=-1), axis=2) y_max = np.max(np.stack((box1[:, :, 1], box2[:, :, 1]), axis=-1), axis=2) y_min = np.min(np.stack((box1[:, :, 3], box2[:, :, 3]), axis=-1), axis=2) tb = x_min-x_max lr = y_min-y_max tb[np.where(tb < 0)] = 0 lr[np.where(lr < 0)] = 0 over_square = tb*lr all_square = (box1[:, :, 2] - box1[:, :, 0]) * (box1[:, :, 3] - box1[:, :, 1]) + (box2[:, :, 2] - \ box2[:, :, 0]) * (box2[:, :, 3] - box2[:, :, 1]) - over_square return over_square / all_square def calculate_eao(dataset_name, all_failures, all_overlaps, gt_traj_length, skipping=5): ''' input:dataset name all_failures: type is list , index of failure all_overlaps: type is list , length of list is the length of all_failures gt_traj_length: type is list , length of list is the length of all_failures skipping:number of skipping per failing ''' if dataset_name == "VOT2016": low = 108 high = 371 elif dataset_name == "VOT2015": low = 108 high = 371 fragment_num = sum([len(x)+1 for x in all_failures]) max_len = max([len(x) for x in all_overlaps]) tags = [1] * max_len seq_weight = 1 / (1 + 1e-10) # division by zero eao = {} # prepare segments fweights = np.ones(fragment_num, dtype=np.float32) * np.nan fragments = np.ones((fragment_num, max_len), dtype=np.float32) * np.nan seg_counter = 0 for traj_len, failures, overlaps in zip(gt_traj_length, all_failures, all_overlaps): if failures: points = [x+skipping for x in failures if x+skipping <= len(overlaps)] points.insert(0, 0) for i, _ in enumerate(points): if i != len(points) - 1: fragment = np.array( overlaps[points[i]:points[i+1]+1], dtype=np.float32) fragments[seg_counter, :] = 0 else: fragment = np.array(overlaps[points[i]:], dtype=np.float32) fragment[np.isnan(fragment)] = 0 fragments[seg_counter, :len(fragment)] = fragment if i != len(points) - 1: tag_value = tags[points[i]:points[i+1]+1] w = sum(tag_value) / (points[i+1] - points[i]+1) fweights[seg_counter] = seq_weight * w else: tag_value = tags[points[i]:len(overlaps)] w = sum(tag_value) / (traj_len - points[i]+1e-16) fweights[seg_counter] = seq_weight * w seg_counter += 1 else: # no failure max_idx = min(len(overlaps), max_len) fragments[seg_counter, :max_idx] = overlaps[:max_idx] tag_value = tags[0: max_idx] w = sum(tag_value) / max_idx fweights[seg_counter] = seq_weight * w seg_counter += 1 expected_overlaps = calculate_expected_overlap(fragments, fweights) print(len(expected_overlaps)) # calculate eao weight = np.zeros((len(expected_overlaps))) weight[low-1:high-1+1] = 1 expected_overlaps = np.array(expected_overlaps, dtype=np.float32) is_valid = np.logical_not(np.isnan(expected_overlaps)) eao_ = np.sum(expected_overlaps[is_valid] * weight[is_valid]) / np.sum(weight[is_valid]) eao = eao_ return eao class SiamRPNTracker: """ Tracker for SiamRPN""" def __init__(self): valid_scope = 2 * config.valid_scope + 1 self.anchors = generate_anchors(config.total_stride, config.anchor_base_size, config.anchor_scales, config.anchor_ratios, valid_scope) self.window = np.tile(np.outer(np.hanning(config.score_size), np.hanning(config.score_size))[None, :], [config.anchor_num, 1, 1]).flatten() def _cosine_window(self, size): """ get the cosine window """ cos_window = np.hanning(int(size[0]))[:, np.newaxis].dot( np.hanning(int(size[1]))[np.newaxis, :]) cos_window = cos_window.astype(np.float32) cos_window /= np.sum(cos_window) return cos_window def init(self, frame, bbox): """ initialize siamfc tracker Args: frame: an RGB image bbox: one-based bounding box [x, y, width, height] """ self.shape = frame.shape self.pos = np.array( [bbox[0] + bbox[2] / 2 - 1 / 2, bbox[1] + bbox[3] / 2 - 1 / 2]) # center x, center y, zero based self.target_sz = np.array([bbox[2], bbox[3]]) # width, height self.bbox = np.array([bbox[0] + bbox[2] / 2 - 1 / 2, bbox[1] + bbox[3] / 2 - 1 / 2, bbox[2], bbox[3]]) self.origin_target_sz = np.array([bbox[2], bbox[3]]) # get exemplar img self.img_mean = np.mean(frame, axis=(0, 1)) exemplar_img, _, _ = get_exemplar_image(frame, self.bbox, config.exemplar_size, config.context_amount, self.img_mean) exemplar_img = exemplar_img.transpose((2, 0, 1)).astype(np.float32) exemplar_img = np.expand_dims(exemplar_img, axis=0) return exemplar_img def update(self, frame): """track object based on the previous frame Args: frame: an RGB image Returns: bbox: tuple of 1-based bounding box(xmin, ymin, xmax, ymax) """ self.img_mean = np.mean(frame, axis=(0, 1)) instance_img_np, _, _, scale_x = get_instance_image(frame, self.bbox, config.exemplar_size, config.instance_size, config.context_amount, self.img_mean) self.scale_x = scale_x instance_img_np = instance_img_np.transpose( (2, 0, 1)).astype(np.float32) instance_img_np = np.expand_dims(instance_img_np, axis=0) return instance_img_np def postprocess(self, pred_score, pred_regression): """postprocess of prediction""" pred_score = np.frombuffer(pred_score, dtype=np.float32) pred_regression = np.frombuffer(pred_regression, dtype=np.float32) pred_conf = pred_score.reshape( (config.anchor_num * config.score_size * config.score_size, 2)) pred_offset = pred_regression.reshape( (config.anchor_num * config.score_size * config.score_size, 4)) delta = pred_offset box_pred = box_transform_inv(self.anchors, delta) score_pred = softmax(pred_conf)[:, 1] def change(r): return np.maximum(r, 1. / r) def sz(w, h): pad = (w + h) * 0.5 sz2 = (w + pad) * (h + pad) return np.sqrt(sz2) def sz_wh(wh): pad = (wh[0] + wh[1]) * 0.5 sz2 = (wh[0] + pad) * (wh[1] + pad) return np.sqrt(sz2) s_c = change(sz(box_pred[:, 2], box_pred[:, 3]) / (sz_wh(self.target_sz * self.scale_x))) # scale penalty r_c = change((self.target_sz[0] / self.target_sz[1]) / (box_pred[:, 2] / box_pred[:, 3])) # ratio penalty penalty = np.exp(-(r_c * s_c - 1.) * config.penalty_k) pscore = penalty * score_pred pscore = pscore * (1 - config.window_influence) + \ self.window * config.window_influence best_pscore_id = np.argmax(pscore) target = box_pred[best_pscore_id, :] / self.scale_x lr = penalty[best_pscore_id] * \ score_pred[best_pscore_id] * config.lr_box res_x = np.clip(target[0] + self.pos[0], 0, self.shape[1]) res_y = np.clip(target[1] + self.pos[1], 0, self.shape[0]) res_w = np.clip(self.target_sz[0] * (1 - lr) + target[2] * lr, config.min_scale * self.origin_target_sz[0], config.max_scale * self.origin_target_sz[0]) res_h = np.clip(self.target_sz[1] * (1 - lr) + target[3] * lr, config.min_scale * self.origin_target_sz[1], config.max_scale * self.origin_target_sz[1]) self.pos = np.array([res_x, res_y]) self.target_sz = np.array([res_w, res_h]) bbox = np.array([res_x, res_y, res_w, res_h]) self.bbox = ( np.clip(bbox[0], 0, self.shape[1]).astype(np.float64), np.clip(bbox[1], 0, self.shape[0]).astype(np.float64), np.clip(bbox[2], 10, self.shape[1]).astype(np.float64), np.clip(bbox[3], 10, self.shape[0]).astype(np.float64)) return self.bbox, score_pred[best_pscore_id] def write_result(path, data): f = open(path, "w") for box in data: f.write(str(box)+'\n') f.close() def image_inference(pipeline_path, dataset, result_dir): """image_inference""" sdk_api = SdkApi(pipeline_path) if not sdk_api.init(): exit(-1) if not os.path.exists(result_dir): os.makedirs(result_dir) print("\nBegin to inference for {}.\n".format(dataset)) direct_file = os.path.join(dataset, 'list.txt') with open(direct_file, 'r') as f: direct_lines = f.readlines() video_names = np.sort([x.split('\n')[0] for x in direct_lines]) video_paths = [os.path.join(dataset, x) for x in video_names] tracker = SiamRPNTracker() # ------------ starting validation ----------- results = {} accuracy = 0 all_overlaps = [] all_failures = [] gt_lenth = [] for video_name in tqdm(video_names, total=len(video_paths)): # ------------ prepare groundtruth ----------- groundtruth_path = os.path.join(dataset, video_name, 'groundtruth.txt') with open(groundtruth_path, 'r') as f: boxes = f.readlines() if ',' in boxes[0]: boxes = [list(map(float, box.split(','))) for box in boxes] else: boxes = [list(map(int, box.split())) for box in boxes] gt = boxes.copy() frames = [os.path.join(dataset, video_name, 'color', x) for x in np.sort( os.listdir(os.path.join(dataset, video_name, 'color')))] frames = [x for x in frames if '.jpg' in x] template_idx = 0 res = [] if not os.path.exists(os.path.join(result_dir, video_name)): os.makedirs(os.path.join(result_dir, video_name)) result_path = os.path.join(result_dir, video_name, "prediction.txt") template_plugin_id = 0 detection_plugin_id = 1 for idx, frame in tqdm(enumerate(frames), total=len(frames)): frame = cv2.imdecode(np.fromfile( frame, dtype=np.uint8), cv2.IMREAD_UNCHANGED) h, w = frame.shape[0], frame.shape[1] print('processing {}/{}'.format(idx + 1, len(frames))) if idx == template_idx: box = get_axis_aligned_bbox(boxes[idx]) template = tracker.init(frame, box) res.append([1]) elif idx < template_idx: res.append([0]) else: detection = tracker.update(frame) sdk_api.send_tensor_input(config.sdk_pipeline_name, template_plugin_id, "appsrc0", template.tobytes(), [ 1, 3, 127, 127], 0) sdk_api.send_img_input(config.sdk_pipeline_name, detection_plugin_id, "appsrc1", detection.tobytes(), detection.shape) result = sdk_api.get_result(config.sdk_pipeline_name) cout, rout = result[0], result[1] bbox, _ = tracker.postprocess(cout, rout) bbox = np.array(bbox) bbox = list((bbox[0] - bbox[2] / 2 + 1 / 2, bbox[1] - bbox[3] / 2 + 1 / 2, \ bbox[0] + bbox[2] / 2 - 1 / 2, bbox[1] + bbox[3] / 2 - 1 / 2)) if judge_failures(bbox, boxes[idx], 0): res.append([2]) print('fail') template_idx = min(idx + 5, len(frames) - 1) else: res.append(bbox) write_result(result_path, res) acc, overlaps, failures, num_failures = calculate_accuracy_failures(res, gt, [w, h]) accuracy += acc result1 = {} result1['acc'] = acc result1['num_failures'] = num_failures results[video_name] = result1 all_overlaps.append(overlaps) all_failures.append(failures) gt_lenth.append(len(frames)) print(acc, overlaps, num_failures) all_length = sum([len(x) for x in all_overlaps]) robustness = sum([len(x) for x in all_failures]) / all_length * 100 eao = calculate_eao("VOT2016", all_failures, all_overlaps, gt_lenth) result1 = {} result1['accuracy'] = accuracy / float(len(video_paths)) result1['robustness'] = robustness result1['eao'] = eao results['all_videos'] = result1 print('accuracy is ', accuracy / float(len(video_paths))) print('robustness is ', robustness) print('eao is ', eao) json.dump(results, open('./result_val.json', 'w')) if __name__ == "__main__": args = parser_args() image_inference(args.pipeline_path, args.img_path, args.infer_result_dir)
[ "numpy.clip", "numpy.hanning", "numpy.fromfile", "numpy.sqrt", "numpy.hstack", "numpy.array", "numpy.nanmean", "numpy.linalg.norm", "numpy.mean", "os.path.exists", "argparse.ArgumentParser", "numpy.where", "api.infer.SdkApi", "numpy.max", "numpy.exp", "numpy.stack", "numpy.frombuffer...
[((924, 980), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""siamRPN inference"""'}), "(description='siamRPN inference')\n", (947, 980), False, 'import argparse\n'), ((1890, 1910), 'numpy.sqrt', 'np.sqrt', (['(wc_z * hc_z)'], {}), '(wc_z * hc_z)\n', (1897, 1910), True, 'import numpy as np\n'), ((2326, 2346), 'numpy.sqrt', 'np.sqrt', (['(wc_z * hc_z)'], {}), '(wc_z * hc_z)\n', (2333, 2346), True, 'import numpy as np\n'), ((4561, 4604), 'numpy.zeros', 'np.zeros', (['(anchor_num, 4)'], {'dtype': 'np.float32'}), '((anchor_num, 4), dtype=np.float32)\n', (4569, 4604), True, 'import numpy as np\n'), ((6110, 6151), 'numpy.hstack', 'np.hstack', (['[box_cx, box_cy, box_w, box_h]'], {}), '([box_cx, box_cy, box_w, box_h])\n', (6119, 6151), True, 'import numpy as np\n'), ((6322, 6338), 'numpy.array', 'np.array', (['region'], {}), '(region)\n', (6330, 6338), True, 'import numpy as np\n'), ((10747, 10776), 'numpy.zeros', 'np.zeros', (['max_len', 'np.float32'], {}), '(max_len, np.float32)\n', (10755, 10776), True, 'import numpy as np\n'), ((14872, 14917), 'numpy.array', 'np.array', (['expected_overlaps'], {'dtype': 'np.float32'}), '(expected_overlaps, dtype=np.float32)\n', (14880, 14917), True, 'import numpy as np\n'), ((20671, 20692), 'api.infer.SdkApi', 'SdkApi', (['pipeline_path'], {}), '(pipeline_path)\n', (20677, 20692), False, 'from api.infer import SdkApi\n'), ((20886, 20919), 'os.path.join', 'os.path.join', (['dataset', '"""list.txt"""'], {}), "(dataset, 'list.txt')\n", (20898, 20919), False, 'import os\n'), ((3513, 3572), 'numpy.zeros', 'np.zeros', (['(r + top + bottom, c + left + right, k)', 'np.uint8'], {}), '((r + top + bottom, c + left + right, k), np.uint8)\n', (3521, 3572), True, 'import numpy as np\n'), ((4113, 4150), 'numpy.array_equal', 'np.array_equal', (['model_sz', 'original_sz'], {}), '(model_sz, original_sz)\n', (4127, 4150), True, 'import numpy as np\n'), ((4215, 4266), 'cv2.resize', 'cv2.resize', (['im_patch_original', '(model_sz, model_sz)'], {}), '(im_patch_original, (model_sz, model_sz))\n', (4225, 4266), False, 'import cv2\n'), ((6043, 6059), 'numpy.exp', 'np.exp', (['offset_w'], {}), '(offset_w)\n', (6049, 6059), True, 'import numpy as np\n'), ((6083, 6099), 'numpy.exp', 'np.exp', (['offset_h'], {}), '(offset_h)\n', (6089, 6099), True, 'import numpy as np\n'), ((6639, 6655), 'numpy.sqrt', 'np.sqrt', (['(A1 / A2)'], {}), '(A1 / A2)\n', (6646, 6655), True, 'import numpy as np\n'), ((6968, 6985), 'numpy.max', 'np.max', (['x'], {'axis': '(1)'}), '(x, axis=1)\n', (6974, 6985), True, 'import numpy as np\n'), ((7040, 7049), 'numpy.exp', 'np.exp', (['x'], {}), '(x)\n', (7046, 7049), True, 'import numpy as np\n'), ((7064, 7081), 'numpy.sum', 'np.sum', (['x'], {'axis': '(1)'}), '(x, axis=1)\n', (7070, 7081), True, 'import numpy as np\n'), ((7148, 7157), 'numpy.max', 'np.max', (['x'], {}), '(x)\n', (7154, 7157), True, 'import numpy as np\n'), ((7187, 7196), 'numpy.exp', 'np.exp', (['x'], {}), '(x)\n', (7193, 7196), True, 'import numpy as np\n'), ((7211, 7220), 'numpy.sum', 'np.sum', (['x'], {}), '(x)\n', (7217, 7220), True, 'import numpy as np\n'), ((10532, 10552), 'numpy.nanmean', 'np.nanmean', (['overlaps'], {}), '(overlaps)\n', (10542, 10552), True, 'import numpy as np\n'), ((10929, 10941), 'numpy.any', 'np.any', (['mask'], {}), '(mask)\n', (10935, 10941), True, 'import numpy as np\n'), ((11407, 11426), 'numpy.zeros', 'np.zeros', (['(1, K, 4)'], {}), '((1, K, 4))\n', (11415, 11426), True, 'import numpy as np\n'), ((11500, 11519), 'numpy.zeros', 'np.zeros', (['(N, 1, 4)'], {}), '((N, 1, 4))\n', (11508, 11519), True, 'import numpy as np\n'), ((11555, 11604), 'numpy.stack', 'np.stack', (['(box1[:, :, 0], box2[:, :, 0])'], {'axis': '(-1)'}), '((box1[:, :, 0], box2[:, :, 0]), axis=-1)\n', (11563, 11604), True, 'import numpy as np\n'), ((11633, 11682), 'numpy.stack', 'np.stack', (['(box1[:, :, 2], box2[:, :, 2])'], {'axis': '(-1)'}), '((box1[:, :, 2], box2[:, :, 2]), axis=-1)\n', (11641, 11682), True, 'import numpy as np\n'), ((11711, 11760), 'numpy.stack', 'np.stack', (['(box1[:, :, 1], box2[:, :, 1])'], {'axis': '(-1)'}), '((box1[:, :, 1], box2[:, :, 1]), axis=-1)\n', (11719, 11760), True, 'import numpy as np\n'), ((11789, 11838), 'numpy.stack', 'np.stack', (['(box1[:, :, 3], box2[:, :, 3])'], {'axis': '(-1)'}), '((box1[:, :, 3], box2[:, :, 3]), axis=-1)\n', (11797, 11838), True, 'import numpy as np\n'), ((11897, 11913), 'numpy.where', 'np.where', (['(tb < 0)'], {}), '(tb < 0)\n', (11905, 11913), True, 'import numpy as np\n'), ((11926, 11942), 'numpy.where', 'np.where', (['(lr < 0)'], {}), '(lr < 0)\n', (11934, 11942), True, 'import numpy as np\n'), ((12987, 13026), 'numpy.ones', 'np.ones', (['fragment_num'], {'dtype': 'np.float32'}), '(fragment_num, dtype=np.float32)\n', (12994, 13026), True, 'import numpy as np\n'), ((13052, 13102), 'numpy.ones', 'np.ones', (['(fragment_num, max_len)'], {'dtype': 'np.float32'}), '((fragment_num, max_len), dtype=np.float32)\n', (13059, 13102), True, 'import numpy as np\n'), ((14948, 14975), 'numpy.isnan', 'np.isnan', (['expected_overlaps'], {}), '(expected_overlaps)\n', (14956, 14975), True, 'import numpy as np\n'), ((14988, 15042), 'numpy.sum', 'np.sum', (['(expected_overlaps[is_valid] * weight[is_valid])'], {}), '(expected_overlaps[is_valid] * weight[is_valid])\n', (14994, 15042), True, 'import numpy as np\n'), ((15063, 15087), 'numpy.sum', 'np.sum', (['weight[is_valid]'], {}), '(weight[is_valid])\n', (15069, 15087), True, 'import numpy as np\n'), ((15934, 15952), 'numpy.sum', 'np.sum', (['cos_window'], {}), '(cos_window)\n', (15940, 15952), True, 'import numpy as np\n'), ((16224, 16296), 'numpy.array', 'np.array', (['[bbox[0] + bbox[2] / 2 - 1 / 2, bbox[1] + bbox[3] / 2 - 1 / 2]'], {}), '([bbox[0] + bbox[2] / 2 - 1 / 2, bbox[1] + bbox[3] / 2 - 1 / 2])\n', (16232, 16296), True, 'import numpy as np\n'), ((16370, 16398), 'numpy.array', 'np.array', (['[bbox[2], bbox[3]]'], {}), '([bbox[2], bbox[3]])\n', (16378, 16398), True, 'import numpy as np\n'), ((16436, 16530), 'numpy.array', 'np.array', (['[bbox[0] + bbox[2] / 2 - 1 / 2, bbox[1] + bbox[3] / 2 - 1 / 2, bbox[2], bbox[3]\n ]'], {}), '([bbox[0] + bbox[2] / 2 - 1 / 2, bbox[1] + bbox[3] / 2 - 1 / 2,\n bbox[2], bbox[3]])\n', (16444, 16530), True, 'import numpy as np\n'), ((16590, 16618), 'numpy.array', 'np.array', (['[bbox[2], bbox[3]]'], {}), '([bbox[2], bbox[3]])\n', (16598, 16618), True, 'import numpy as np\n'), ((16670, 16697), 'numpy.mean', 'np.mean', (['frame'], {'axis': '(0, 1)'}), '(frame, axis=(0, 1))\n', (16677, 16697), True, 'import numpy as np\n'), ((16972, 17008), 'numpy.expand_dims', 'np.expand_dims', (['exemplar_img'], {'axis': '(0)'}), '(exemplar_img, axis=0)\n', (16986, 17008), True, 'import numpy as np\n'), ((17290, 17317), 'numpy.mean', 'np.mean', (['frame'], {'axis': '(0, 1)'}), '(frame, axis=(0, 1))\n', (17297, 17317), True, 'import numpy as np\n'), ((17750, 17789), 'numpy.expand_dims', 'np.expand_dims', (['instance_img_np'], {'axis': '(0)'}), '(instance_img_np, axis=0)\n', (17764, 17789), True, 'import numpy as np\n'), ((17939, 17982), 'numpy.frombuffer', 'np.frombuffer', (['pred_score'], {'dtype': 'np.float32'}), '(pred_score, dtype=np.float32)\n', (17952, 17982), True, 'import numpy as np\n'), ((18009, 18057), 'numpy.frombuffer', 'np.frombuffer', (['pred_regression'], {'dtype': 'np.float32'}), '(pred_regression, dtype=np.float32)\n', (18022, 18057), True, 'import numpy as np\n'), ((19056, 19101), 'numpy.exp', 'np.exp', (['(-(r_c * s_c - 1.0) * config.penalty_k)'], {}), '(-(r_c * s_c - 1.0) * config.penalty_k)\n', (19062, 19101), True, 'import numpy as np\n'), ((19274, 19291), 'numpy.argmax', 'np.argmax', (['pscore'], {}), '(pscore)\n', (19283, 19291), True, 'import numpy as np\n'), ((19467, 19517), 'numpy.clip', 'np.clip', (['(target[0] + self.pos[0])', '(0)', 'self.shape[1]'], {}), '(target[0] + self.pos[0], 0, self.shape[1])\n', (19474, 19517), True, 'import numpy as np\n'), ((19534, 19584), 'numpy.clip', 'np.clip', (['(target[1] + self.pos[1])', '(0)', 'self.shape[0]'], {}), '(target[1] + self.pos[1], 0, self.shape[0])\n', (19541, 19584), True, 'import numpy as np\n'), ((19602, 19750), 'numpy.clip', 'np.clip', (['(self.target_sz[0] * (1 - lr) + target[2] * lr)', '(config.min_scale * self.origin_target_sz[0])', '(config.max_scale * self.origin_target_sz[0])'], {}), '(self.target_sz[0] * (1 - lr) + target[2] * lr, config.min_scale *\n self.origin_target_sz[0], config.max_scale * self.origin_target_sz[0])\n', (19609, 19750), True, 'import numpy as np\n'), ((19787, 19935), 'numpy.clip', 'np.clip', (['(self.target_sz[1] * (1 - lr) + target[3] * lr)', '(config.min_scale * self.origin_target_sz[1])', '(config.max_scale * self.origin_target_sz[1])'], {}), '(self.target_sz[1] * (1 - lr) + target[3] * lr, config.min_scale *\n self.origin_target_sz[1], config.max_scale * self.origin_target_sz[1])\n', (19794, 19935), True, 'import numpy as np\n'), ((19976, 20000), 'numpy.array', 'np.array', (['[res_x, res_y]'], {}), '([res_x, res_y])\n', (19984, 20000), True, 'import numpy as np\n'), ((20026, 20050), 'numpy.array', 'np.array', (['[res_w, res_h]'], {}), '([res_w, res_h])\n', (20034, 20050), True, 'import numpy as np\n'), ((20066, 20104), 'numpy.array', 'np.array', (['[res_x, res_y, res_w, res_h]'], {}), '([res_x, res_y, res_w, res_h])\n', (20074, 20104), True, 'import numpy as np\n'), ((20748, 20774), 'os.path.exists', 'os.path.exists', (['result_dir'], {}), '(result_dir)\n', (20762, 20774), False, 'import os\n'), ((20784, 20807), 'os.makedirs', 'os.makedirs', (['result_dir'], {}), '(result_dir)\n', (20795, 20807), False, 'import os\n'), ((21082, 21106), 'os.path.join', 'os.path.join', (['dataset', 'x'], {}), '(dataset, x)\n', (21094, 21106), False, 'import os\n'), ((21456, 21508), 'os.path.join', 'os.path.join', (['dataset', 'video_name', '"""groundtruth.txt"""'], {}), "(dataset, video_name, 'groundtruth.txt')\n", (21468, 21508), False, 'import os\n'), ((22196, 22250), 'os.path.join', 'os.path.join', (['result_dir', 'video_name', '"""prediction.txt"""'], {}), "(result_dir, video_name, 'prediction.txt')\n", (22208, 22250), False, 'import os\n'), ((4694, 4715), 'numpy.sqrt', 'np.sqrt', (['(size / ratio)'], {}), '(size / ratio)\n', (4701, 4715), True, 'import numpy as np\n'), ((5005, 5045), 'numpy.tile', 'np.tile', (['anchor', '(score_size * score_size)'], {}), '(anchor, score_size * score_size)\n', (5012, 5045), True, 'import numpy as np\n'), ((6492, 6533), 'numpy.linalg.norm', 'np.linalg.norm', (['(region[0:2] - region[2:4])'], {}), '(region[0:2] - region[2:4])\n', (6506, 6533), True, 'import numpy as np\n'), ((6550, 6591), 'numpy.linalg.norm', 'np.linalg.norm', (['(region[2:4] - region[4:6])'], {}), '(region[2:4] - region[4:6])\n', (6564, 6591), True, 'import numpy as np\n'), ((10891, 10916), 'numpy.isnan', 'np.isnan', (['fragments[:, i]'], {}), '(fragments[:, i])\n', (10899, 10916), True, 'import numpy as np\n'), ((18472, 18494), 'numpy.maximum', 'np.maximum', (['r', '(1.0 / r)'], {}), '(r, 1.0 / r)\n', (18482, 18494), True, 'import numpy as np\n'), ((18608, 18620), 'numpy.sqrt', 'np.sqrt', (['sz2'], {}), '(sz2)\n', (18615, 18620), True, 'import numpy as np\n'), ((18752, 18764), 'numpy.sqrt', 'np.sqrt', (['sz2'], {}), '(sz2)\n', (18759, 18764), True, 'import numpy as np\n'), ((21816, 21861), 'os.path.join', 'os.path.join', (['dataset', 'video_name', '"""color"""', 'x'], {}), "(dataset, video_name, 'color', x)\n", (21828, 21861), False, 'import os\n'), ((7535, 7670), 'numpy.array', 'np.array', (['[[pred_bbox[0], pred_bbox[1]], [pred_bbox[2], pred_bbox[1]], [pred_bbox[2],\n pred_bbox[3]], [pred_bbox[0], pred_bbox[3]]]'], {}), '([[pred_bbox[0], pred_bbox[1]], [pred_bbox[2], pred_bbox[1]], [\n pred_bbox[2], pred_bbox[3]], [pred_bbox[0], pred_bbox[3]]])\n', (7543, 7670), True, 'import numpy as np\n'), ((11012, 11031), 'numpy.sum', 'np.sum', (['fragment', '(1)'], {}), '(fragment, 1)\n', (11018, 11031), True, 'import numpy as np\n'), ((11087, 11120), 'numpy.sum', 'np.sum', (['(seq_mean * fweights[mask])'], {}), '(seq_mean * fweights[mask])\n', (11093, 11120), True, 'import numpy as np\n'), ((11165, 11187), 'numpy.sum', 'np.sum', (['fweights[mask]'], {}), '(fweights[mask])\n', (11171, 11187), True, 'import numpy as np\n'), ((22073, 22109), 'os.path.join', 'os.path.join', (['result_dir', 'video_name'], {}), '(result_dir, video_name)\n', (22085, 22109), False, 'import os\n'), ((22136, 22172), 'os.path.join', 'os.path.join', (['result_dir', 'video_name'], {}), '(result_dir, video_name)\n', (22148, 22172), False, 'import os\n'), ((22417, 22451), 'numpy.fromfile', 'np.fromfile', (['frame'], {'dtype': 'np.uint8'}), '(frame, dtype=np.uint8)\n', (22428, 22451), True, 'import numpy as np\n'), ((13494, 13559), 'numpy.array', 'np.array', (['overlaps[points[i]:points[i + 1] + 1]'], {'dtype': 'np.float32'}), '(overlaps[points[i]:points[i + 1] + 1], dtype=np.float32)\n', (13502, 13559), True, 'import numpy as np\n'), ((13684, 13732), 'numpy.array', 'np.array', (['overlaps[points[i]:]'], {'dtype': 'np.float32'}), '(overlaps[points[i]:], dtype=np.float32)\n', (13692, 13732), True, 'import numpy as np\n'), ((13758, 13776), 'numpy.isnan', 'np.isnan', (['fragment'], {}), '(fragment)\n', (13766, 13776), True, 'import numpy as np\n'), ((20139, 20173), 'numpy.clip', 'np.clip', (['bbox[0]', '(0)', 'self.shape[1]'], {}), '(bbox[0], 0, self.shape[1])\n', (20146, 20173), True, 'import numpy as np\n'), ((20206, 20240), 'numpy.clip', 'np.clip', (['bbox[1]', '(0)', 'self.shape[0]'], {}), '(bbox[1], 0, self.shape[0])\n', (20213, 20240), True, 'import numpy as np\n'), ((20273, 20308), 'numpy.clip', 'np.clip', (['bbox[2]', '(10)', 'self.shape[1]'], {}), '(bbox[2], 10, self.shape[1])\n', (20280, 20308), True, 'import numpy as np\n'), ((20341, 20376), 'numpy.clip', 'np.clip', (['bbox[3]', '(10)', 'self.shape[0]'], {}), '(bbox[3], 10, self.shape[0])\n', (20348, 20376), True, 'import numpy as np\n'), ((23607, 23621), 'numpy.array', 'np.array', (['bbox'], {}), '(bbox)\n', (23615, 23621), True, 'import numpy as np\n'), ((7389, 7408), 'numpy.array', 'np.array', (['pred_bbox'], {}), '(pred_bbox)\n', (7397, 7408), True, 'import numpy as np\n'), ((7425, 7442), 'numpy.array', 'np.array', (['gt_bbox'], {}), '(gt_bbox)\n', (7433, 7442), True, 'import numpy as np\n'), ((7858, 7875), 'numpy.array', 'np.array', (['gt_bbox'], {}), '(gt_bbox)\n', (7866, 7875), True, 'import numpy as np\n'), ((8861, 8931), 'numpy.array', 'np.array', (['[[0, 0], [0, bound[1]], [bound[0], bound[1]], [bound[0], 0]]'], {}), '([[0, 0], [0, bound[1]], [bound[0], bound[1]], [bound[0], 0]])\n', (8869, 8931), True, 'import numpy as np\n'), ((9161, 9373), 'numpy.array', 'np.array', (['[[pred_trajectory[i][0], pred_trajectory[i][1]], [pred_trajectory[i][2],\n pred_trajectory[i][1]], [pred_trajectory[i][2], pred_trajectory[i][3]],\n [pred_trajectory[i][0], pred_trajectory[i][3]]]'], {}), '([[pred_trajectory[i][0], pred_trajectory[i][1]], [pred_trajectory[\n i][2], pred_trajectory[i][1]], [pred_trajectory[i][2], pred_trajectory[\n i][3]], [pred_trajectory[i][0], pred_trajectory[i][3]]])\n', (9169, 9373), True, 'import numpy as np\n'), ((21903, 21945), 'os.path.join', 'os.path.join', (['dataset', 'video_name', '"""color"""'], {}), "(dataset, video_name, 'color')\n", (21915, 21945), False, 'import os\n'), ((15508, 15537), 'numpy.hanning', 'np.hanning', (['config.score_size'], {}), '(config.score_size)\n', (15518, 15537), True, 'import numpy as np\n'), ((15539, 15568), 'numpy.hanning', 'np.hanning', (['config.score_size'], {}), '(config.score_size)\n', (15549, 15568), True, 'import numpy as np\n'), ((9617, 9643), 'numpy.array', 'np.array', (['gt_trajectory[i]'], {}), '(gt_trajectory[i])\n', (9625, 9643), True, 'import numpy as np\n'), ((10331, 10359), 'numpy.array', 'np.array', (['pred_trajectory[i]'], {}), '(pred_trajectory[i])\n', (10339, 10359), True, 'import numpy as np\n'), ((10376, 10402), 'numpy.array', 'np.array', (['gt_trajectory[i]'], {}), '(gt_trajectory[i])\n', (10384, 10402), True, 'import numpy as np\n')]
# Simple systolic array of P processing element, each one increments by 1 the incoming element import argparse import dace import numpy as np import pdb import select import sys N = dace.symbol("N") P = dace.symbol("P") def make_copy_to_fpga_state(sdfg): ########################################################################### # Copy data to FPGA state = sdfg.add_state("copy_to_device") A_host = state.add_array("A", [N], dtype=dace.int32) A_device = state.add_array( "A_device", [N], dtype=dace.int32, transient=True, storage=dace.dtypes.StorageType.FPGA_Global) state.add_edge(A_host, None, A_device, None, dace.memlet.Memlet.simple(A_device, "0:N")) return state def make_copy_to_host_state(sdfg): ########################################################################### # Copy data to FPGA state = sdfg.add_state("copy_to_host") A_device = state.add_array( "A_device", [N], dtype=dace.int32, transient=True, storage=dace.dtypes.StorageType.FPGA_Global) A_host = state.add_array("A", [N], dtype=dace.int32) state.add_edge(A_device, None, A_host, None, dace.memlet.Memlet.simple(A_host, "0:N")) return state def make_read_A_sdfg(): sdfg = dace.SDFG("array_read_A") n_inner_begin = sdfg.add_state("n_inner_begin") n_inner_entry = sdfg.add_state("n_inner_entry") n_inner_end = sdfg.add_state("n_inner_end") loop_body = sdfg.add_state("read_memory") sdfg.add_edge( n_inner_begin, n_inner_entry, dace.graph.edges.InterstateEdge(assignments={"n": 0})) sdfg.add_edge( n_inner_entry, loop_body, dace.graph.edges.InterstateEdge( condition=dace.properties.CodeProperty.from_string( "n < N", language=dace.dtypes.Language.Python))) sdfg.add_edge( n_inner_entry, n_inner_end, dace.graph.edges.InterstateEdge( condition=dace.properties.CodeProperty.from_string( "n >= N", language=dace.dtypes.Language.Python))) sdfg.add_edge( loop_body, n_inner_entry, dace.graph.edges.InterstateEdge(assignments={"n": "n + 1"})) mem = loop_body.add_array( "mem", [N], dtype=dace.int32, storage=dace.dtypes.StorageType.FPGA_Global) pipe = loop_body.add_stream( "pipe", dace.int32, storage=dace.dtypes.StorageType.FPGA_Local) loop_body.add_memlet_path( mem, pipe, memlet=dace.memlet.Memlet( pipe, dace.symbolic.pystr_to_symbolic("1"), dace.properties.SubsetProperty.from_string("0"), 1, other_subset=dace.properties.SubsetProperty.from_string("n"))) return sdfg def make_write_A_sdfg(): sdfg = dace.SDFG("array_write_A") n_begin = sdfg.add_state("n_begin") n_entry = sdfg.add_state("n_entry") n_end = sdfg.add_state("n_end") loop_body = sdfg.add_state("write_memory") sdfg.add_edge( n_begin, n_entry, dace.graph.edges.InterstateEdge(assignments={"n": 0})) sdfg.add_edge( n_entry, loop_body, dace.graph.edges.InterstateEdge( condition=dace.properties.CodeProperty.from_string( "n < N", language=dace.dtypes.Language.Python))) sdfg.add_edge( loop_body, n_entry, dace.graph.edges.InterstateEdge(assignments={"n": "n + 1"})) sdfg.add_edge( n_entry, n_end, dace.graph.edges.InterstateEdge( condition=dace.properties.CodeProperty.from_string( "n >= N", language=dace.dtypes.Language.Python))) mem = loop_body.add_array( "mem", [N], dtype=dace.int32, storage=dace.dtypes.StorageType.FPGA_Global) pipe = loop_body.add_stream( "pipe", dace.int32, storage=dace.dtypes.StorageType.FPGA_Local) loop_body.add_memlet_path( pipe, mem, memlet=dace.memlet.Memlet( mem, dace.symbolic.pystr_to_symbolic("1"), dace.properties.SubsetProperty.from_string("n"), 1, other_subset=dace.properties.SubsetProperty.from_string("0"))) return sdfg def make_compute_sdfg(): sdfg = dace.SDFG("gemm_compute") n_begin = sdfg.add_state("n_begin") n_entry = sdfg.add_state("n_entry") n_end = sdfg.add_state("n_end") state = sdfg.add_state("compute") # Data nodes A_pipe_in = state.add_stream( "A_stream_in", dace.int32, storage=dace.dtypes.StorageType.FPGA_Local) A_pipe_out = state.add_stream( "A_stream_out", dace.int32, storage=dace.dtypes.StorageType.FPGA_Local) # N-loop sdfg.add_edge( n_begin, n_entry, dace.graph.edges.InterstateEdge(assignments={"n": 0})) sdfg.add_edge( n_entry, state, dace.graph.edges.InterstateEdge( condition=dace.properties.CodeProperty.from_string( "n < N", language=dace.dtypes.Language.Python))) sdfg.add_edge( n_entry, n_end, dace.graph.edges.InterstateEdge( condition=dace.properties.CodeProperty.from_string( "n >= N", language=dace.dtypes.Language.Python))) # Backtrack two loops sdfg.add_edge( state, n_entry, dace.graph.edges.InterstateEdge(assignments={"n": "n + 1"})) # Compute tasklet compute_tasklet = state.add_tasklet("add", {"a_in"}, {"a_out"}, "a_out = a_in +1") state.add_memlet_path( A_pipe_in, compute_tasklet, memlet=dace.memlet.Memlet( A_pipe_in, dace.symbolic.pystr_to_symbolic("-1"), dace.properties.SubsetProperty.from_string("0"), 1), dst_conn="a_in") state.add_memlet_path( compute_tasklet, A_pipe_out, memlet=dace.memlet.Memlet( A_pipe_out, dace.symbolic.pystr_to_symbolic("-1"), dace.properties.SubsetProperty.from_string("0"), 1), src_conn="a_out") return sdfg def make_fpga_state(sdfg): state = sdfg.add_state("simple_array") read_A_sdfg = make_read_A_sdfg() read_A_sdfg_node = state.add_nested_sdfg(read_A_sdfg, sdfg, {"mem"}, {"pipe"}) compute_sdfg = make_compute_sdfg() compute_sdfg_node = state.add_nested_sdfg( compute_sdfg, sdfg, {"A_stream_in"}, {"A_stream_out"}) write_A_sdfg = make_write_A_sdfg() write_A_sdfg_node = state.add_nested_sdfg(write_A_sdfg, sdfg, {"pipe"}, {"mem"}) A_IN = state.add_array( "A_device", [N], dtype=dace.int32, transient=True, storage=dace.dtypes.StorageType.FPGA_Global) A_OUT = state.add_array( "A_device", [N], dtype=dace.int32, transient=True, storage=dace.dtypes.StorageType.FPGA_Global) A_pipe_read = state.add_stream( "A_pipe", dace.int32, transient=True, shape=(P + 1, ), storage=dace.dtypes.StorageType.FPGA_Local) A_pipe_in = state.add_stream( "A_pipe", dace.int32, transient=True, shape=(P + 1, ), storage=dace.dtypes.StorageType.FPGA_Local) A_pipe_write = state.add_stream( "A_pipe", dace.int32, transient=True, shape=(P + 1, ), storage=dace.dtypes.StorageType.FPGA_Local) A_pipe_out = state.add_stream( "A_pipe", dace.int32, transient=True, shape=(P + 1, ), storage=dace.dtypes.StorageType.FPGA_Local) compute_entry, compute_exit = state.add_map( "unroll_compute", {"p": "0:P"}, schedule=dace.ScheduleType.FPGA_Device, unroll=True) # Bring data nodes into scope state.add_memlet_path( compute_entry, A_pipe_in, memlet=dace.memlet.EmptyMemlet()) state.add_memlet_path( A_pipe_out, compute_exit, memlet=dace.memlet.EmptyMemlet()) # Connect data nodes state.add_memlet_path( A_pipe_in, compute_sdfg_node, dst_conn="A_stream_in", memlet=dace.memlet.Memlet( A_pipe_in, dace.symbolic.pystr_to_symbolic("N/P"), dace.properties.SubsetProperty.from_string("p"), 1)) state.add_memlet_path( compute_sdfg_node, A_pipe_out, src_conn="A_stream_out", memlet=dace.memlet.Memlet( A_pipe_out, dace.symbolic.pystr_to_symbolic("N/P"), dace.properties.SubsetProperty.from_string("p + 1"), 1)) state.add_memlet_path( A_IN, read_A_sdfg_node, dst_conn="mem", memlet=dace.memlet.Memlet( A_IN, dace.symbolic.pystr_to_symbolic("N"), dace.properties.SubsetProperty.from_string("0:N"), 1)) state.add_memlet_path( read_A_sdfg_node, A_pipe_read, src_conn="pipe", memlet=dace.memlet.Memlet( A_pipe_in, dace.symbolic.pystr_to_symbolic("N"), dace.properties.SubsetProperty.from_string("0"), 1)) state.add_memlet_path( A_pipe_write, write_A_sdfg_node, dst_conn="pipe", memlet=dace.memlet.Memlet( A_pipe_out, dace.symbolic.pystr_to_symbolic("N"), dace.properties.SubsetProperty.from_string("P"), 1)) state.add_memlet_path( write_A_sdfg_node, A_OUT, src_conn="mem", memlet=dace.memlet.Memlet( A_OUT, dace.symbolic.pystr_to_symbolic("N"), dace.properties.SubsetProperty.from_string("0:N"), 1)) return state def make_sdfg(specialized): sdfg = dace.SDFG("simple_systolic_array_{}".format(P.get())) pre_state = make_copy_to_fpga_state(sdfg) compute_state = make_fpga_state(sdfg) post_state = make_copy_to_host_state(sdfg) sdfg.add_edge(pre_state, compute_state, dace.graph.edges.InterstateEdge()) sdfg.add_edge(compute_state, post_state, dace.graph.edges.InterstateEdge()) return sdfg if __name__ == "__main__": print("==== Program start ====") parser = argparse.ArgumentParser() parser.add_argument("N", type=int) parser.add_argument("P", type=int) args = vars(parser.parse_args()) P.set(args["P"]) N.set(args["N"]) sdfg = make_sdfg(False) sdfg.specialize(dict(P=P, N=N)) print("Simple Systolic array") # Initialize arrays: Randomize A and B, zero C A = np.ndarray([N.get()], dtype=dace.int32.type) A[:] = np.random.randint(0, 1000, N.get()).astype(dace.int32.type) A_Exp = A + P.get() sdfg.draw_to_file() sdfg(A=A) # print("A: ", A) # print("A_Exp: ", A_Exp) diff = np.abs(A_Exp - A) diff_total = np.sum(diff) highest_diff = np.max(diff) wrong_elements = np.transpose(np.nonzero(diff >= 0.01)) print("==== Program end ====") if diff_total >= 0.01: print("Verification failed!") exit(1) else: print("Results verified successfully.") exit(0)
[ "dace.memlet.EmptyMemlet", "numpy.abs", "argparse.ArgumentParser", "dace.graph.edges.InterstateEdge", "dace.properties.CodeProperty.from_string", "dace.properties.SubsetProperty.from_string", "dace.memlet.Memlet.simple", "dace.symbol", "numpy.max", "numpy.sum", "dace.SDFG", "numpy.nonzero", ...
[((184, 200), 'dace.symbol', 'dace.symbol', (['"""N"""'], {}), "('N')\n", (195, 200), False, 'import dace\n'), ((205, 221), 'dace.symbol', 'dace.symbol', (['"""P"""'], {}), "('P')\n", (216, 221), False, 'import dace\n'), ((1330, 1355), 'dace.SDFG', 'dace.SDFG', (['"""array_read_A"""'], {}), "('array_read_A')\n", (1339, 1355), False, 'import dace\n'), ((2887, 2913), 'dace.SDFG', 'dace.SDFG', (['"""array_write_A"""'], {}), "('array_write_A')\n", (2896, 2913), False, 'import dace\n'), ((4375, 4400), 'dace.SDFG', 'dace.SDFG', (['"""gemm_compute"""'], {}), "('gemm_compute')\n", (4384, 4400), False, 'import dace\n'), ((10269, 10294), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (10292, 10294), False, 'import argparse\n'), ((10857, 10874), 'numpy.abs', 'np.abs', (['(A_Exp - A)'], {}), '(A_Exp - A)\n', (10863, 10874), True, 'import numpy as np\n'), ((10892, 10904), 'numpy.sum', 'np.sum', (['diff'], {}), '(diff)\n', (10898, 10904), True, 'import numpy as np\n'), ((10924, 10936), 'numpy.max', 'np.max', (['diff'], {}), '(diff)\n', (10930, 10936), True, 'import numpy as np\n'), ((698, 740), 'dace.memlet.Memlet.simple', 'dace.memlet.Memlet.simple', (['A_device', '"""0:N"""'], {}), "(A_device, '0:N')\n", (723, 740), False, 'import dace\n'), ((1232, 1272), 'dace.memlet.Memlet.simple', 'dace.memlet.Memlet.simple', (['A_host', '"""0:N"""'], {}), "(A_host, '0:N')\n", (1257, 1272), False, 'import dace\n'), ((1630, 1683), 'dace.graph.edges.InterstateEdge', 'dace.graph.edges.InterstateEdge', ([], {'assignments': "{'n': 0}"}), "(assignments={'n': 0})\n", (1661, 1683), False, 'import dace\n'), ((2220, 2279), 'dace.graph.edges.InterstateEdge', 'dace.graph.edges.InterstateEdge', ([], {'assignments': "{'n': 'n + 1'}"}), "(assignments={'n': 'n + 1'})\n", (2251, 2279), False, 'import dace\n'), ((3141, 3194), 'dace.graph.edges.InterstateEdge', 'dace.graph.edges.InterstateEdge', ([], {'assignments': "{'n': 0}"}), "(assignments={'n': 0})\n", (3172, 3194), False, 'import dace\n'), ((3486, 3545), 'dace.graph.edges.InterstateEdge', 'dace.graph.edges.InterstateEdge', ([], {'assignments': "{'n': 'n + 1'}"}), "(assignments={'n': 'n + 1'})\n", (3517, 3545), False, 'import dace\n'), ((4878, 4931), 'dace.graph.edges.InterstateEdge', 'dace.graph.edges.InterstateEdge', ([], {'assignments': "{'n': 0}"}), "(assignments={'n': 0})\n", (4909, 4931), False, 'import dace\n'), ((5462, 5521), 'dace.graph.edges.InterstateEdge', 'dace.graph.edges.InterstateEdge', ([], {'assignments': "{'n': 'n + 1'}"}), "(assignments={'n': 'n + 1'})\n", (5493, 5521), False, 'import dace\n'), ((10057, 10090), 'dace.graph.edges.InterstateEdge', 'dace.graph.edges.InterstateEdge', ([], {}), '()\n', (10088, 10090), False, 'import dace\n'), ((10137, 10170), 'dace.graph.edges.InterstateEdge', 'dace.graph.edges.InterstateEdge', ([], {}), '()\n', (10168, 10170), False, 'import dace\n'), ((10971, 10995), 'numpy.nonzero', 'np.nonzero', (['(diff >= 0.01)'], {}), '(diff >= 0.01)\n', (10981, 10995), True, 'import numpy as np\n'), ((8045, 8070), 'dace.memlet.EmptyMemlet', 'dace.memlet.EmptyMemlet', ([], {}), '()\n', (8068, 8070), False, 'import dace\n'), ((8140, 8165), 'dace.memlet.EmptyMemlet', 'dace.memlet.EmptyMemlet', ([], {}), '()\n', (8163, 8165), False, 'import dace\n'), ((1809, 1901), 'dace.properties.CodeProperty.from_string', 'dace.properties.CodeProperty.from_string', (['"""n < N"""'], {'language': 'dace.dtypes.Language.Python'}), "('n < N', language=dace.dtypes.\n Language.Python)\n", (1849, 1901), False, 'import dace\n'), ((2042, 2135), 'dace.properties.CodeProperty.from_string', 'dace.properties.CodeProperty.from_string', (['"""n >= N"""'], {'language': 'dace.dtypes.Language.Python'}), "('n >= N', language=dace.dtypes.\n Language.Python)\n", (2082, 2135), False, 'import dace\n'), ((2642, 2678), 'dace.symbolic.pystr_to_symbolic', 'dace.symbolic.pystr_to_symbolic', (['"""1"""'], {}), "('1')\n", (2673, 2678), False, 'import dace\n'), ((2692, 2739), 'dace.properties.SubsetProperty.from_string', 'dace.properties.SubsetProperty.from_string', (['"""0"""'], {}), "('0')\n", (2734, 2739), False, 'import dace\n'), ((3315, 3407), 'dace.properties.CodeProperty.from_string', 'dace.properties.CodeProperty.from_string', (['"""n < N"""'], {'language': 'dace.dtypes.Language.Python'}), "('n < N', language=dace.dtypes.\n Language.Python)\n", (3355, 3407), False, 'import dace\n'), ((3662, 3755), 'dace.properties.CodeProperty.from_string', 'dace.properties.CodeProperty.from_string', (['"""n >= N"""'], {'language': 'dace.dtypes.Language.Python'}), "('n >= N', language=dace.dtypes.\n Language.Python)\n", (3702, 3755), False, 'import dace\n'), ((4130, 4166), 'dace.symbolic.pystr_to_symbolic', 'dace.symbolic.pystr_to_symbolic', (['"""1"""'], {}), "('1')\n", (4161, 4166), False, 'import dace\n'), ((4180, 4227), 'dace.properties.SubsetProperty.from_string', 'dace.properties.SubsetProperty.from_string', (['"""n"""'], {}), "('n')\n", (4222, 4227), False, 'import dace\n'), ((5047, 5139), 'dace.properties.CodeProperty.from_string', 'dace.properties.CodeProperty.from_string', (['"""n < N"""'], {'language': 'dace.dtypes.Language.Python'}), "('n < N', language=dace.dtypes.\n Language.Python)\n", (5087, 5139), False, 'import dace\n'), ((5268, 5361), 'dace.properties.CodeProperty.from_string', 'dace.properties.CodeProperty.from_string', (['"""n >= N"""'], {'language': 'dace.dtypes.Language.Python'}), "('n >= N', language=dace.dtypes.\n Language.Python)\n", (5308, 5361), False, 'import dace\n'), ((5804, 5841), 'dace.symbolic.pystr_to_symbolic', 'dace.symbolic.pystr_to_symbolic', (['"""-1"""'], {}), "('-1')\n", (5835, 5841), False, 'import dace\n'), ((5855, 5902), 'dace.properties.SubsetProperty.from_string', 'dace.properties.SubsetProperty.from_string', (['"""0"""'], {}), "('0')\n", (5897, 5902), False, 'import dace\n'), ((6064, 6101), 'dace.symbolic.pystr_to_symbolic', 'dace.symbolic.pystr_to_symbolic', (['"""-1"""'], {}), "('-1')\n", (6095, 6101), False, 'import dace\n'), ((6115, 6162), 'dace.properties.SubsetProperty.from_string', 'dace.properties.SubsetProperty.from_string', (['"""0"""'], {}), "('0')\n", (6157, 6162), False, 'import dace\n'), ((8356, 8394), 'dace.symbolic.pystr_to_symbolic', 'dace.symbolic.pystr_to_symbolic', (['"""N/P"""'], {}), "('N/P')\n", (8387, 8394), False, 'import dace\n'), ((8408, 8455), 'dace.properties.SubsetProperty.from_string', 'dace.properties.SubsetProperty.from_string', (['"""p"""'], {}), "('p')\n", (8450, 8455), False, 'import dace\n'), ((8627, 8665), 'dace.symbolic.pystr_to_symbolic', 'dace.symbolic.pystr_to_symbolic', (['"""N/P"""'], {}), "('N/P')\n", (8658, 8665), False, 'import dace\n'), ((8679, 8730), 'dace.properties.SubsetProperty.from_string', 'dace.properties.SubsetProperty.from_string', (['"""p + 1"""'], {}), "('p + 1')\n", (8721, 8730), False, 'import dace\n'), ((8881, 8917), 'dace.symbolic.pystr_to_symbolic', 'dace.symbolic.pystr_to_symbolic', (['"""N"""'], {}), "('N')\n", (8912, 8917), False, 'import dace\n'), ((8931, 8980), 'dace.properties.SubsetProperty.from_string', 'dace.properties.SubsetProperty.from_string', (['"""0:N"""'], {}), "('0:N')\n", (8973, 8980), False, 'import dace\n'), ((9143, 9179), 'dace.symbolic.pystr_to_symbolic', 'dace.symbolic.pystr_to_symbolic', (['"""N"""'], {}), "('N')\n", (9174, 9179), False, 'import dace\n'), ((9193, 9240), 'dace.properties.SubsetProperty.from_string', 'dace.properties.SubsetProperty.from_string', (['"""0"""'], {}), "('0')\n", (9235, 9240), False, 'import dace\n'), ((9407, 9443), 'dace.symbolic.pystr_to_symbolic', 'dace.symbolic.pystr_to_symbolic', (['"""N"""'], {}), "('N')\n", (9438, 9443), False, 'import dace\n'), ((9457, 9504), 'dace.properties.SubsetProperty.from_string', 'dace.properties.SubsetProperty.from_string', (['"""P"""'], {}), "('P')\n", (9499, 9504), False, 'import dace\n'), ((9657, 9693), 'dace.symbolic.pystr_to_symbolic', 'dace.symbolic.pystr_to_symbolic', (['"""N"""'], {}), "('N')\n", (9688, 9693), False, 'import dace\n'), ((9707, 9756), 'dace.properties.SubsetProperty.from_string', 'dace.properties.SubsetProperty.from_string', (['"""0:N"""'], {}), "('0:N')\n", (9749, 9756), False, 'import dace\n'), ((2781, 2828), 'dace.properties.SubsetProperty.from_string', 'dace.properties.SubsetProperty.from_string', (['"""n"""'], {}), "('n')\n", (2823, 2828), False, 'import dace\n'), ((4269, 4316), 'dace.properties.SubsetProperty.from_string', 'dace.properties.SubsetProperty.from_string', (['"""0"""'], {}), "('0')\n", (4311, 4316), False, 'import dace\n')]
# coding=utf-8 import traceback import h5py import skimage.transform from keras.utils import Sequence import numpy as np import cv2 import glob import pandas as pd import os from kf_util import flip_axis def rgbf2bgr(rgbf): t = rgbf*255.0 t = np.clip(t, 0.,255.0) bgr = t.astype(np.uint8)[..., ::-1] return bgr def get_depth_data(paths=None): path_in=[] if paths is None: paths = ['../data/nyudepthv2/train'] for path in paths: for file in glob.glob(path+"/*/*.h5"): path_in.append(file) df = pd.DataFrame(path_in,columns=['path_in']) return df def read_rgbd(filename): f = h5py.File(filename, 'r') rgb = np.array(f['rgb'], dtype=np.float32) #channels_first rgb = np.moveaxis(rgb, 0, 2) #channels_last depth = np.array(f['depth'], dtype=np.float32) depth = np.expand_dims(depth,axis=2) f.close() return rgb, depth class DepthImageSequence(Sequence): def __init__(self, df, batch_size=8, input_size=(128, 128), crop_mode='random', random_flip=False, random_rot90=False, scale_down_to=None, random_color=False, augment_bright_contrast=False, max_depth = 10.0, #max depth in m randomize_epoch=False): # self.random_squeeze = random_squeeze self.max_depth = max_depth self.random_color = random_color self.augment_bright_contrast = augment_bright_contrast self.random_rot90 = random_rot90 self.random_flip = random_flip self.scale_down_to = scale_down_to self.randomize_epoch = randomize_epoch self.input_shape = input_size + (3,) self.batch_size = batch_size self.crop_mode = crop_mode self.df = df self.epoch = 0 def crop_rand(self, img1,img2): assert img1.shape[0] == img2.shape[0] and img1.shape[1] == img2.shape[1] if img1.shape[0] == self.input_shape[0] and img1.shape[1] == self.input_shape[1]: return img1, img2 w = self.input_shape[0] h = self.input_shape[1] dx = img1.shape[0] - w dy = img1.shape[1] - h if dx > 0: dx = np.random.randint(0, dx) if dy > 0: dy = np.random.randint(0, dy) return img1[dx:dx + w, dy:dy + h, :],img2[dx:dx + w, dy:dy + h, :] def crop_center(self, img1,img2): if img1.shape[0] == self.input_shape[0] and img1.shape[1] == self.input_shape[1]: return img1, img2 assert img1.shape[0] == img2.shape[0] and img1.shape[1] == img2.shape[1] w = self.input_shape[0] h = self.input_shape[1] dx = (img1.shape[0] - w) // 2 dy = (img1.shape[1] - h) // 2 return img1[dx:dx + w, dy:dy + h, :],img2[dx:dx + w, dy:dy + h, :] # number of steps def __len__(self): return (len(self.df) + self.batch_size - 1) // self.batch_size def read_scaled_images_bgr(self, row): bgr = self.read_bgr_scaled(row.path_in) obgr = self.read_bgr_scaled(row.path_out) return bgr, obgr def read_scaled_images_rgb(self, row): bgr,obgr = self.read_scaled_images_bgr(row) return bgr[..., ::-1], obgr[..., ::-1] if obgr is not None else None def read_images_bgr(self, row): bgr = cv2.imread(row.path_in) obgr = cv2.imread(row.path_out) return bgr, obgr def random_color_change(self, ximg): random_color = np.random.uniform(0.6, 1.2, size=3) return ximg * random_color def random_hsv_change(self, ximg): imghsv = cv2.cvtColor(ximg, cv2.COLOR_RGB2HSV).astype("float32") (h, s, v) = cv2.split(imghsv) ss = np.random.random() * 0.7 s = s * (ss + 0.3) s = np.clip(s,0,255) vs = np.random.random() * 0.9 v = v * (vs + 0.8) v = np.clip(v,0,255) imghsv = cv2.merge([h,s,v]) imgrgb = cv2.cvtColor(imghsv.astype("uint8"), cv2.COLOR_HSV2RGB) return imgrgb def random_bright_contrast(self, ximg): alpha = (np.random.random()*0.8 + 0.2) beta = np.random.random()*150.0 xf = ximg.astype("float32")*alpha + beta xf = np.clip(xf,0.0,255.0) ximg = xf.astype("uint8") return ximg # called every step def __getitem__(self, idx): if idx >= self.__len__(): raise IndexError x_batch = [] y_batch = [] start = idx * self.batch_size end = min(start + self.batch_size, len(self.df)) df_batch = self.df.iloc[start:end] for i, d in df_batch.iterrows(): ximgo, yimgo = read_rgbd(d.path_in) if self.scale_down_to == 'random': if np.random.random() < 0.5: h = int(np.random.uniform(self.input_shape[0]+8, ximgo.shape[0])) w = int(np.random.uniform(self.input_shape[1]+8, ximgo.shape[1])) ximgo = skimage.transform.resize(ximgo, (h,w), order=3, preserve_range=True, mode='reflect') yimgo = skimage.transform.resize(yimgo, (h,w), order=0, preserve_range=True, mode='reflect') elif self.scale_down_to is not None: ximgo = skimage.transform.resize(ximgo, self.scale_down_to, order=3, preserve_range=True, mode='reflect') yimgo = skimage.transform.resize(yimgo, self.scale_down_to, order=0, preserve_range=True, mode='reflect') if self.crop_mode == 'random': ximg,yimg = self.crop_rand(ximgo,yimgo) elif self.crop_mode == 'center': ximg,yimg = self.crop_center(ximgo,yimgo) else: raise ValueError("Unknown crop mode " + self.crop_mode) if self.augment_bright_contrast: if np.random.random() < 0.5: ximg = self.random_bright_contrast(ximg) if self.random_color: if np.random.random() < 0.5: ximg = self.random_color_change(ximg) if self.random_flip: if np.random.random() < 0.5: ximg = flip_axis(ximg, 0) yimg = flip_axis(yimg, 0) if np.random.random() < 0.5: ximg = flip_axis(ximg, 1) yimg = flip_axis(yimg, 1) if self.random_rot90: if np.random.random() < 0.5: ximg = np.rot90(ximg) yimg = np.rot90(yimg) x_batch.append(ximg) y_batch.append(yimg) x_batch = np.array(x_batch, np.float32) / 255.0 y_batch = np.array(y_batch, np.float32) / self.max_depth return x_batch,y_batch def on_epoch_end(self): self.epoch += 1 if self.randomize_epoch: self.df = self.df.sample(frac=1) # shuffle def show_samples(): df = get_depth_data(['../data/nyudepthv2/train']) df = df.sample(frac=1, random_state=42) # shuffle train_seq = DepthImageSequence(df, input_size=(384, 384), scale_down_to='random', random_flip=True, random_rot90=True, random_color=False, augment_bright_contrast=True, crop_mode='random') import matplotlib.pylab as plt plt.figure(figsize=(20, 20)) for x_batch, y_batch in train_seq: for x, y in zip(x_batch, y_batch): plt.imshow(rgbf2bgr(x[:, :, 0:3])) plt.show(block=False) plt.imshow(y[:,:,0]) plt.show(block=False) #if __name__ == '__main__': #show_samples()
[ "numpy.clip", "numpy.array", "matplotlib.pylab.imshow", "matplotlib.pylab.show", "numpy.rot90", "numpy.moveaxis", "matplotlib.pylab.figure", "numpy.random.random", "pandas.DataFrame", "glob.glob", "cv2.merge", "kf_util.flip_axis", "h5py.File", "cv2.split", "cv2.cvtColor", "cv2.imread",...
[((248, 270), 'numpy.clip', 'np.clip', (['t', '(0.0)', '(255.0)'], {}), '(t, 0.0, 255.0)\n', (255, 270), True, 'import numpy as np\n'), ((512, 554), 'pandas.DataFrame', 'pd.DataFrame', (['path_in'], {'columns': "['path_in']"}), "(path_in, columns=['path_in'])\n", (524, 554), True, 'import pandas as pd\n'), ((596, 620), 'h5py.File', 'h5py.File', (['filename', '"""r"""'], {}), "(filename, 'r')\n", (605, 620), False, 'import h5py\n'), ((628, 664), 'numpy.array', 'np.array', (["f['rgb']"], {'dtype': 'np.float32'}), "(f['rgb'], dtype=np.float32)\n", (636, 664), True, 'import numpy as np\n'), ((688, 710), 'numpy.moveaxis', 'np.moveaxis', (['rgb', '(0)', '(2)'], {}), '(rgb, 0, 2)\n', (699, 710), True, 'import numpy as np\n'), ((735, 773), 'numpy.array', 'np.array', (["f['depth']"], {'dtype': 'np.float32'}), "(f['depth'], dtype=np.float32)\n", (743, 773), True, 'import numpy as np\n'), ((783, 812), 'numpy.expand_dims', 'np.expand_dims', (['depth'], {'axis': '(2)'}), '(depth, axis=2)\n', (797, 812), True, 'import numpy as np\n'), ((6184, 6212), 'matplotlib.pylab.figure', 'plt.figure', ([], {'figsize': '(20, 20)'}), '(figsize=(20, 20))\n', (6194, 6212), True, 'import matplotlib.pylab as plt\n'), ((455, 482), 'glob.glob', 'glob.glob', (["(path + '/*/*.h5')"], {}), "(path + '/*/*.h5')\n", (464, 482), False, 'import glob\n'), ((2937, 2960), 'cv2.imread', 'cv2.imread', (['row.path_in'], {}), '(row.path_in)\n', (2947, 2960), False, 'import cv2\n'), ((2970, 2994), 'cv2.imread', 'cv2.imread', (['row.path_out'], {}), '(row.path_out)\n', (2980, 2994), False, 'import cv2\n'), ((3070, 3105), 'numpy.random.uniform', 'np.random.uniform', (['(0.6)', '(1.2)'], {'size': '(3)'}), '(0.6, 1.2, size=3)\n', (3087, 3105), True, 'import numpy as np\n'), ((3253, 3270), 'cv2.split', 'cv2.split', (['imghsv'], {}), '(imghsv)\n', (3262, 3270), False, 'import cv2\n'), ((3330, 3348), 'numpy.clip', 'np.clip', (['s', '(0)', '(255)'], {}), '(s, 0, 255)\n', (3337, 3348), True, 'import numpy as np\n'), ((3406, 3424), 'numpy.clip', 'np.clip', (['v', '(0)', '(255)'], {}), '(v, 0, 255)\n', (3413, 3424), True, 'import numpy as np\n'), ((3434, 3454), 'cv2.merge', 'cv2.merge', (['[h, s, v]'], {}), '([h, s, v])\n', (3443, 3454), False, 'import cv2\n'), ((3703, 3726), 'numpy.clip', 'np.clip', (['xf', '(0.0)', '(255.0)'], {}), '(xf, 0.0, 255.0)\n', (3710, 3726), True, 'import numpy as np\n'), ((1945, 1969), 'numpy.random.randint', 'np.random.randint', (['(0)', 'dx'], {}), '(0, dx)\n', (1962, 1969), True, 'import numpy as np\n'), ((1991, 2015), 'numpy.random.randint', 'np.random.randint', (['(0)', 'dy'], {}), '(0, dy)\n', (2008, 2015), True, 'import numpy as np\n'), ((3278, 3296), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (3294, 3296), True, 'import numpy as np\n'), ((3354, 3372), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (3370, 3372), True, 'import numpy as np\n'), ((3628, 3646), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (3644, 3646), True, 'import numpy as np\n'), ((5595, 5624), 'numpy.array', 'np.array', (['x_batch', 'np.float32'], {}), '(x_batch, np.float32)\n', (5603, 5624), True, 'import numpy as np\n'), ((5645, 5674), 'numpy.array', 'np.array', (['y_batch', 'np.float32'], {}), '(y_batch, np.float32)\n', (5653, 5674), True, 'import numpy as np\n'), ((6327, 6348), 'matplotlib.pylab.show', 'plt.show', ([], {'block': '(False)'}), '(block=False)\n', (6335, 6348), True, 'import matplotlib.pylab as plt\n'), ((6352, 6374), 'matplotlib.pylab.imshow', 'plt.imshow', (['y[:, :, 0]'], {}), '(y[:, :, 0])\n', (6362, 6374), True, 'import matplotlib.pylab as plt\n'), ((6376, 6397), 'matplotlib.pylab.show', 'plt.show', ([], {'block': '(False)'}), '(block=False)\n', (6384, 6397), True, 'import matplotlib.pylab as plt\n'), ((3183, 3220), 'cv2.cvtColor', 'cv2.cvtColor', (['ximg', 'cv2.COLOR_RGB2HSV'], {}), '(ximg, cv2.COLOR_RGB2HSV)\n', (3195, 3220), False, 'import cv2\n'), ((3589, 3607), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (3605, 3607), True, 'import numpy as np\n'), ((4136, 4154), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (4152, 4154), True, 'import numpy as np\n'), ((5034, 5052), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (5050, 5052), True, 'import numpy as np\n'), ((5138, 5156), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (5154, 5156), True, 'import numpy as np\n'), ((5238, 5256), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (5254, 5256), True, 'import numpy as np\n'), ((5276, 5294), 'kf_util.flip_axis', 'flip_axis', (['ximg', '(0)'], {}), '(ximg, 0)\n', (5285, 5294), False, 'from kf_util import flip_axis\n'), ((5307, 5325), 'kf_util.flip_axis', 'flip_axis', (['yimg', '(0)'], {}), '(yimg, 0)\n', (5316, 5325), False, 'from kf_util import flip_axis\n'), ((5333, 5351), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (5349, 5351), True, 'import numpy as np\n'), ((5371, 5389), 'kf_util.flip_axis', 'flip_axis', (['ximg', '(1)'], {}), '(ximg, 1)\n', (5380, 5389), False, 'from kf_util import flip_axis\n'), ((5402, 5420), 'kf_util.flip_axis', 'flip_axis', (['yimg', '(1)'], {}), '(yimg, 1)\n', (5411, 5420), False, 'from kf_util import flip_axis\n'), ((5453, 5471), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (5469, 5471), True, 'import numpy as np\n'), ((5491, 5505), 'numpy.rot90', 'np.rot90', (['ximg'], {}), '(ximg)\n', (5499, 5505), True, 'import numpy as np\n'), ((5518, 5532), 'numpy.rot90', 'np.rot90', (['yimg'], {}), '(yimg)\n', (5526, 5532), True, 'import numpy as np\n'), ((4175, 4233), 'numpy.random.uniform', 'np.random.uniform', (['(self.input_shape[0] + 8)', 'ximgo.shape[0]'], {}), '(self.input_shape[0] + 8, ximgo.shape[0])\n', (4192, 4233), True, 'import numpy as np\n'), ((4246, 4304), 'numpy.random.uniform', 'np.random.uniform', (['(self.input_shape[1] + 8)', 'ximgo.shape[1]'], {}), '(self.input_shape[1] + 8, ximgo.shape[1])\n', (4263, 4304), True, 'import numpy as np\n')]
import tweepy import logging import time from newsplease import NewsPlease from newspaper import Article from newspaper import fulltext import requests from lxml import html import requests from bs4 import BeautifulSoup from urllib.request import Request, urlopen # text to image import numpy as np import textwrap import PIL import PIL.Image as Image import PIL.ImageDraw as ImageDraw import PIL.ImageFont as ImageFont import logging from urllib3 import exceptions import socket from config import create_api import logging logging.basicConfig( filename='bot.log', level=logging.DEBUG, format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S', ) logger = logging.getLogger() mentions_hash_table = {} filepath = './hash_table.txt' with open(filepath, 'r') as fp: for line in fp: print(line.strip()) mentions_hash_table[str(line.strip())] = str(line.strip()) line = fp.readline().strip() print(line) while line: line = fp.readline().strip() print(line) mentions_hash_table[str(line)] = str(line) def text_to_image(text): ''' If text is too long this function put text in a image. ''' font_fname = 'arial.ttf' font_size = 18 font = ImageFont.truetype(font_fname, font_size) h, w = 1080, 1920 bg_colour = (21,32,43) bg_image = np.dot(np.ones((h,w,3), dtype='uint8'), np.diag(np.asarray((bg_colour), dtype='uint8'))) image0 = Image.fromarray(bg_image) draw = ImageDraw.Draw(image0) margin = offset = 40 for line in textwrap.wrap(text, width=160): draw.text((margin, offset), line, font=font, fill="#DBDBDB") offset += font.getsize(line)[1] # draw.text((30, 15), haber, font=font, fill='rgb(0, 0, 0)') # image0.save('hello_world.jpg') return image0 def get_text_hard_way(url): ''' If newsplease cant get the news and returns "None" this function getting the url's all text. ''' req = Request(url, headers={'User-Agent': 'Mozilla/5.0'}) webpage = urlopen(req).read() soup = BeautifulSoup(webpage, "lxml") # kill all script and style elements for script in soup(["script", "style"]): script.decompose() # rip it out # get text text = soup.get_text() # break into lines and remove leading and trailing space on each lines = (line.strip() for line in text.splitlines()) # break multi-headlines into a line each chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) # drop blank lines text = '\n'.join(chunk for chunk in chunks if chunk) return text def check_mentions(api): ''' getting mentions and reply them. ''' mention_list = api.mentions_timeline() # get the mentions filepath = '/home/berkay/Desktop/projects/twitter/hash_table.txt' logger.info("Getting mentions") for mention in mention_list: time_of_mention = str(mention.created_at) if not (time_of_mention in mentions_hash_table): # if not previously replied parent_tweet_id = mention.in_reply_to_status_id_str if parent_tweet_id is None: # If this tweet is not a mention print(parent_tweet_id, "geldi") mentions_hash_table[time_of_mention] = time_of_mention with open(filepath, 'a') as fp: fp.write('\n') fp.write(time_of_mention) status = '@' + mention.user.screen_name + ' Please mention me below of the news tweet.' api.update_status(status, mention.id) continue try: status = api.get_status(parent_tweet_id, tweet_mode="extended") logger.info("parent tweet id: %s", parent_tweet_id) logger.info("tweet text: %s", status.full_text) logger.info("status urls in tweet: %s", status.entities['urls'][0]['url']) if "@clickbaitednews" in mention.text: logger.info(f"Answering to {mention.user.name}") mentions_hash_table[time_of_mention] = time_of_mention with open(filepath, 'a') as fp: fp.write('\n') fp.write(time_of_mention) parent_tweet_id = mention.in_reply_to_status_id_str status = api.get_status(parent_tweet_id, tweet_mode="extended") news_url = status.entities['urls'][0]['url'] article = NewsPlease.from_url(news_url) news_text = article.text logger.info("text of tweet: %s", news_text) beginning_of_tweet = 0 end_of_tweet = 255-13 keyword = 255-13 try: print(news_text) if len(news_text) <= 1000: tweet_sayisi = len(news_text) // keyword LAST_TWEET = len(news_text) % keyword for i in range(tweet_sayisi+1): tweet_no = str(i+1) tweet_no = tweet_no + '/' tweet_no = tweet_no + str(tweet_sayisi+1) news_text_tweet = news_text[beginning_of_tweet:end_of_tweet] beginning_of_tweet = end_of_tweet end_of_tweet = end_of_tweet + keyword if end_of_tweet >= len(news_text): end_of_tweet = len(news_text) beginning_of_tweet = end_of_tweet - LAST_TWEET status = '@' + mention.user.screen_name + ' ' + news_text_tweet + ' ' + tweet_no api.update_status(status, mention.id) news_text_tweet = [] else: status = '@' + mention.user.screen_name + ' ' + news_text_tweet + ' ' + tweet_no api.update_status(status, mention.id) news_text_tweet = [] else: image = text_to_image(news_text) image.save('news_pic.jpg') status = '@' + mention.user.screen_name + ' This text is too long we are adding text to the image. ' + news_url api.update_with_media('news_pic.jpg', status=status) except TypeError: text = get_text_hard_way(news_url) if len(text) >= 600: image = text_to_image(text) image.save('news_pic.jpg') status = '@' + mention.user.screen_name + ' This text is too long we are adding text to the image. ' + news_url api.update_with_media('news_pic.jpg', status=status) else: tweet_sayisi = len(news_text) // keyword LAST_TWEET = len(news_text) % keyword for i in range(tweet_sayisi+1): tweet_no = str(i+1) tweet_no = tweet_no + '/' tweet_no = tweet_no + str(tweet_sayisi+1) news_text_tweet = news_text[beginning_of_tweet:end_of_tweet] beginning_of_tweet = end_of_tweet end_of_tweet = end_of_tweet + keyword if end_of_tweet >= len(news_text): end_of_tweet = len(news_text) beginning_of_tweet = end_of_tweet - LAST_TWEET status = '@' + mention.user.screen_name + ' ' + news_text_tweet + ' ' + tweet_no api.update_status(status, mention.id) news_text_tweet = [] else: status = '@' + mention.user.screen_name + ' ' + news_text_tweet + ' ' + tweet_no api.update_status(status, mention.id) news_text_tweet = [] except tweepy.TweepError as e: logger.error("Tweepy error", exc_info=True) def main(): api = create_api() # since_id = 1 while True: check_mentions(api) logger.info("Waiting...") time.sleep(15) if __name__ == "__main__": main()
[ "logging.basicConfig", "logging.getLogger", "PIL.Image.fromarray", "config.create_api", "numpy.ones", "urllib.request.Request", "numpy.asarray", "PIL.ImageFont.truetype", "time.sleep", "bs4.BeautifulSoup", "newsplease.NewsPlease.from_url", "PIL.ImageDraw.Draw", "textwrap.wrap", "urllib.req...
[((527, 713), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': '"""bot.log"""', 'level': 'logging.DEBUG', 'format': '"""%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s"""', 'datefmt': '"""%Y-%m-%d %H:%M:%S"""'}), "(filename='bot.log', level=logging.DEBUG, format=\n '%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s'\n , datefmt='%Y-%m-%d %H:%M:%S')\n", (546, 713), False, 'import logging\n'), ((732, 751), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (749, 751), False, 'import logging\n'), ((1299, 1340), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['font_fname', 'font_size'], {}), '(font_fname, font_size)\n', (1317, 1340), True, 'import PIL.ImageFont as ImageFont\n'), ((1507, 1532), 'PIL.Image.fromarray', 'Image.fromarray', (['bg_image'], {}), '(bg_image)\n', (1522, 1532), True, 'import PIL.Image as Image\n'), ((1545, 1567), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['image0'], {}), '(image0)\n', (1559, 1567), True, 'import PIL.ImageDraw as ImageDraw\n'), ((1609, 1639), 'textwrap.wrap', 'textwrap.wrap', (['text'], {'width': '(160)'}), '(text, width=160)\n', (1622, 1639), False, 'import textwrap\n'), ((2026, 2077), 'urllib.request.Request', 'Request', (['url'], {'headers': "{'User-Agent': 'Mozilla/5.0'}"}), "(url, headers={'User-Agent': 'Mozilla/5.0'})\n", (2033, 2077), False, 'from urllib.request import Request, urlopen\n'), ((2124, 2154), 'bs4.BeautifulSoup', 'BeautifulSoup', (['webpage', '"""lxml"""'], {}), "(webpage, 'lxml')\n", (2137, 2154), False, 'from bs4 import BeautifulSoup\n'), ((8679, 8691), 'config.create_api', 'create_api', ([], {}), '()\n', (8689, 8691), False, 'from config import create_api\n'), ((1412, 1445), 'numpy.ones', 'np.ones', (['(h, w, 3)'], {'dtype': '"""uint8"""'}), "((h, w, 3), dtype='uint8')\n", (1419, 1445), True, 'import numpy as np\n'), ((8797, 8811), 'time.sleep', 'time.sleep', (['(15)'], {}), '(15)\n', (8807, 8811), False, 'import time\n'), ((1453, 1489), 'numpy.asarray', 'np.asarray', (['bg_colour'], {'dtype': '"""uint8"""'}), "(bg_colour, dtype='uint8')\n", (1463, 1489), True, 'import numpy as np\n'), ((2092, 2104), 'urllib.request.urlopen', 'urlopen', (['req'], {}), '(req)\n', (2099, 2104), False, 'from urllib.request import Request, urlopen\n'), ((4572, 4601), 'newsplease.NewsPlease.from_url', 'NewsPlease.from_url', (['news_url'], {}), '(news_url)\n', (4591, 4601), False, 'from newsplease import NewsPlease\n')]
# coding=utf-8 # Copyright 2021 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Functions for computing performance metrics of various inference methods. """ import collections import functools import itertools import jax import jax.numpy as jnp import numpy as onp import sklearn import sklearn.cluster import sklearn.metrics import sklearn.mixture def accuracy(preds, labels, unused_num_modes): return onp.mean(preds == labels) @functools.partial(onp.vectorize, signature="(n)->(m)") def to_pairwise(x): pairwise = x[onp.newaxis, :] == x[:, onp.newaxis] return pairwise[onp.tril_indices_from(pairwise, k=-1)] def pairwise_accuracy(preds, labels, unused_num_modes): preds = to_pairwise(preds) labels = to_pairwise(labels) return jnp.mean(preds == labels) def permutation_invariant_accuracy(preds, labels, num_modes): permutations = jnp.array(list(itertools.permutations(range(num_modes)))) permuted_labels = jax.lax.map(lambda p: p[labels], permutations) acc = jnp.max( jax.lax.map(lambda ls: jnp.mean(ls == preds), permuted_labels)) return acc def pairwise_f1(preds, labels, unused_num_modes): preds = to_pairwise(preds) labels = to_pairwise(labels) return binary_f1(preds, labels, unused_num_modes) def pairwise_micro_f1(preds, labels, unused_num_modes): preds = to_pairwise(preds) labels = to_pairwise(labels) return micro_f1(preds, labels, unused_num_modes) def pairwise_macro_f1(preds, labels, unused_num_modes): preds = to_pairwise(preds) labels = to_pairwise(labels) return macro_f1(preds, labels, unused_num_modes) def binary_f1(preds, labels, unused_num_modes): return sklearn.metrics.f1_score(labels, preds, average="binary") def macro_f1(preds, labels, unused_num_modes): return sklearn.metrics.f1_score(labels, preds, average="macro") def micro_f1(preds, labels, unused_num_modes): return sklearn.metrics.f1_score(labels, preds, average="micro") def permutation_invariant_binary_f1(preds, labels, unused_num_modes): f1_pos = binary_f1(preds, labels, unused_num_modes) permuted_predictions = onp.array([1, 0])[preds] f1_neg = binary_f1(permuted_predictions, labels, unused_num_modes) return onp.maximum(onp.mean(f1_pos), onp.mean(f1_neg)) METRIC_FNS = { "accuracy": accuracy, "pairwise_accuracy": pairwise_accuracy, "permutation_invariant_accuracy": permutation_invariant_accuracy, "binary_f1": binary_f1, "permutation_invariant_binary_f1": permutation_invariant_binary_f1, "pairwise_f1": pairwise_f1, "micro_f1": micro_f1, "macro_f1": macro_f1, "pairwise_micro_f1": pairwise_micro_f1, "pairwise_macro_f1": pairwise_macro_f1 } def em_fit_and_predict(xs, num_modes): return sklearn.mixture.GaussianMixture( n_components=num_modes, covariance_type="full", init_params="kmeans", n_init=3).fit_predict(xs) def spectral_rbf_fit_and_predict(xs, num_modes): return sklearn.cluster.SpectralClustering( n_clusters=num_modes, n_init=3, affinity="rbf").fit_predict(xs) def agglomerative_fit_and_predict(xs, num_modes): return sklearn.cluster.AgglomerativeClustering( n_clusters=num_modes, affinity="euclidean").fit_predict(xs) METHODS = {"em": em_fit_and_predict, "spectral_rbf": spectral_rbf_fit_and_predict, "agglomerative": agglomerative_fit_and_predict} def compute_baseline_metrics(xs, cs, num_modes, predict_fns=METHODS, metrics=[ "pairwise_accuracy", "pairwise_f1", "pairwise_micro_f1", "pairwise_macro_f1" ]): batch_size = xs.shape[0] metric_lists = collections.defaultdict(lambda: collections.defaultdict(list)) for i in range(batch_size): for name, predict_fn in predict_fns.items(): predicted_cs = predict_fn(xs[i], num_modes) for metric_name in metrics: m = METRIC_FNS[metric_name](predicted_cs, cs[i], num_modes) metric_lists[name][metric_name].append(m) avg_metrics = collections.defaultdict(dict) for method_name, metric_dict in metric_lists.items(): for metric_name, metric_list in metric_dict.items(): avg_metrics[method_name][metric_name] = onp.mean(metric_list) return avg_metrics def compute_metrics(cs, pred_cs, num_modes, metrics=["pairwise_accuracy", "pairwise_f1", "pairwise_micro_f1", "pairwise_macro_f1"]): batch_size = cs.shape[0] metric_lists = collections.defaultdict(list) for i in range(batch_size): for metric_name in metrics: m = METRIC_FNS[metric_name](pred_cs[i], cs[i], num_modes) metric_lists[metric_name].append(m) avg_metrics = {} for metric_name, metric_list in metric_lists.items(): avg_metrics[metric_name] = onp.mean(metric_list) return avg_metrics def compute_masked_metrics(cs, pred_cs, num_modes, num_points, metrics=["pairwise_accuracy", "pairwise_f1", "pairwise_micro_f1", "pairwise_macro_f1"]): batch_size = cs.shape[0] metric_lists = collections.defaultdict(list) for i in range(batch_size): for metric_name in metrics: m = METRIC_FNS[metric_name](pred_cs[i, :num_points[i]], cs[i, :num_points[i]], num_modes[i]) metric_lists[metric_name].append(m) avg_metrics = {} for metric_name, metric_list in metric_lists.items(): avg_metrics[metric_name] = onp.mean(metric_list) return avg_metrics def compute_masked_baseline_metrics(xs, cs, num_modes, num_points, predict_fns=METHODS, metrics=[ "pairwise_accuracy", "pairwise_f1", "pairwise_micro_f1", "pairwise_macro_f1" ]): batch_size = xs.shape[0] metric_lists = collections.defaultdict(lambda: collections.defaultdict(list)) for i in range(batch_size): for name, predict_fn in predict_fns.items(): predicted_cs = predict_fn(xs[i, :num_points[i]], num_modes[i]) for metric_name in metrics: m = METRIC_FNS[metric_name](predicted_cs, cs[i, :num_points[i]], num_modes[i]) metric_lists[name][metric_name].append(m) avg_metrics = collections.defaultdict(dict) for method_name, metric_dict in metric_lists.items(): for metric_name, metric_list in metric_dict.items(): avg_metrics[method_name][metric_name] = onp.mean(metric_list) return avg_metrics
[ "numpy.mean", "numpy.tril_indices_from", "sklearn.metrics.f1_score", "sklearn.mixture.GaussianMixture", "sklearn.cluster.SpectralClustering", "sklearn.cluster.AgglomerativeClustering", "jax.lax.map", "numpy.array", "functools.partial", "collections.defaultdict", "jax.numpy.mean" ]
[((969, 1023), 'functools.partial', 'functools.partial', (['onp.vectorize'], {'signature': '"""(n)->(m)"""'}), "(onp.vectorize, signature='(n)->(m)')\n", (986, 1023), False, 'import functools\n'), ((940, 965), 'numpy.mean', 'onp.mean', (['(preds == labels)'], {}), '(preds == labels)\n', (948, 965), True, 'import numpy as onp\n'), ((1280, 1305), 'jax.numpy.mean', 'jnp.mean', (['(preds == labels)'], {}), '(preds == labels)\n', (1288, 1305), True, 'import jax.numpy as jnp\n'), ((1465, 1511), 'jax.lax.map', 'jax.lax.map', (['(lambda p: p[labels])', 'permutations'], {}), '(lambda p: p[labels], permutations)\n', (1476, 1511), False, 'import jax\n'), ((2173, 2230), 'sklearn.metrics.f1_score', 'sklearn.metrics.f1_score', (['labels', 'preds'], {'average': '"""binary"""'}), "(labels, preds, average='binary')\n", (2197, 2230), False, 'import sklearn\n'), ((2289, 2345), 'sklearn.metrics.f1_score', 'sklearn.metrics.f1_score', (['labels', 'preds'], {'average': '"""macro"""'}), "(labels, preds, average='macro')\n", (2313, 2345), False, 'import sklearn\n'), ((2404, 2460), 'sklearn.metrics.f1_score', 'sklearn.metrics.f1_score', (['labels', 'preds'], {'average': '"""micro"""'}), "(labels, preds, average='micro')\n", (2428, 2460), False, 'import sklearn\n'), ((4651, 4680), 'collections.defaultdict', 'collections.defaultdict', (['dict'], {}), '(dict)\n', (4674, 4680), False, 'import collections\n'), ((5111, 5140), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (5134, 5140), False, 'import collections\n'), ((5720, 5749), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (5743, 5749), False, 'import collections\n'), ((7021, 7050), 'collections.defaultdict', 'collections.defaultdict', (['dict'], {}), '(dict)\n', (7044, 7050), False, 'import collections\n'), ((1114, 1151), 'numpy.tril_indices_from', 'onp.tril_indices_from', (['pairwise'], {'k': '(-1)'}), '(pairwise, k=-1)\n', (1135, 1151), True, 'import numpy as onp\n'), ((2612, 2629), 'numpy.array', 'onp.array', (['[1, 0]'], {}), '([1, 0])\n', (2621, 2629), True, 'import numpy as onp\n'), ((2727, 2743), 'numpy.mean', 'onp.mean', (['f1_pos'], {}), '(f1_pos)\n', (2735, 2743), True, 'import numpy as onp\n'), ((2745, 2761), 'numpy.mean', 'onp.mean', (['f1_neg'], {}), '(f1_neg)\n', (2753, 2761), True, 'import numpy as onp\n'), ((5416, 5437), 'numpy.mean', 'onp.mean', (['metric_list'], {}), '(metric_list)\n', (5424, 5437), True, 'import numpy as onp\n'), ((6094, 6115), 'numpy.mean', 'onp.mean', (['metric_list'], {}), '(metric_list)\n', (6102, 6115), True, 'import numpy as onp\n'), ((3242, 3358), 'sklearn.mixture.GaussianMixture', 'sklearn.mixture.GaussianMixture', ([], {'n_components': 'num_modes', 'covariance_type': '"""full"""', 'init_params': '"""kmeans"""', 'n_init': '(3)'}), "(n_components=num_modes, covariance_type=\n 'full', init_params='kmeans', n_init=3)\n", (3273, 3358), False, 'import sklearn\n'), ((3455, 3542), 'sklearn.cluster.SpectralClustering', 'sklearn.cluster.SpectralClustering', ([], {'n_clusters': 'num_modes', 'n_init': '(3)', 'affinity': '"""rbf"""'}), "(n_clusters=num_modes, n_init=3, affinity\n ='rbf')\n", (3489, 3542), False, 'import sklearn\n'), ((3634, 3722), 'sklearn.cluster.AgglomerativeClustering', 'sklearn.cluster.AgglomerativeClustering', ([], {'n_clusters': 'num_modes', 'affinity': '"""euclidean"""'}), "(n_clusters=num_modes, affinity=\n 'euclidean')\n", (3673, 3722), False, 'import sklearn\n'), ((4322, 4351), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (4345, 4351), False, 'import collections\n'), ((4840, 4861), 'numpy.mean', 'onp.mean', (['metric_list'], {}), '(metric_list)\n', (4848, 4861), True, 'import numpy as onp\n'), ((6582, 6611), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (6605, 6611), False, 'import collections\n'), ((7210, 7231), 'numpy.mean', 'onp.mean', (['metric_list'], {}), '(metric_list)\n', (7218, 7231), True, 'import numpy as onp\n'), ((1558, 1579), 'jax.numpy.mean', 'jnp.mean', (['(ls == preds)'], {}), '(ls == preds)\n', (1566, 1579), True, 'import jax.numpy as jnp\n')]
import numpy as np import matplotlib.pylab as plt import os clear = lambda: os.system('cls' if os.name=='nt' else 'clear') # Activation def step_function(x): # if x > 0: # return 1 # else: # return 0 y = x > 0 return y.astype(np.int) def sigmoid(x): return 1 / (1 + np.exp(-x)) def relu(x): return np.maximum(0, x) def softmax(x): exp_x = np.exp(x-np.max(x)) sum_exp_x = np.sum(exp_x) return exp_x / sum_exp_x # Run test def plotting(x, y): plt.plot(x, y) plt.ylim(-0.1, 1.1) plt.show() def test(func_str): x = np.arange(-5, 5, 0.1) y = globals()[func_str](x) plotting(x, y) def test_activation(): function_list = ['sigmoid', 'relu', 'step_function'] while True: func_str = input('function? ' + ', '.join(function_list) + ' : ') if func_str in function_list: break # clear() test(func_str) test_activation()
[ "matplotlib.pylab.ylim", "numpy.max", "numpy.exp", "numpy.sum", "matplotlib.pylab.show", "numpy.maximum", "os.system", "matplotlib.pylab.plot", "numpy.arange" ]
[((76, 124), 'os.system', 'os.system', (["('cls' if os.name == 'nt' else 'clear')"], {}), "('cls' if os.name == 'nt' else 'clear')\n", (85, 124), False, 'import os\n'), ((344, 360), 'numpy.maximum', 'np.maximum', (['(0)', 'x'], {}), '(0, x)\n', (354, 360), True, 'import numpy as np\n'), ((427, 440), 'numpy.sum', 'np.sum', (['exp_x'], {}), '(exp_x)\n', (433, 440), True, 'import numpy as np\n'), ((507, 521), 'matplotlib.pylab.plot', 'plt.plot', (['x', 'y'], {}), '(x, y)\n', (515, 521), True, 'import matplotlib.pylab as plt\n'), ((526, 545), 'matplotlib.pylab.ylim', 'plt.ylim', (['(-0.1)', '(1.1)'], {}), '(-0.1, 1.1)\n', (534, 545), True, 'import matplotlib.pylab as plt\n'), ((550, 560), 'matplotlib.pylab.show', 'plt.show', ([], {}), '()\n', (558, 560), True, 'import matplotlib.pylab as plt\n'), ((591, 612), 'numpy.arange', 'np.arange', (['(-5)', '(5)', '(0.1)'], {}), '(-5, 5, 0.1)\n', (600, 612), True, 'import numpy as np\n'), ((306, 316), 'numpy.exp', 'np.exp', (['(-x)'], {}), '(-x)\n', (312, 316), True, 'import numpy as np\n'), ((400, 409), 'numpy.max', 'np.max', (['x'], {}), '(x)\n', (406, 409), True, 'import numpy as np\n')]