signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def print_result(filt, full=None): | print('<STR_LIT>' % filt.base.size)<EOL>print('<STR_LIT>')<EOL>if full: <EOL><INDENT>if full[<NUM_LIT:4>] == <NUM_LIT:0>: <EOL><INDENT>print('<STR_LIT>' % full[<NUM_LIT:1>])<EOL><DEDENT>else: <EOL><INDENT>r = <NUM_LIT:1>/full[<NUM_LIT:1>]<EOL>print('<STR_LIT>' % r)<EOL><DEDENT>spacing = full[<NUM_LIT:0>][<NUM_LIT:0>]<EOL>shift = full[<NUM_LIT:0>][<NUM_LIT:1>]<EOL><DEDENT>else: <EOL><INDENT>n = filt.base.size<EOL>a = filt.base[-<NUM_LIT:1>]<EOL>b = filt.base[-<NUM_LIT:2>]<EOL>spacing = np.log(a)-np.log(b)<EOL>shift = np.log(a)-spacing*(n//<NUM_LIT:2>)<EOL><DEDENT>print('<STR_LIT>' % spacing)<EOL>print('<STR_LIT>' % shift)<EOL>print('<STR_LIT>' % (filt.base.min(), filt.base.max()))<EOL> | r"""Print best filter information.
Parameters
----------
- filt, full as returned from fdesign.design with full_output=True | f13208:m4 |
def _call_qc_transform_pairs(n, ispacing, ishift, fI, fC, r, r_def, reim): | print('<STR_LIT>')<EOL>print('<STR_LIT>' +<EOL>'<STR_LIT>')<EOL>print('<STR_LIT>' +<EOL>'<STR_LIT>')<EOL>minspace = np.arange(*ispacing).min()<EOL>maxspace = np.arange(*ispacing).max()<EOL>minshift = np.arange(*ishift).min()<EOL>maxshift = np.arange(*ishift).max()<EOL>maxbase = np.exp(maxspace*(n//<NUM_LIT:2>) + maxshift)<EOL>minbase = np.exp(maxspace*(-n//<NUM_LIT:2>+<NUM_LIT:1>) + minshift)<EOL>kmax = maxbase/r.min()<EOL>kmin = minbase/r.max()<EOL>k = np.logspace(np.log10(kmin), np.log10(kmax) + minspace, r.size)<EOL>rI = np.logspace(np.log10(<NUM_LIT:1>/maxbase) - r_def[<NUM_LIT:0>],<EOL>np.log10(<NUM_LIT:1>/minbase) + r_def[<NUM_LIT:1>], r_def[<NUM_LIT:2>]*n)<EOL>kmaxI = maxbase/rI.min()<EOL>kminI = minbase/rI.max()<EOL>kI = np.logspace(np.log10(kminI), np.log10(kmaxI) + minspace,<EOL>r_def[<NUM_LIT:2>]*n)<EOL>fig, axs = plt.subplots(figsize=(<NUM_LIT>, <NUM_LIT:6>), nrows=<NUM_LIT:2>, ncols=<NUM_LIT:2>,<EOL>num="<STR_LIT>")<EOL>axs = axs.ravel()<EOL>plt.subplots_adjust(wspace=<NUM_LIT>, hspace=<NUM_LIT>)<EOL>_plot_transform_pairs(fC, r, k, axs[:<NUM_LIT:2>], '<STR_LIT>')<EOL>if reim == np.real:<EOL><INDENT>tit = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>tit = '<STR_LIT>'<EOL><DEDENT>_plot_transform_pairs(fI, rI, kI, axs[<NUM_LIT:2>:], tit)<EOL>fig.canvas.draw() <EOL>plt.show()<EOL> | r"""QC the input transform pairs. | f13208:m5 |
def _plot_transform_pairs(fCI, r, k, axes, tit): | <EOL>plt.sca(axes[<NUM_LIT:0>])<EOL>plt.title('<STR_LIT:|>' + tit + '<STR_LIT>')<EOL>for f in fCI:<EOL><INDENT>if f.name == '<STR_LIT>':<EOL><INDENT>lhs = f.lhs(k)<EOL>plt.loglog(k, np.abs(lhs[<NUM_LIT:0>]), lw=<NUM_LIT:2>, label='<STR_LIT>')<EOL>plt.loglog(k, np.abs(lhs[<NUM_LIT:1>]), lw=<NUM_LIT:2>, label='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>plt.loglog(k, np.abs(f.lhs(k)), lw=<NUM_LIT:2>, label=f.name)<EOL><DEDENT><DEDENT>if tit != '<STR_LIT>':<EOL><INDENT>plt.xlabel('<STR_LIT:l>')<EOL><DEDENT>plt.legend(loc='<STR_LIT>')<EOL>plt.sca(axes[<NUM_LIT:1>])<EOL>plt.title('<STR_LIT:|>' + tit + '<STR_LIT>')<EOL>for f in fCI:<EOL><INDENT>if tit == '<STR_LIT>':<EOL><INDENT>plt.loglog(r, np.abs(f.rhs), lw=<NUM_LIT:2>, label=f.name)<EOL><DEDENT>else:<EOL><INDENT>plt.loglog(r, np.abs(f.rhs(r)), lw=<NUM_LIT:2>, label=f.name)<EOL><DEDENT><DEDENT>for f in fCI:<EOL><INDENT>if f.name[<NUM_LIT:1>] in ['<STR_LIT:0>', '<STR_LIT:1>', '<STR_LIT:2>']:<EOL><INDENT>filt = j0j1filt()<EOL><DEDENT>else:<EOL><INDENT>filt = sincosfilt()<EOL><DEDENT>kk = filt.base/r[:, None]<EOL>if f.name == '<STR_LIT>':<EOL><INDENT>lhs = f.lhs(kk)<EOL>kr0 = np.dot(lhs[<NUM_LIT:0>], getattr(filt, '<STR_LIT>'))/r<EOL>kr1 = np.dot(lhs[<NUM_LIT:1>], getattr(filt, '<STR_LIT>'))/r**<NUM_LIT:2><EOL>kr = kr0+kr1<EOL><DEDENT>else:<EOL><INDENT>kr = np.dot(f.lhs(kk), getattr(filt, f.name))/r<EOL><DEDENT>plt.loglog(r, np.abs(kr), '<STR_LIT>', lw=<NUM_LIT:2>, label=filt.name)<EOL><DEDENT>if tit != '<STR_LIT>':<EOL><INDENT>plt.xlabel('<STR_LIT:r>')<EOL><DEDENT>plt.legend(loc='<STR_LIT>')<EOL> | r"""Plot the input transform pairs. | f13208:m6 |
def _plot_inversion(f, rhs, r, k, imin, spacing, shift, cvar): | <EOL>if not plt:<EOL><INDENT>print(plt_msg)<EOL>return<EOL><DEDENT>plt.figure("<STR_LIT>"+f.name, figsize=(<NUM_LIT>, <NUM_LIT:4>))<EOL>plt.subplots_adjust(wspace=<NUM_LIT>, bottom=<NUM_LIT>)<EOL>plt.clf()<EOL>tk = np.logspace(np.log10(k.min()), np.log10(k.max()), r.size)<EOL>plt.suptitle(f.name+'<STR_LIT>'+str(spacing)+'<STR_LIT>'+str(shift))<EOL>plt.subplot(<NUM_LIT>)<EOL>plt.title('<STR_LIT>')<EOL>if f.name == '<STR_LIT>':<EOL><INDENT>lhs = f.lhs(tk)<EOL>plt.loglog(tk, np.abs(lhs[<NUM_LIT:0>]), lw=<NUM_LIT:2>, label='<STR_LIT>')<EOL>plt.loglog(tk, np.abs(lhs[<NUM_LIT:1>]), lw=<NUM_LIT:2>, label='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>plt.loglog(tk, np.abs(f.lhs(tk)), lw=<NUM_LIT:2>, label='<STR_LIT>')<EOL><DEDENT>plt.xlabel('<STR_LIT:l>')<EOL>plt.legend(loc='<STR_LIT>')<EOL>plt.subplot(<NUM_LIT>)<EOL>plt.title('<STR_LIT>')<EOL>plt.loglog(r, np.abs(f.rhs), lw=<NUM_LIT:2>, label='<STR_LIT>')<EOL>plt.loglog(r, np.abs(rhs), '<STR_LIT>', lw=<NUM_LIT:2>, label='<STR_LIT>')<EOL>if cvar == '<STR_LIT>':<EOL><INDENT>label = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>label = '<STR_LIT>'<EOL><DEDENT>plt.loglog(r[imin], np.abs(rhs[imin]), '<STR_LIT>', label=label)<EOL>plt.xlabel('<STR_LIT:r>')<EOL>plt.legend(loc='<STR_LIT>')<EOL>plt.gcf().canvas.draw() <EOL>plt.show()<EOL> | r"""QC the resulting filter. | f13208:m7 |
def j0_1(a=<NUM_LIT:1>): | def lhs(x):<EOL><INDENT>return x*np.exp(-a*x**<NUM_LIT:2>)<EOL><DEDENT>def rhs(b):<EOL><INDENT>return np.exp(-b**<NUM_LIT:2>/(<NUM_LIT:4>*a))/(<NUM_LIT:2>*a)<EOL><DEDENT>return Ghosh('<STR_LIT>', lhs, rhs)<EOL> | r"""Hankel transform pair J0_1 ([Ande75]_). | f13208:m8 |
def j0_2(a=<NUM_LIT:1>): | def lhs(x):<EOL><INDENT>return np.exp(-a*x)<EOL><DEDENT>def rhs(b):<EOL><INDENT>return <NUM_LIT:1>/np.sqrt(b**<NUM_LIT:2> + a**<NUM_LIT:2>)<EOL><DEDENT>return Ghosh('<STR_LIT>', lhs, rhs)<EOL> | r"""Hankel transform pair J0_2 ([Ande75]_). | f13208:m9 |
def j0_3(a=<NUM_LIT:1>): | def lhs(x):<EOL><INDENT>return x*np.exp(-a*x)<EOL><DEDENT>def rhs(b):<EOL><INDENT>return a/(b**<NUM_LIT:2> + a**<NUM_LIT:2>)**<NUM_LIT><EOL><DEDENT>return Ghosh('<STR_LIT>', lhs, rhs)<EOL> | r"""Hankel transform pair J0_3 ([GuSi97]_). | f13208:m10 |
def j0_4(f=<NUM_LIT:1>, rho=<NUM_LIT>, z=<NUM_LIT:50>): | gam = np.sqrt(<NUM_LIT>*np.pi*mu_0*f/rho)<EOL>def lhs(x):<EOL><INDENT>beta = np.sqrt(x**<NUM_LIT:2> + gam**<NUM_LIT:2>)<EOL>return x*np.exp(-beta*np.abs(z))/beta<EOL><DEDENT>def rhs(b):<EOL><INDENT>R = np.sqrt(b**<NUM_LIT:2> + z**<NUM_LIT:2>)<EOL>return np.exp(-gam*R)/R<EOL><DEDENT>return Ghosh('<STR_LIT>', lhs, rhs)<EOL> | r"""Hankel transform pair J0_4 ([ChCo82]_).
Parameters
----------
f : float
Frequency (Hz)
rho : float
Resistivity (Ohm.m)
z : float
Vertical distance between source and receiver (m) | f13208:m11 |
def j0_5(f=<NUM_LIT:1>, rho=<NUM_LIT>, z=<NUM_LIT:50>): | gam = np.sqrt(<NUM_LIT>*np.pi*mu_0*f/rho)<EOL>def lhs(x):<EOL><INDENT>beta = np.sqrt(x**<NUM_LIT:2> + gam**<NUM_LIT:2>)<EOL>return x*np.exp(-beta*np.abs(z))<EOL><DEDENT>def rhs(b):<EOL><INDENT>R = np.sqrt(b**<NUM_LIT:2> + z**<NUM_LIT:2>)<EOL>return np.abs(z)*(gam*R + <NUM_LIT:1>)*np.exp(-gam*R)/R**<NUM_LIT:3><EOL><DEDENT>return Ghosh('<STR_LIT>', lhs, rhs)<EOL> | r"""Hankel transform pair J0_5 ([ChCo82]_).
Parameters
----------
f : float
Frequency (Hz)
rho : float
Resistivity (Ohm.m)
z : float
Vertical distance between source and receiver (m) | f13208:m12 |
def j1_1(a=<NUM_LIT:1>): | def lhs(x):<EOL><INDENT>return x**<NUM_LIT:2>*np.exp(-a*x**<NUM_LIT:2>)<EOL><DEDENT>def rhs(b):<EOL><INDENT>return b/(<NUM_LIT:4>*a**<NUM_LIT:2>)*np.exp(-b**<NUM_LIT:2>/(<NUM_LIT:4>*a))<EOL><DEDENT>return Ghosh('<STR_LIT>', lhs, rhs)<EOL> | r"""Hankel transform pair J1_1 ([Ande75]_). | f13208:m13 |
def j1_2(a=<NUM_LIT:1>): | def lhs(x):<EOL><INDENT>return np.exp(-a*x)<EOL><DEDENT>def rhs(b):<EOL><INDENT>return (np.sqrt(b**<NUM_LIT:2> + a**<NUM_LIT:2>) - a)/(b*np.sqrt(b**<NUM_LIT:2> + a**<NUM_LIT:2>))<EOL><DEDENT>return Ghosh('<STR_LIT>', lhs, rhs)<EOL> | r"""Hankel transform pair J1_2 ([Ande75]_). | f13208:m14 |
def j1_3(a=<NUM_LIT:1>): | def lhs(x):<EOL><INDENT>return x*np.exp(-a*x)<EOL><DEDENT>def rhs(b):<EOL><INDENT>return b/(b**<NUM_LIT:2> + a**<NUM_LIT:2>)**<NUM_LIT><EOL><DEDENT>return Ghosh('<STR_LIT>', lhs, rhs)<EOL> | r"""Hankel transform pair J1_3 ([Ande75]_). | f13208:m15 |
def j1_4(f=<NUM_LIT:1>, rho=<NUM_LIT>, z=<NUM_LIT:50>): | gam = np.sqrt(<NUM_LIT>*np.pi*mu_0*f/rho)<EOL>def lhs(x):<EOL><INDENT>beta = np.sqrt(x**<NUM_LIT:2> + gam**<NUM_LIT:2>)<EOL>return x**<NUM_LIT:2>*np.exp(-beta*np.abs(z))/beta<EOL><DEDENT>def rhs(b):<EOL><INDENT>R = np.sqrt(b**<NUM_LIT:2> + z**<NUM_LIT:2>)<EOL>return b*(gam*R + <NUM_LIT:1>)*np.exp(-gam*R)/R**<NUM_LIT:3><EOL><DEDENT>return Ghosh('<STR_LIT>', lhs, rhs)<EOL> | r"""Hankel transform pair J1_4 ([ChCo82]_).
Parameters
----------
f : float
Frequency (Hz)
rho : float
Resistivity (Ohm.m)
z : float
Vertical distance between source and receiver (m) | f13208:m16 |
def j1_5(f=<NUM_LIT:1>, rho=<NUM_LIT>, z=<NUM_LIT:50>): | gam = np.sqrt(<NUM_LIT>*np.pi*mu_0*f/rho)<EOL>def lhs(x):<EOL><INDENT>beta = np.sqrt(x**<NUM_LIT:2> + gam**<NUM_LIT:2>)<EOL>return x**<NUM_LIT:2>*np.exp(-beta*np.abs(z))<EOL><DEDENT>def rhs(b):<EOL><INDENT>R = np.sqrt(b**<NUM_LIT:2> + z**<NUM_LIT:2>)<EOL>return np.abs(z)*b*(gam**<NUM_LIT:2>*R**<NUM_LIT:2> + <NUM_LIT:3>*gam*R + <NUM_LIT:3>)*np.exp(-gam*R)/R**<NUM_LIT:5><EOL><DEDENT>return Ghosh('<STR_LIT>', lhs, rhs)<EOL> | r"""Hankel transform pair J1_5 ([ChCo82]_).
Parameters
----------
f : float
Frequency (Hz)
rho : float
Resistivity (Ohm.m)
z : float
Vertical distance between source and receiver (m) | f13208:m17 |
def sin_1(a=<NUM_LIT:1>): | def lhs(x):<EOL><INDENT>return x*np.exp(-a**<NUM_LIT:2>*x**<NUM_LIT:2>)<EOL><DEDENT>def rhs(b):<EOL><INDENT>return np.sqrt(np.pi)*b*np.exp(-b**<NUM_LIT:2>/(<NUM_LIT:4>*a**<NUM_LIT:2>))/(<NUM_LIT:4>*a**<NUM_LIT:3>)<EOL><DEDENT>return Ghosh('<STR_LIT>', lhs, rhs)<EOL> | r"""Fourier sine transform pair sin_1 ([Ande75]_). | f13208:m18 |
def sin_2(a=<NUM_LIT:1>): | def lhs(x):<EOL><INDENT>return np.exp(-a*x)<EOL><DEDENT>def rhs(b):<EOL><INDENT>return b/(b**<NUM_LIT:2> + a**<NUM_LIT:2>)<EOL><DEDENT>return Ghosh('<STR_LIT>', lhs, rhs)<EOL> | r"""Fourier sine transform pair sin_2 ([Ande75]_). | f13208:m19 |
def sin_3(a=<NUM_LIT:1>): | def lhs(x):<EOL><INDENT>return x/(a**<NUM_LIT:2> + x**<NUM_LIT:2>)<EOL><DEDENT>def rhs(b):<EOL><INDENT>return np.pi*np.exp(-a*b)/<NUM_LIT:2><EOL><DEDENT>return Ghosh('<STR_LIT>', lhs, rhs)<EOL> | r"""Fourier sine transform pair sin_3 ([Ande75]_). | f13208:m20 |
def cos_1(a=<NUM_LIT:1>): | def lhs(x):<EOL><INDENT>return np.exp(-a**<NUM_LIT:2>*x**<NUM_LIT:2>)<EOL><DEDENT>def rhs(b):<EOL><INDENT>return np.sqrt(np.pi)*np.exp(-b**<NUM_LIT:2>/(<NUM_LIT:4>*a**<NUM_LIT:2>))/(<NUM_LIT:2>*a)<EOL><DEDENT>return Ghosh('<STR_LIT>', lhs, rhs)<EOL> | r"""Fourier cosine transform pair cos_1 ([Ande75]_). | f13208:m21 |
def cos_2(a=<NUM_LIT:1>): | def lhs(x):<EOL><INDENT>return np.exp(-a*x)<EOL><DEDENT>def rhs(b):<EOL><INDENT>return a/(b**<NUM_LIT:2> + a**<NUM_LIT:2>)<EOL><DEDENT>return Ghosh('<STR_LIT>', lhs, rhs)<EOL> | r"""Fourier cosine transform pair cos_2 ([Ande75]_). | f13208:m22 |
def cos_3(a=<NUM_LIT:1>): | def lhs(x):<EOL><INDENT>return <NUM_LIT:1>/(a**<NUM_LIT:2> + x**<NUM_LIT:2>)<EOL><DEDENT>def rhs(b):<EOL><INDENT>return np.pi*np.exp(-a*b)/(<NUM_LIT:2>*a)<EOL><DEDENT>return Ghosh('<STR_LIT>', lhs, rhs)<EOL> | r"""Fourier cosine transform pair cos_3 ([Ande75]_). | f13208:m23 |
def empy_hankel(ftype, zsrc, zrec, res, freqtime, depth=None, aniso=None,<EOL>epermH=None, epermV=None, mpermH=None, mpermV=None,<EOL>htarg=None, verblhs=<NUM_LIT:0>, verbrhs=<NUM_LIT:0>): | <EOL>if isinstance(ftype, list):<EOL><INDENT>out = []<EOL>for f in ftype:<EOL><INDENT>out.append(empy_hankel(f, zsrc, zrec, res, freqtime, depth, aniso,<EOL>epermH, epermV, mpermH, mpermV, htarg,<EOL>verblhs, verbrhs))<EOL><DEDENT>return out<EOL><DEDENT>model = {'<STR_LIT:src>': [<NUM_LIT:0>, <NUM_LIT:0>, zsrc],<EOL>'<STR_LIT>': depth,<EOL>'<STR_LIT>': res,<EOL>'<STR_LIT>': aniso,<EOL>'<STR_LIT>': epermH,<EOL>'<STR_LIT>': epermV,<EOL>'<STR_LIT>': mpermH,<EOL>'<STR_LIT>': mpermV}<EOL>if ftype == '<STR_LIT>': <EOL><INDENT>model['<STR_LIT>'] = <NUM_LIT:11><EOL>x = <NUM_LIT:1>/np.sqrt(<NUM_LIT:2>)<EOL>y = <NUM_LIT:1>/np.sqrt(<NUM_LIT:2>)<EOL><DEDENT>elif ftype == '<STR_LIT>': <EOL><INDENT>model['<STR_LIT>'] = <NUM_LIT><EOL>x = <NUM_LIT:1><EOL>y = <NUM_LIT:0><EOL><DEDENT>elif ftype == '<STR_LIT>': <EOL><INDENT>model['<STR_LIT>'] = <NUM_LIT:12><EOL>x = <NUM_LIT:1>/np.sqrt(<NUM_LIT:2>)<EOL>y = <NUM_LIT:1>/np.sqrt(<NUM_LIT:2>)<EOL><DEDENT>def rhs(r):<EOL><INDENT>out = dipole(rec=[r*x, r*y, zrec], ht='<STR_LIT>', xdirect=True,<EOL>verb=verbrhs, htarg=htarg, freqtime=freqtime, **model)<EOL>return out<EOL><DEDENT>def lhs(k):<EOL><INDENT>lhs0, lhs1 = dipole_k(rec=[x, y, zrec], wavenumber=k, verb=verblhs,<EOL>freq=freqtime, **model)<EOL>if ftype == '<STR_LIT>':<EOL><INDENT>return lhs0<EOL><DEDENT>elif ftype == '<STR_LIT>':<EOL><INDENT>return lhs1<EOL><DEDENT>elif ftype == '<STR_LIT>':<EOL><INDENT>return (lhs0, lhs1)<EOL><DEDENT><DEDENT>return Ghosh(ftype, lhs, rhs)<EOL> | r"""Numerical transform pair with empymod.
All parameters except ``ftype``, ``verblhs``, and ``verbrhs`` correspond to
the input parameters to ``empymod.dipole``. See there for more information.
Note that if depth=None or [], the analytical full-space solutions will be
used (much faster).
Parameters
----------
ftype : str or list of strings
Either of: {'j0', 'j1', 'j2', ['j0', 'j1']}
- 'j0': Analyze J0-term with ab=11, angle=45°
- 'j1': Analyze J1-term with ab=31, angle=0°
- 'j2': Analyze J0- and J1-terms jointly with ab=12, angle=45°
- ['j0', 'j1']: Same as calling empy_hankel twice, once with 'j0' and
one with 'j1'; can be provided like this to
fdesign.design.
verblhs, verbrhs: int
verb-values provided to empymod for lhs and rhs.
Note that ftype='j2' only works for fC, not for fI. | f13208:m24 |
def _get_min_val(spaceshift, *params): | <EOL>spacing, shift = spaceshift<EOL>n, fI, fC, r, r_def, error, reim, cvar, verb, plot, log = params<EOL>dlf = _calculate_filter(n, spacing, shift, fI, r_def, reim, '<STR_LIT>')<EOL>k = dlf.base/r[:, None]<EOL>for i, f in enumerate(fC):<EOL><INDENT>lhs = f.lhs(k)<EOL>if f.name == '<STR_LIT>':<EOL><INDENT>rhs0 = np.dot(lhs[<NUM_LIT:0>], getattr(dlf, '<STR_LIT>'))/r<EOL>rhs1 = np.dot(lhs[<NUM_LIT:1>], getattr(dlf, '<STR_LIT>'))/r**<NUM_LIT:2><EOL>rhs = rhs0 + rhs1<EOL><DEDENT>else:<EOL><INDENT>rhs = np.dot(lhs, getattr(dlf, f.name))/r<EOL><DEDENT>rel_error = np.abs((rhs - f.rhs)/f.rhs)<EOL>imin0 = np.where(rel_error > error)[<NUM_LIT:0>]<EOL>if np.all(rhs == <NUM_LIT:0>) or np.all(np.isnan(rhs)):<EOL><INDENT>imin0 = <NUM_LIT:0><EOL><DEDENT>elif imin0.size == <NUM_LIT:0>:<EOL><INDENT>imin0 = rhs.size-<NUM_LIT:1> <EOL>if verb > <NUM_LIT:0> and log['<STR_LIT>'] == <NUM_LIT:0>:<EOL><INDENT>print('<STR_LIT>' + str(error) +<EOL>'<STR_LIT>')<EOL>log['<STR_LIT>'] = <NUM_LIT:1> <EOL><DEDENT><DEDENT>else:<EOL><INDENT>if imin0.size > <NUM_LIT:4>:<EOL><INDENT>imin0 = np.max([<NUM_LIT:0>, imin0[<NUM_LIT:4>]-<NUM_LIT:5>])<EOL><DEDENT>else: <EOL><INDENT>imin0 = np.max([<NUM_LIT:0>, imin0[<NUM_LIT:0>]-<NUM_LIT:1>])<EOL><DEDENT><DEDENT>if cvar == '<STR_LIT>':<EOL><INDENT>min_val0 = np.abs(rhs[imin0])<EOL><DEDENT>else:<EOL><INDENT>min_val0 = <NUM_LIT:1>/r[imin0]<EOL><DEDENT>if i == <NUM_LIT:0>: <EOL><INDENT>imin = dc(imin0)<EOL>min_val = dc(min_val0)<EOL><DEDENT>else: <EOL><INDENT>if min_val0 > min_val:<EOL><INDENT>min_val = dc(min_val0)<EOL>imin = dc(imin0)<EOL><DEDENT><DEDENT>if plot > <NUM_LIT:2>:<EOL><INDENT>_plot_inversion(f, rhs, r, k, imin0, spacing, shift, cvar)<EOL><DEDENT><DEDENT>if verb > <NUM_LIT:1>:<EOL><INDENT>log = _print_count(log)<EOL><DEDENT>return np.where(imin == <NUM_LIT:0>, np.inf, min_val)<EOL> | r"""Calculate minimum resolved amplitude or maximum r. | f13208:m25 |
def _calculate_filter(n, spacing, shift, fI, r_def, reim, name): | <EOL>base = np.exp(spacing*(np.arange(n)-n//<NUM_LIT:2>) + shift)<EOL>r = np.logspace(np.log10(<NUM_LIT:1>/np.max(base)) - r_def[<NUM_LIT:0>],<EOL>np.log10(<NUM_LIT:1>/np.min(base)) + r_def[<NUM_LIT:1>], r_def[<NUM_LIT:2>]*n)<EOL>k = base/r[:, None]<EOL>dlf = DigitalFilter(name.split('<STR_LIT:.>')[<NUM_LIT:0>])<EOL>dlf.base = base<EOL>dlf.factor = np.around(np.average(base[<NUM_LIT:1>:]/base[:-<NUM_LIT:1>]), <NUM_LIT:15>)<EOL>for f in fI:<EOL><INDENT>lhs = reim(f.lhs(k))<EOL>rhs = reim(f.rhs(r)*r)<EOL>try:<EOL><INDENT>qq, rr = np.linalg.qr(lhs)<EOL>J = np.linalg.solve(rr, rhs.dot(qq))<EOL><DEDENT>except np.linalg.LinAlgError:<EOL><INDENT>J = np.zeros((base.size,))<EOL><DEDENT>setattr(dlf, f.name, J)<EOL><DEDENT>return dlf<EOL> | r"""Calculate filter for this spacing, shift, n. | f13208:m26 |
def _ls2ar(inp, strinp): | <EOL>if np.size(inp) == <NUM_LIT:1>:<EOL><INDENT>start = np.squeeze(inp)<EOL>stop = start+<NUM_LIT:1><EOL>num = <NUM_LIT:1><EOL><DEDENT>elif np.size(inp) == <NUM_LIT:3>:<EOL><INDENT>start = inp[<NUM_LIT:0>]<EOL>stop = inp[<NUM_LIT:1>]<EOL>num = inp[<NUM_LIT:2>]<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>"+strinp+"<STR_LIT>" +<EOL>"<STR_LIT>"+strinp+"<STR_LIT>" + str(inp))<EOL>raise ValueError(strinp)<EOL><DEDENT>if num < <NUM_LIT:2> or start == stop:<EOL><INDENT>stop = start<EOL>step = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>step = (stop-start)/(num-<NUM_LIT:1>)<EOL><DEDENT>return (start, stop+step/<NUM_LIT:2>, step)<EOL> | r"""Convert float or linspace-input to arange/slice-input for brute. | f13208:m27 |
def _print_count(log): | log['<STR_LIT>'] += <NUM_LIT:1> <EOL>cp = log['<STR_LIT>']/log['<STR_LIT>']*<NUM_LIT:100> <EOL>if log['<STR_LIT>'] == <NUM_LIT:0>: <EOL><INDENT>pass <EOL><DEDENT>elif log['<STR_LIT>'] > log['<STR_LIT>']: <EOL><INDENT>print("<STR_LIT>" % (log['<STR_LIT>']-log['<STR_LIT>']), end='<STR_LIT:\r>')<EOL><DEDENT>elif int(cp) > log['<STR_LIT>'] or cp < <NUM_LIT:1> or log['<STR_LIT>'] == log['<STR_LIT>']:<EOL><INDENT>sec = int(default_timer() - log['<STR_LIT:time>'])<EOL>tleft = str(timedelta(seconds=int(<NUM_LIT:100>*sec/cp - sec)))<EOL>pstr = ("<STR_LIT>"<EOL>% (log['<STR_LIT>'], log['<STR_LIT>']))<EOL>if log['<STR_LIT>'] > <NUM_LIT:100>:<EOL><INDENT>pstr += ("<STR_LIT>" % (cp, tleft))<EOL><DEDENT>print(pstr, end='<STR_LIT:\r>')<EOL>if log['<STR_LIT>'] == log['<STR_LIT>']:<EOL><INDENT>print("<STR_LIT:U+0020>"*len(pstr), end='<STR_LIT:\r>')<EOL>print("<STR_LIT>" % log['<STR_LIT>'])<EOL><DEDENT>log['<STR_LIT>'] = cp<EOL><DEDENT>return log<EOL> | r"""Print run-count information. | f13208:m28 |
def __init__(self, name, lhs, rhs): | self.name = name<EOL>self.lhs = lhs<EOL>self.rhs = rhs<EOL> | r"""Add the filter name, lhs, and rhs. | f13208:c0:m0 |
def versions(mode=None, add_pckg=None, ncol=<NUM_LIT:4>): | <EOL>mesg = ("<STR_LIT>" +<EOL>"<STR_LIT>")<EOL>warnings.warn(mesg, DeprecationWarning)<EOL>return Versions(add_pckg, ncol)<EOL> | r"""Old func-way of class `Versions`, here for backwards compatibility.
``mode`` is not used any longer, dummy here. | f13209:m0 |
def __init__(self, add_pckg=None, ncol=<NUM_LIT:4>): | self.add_pckg = add_pckg<EOL>self.ncol = ncol<EOL> | r"""Print date, time, and version information.
Print date, time, and package version information in any environment
(Jupyter notebook, IPython console, Python console, QT console), either
as html-table (notebook) or as plain text (anywhere).
This script was heavily inspired by:
- ipynbtools.py from qutip https://github.com/qutip
- watermark.py from https://github.com/rasbt/watermark
Parameters
----------
add_pckg : packages, optional
Package or list of packages to add to output information (must be
imported beforehand).
ncol : int, optional
Number of package-columns in html table; only has effect if
``mode='HTML'`` or ``mode='html'``. Defaults to 3.
Examples
--------
>>> import pytest
>>> import dateutil
>>> from empymod import Versions
>>> Versions() # Default values
>>> Versions(pytest) # Provide additional package
>>> Versions([pytest, dateutil], ncol=5) # Set nr of columns | f13209:c0:m0 |
def __repr__(self): | <EOL>n = <NUM_LIT><EOL>text = '<STR_LIT:\n>' + n*'<STR_LIT:->' + '<STR_LIT:\n>'<EOL>text += time.strftime('<STR_LIT>')<EOL>text += '<STR_LIT>'.format(platform.system())+'<STR_LIT>'<EOL>text += '<STR_LIT>'.format(multiprocessing.cpu_count())+'<STR_LIT>'<EOL>for pckg in self._get_packages(self.add_pckg):<EOL><INDENT>text += '<STR_LIT>'.format(pckg.__version__, pckg.__name__)<EOL><DEDENT>text += '<STR_LIT:\n>'<EOL>for txt in textwrap.wrap(sys.version, n-<NUM_LIT:4>):<EOL><INDENT>text += '<STR_LIT:U+0020>'+txt+'<STR_LIT:\n>'<EOL><DEDENT>if mklinfo:<EOL><INDENT>text += '<STR_LIT:\n>'<EOL>for txt in textwrap.wrap(mklinfo, n-<NUM_LIT:4>):<EOL><INDENT>text += '<STR_LIT:U+0020>'+txt+'<STR_LIT:\n>'<EOL><DEDENT><DEDENT>text += n*'<STR_LIT:->'<EOL>return text<EOL> | Plain text information. | f13209:c0:m1 |
def _repr_html_(self): | <EOL>ncol = int(self.ncol)<EOL>border = "<STR_LIT>"<EOL>def colspan(html, txt, ncol, nrow):<EOL><INDENT>r"""<STR_LIT>"""<EOL>html += "<STR_LIT>"<EOL>html += "<STR_LIT>"<EOL>if nrow == <NUM_LIT:0>:<EOL><INDENT>html += "<STR_LIT>"<EOL><DEDENT>elif nrow % <NUM_LIT:2> == <NUM_LIT:0>:<EOL><INDENT>html += "<STR_LIT>"<EOL><DEDENT>html += border + "<STR_LIT>"<EOL>html += str(<NUM_LIT:2>*ncol)+"<STR_LIT>" % txt<EOL>html += "<STR_LIT>"<EOL>return html<EOL><DEDENT>def cols(html, version, name, ncol, i):<EOL><INDENT>r"""<STR_LIT>"""<EOL>if i > <NUM_LIT:0> and i % ncol == <NUM_LIT:0>:<EOL><INDENT>html += "<STR_LIT>"<EOL>html += "<STR_LIT>"<EOL><DEDENT>html += "<STR_LIT>"<EOL>html += "<STR_LIT>" + border + "<STR_LIT>" % version<EOL>html += "<STR_LIT>"<EOL>html += border + "<STR_LIT>" % name<EOL>return html, i+<NUM_LIT:1><EOL><DEDENT>html = "<STR_LIT>"<EOL>html = colspan(html, time.strftime('<STR_LIT>'), ncol, <NUM_LIT:0>)<EOL>html += "<STR_LIT>"<EOL>html, i = cols(html, platform.system(), '<STR_LIT>', ncol, <NUM_LIT:0>)<EOL>html, i = cols(html, multiprocessing.cpu_count(), '<STR_LIT>', ncol, i)<EOL>for pckg in self._get_packages(self.add_pckg):<EOL><INDENT>html, i = cols(html, pckg.__version__, pckg.__name__, ncol, i)<EOL><DEDENT>while i % ncol != <NUM_LIT:0>:<EOL><INDENT>html += "<STR_LIT>" + border + "<STR_LIT>"<EOL>html += "<STR_LIT>" + border + "<STR_LIT>"<EOL>i += <NUM_LIT:1><EOL><DEDENT>html += "<STR_LIT>"<EOL>html = colspan(html, sys.version, ncol, <NUM_LIT:1>)<EOL>if mklinfo:<EOL><INDENT>html = colspan(html, mklinfo, ncol, <NUM_LIT:2>)<EOL><DEDENT>html += "<STR_LIT>"<EOL>return html<EOL> | HTML-rendered versions information. | f13209:c0:m2 |
@staticmethod<EOL><INDENT>def _get_packages(add_pckg):<DEDENT> | <EOL>pckgs = [numpy, scipy, empymod]<EOL>for module in [IPython, numexpr, matplotlib]:<EOL><INDENT>if module:<EOL><INDENT>pckgs += [module]<EOL><DEDENT><DEDENT>if add_pckg is not None:<EOL><INDENT>if isinstance(add_pckg, tuple):<EOL><INDENT>add_pckg = list(add_pckg)<EOL><DEDENT>if not isinstance(add_pckg, list):<EOL><INDENT>add_pckg = [add_pckg, ]<EOL><DEDENT>pckgs += add_pckg<EOL><DEDENT>return pckgs<EOL> | r"""Create list of packages. | f13209:c0:m3 |
def dipole(src, rec, depth, res, freqtime, aniso=None, eperm=None, mperm=None,<EOL>verb=<NUM_LIT:2>): | <EOL>t0 = printstartfinish(verb)<EOL>model = check_model(depth, res, aniso, eperm, eperm, mperm, mperm, False,<EOL>verb)<EOL>depth, res, aniso, epermH, epermV, mpermH, mpermV, _ = model<EOL>frequency = check_frequency(freqtime, res, aniso, epermH, epermV, mpermH,<EOL>mpermV, verb)<EOL>freq, etaH, etaV, zetaH, zetaV = frequency<EOL>src, nsrc = check_dipole(src, '<STR_LIT:src>', verb)<EOL>rec, nrec = check_dipole(rec, '<STR_LIT>', verb)<EOL>off, ang = get_off_ang(src, rec, nsrc, nrec, verb)<EOL>lsrc, zsrc = get_layer_nr(src, depth)<EOL>lrec, zrec = get_layer_nr(rec, depth)<EOL>if lsrc != lrec: <EOL><INDENT>print("<STR_LIT>" +<EOL>"<STR_LIT>"+str(lsrc)+"<STR_LIT:/>"+str(lrec))<EOL>raise ValueError('<STR_LIT>')<EOL><DEDENT>if depth.size < <NUM_LIT:2>: <EOL><INDENT>print("<STR_LIT>" +<EOL>"<STR_LIT>"+_strvar(depth[<NUM_LIT:1>:]))<EOL>raise ValueError('<STR_LIT>')<EOL><DEDENT>if freq.size > <NUM_LIT:1>: <EOL><INDENT>print("<STR_LIT>" +<EOL>"<STR_LIT>"+_strvar(freqtime))<EOL>raise ValueError('<STR_LIT>')<EOL><DEDENT>filt = key_201_2012()<EOL>lambd = filt.base/off[:, None]<EOL>PTM, PTE = greenfct(zsrc, zrec, lsrc, lrec, depth, etaH, etaV, zetaH,<EOL>zetaV, lambd)<EOL>factAng = angle_factor(ang, <NUM_LIT:11>, False, False)<EOL>zmfactAng = (factAng[:, np.newaxis]-<NUM_LIT:1>)/<NUM_LIT:2><EOL>zpfactAng = (factAng[:, np.newaxis]+<NUM_LIT:1>)/<NUM_LIT:2><EOL>fact = <NUM_LIT:4>*np.pi*off<EOL>for i, val in enumerate(PTE):<EOL><INDENT>PTE[i] = (factAng*np.dot(-val, filt.j1)/off +<EOL>np.dot(zmfactAng*val*lambd, filt.j0))/fact<EOL><DEDENT>for i, val in enumerate(PTM):<EOL><INDENT>PTM[i] = (factAng*np.dot(-val, filt.j1)/off +<EOL>np.dot(zpfactAng*val*lambd, filt.j0))/fact<EOL><DEDENT>Gam = np.sqrt((zetaH*etaH)[:, None, :, None]) <EOL>iGam = Gam[:, :, lsrc, <NUM_LIT:0>]<EOL>lgam = np.sqrt(zetaH[:, lsrc]*etaH[:, lsrc])<EOL>ddepth = np.r_[depth, np.inf]<EOL>ds = ddepth[lsrc+<NUM_LIT:1>] - ddepth[lsrc]<EOL>def get_rp_rm(z_eta):<EOL><INDENT>r"""<STR_LIT>"""<EOL>Rp, Rm = reflections(depth, z_eta, Gam, lrec, lsrc, False)<EOL>if Rp.ndim == <NUM_LIT:4>:<EOL><INDENT>Rp = np.squeeze(Rp, axis=<NUM_LIT:3>)<EOL><DEDENT>if Rm.ndim == <NUM_LIT:4>:<EOL><INDENT>Rm = np.squeeze(Rm, axis=<NUM_LIT:3>)<EOL><DEDENT>Rp = np.squeeze(Rp, axis=<NUM_LIT:2>)<EOL>Rm = np.squeeze(Rm, axis=<NUM_LIT:2>)<EOL>Ms = <NUM_LIT:1> - Rp*Rm*np.exp(-<NUM_LIT:2>*iGam*ds)<EOL>npfct = factAng*zetaH[:, lsrc]/(fact*off*lgam*Ms)<EOL>return Rp, Rm, npfct<EOL><DEDENT>Rp, Rm, npfct = get_rp_rm(zetaH)<EOL>PTE[<NUM_LIT:0>] += npfct*Rp*Rm*np.exp(-lgam*(<NUM_LIT:2>*ds - zrec + zsrc))<EOL>PTE[<NUM_LIT:1>] += npfct*Rp*np.exp(-lgam*(<NUM_LIT:2>*ddepth[lrec+<NUM_LIT:1>] - zrec - zsrc))<EOL>PTE[<NUM_LIT:2>] += npfct*Rm*np.exp(-lgam*(zrec + zsrc))<EOL>PTE[<NUM_LIT:3>] += npfct*Rp*Rm*np.exp(-lgam*(<NUM_LIT:2>*ds + zrec - zsrc))<EOL>Rp, Rm, npfct = get_rp_rm(etaH)<EOL>PTM[<NUM_LIT:0>] -= npfct*Rp*Rm*np.exp(-lgam*(<NUM_LIT:2>*ds - zrec + zsrc))<EOL>PTM[<NUM_LIT:1>] += npfct*Rp*np.exp(-lgam*(<NUM_LIT:2>*ddepth[lrec+<NUM_LIT:1>] - zrec - zsrc))<EOL>PTM[<NUM_LIT:2>] += npfct*Rm*np.exp(-lgam*(zrec + zsrc))<EOL>PTM[<NUM_LIT:3>] -= npfct*Rp*Rm*np.exp(-lgam*(<NUM_LIT:2>*ds + zrec - zsrc))<EOL>for i, val in enumerate(PTE):<EOL><INDENT>PTE[i] = np.squeeze(val.reshape((-<NUM_LIT:1>, nrec, nsrc), order='<STR_LIT:F>'))<EOL><DEDENT>for i, val in enumerate(PTM):<EOL><INDENT>PTM[i] = np.squeeze(val.reshape((-<NUM_LIT:1>, nrec, nsrc), order='<STR_LIT:F>'))<EOL><DEDENT>printstartfinish(verb, t0)<EOL>return PTM, PTE<EOL> | r"""Return the electromagnetic field due to a dipole source.
This is a modified version of ``empymod.model.dipole()``. It returns the
separated contributions of TM--, TM-+, TM+-, TM++, TMdirect, TE--, TE-+,
TE+-, TE++, and TEdirect.
Parameters
----------
src, rec : list of floats or arrays
Source and receiver coordinates (m): [x, y, z].
The x- and y-coordinates can be arrays, z is a single value.
The x- and y-coordinates must have the same dimension.
Sources or receivers placed on a layer interface are considered in the
upper layer.
Sources and receivers must be in the same layer.
depth : list
Absolute layer interfaces z (m); #depth = #res - 1
(excluding +/- infinity).
res : array_like
Horizontal resistivities rho_h (Ohm.m); #res = #depth + 1.
freqtime : float
Frequency f (Hz). (The name ``freqtime`` is kept for consistency with
``empymod.model.dipole()``. Only one frequency at once.
aniso : array_like, optional
Anisotropies lambda = sqrt(rho_v/rho_h) (-); #aniso = #res.
Defaults to ones.
eperm : array_like, optional
Relative electric permittivities epsilon (-);
#eperm = #res. Default is ones.
mperm : array_like, optional
Relative magnetic permeabilities mu (-);
#mperm = #res. Default is ones.
verb : {0, 1, 2, 3, 4}, optional
Level of verbosity, default is 2:
- 0: Print nothing.
- 1: Print warnings.
- 2: Print additional runtime and kernel calls
- 3: Print additional start/stop, condensed parameter information.
- 4: Print additional full parameter information
Returns
-------
TM, TE : list of ndarrays, (nfreq, nrec, nsrc)
Frequency-domain EM field [V/m], separated into
TM = [TM--, TM-+, TM+-, TM++, TMdirect]
and
TE = [TE--, TE-+, TE+-, TE++, TEdirect].
However, source and receiver are normalised. So the source strength is
1 A and its length is 1 m. Therefore the electric field could also be
written as [V/(A.m2)].
The shape of EM is (nfreq, nrec, nsrc). However, single dimensions
are removed. | f13210:m0 |
def greenfct(zsrc, zrec, lsrc, lrec, depth, etaH, etaV, zetaH, zetaV, lambd): | <EOL>for TM in [True, False]:<EOL><INDENT>if TM:<EOL><INDENT>e_zH, e_zV, z_eH = etaH, etaV, zetaH <EOL><DEDENT>else:<EOL><INDENT>e_zH, e_zV, z_eH = zetaH, zetaV, etaH <EOL><DEDENT>Gam = np.sqrt((e_zH/e_zV)[:, None, :, None] *<EOL>(lambd*lambd)[None, :, None, :] +<EOL>(z_eH*e_zH)[:, None, :, None])<EOL>lrecGam = Gam[:, :, lrec, :]<EOL>Rp, Rm = reflections(depth, e_zH, Gam, lrec, lsrc, False)<EOL>if lrec != depth.size-<NUM_LIT:1>: <EOL><INDENT>ddepth = depth[lrec + <NUM_LIT:1>] - zrec<EOL>Wu = np.exp(-lrecGam*ddepth)<EOL><DEDENT>else:<EOL><INDENT>Wu = np.full_like(lrecGam, <NUM_LIT:0>+<NUM_LIT>)<EOL><DEDENT>if lrec != <NUM_LIT:0>: <EOL><INDENT>ddepth = zrec - depth[lrec]<EOL>Wd = np.exp(-lrecGam*ddepth)<EOL><DEDENT>else:<EOL><INDENT>Wd = np.full_like(lrecGam, <NUM_LIT:0>+<NUM_LIT>)<EOL><DEDENT>Puu, Pud, Pdu, Pdd = fields(depth, Rp, Rm, Gam, lrec, lsrc, zsrc, TM)<EOL>df = np.exp(-lrecGam*abs(zsrc - zrec)) <EOL>fTM = Gam[:, :, lrec, :]/etaH[:, None, lrec, None]<EOL>fTE = zetaH[:, None, lsrc, None]/Gam[:, :, lsrc, :]<EOL>if TM:<EOL><INDENT>PTM = [Puu*Wu*fTM, Pud*Wu*fTM, Pdu*Wd*fTM, Pdd*Wd*fTM, -df*fTM]<EOL><DEDENT>else:<EOL><INDENT>PTE = [Puu*Wu*fTE, Pud*Wu*fTE, Pdu*Wd*fTE, Pdd*Wd*fTE, df*fTE]<EOL><DEDENT><DEDENT>return PTM, PTE<EOL> | r"""Calculate Green's function for TM and TE.
This is a modified version of empymod.kernel.greenfct(). See the original
version for more information. | f13210:m1 |
def fields(depth, Rp, Rm, Gam, lrec, lsrc, zsrc, TM): | <EOL>first_layer = lsrc == <NUM_LIT:0><EOL>last_layer = lsrc == depth.size-<NUM_LIT:1><EOL>if lsrc != depth.size-<NUM_LIT:1>:<EOL><INDENT>ds = depth[lsrc+<NUM_LIT:1>]-depth[lsrc]<EOL>dp = depth[lsrc+<NUM_LIT:1>]-zsrc<EOL><DEDENT>dm = zsrc-depth[lsrc]<EOL>Rmp = Rm<EOL>Rpm = Rp<EOL>if TM:<EOL><INDENT>plus = False<EOL><DEDENT>else:<EOL><INDENT>plus = True<EOL><DEDENT>pm = <NUM_LIT:1> <EOL>if not plus:<EOL><INDENT>pm = -<NUM_LIT:1><EOL><DEDENT>for up in [False, True]:<EOL><INDENT>if up and (lrec == depth.size-<NUM_LIT:1> or lrec > lsrc):<EOL><INDENT>Puu = np.full_like(Gam[:, :, lsrc, :], <NUM_LIT:0>+<NUM_LIT>)<EOL>Pud = np.full_like(Gam[:, :, lsrc, :], <NUM_LIT:0>+<NUM_LIT>)<EOL>continue<EOL><DEDENT>if not up and (lrec == <NUM_LIT:0> or lrec < lsrc):<EOL><INDENT>Pdu = np.full_like(Gam[:, :, lsrc, :], <NUM_LIT:0>+<NUM_LIT>)<EOL>Pdd = np.full_like(Gam[:, :, lsrc, :], <NUM_LIT:0>+<NUM_LIT>)<EOL>continue<EOL><DEDENT>if up:<EOL><INDENT>dp, dm = dm, dp<EOL>Rmp, Rpm = Rpm, Rmp<EOL>first_layer, last_layer = last_layer, first_layer<EOL><DEDENT>iGam = Gam[:, :, lsrc, :]<EOL>if last_layer: <EOL><INDENT>Pd = Rmp*np.exp(-iGam*dm)<EOL>Pu = np.full_like(Gam[:, :, lsrc, :], <NUM_LIT:0>+<NUM_LIT>)<EOL><DEDENT>else: <EOL><INDENT>Ms = <NUM_LIT:1> - Rmp*Rpm*np.exp(-<NUM_LIT:2>*iGam*ds)<EOL>Pd = Rmp/Ms*np.exp(-iGam*dm)<EOL>Pu = Rmp/Ms*pm*Rpm*np.exp(-iGam*(ds+dp))<EOL><DEDENT>if up:<EOL><INDENT>Puu = Pu<EOL>Pud = Pd<EOL><DEDENT>else:<EOL><INDENT>Pdu = Pd<EOL>Pdd = Pu<EOL><DEDENT><DEDENT>return Puu, Pud, Pdu, Pdd<EOL> | r"""Calculate Pu+, Pu-, Pd+, Pd-.
This is a modified version of empymod.kernel.fields(). See the original
version for more information. | f13210:m2 |
def __init__(self, auth, api='<STR_LIT>', **kwargs): | self.api = api<EOL>self.log = auth.log<EOL>try:<EOL><INDENT>self.url = '<STR_LIT>' % (auth.get_url(), self.api)<EOL><DEDENT>except AttributeError:<EOL><INDENT>self.url = '<STR_LIT>' % self.api<EOL><DEDENT>try:<EOL><INDENT>self.auth = auth.get_auth()<EOL><DEDENT>except AttributeError:<EOL><INDENT>self.auth = auth<EOL><DEDENT> | Search the logs.
Args:
auth (Client): Authentication object
api (str): Api endpath | f13218:c0:m0 |
def query(self, criteria, **opts): | time_now = datetime.datetime.now().replace(second=<NUM_LIT:0>, microsecond=<NUM_LIT:0>)<EOL>right_now = time_now.isoformat()<EOL>minutes_ago = (time_now - datetime.timedelta(minutes=<NUM_LIT:15>)).isoformat()<EOL>formats = opts.get('<STR_LIT>', '<STR_LIT>')<EOL>timezone = opts.get('<STR_LIT>', '<STR_LIT>')<EOL>time_from = opts.get('<STR_LIT>', minutes_ago)<EOL>time_to = opts.get('<STR_LIT>', right_now)<EOL>t_options = {<EOL>'<STR_LIT:q>': criteria,<EOL>'<STR_LIT>': formats,<EOL>'<STR_LIT>': timezone,<EOL>'<STR_LIT>': time_from,<EOL>'<STR_LIT:to>': time_to,<EOL>}<EOL>options = '<STR_LIT:&>'.join(['<STR_LIT>'.format(k, v)<EOL>for k, v in t_options.items()])<EOL>req = requests.get('<STR_LIT>' %<EOL>(self.url, options), auth=self.auth)<EOL>try:<EOL><INDENT>data = req.json()<EOL><DEDENT>except json.decoder.JSONDecodeError:<EOL><INDENT>data = []<EOL><DEDENT>return {<EOL>'<STR_LIT:data>': data,<EOL>'<STR_LIT>': req.status_code,<EOL>'<STR_LIT>': req.reason,<EOL>}<EOL> | Returns a dict of the query, including the results
:param critera: string of search criteria
:param **opts:
:formats: json/xml (default: json)
:timezone: timezone to use (default: UTC)
:time_from: 15m ago from now (datetime)
:time_to: right now (datetime) | f13218:c0:m1 |
def __init__(self, auth, **kwargs): | self.auth = auth<EOL>self.protocol = kwargs.get('<STR_LIT>', '<STR_LIT>')<EOL>self.domain = kwargs.get('<STR_LIT>', '<STR_LIT>')<EOL>self.api = kwargs.get('<STR_LIT>', '<STR_LIT>')<EOL>api_path = '<STR_LIT:%s>' % self.api<EOL>self.url = '<STR_LIT>' % (self.protocol, self.domain, api_path)<EOL>self._debug_mode = kwargs.get('<STR_LIT>', False)<EOL>self.log = logging.getLogger(__name__)<EOL>self.log.addHandler(logging.StreamHandler())<EOL>self.log.setLevel(get_logging_level(self._debug_mode))<EOL> | Initializes Client object.
Args:
auth (tuple): Authentication object
api (str): Api endpath | f13219:c0:m0 |
def get_url(self): | return self.url<EOL> | Returns full api url | f13219:c0:m1 |
def get_auth(self): | return self.auth<EOL> | Returns api auth details | f13219:c0:m2 |
def __init__(self, auth, api='<STR_LIT>', **kwargs): | self.api = api<EOL>self.collector_id = None<EOL>self.log = auth.log<EOL>try:<EOL><INDENT>self.url = '<STR_LIT>' % (auth.get_url(), self.api)<EOL><DEDENT>except AttributeError:<EOL><INDENT>self.url = '<STR_LIT>' % self.api<EOL><DEDENT>try:<EOL><INDENT>self.auth = auth.get_auth()<EOL><DEDENT>except AttributeError:<EOL><INDENT>self.auth = auth<EOL><DEDENT> | Access sumologic Collectors.
Args:
auth (Client): Authentication object
api (str): Api endpath | f13221:c0:m0 |
def get_collectors(self, limit=<NUM_LIT:1000>, offset=<NUM_LIT:0>): | options = {<EOL>'<STR_LIT>': limit,<EOL>'<STR_LIT>': offset,<EOL>}<EOL>request = requests.get(self.url, params=options, auth=self.auth)<EOL>try:<EOL><INDENT>results = request.json()['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>results = request.json()<EOL><DEDENT>except json.decoder.JSONDecodeError:<EOL><INDENT>results = []<EOL><DEDENT>return results<EOL> | Returns a dict of collectors.
Args:
limit (int): number of collectors to return
offset (int): the offset of where the list of collectors should begin from | f13221:c0:m1 |
def find(self, name): | collectors = self.get_collectors()<EOL>for collector in collectors:<EOL><INDENT>if name.lower() == collector['<STR_LIT:name>'].lower():<EOL><INDENT>self.collector_id = collector['<STR_LIT:id>']<EOL>return collector<EOL><DEDENT><DEDENT>return {'<STR_LIT:status>': '<STR_LIT>'}<EOL> | Returns a dict of collector's details if found.
Args:
name (str): name of collector searching for | f13221:c0:m2 |
def delete(self, collector_id=None): | cid = self.collector_id<EOL>if collector_id:<EOL><INDENT>cid = collector_id<EOL><DEDENT>url = '<STR_LIT>'.format(self.url, cid)<EOL>request = requests.delete(url, auth=self.auth)<EOL>try:<EOL><INDENT>response = request.json()<EOL><DEDENT>except ValueError:<EOL><INDENT>response = {<EOL>u'<STR_LIT:message>': u'<STR_LIT>',<EOL>u'<STR_LIT:status>': <NUM_LIT:200>,<EOL>}<EOL><DEDENT>return response<EOL> | Delete a collector from inventory.
Args:
collector_id (int): id of collector (optional) | f13221:c0:m3 |
def info(self, collector_id): | cid = self.collector_id<EOL>if collector_id:<EOL><INDENT>cid = collector_id<EOL><DEDENT>url = '<STR_LIT>'.format(self.url, cid)<EOL>request = requests.get(url, auth=self.auth)<EOL>return request.json()<EOL> | Return a dict of collector.
Args:
collector_id (int): id of collector (optional) | f13221:c0:m4 |
def get_id(self): | return self.collector_id<EOL> | Return the collector's id | f13221:c0:m5 |
def get_logging_level(debug): | level = logging.INFO<EOL>if debug:<EOL><INDENT>level = logging.DEBUG<EOL><DEDENT>return level<EOL> | Returns logging level based on boolean | f13222:m0 |
@staticmethod<EOL><INDENT>def _strip_top_comments(lines: Sequence[str], line_separator: str) -> str:<DEDENT> | lines = copy.copy(lines)<EOL>while lines and lines[<NUM_LIT:0>].startswith("<STR_LIT:#>"):<EOL><INDENT>lines = lines[<NUM_LIT:1>:]<EOL><DEDENT>return line_separator.join(lines)<EOL> | Strips # comments that exist at the top of the given lines | f13225:c0:m5 |
def place_module(self, module_name: str) -> Optional[str]: | return self.finder.find(module_name)<EOL> | Tries to determine if a module is a python std import, third party import, or project code:
if it can't determine - it assumes it is project code | f13225:c0:m6 |
def _get_line(self) -> str: | line = self.in_lines[self.index]<EOL>self.index += <NUM_LIT:1><EOL>return line<EOL> | Returns the current line from the file while incrementing the index. | f13225:c0:m7 |
@staticmethod<EOL><INDENT>def _import_type(line: str) -> Optional[str]:<DEDENT> | if "<STR_LIT>" in line or "<STR_LIT>" in line:<EOL><INDENT>return None<EOL><DEDENT>elif line.startswith('<STR_LIT>'):<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif line.startswith('<STR_LIT>'):<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT> | If the current line is an import line it will return its type (from or straight) | f13225:c0:m8 |
def _at_end(self) -> bool: | return self.index == self.number_of_lines<EOL> | returns True if we are at the end of the file. | f13225:c0:m9 |
def _add_comments(<EOL>self,<EOL>comments: Optional[Sequence[str]],<EOL>original_string: str = "<STR_LIT>"<EOL>) -> str: | if self.config['<STR_LIT>']:<EOL><INDENT>return self._strip_comments(original_string)[<NUM_LIT:0>]<EOL><DEDENT>if not comments:<EOL><INDENT>return original_string<EOL><DEDENT>else:<EOL><INDENT>return "<STR_LIT>".format(self._strip_comments(original_string)[<NUM_LIT:0>],<EOL>self.config['<STR_LIT>'],<EOL>"<STR_LIT>".join(comments))<EOL><DEDENT> | Returns a string with comments added if ignore_comments is not set. | f13225:c0:m11 |
def _wrap(self, line: str) -> str: | wrap_mode = self.config['<STR_LIT>']<EOL>if len(line) > self.config['<STR_LIT>'] and wrap_mode != WrapModes.NOQA:<EOL><INDENT>line_without_comment = line<EOL>comment = None<EOL>if '<STR_LIT:#>' in line:<EOL><INDENT>line_without_comment, comment = line.split('<STR_LIT:#>', <NUM_LIT:1>)<EOL><DEDENT>for splitter in ("<STR_LIT>", "<STR_LIT:.>", "<STR_LIT>"):<EOL><INDENT>exp = r"<STR_LIT>" + re.escape(splitter) + r"<STR_LIT>"<EOL>if re.search(exp, line_without_comment) and not line_without_comment.strip().startswith(splitter):<EOL><INDENT>line_parts = re.split(exp, line_without_comment)<EOL>if comment:<EOL><INDENT>line_parts[-<NUM_LIT:1>] = '<STR_LIT>'.format(line_parts[-<NUM_LIT:1>], comment)<EOL><DEDENT>next_line = []<EOL>while (len(line) + <NUM_LIT:2>) > (self.config['<STR_LIT>'] or self.config['<STR_LIT>']) and line_parts:<EOL><INDENT>next_line.append(line_parts.pop())<EOL>line = splitter.join(line_parts)<EOL><DEDENT>if not line:<EOL><INDENT>line = next_line.pop()<EOL><DEDENT>cont_line = self._wrap(self.config['<STR_LIT>'] + splitter.join(next_line).lstrip())<EOL>if self.config['<STR_LIT>']:<EOL><INDENT>output = "<STR_LIT>".format(<EOL>line, splitter, self.line_separator, cont_line,<EOL>"<STR_LIT:U+002C>" if self.config['<STR_LIT>'] else "<STR_LIT>",<EOL>self.line_separator if wrap_mode in {WrapModes.VERTICAL_HANGING_INDENT,<EOL>WrapModes.VERTICAL_GRID_GROUPED}<EOL>else "<STR_LIT>")<EOL>lines = output.split(self.line_separator)<EOL>if self.config['<STR_LIT>'] in lines[-<NUM_LIT:1>] and lines[-<NUM_LIT:1>].endswith('<STR_LIT:)>'):<EOL><INDENT>line, comment = lines[-<NUM_LIT:1>].split(self.config['<STR_LIT>'], <NUM_LIT:1>)<EOL>lines[-<NUM_LIT:1>] = line + '<STR_LIT:)>' + self.config['<STR_LIT>'] + comment[:-<NUM_LIT:1>]<EOL><DEDENT>return self.line_separator.join(lines)<EOL><DEDENT>return "<STR_LIT>".format(line, splitter, self.line_separator, cont_line)<EOL><DEDENT><DEDENT><DEDENT>elif len(line) > self.config['<STR_LIT>'] and wrap_mode == settings.WrapModes.NOQA:<EOL><INDENT>if "<STR_LIT>" not in line:<EOL><INDENT>return "<STR_LIT>".format(line, self.config['<STR_LIT>'])<EOL><DEDENT><DEDENT>return line<EOL> | Returns an import wrapped to the specified line-length, if possible. | f13225:c0:m12 |
def _add_formatted_imports(self) -> None: | sort_ignore_case = self.config['<STR_LIT>']<EOL>sections = itertools.chain(self.sections, self.config['<STR_LIT>']) <EOL>if self.config['<STR_LIT>']:<EOL><INDENT>self.imports['<STR_LIT>'] = {'<STR_LIT>': [], '<STR_LIT>': {}}<EOL>for section in sections:<EOL><INDENT>self.imports['<STR_LIT>']['<STR_LIT>'].extend(self.imports[section].get('<STR_LIT>', []))<EOL>self.imports['<STR_LIT>']['<STR_LIT>'].update(self.imports[section].get('<STR_LIT>', {}))<EOL><DEDENT>sections = ('<STR_LIT>', )<EOL><DEDENT>output = [] <EOL>pending_lines_before = False<EOL>for section in sections:<EOL><INDENT>straight_modules = self.imports[section]['<STR_LIT>']<EOL>straight_modules = nsorted(straight_modules, key=lambda key: self._module_key(key, self.config, section_name=section))<EOL>from_modules = self.imports[section]['<STR_LIT>']<EOL>from_modules = nsorted(from_modules, key=lambda key: self._module_key(key, self.config, section_name=section))<EOL>section_output = [] <EOL>if self.config['<STR_LIT>']:<EOL><INDENT>self._add_from_imports(from_modules, section, section_output, sort_ignore_case)<EOL>if self.config['<STR_LIT>'] and from_modules and straight_modules:<EOL><INDENT>section_output.extend(['<STR_LIT>'] * self.config['<STR_LIT>'])<EOL><DEDENT>self._add_straight_imports(straight_modules, section, section_output)<EOL><DEDENT>else:<EOL><INDENT>self._add_straight_imports(straight_modules, section, section_output)<EOL>if self.config['<STR_LIT>'] and from_modules and straight_modules:<EOL><INDENT>section_output.extend(['<STR_LIT>'] * self.config['<STR_LIT>'])<EOL><DEDENT>self._add_from_imports(from_modules, section, section_output, sort_ignore_case)<EOL><DEDENT>if self.config['<STR_LIT>']:<EOL><INDENT>def by_module(line: str) -> str:<EOL><INDENT>section = '<STR_LIT:B>'<EOL>if line.startswith('<STR_LIT:#>'):<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>line = re.sub('<STR_LIT>', '<STR_LIT>', line)<EOL>line = re.sub('<STR_LIT>', '<STR_LIT>', line)<EOL>if line.split('<STR_LIT:U+0020>')[<NUM_LIT:0>] in self.config['<STR_LIT>']:<EOL><INDENT>section = '<STR_LIT:A>'<EOL><DEDENT>if not self.config['<STR_LIT>']:<EOL><INDENT>line = line.lower()<EOL><DEDENT>return '<STR_LIT>'.format(section, line)<EOL><DEDENT>section_output = nsorted(section_output, key=by_module)<EOL><DEDENT>section_name = section<EOL>no_lines_before = section_name in self.config['<STR_LIT>']<EOL>if section_output:<EOL><INDENT>if section_name in self.place_imports:<EOL><INDENT>self.place_imports[section_name] = section_output<EOL>continue<EOL><DEDENT>section_title = self.config.get('<STR_LIT>' + str(section_name).lower(), '<STR_LIT>')<EOL>if section_title:<EOL><INDENT>section_comment = "<STR_LIT>".format(section_title)<EOL>if section_comment not in self.out_lines[<NUM_LIT:0>:<NUM_LIT:1>] and section_comment not in self.in_lines[<NUM_LIT:0>:<NUM_LIT:1>]:<EOL><INDENT>section_output.insert(<NUM_LIT:0>, section_comment)<EOL><DEDENT><DEDENT>if pending_lines_before or not no_lines_before:<EOL><INDENT>output += (['<STR_LIT>'] * self.config['<STR_LIT>'])<EOL><DEDENT>output += section_output<EOL>pending_lines_before = False<EOL><DEDENT>else:<EOL><INDENT>pending_lines_before = pending_lines_before or not no_lines_before<EOL><DEDENT><DEDENT>while output and output[-<NUM_LIT:1>].strip() == '<STR_LIT>':<EOL><INDENT>output.pop()<EOL><DEDENT>while output and output[<NUM_LIT:0>].strip() == '<STR_LIT>':<EOL><INDENT>output.pop(<NUM_LIT:0>)<EOL><DEDENT>output_at = <NUM_LIT:0><EOL>if self.import_index < self.original_num_of_lines:<EOL><INDENT>output_at = self.import_index<EOL><DEDENT>elif self._first_comment_index_end != -<NUM_LIT:1> and self._first_comment_index_start <= <NUM_LIT:2>:<EOL><INDENT>output_at = self._first_comment_index_end<EOL><DEDENT>self.out_lines[output_at:<NUM_LIT:0>] = output<EOL>imports_tail = output_at + len(output)<EOL>while [character.strip() for character in self.out_lines[imports_tail: imports_tail + <NUM_LIT:1>]] == ["<STR_LIT>"]:<EOL><INDENT>self.out_lines.pop(imports_tail)<EOL><DEDENT>if len(self.out_lines) > imports_tail:<EOL><INDENT>next_construct = "<STR_LIT>"<EOL>self._in_quote = False <EOL>tail = self.out_lines[imports_tail:]<EOL>for index, line in enumerate(tail):<EOL><INDENT>in_quote = self._in_quote<EOL>if not self._skip_line(line) and line.strip():<EOL><INDENT>if line.strip().startswith("<STR_LIT:#>") and len(tail) > (index + <NUM_LIT:1>) and tail[index + <NUM_LIT:1>].strip():<EOL><INDENT>continue<EOL><DEDENT>next_construct = line<EOL>break<EOL><DEDENT>elif not in_quote:<EOL><INDENT>parts = line.split()<EOL>if len(parts) >= <NUM_LIT:3> and parts[<NUM_LIT:1>] == '<STR_LIT:=>' and "<STR_LIT:'>" not in parts[<NUM_LIT:0>] and '<STR_LIT:">' not in parts[<NUM_LIT:0>]:<EOL><INDENT>next_construct = line<EOL>break<EOL><DEDENT><DEDENT><DEDENT>if self.config['<STR_LIT>'] != -<NUM_LIT:1>:<EOL><INDENT>self.out_lines[imports_tail:<NUM_LIT:0>] = ["<STR_LIT>" for line in range(self.config['<STR_LIT>'])]<EOL><DEDENT>elif next_construct.startswith("<STR_LIT>") or next_construct.startswith("<STR_LIT>") ornext_construct.startswith("<STR_LIT:@>") or next_construct.startswith("<STR_LIT>"):<EOL><INDENT>self.out_lines[imports_tail:<NUM_LIT:0>] = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>else:<EOL><INDENT>self.out_lines[imports_tail:<NUM_LIT:0>] = ["<STR_LIT>"]<EOL><DEDENT><DEDENT>if self.place_imports:<EOL><INDENT>new_out_lines = []<EOL>for index, line in enumerate(self.out_lines):<EOL><INDENT>new_out_lines.append(line)<EOL>if line in self.import_placements:<EOL><INDENT>new_out_lines.extend(self.place_imports[self.import_placements[line]])<EOL>if len(self.out_lines) <= index or self.out_lines[index + <NUM_LIT:1>].strip() != "<STR_LIT>":<EOL><INDENT>new_out_lines.append("<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>self.out_lines = new_out_lines<EOL><DEDENT> | Adds the imports back to the file.
(at the index of the first import) sorted alphabetically and split between groups | f13225:c0:m16 |
@staticmethod<EOL><INDENT>def _strip_comments(<EOL>line: str,<EOL>comments: Optional[List[str]] = None<EOL>) -> Tuple[str, List[str], bool]:<DEDENT> | if comments is None:<EOL><INDENT>comments = []<EOL><DEDENT>new_comments = False<EOL>comment_start = line.find("<STR_LIT:#>")<EOL>if comment_start != -<NUM_LIT:1>:<EOL><INDENT>comments.append(line[comment_start + <NUM_LIT:1>:].strip())<EOL>new_comments = True<EOL>line = line[:comment_start]<EOL><DEDENT>return line, comments, new_comments<EOL> | Removes comments from import line. | f13225:c0:m26 |
def _parse(self) -> None: | self._in_quote = False<EOL>self._in_top_comment = False<EOL>while not self._at_end():<EOL><INDENT>raw_line = line = self._get_line()<EOL>line = line.replace("<STR_LIT>", "<STR_LIT>")<EOL>line = line.replace("<STR_LIT:\t>", "<STR_LIT:U+0020>").replace('<STR_LIT>', '<STR_LIT>')<EOL>line = line.replace("<STR_LIT>", "<STR_LIT>")<EOL>statement_index = self.index<EOL>skip_line = self._skip_line(line)<EOL>if line in self._section_comments and not skip_line:<EOL><INDENT>if self.import_index == -<NUM_LIT:1>:<EOL><INDENT>self.import_index = self.index - <NUM_LIT:1><EOL><DEDENT>continue<EOL><DEDENT>if "<STR_LIT>" in line and line.startswith("<STR_LIT:#>"):<EOL><INDENT>section = line.split("<STR_LIT>")[-<NUM_LIT:1>].split()[<NUM_LIT:0>].upper()<EOL>self.place_imports[section] = []<EOL>self.import_placements[line] = section<EOL><DEDENT>if "<STR_LIT:;>" in line:<EOL><INDENT>for part in (part.strip() for part in line.split("<STR_LIT:;>")):<EOL><INDENT>if part and not part.startswith("<STR_LIT>") and not part.startswith("<STR_LIT>"):<EOL><INDENT>skip_line = True<EOL><DEDENT><DEDENT><DEDENT>import_type = self._import_type(line)<EOL>if not import_type or skip_line:<EOL><INDENT>self.out_lines.append(raw_line)<EOL>continue<EOL><DEDENT>for line in (line.strip() for line in line.split("<STR_LIT:;>")):<EOL><INDENT>import_type = self._import_type(line)<EOL>if not import_type:<EOL><INDENT>self.out_lines.append(line)<EOL>continue<EOL><DEDENT>if self.import_index == -<NUM_LIT:1>:<EOL><INDENT>self.import_index = self.index - <NUM_LIT:1><EOL><DEDENT>nested_comments = {}<EOL>import_string, comments, new_comments = self._strip_comments(line)<EOL>line_parts = [part for part in self._strip_syntax(import_string).strip().split("<STR_LIT:U+0020>") if part]<EOL>if import_type == "<STR_LIT>" and len(line_parts) == <NUM_LIT:2> and line_parts[<NUM_LIT:1>] != "<STR_LIT:*>" and new_comments:<EOL><INDENT>nested_comments[line_parts[-<NUM_LIT:1>]] = comments[<NUM_LIT:0>]<EOL><DEDENT>if "<STR_LIT:(>" in line.split("<STR_LIT:#>")[<NUM_LIT:0>] and not self._at_end():<EOL><INDENT>while not line.strip().endswith("<STR_LIT:)>") and not self._at_end():<EOL><INDENT>line, comments, new_comments = self._strip_comments(self._get_line(), comments)<EOL>stripped_line = self._strip_syntax(line).strip()<EOL>if import_type == "<STR_LIT>" and stripped_line and "<STR_LIT:U+0020>" not in stripped_line and new_comments:<EOL><INDENT>nested_comments[stripped_line] = comments[-<NUM_LIT:1>]<EOL><DEDENT>import_string += self.line_separator + line<EOL><DEDENT><DEDENT>else:<EOL><INDENT>while line.strip().endswith("<STR_LIT:\\>"):<EOL><INDENT>line, comments, new_comments = self._strip_comments(self._get_line(), comments)<EOL>if "<STR_LIT:(>" in line.split("<STR_LIT:#>")[<NUM_LIT:0>] and "<STR_LIT:)>" not in line.split("<STR_LIT:#>")[<NUM_LIT:0>] and not self._at_end():<EOL><INDENT>stripped_line = self._strip_syntax(line).strip()<EOL>if import_type == "<STR_LIT>" and stripped_line and "<STR_LIT:U+0020>" not in stripped_line and new_comments:<EOL><INDENT>nested_comments[stripped_line] = comments[-<NUM_LIT:1>]<EOL><DEDENT>import_string += self.line_separator + line<EOL>while not line.strip().endswith("<STR_LIT:)>") and not self._at_end():<EOL><INDENT>line, comments, new_comments = self._strip_comments(self._get_line(), comments)<EOL>stripped_line = self._strip_syntax(line).strip()<EOL>if import_type == "<STR_LIT>" and stripped_line and "<STR_LIT:U+0020>" not in stripped_line and new_comments:<EOL><INDENT>nested_comments[stripped_line] = comments[-<NUM_LIT:1>]<EOL><DEDENT>import_string += self.line_separator + line<EOL><DEDENT><DEDENT>stripped_line = self._strip_syntax(line).strip()<EOL>if import_type == "<STR_LIT>" and stripped_line and "<STR_LIT:U+0020>" not in stripped_line and new_comments:<EOL><INDENT>nested_comments[stripped_line] = comments[-<NUM_LIT:1>]<EOL><DEDENT>if import_string.strip().endswith("<STR_LIT>") or line.strip().startswith("<STR_LIT>"):<EOL><INDENT>import_string += self.line_separator + line<EOL><DEDENT>else:<EOL><INDENT>import_string = import_string.rstrip().rstrip("<STR_LIT:\\>") + "<STR_LIT:U+0020>" + line.lstrip()<EOL><DEDENT><DEDENT><DEDENT>if import_type == "<STR_LIT>":<EOL><INDENT>import_string = import_string.replace("<STR_LIT>", "<STR_LIT>")<EOL>parts = import_string.split("<STR_LIT>")<EOL>from_import = parts[<NUM_LIT:0>].split("<STR_LIT:U+0020>")<EOL>import_string = "<STR_LIT>".join([from_import[<NUM_LIT:0>] + "<STR_LIT:U+0020>" + "<STR_LIT>".join(from_import[<NUM_LIT:1>:])] + parts[<NUM_LIT:1>:])<EOL><DEDENT>imports = [item.replace("<STR_LIT>", "<STR_LIT>").replace("<STR_LIT>", "<STR_LIT>") for item in<EOL>self._strip_syntax(import_string).split()]<EOL>if "<STR_LIT>" in imports and (imports.index('<STR_LIT>') + <NUM_LIT:1>) < len(imports):<EOL><INDENT>while "<STR_LIT>" in imports:<EOL><INDENT>index = imports.index('<STR_LIT>')<EOL>if import_type == "<STR_LIT>":<EOL><INDENT>module = imports[<NUM_LIT:0>] + "<STR_LIT:.>" + imports[index - <NUM_LIT:1>]<EOL>self.as_map[module] = imports[index + <NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>module = imports[index - <NUM_LIT:1>]<EOL>self.as_map[module] = imports[index + <NUM_LIT:1>]<EOL><DEDENT>if not self.config['<STR_LIT>']:<EOL><INDENT>self.comments['<STR_LIT>'][module] = comments<EOL>comments = []<EOL><DEDENT>del imports[index:index + <NUM_LIT:2>]<EOL><DEDENT><DEDENT>if import_type == "<STR_LIT>":<EOL><INDENT>import_from = imports.pop(<NUM_LIT:0>)<EOL>placed_module = self.place_module(import_from)<EOL>if self.config['<STR_LIT>']:<EOL><INDENT>print("<STR_LIT>" % (import_from, placed_module))<EOL><DEDENT>if placed_module == '<STR_LIT>':<EOL><INDENT>print(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(import_from, line)<EOL>)<EOL><DEDENT>root = self.imports[placed_module][import_type]<EOL>for import_name in imports:<EOL><INDENT>associated_comment = nested_comments.get(import_name)<EOL>if associated_comment:<EOL><INDENT>self.comments['<STR_LIT>'].setdefault(import_from, {})[import_name] = associated_comment<EOL>comments.pop(comments.index(associated_comment))<EOL><DEDENT><DEDENT>if comments:<EOL><INDENT>self.comments['<STR_LIT>'].setdefault(import_from, []).extend(comments)<EOL><DEDENT>if len(self.out_lines) > max(self.import_index, self._first_comment_index_end + <NUM_LIT:1>, <NUM_LIT:1>) - <NUM_LIT:1>:<EOL><INDENT>last = self.out_lines and self.out_lines[-<NUM_LIT:1>].rstrip() or "<STR_LIT>"<EOL>while (last.startswith("<STR_LIT:#>") and not last.endswith('<STR_LIT>') and not last.endswith("<STR_LIT>") and<EOL>'<STR_LIT>' not in last):<EOL><INDENT>self.comments['<STR_LIT>']['<STR_LIT>'].setdefault(import_from, []).insert(<NUM_LIT:0>, self.out_lines.pop(-<NUM_LIT:1>))<EOL>if len(self.out_lines) > max(self.import_index - <NUM_LIT:1>, self._first_comment_index_end + <NUM_LIT:1>, <NUM_LIT:1>) - <NUM_LIT:1>:<EOL><INDENT>last = self.out_lines[-<NUM_LIT:1>].rstrip()<EOL><DEDENT>else:<EOL><INDENT>last = "<STR_LIT>"<EOL><DEDENT><DEDENT>if statement_index - <NUM_LIT:1> == self.import_index:<EOL><INDENT>self.import_index -= len(self.comments['<STR_LIT>']['<STR_LIT>'].get(import_from, []))<EOL><DEDENT><DEDENT>if import_from not in root:<EOL><INDENT>root[import_from] = OrderedDict()<EOL><DEDENT>root[import_from].update((module, None) for module in imports)<EOL><DEDENT>else:<EOL><INDENT>for module in imports:<EOL><INDENT>if comments:<EOL><INDENT>self.comments['<STR_LIT>'][module] = comments<EOL>comments = None<EOL><DEDENT>if len(self.out_lines) > max(self.import_index, self._first_comment_index_end + <NUM_LIT:1>, <NUM_LIT:1>) - <NUM_LIT:1>:<EOL><INDENT>last = self.out_lines and self.out_lines[-<NUM_LIT:1>].rstrip() or "<STR_LIT>"<EOL>while (last.startswith("<STR_LIT:#>") and not last.endswith('<STR_LIT>') and not last.endswith("<STR_LIT>") and<EOL>'<STR_LIT>' not in last):<EOL><INDENT>self.comments['<STR_LIT>']['<STR_LIT>'].setdefault(module, []).insert(<NUM_LIT:0>,<EOL>self.out_lines.pop(-<NUM_LIT:1>))<EOL>if len(self.out_lines) > <NUM_LIT:0> and len(self.out_lines) != self._first_comment_index_end:<EOL><INDENT>last = self.out_lines[-<NUM_LIT:1>].rstrip()<EOL><DEDENT>else:<EOL><INDENT>last = "<STR_LIT>"<EOL><DEDENT><DEDENT>if self.index - <NUM_LIT:1> == self.import_index:<EOL><INDENT>self.import_index -= len(self.comments['<STR_LIT>']['<STR_LIT>'].get(module, []))<EOL><DEDENT><DEDENT>placed_module = self.place_module(module)<EOL>if self.config['<STR_LIT>']:<EOL><INDENT>print("<STR_LIT>" % (module, placed_module))<EOL><DEDENT>if placed_module == '<STR_LIT>':<EOL><INDENT>print(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(import_from, line)<EOL>)<EOL><DEDENT>self.imports[placed_module][import_type][module] = None<EOL><DEDENT><DEDENT><DEDENT><DEDENT> | Parses a python file taking out and categorizing imports. | f13225:c0:m29 |
def iter_source_code(paths: Iterable[str], config: MutableMapping[str, Any], skipped: List[str]) -> Iterator[str]: | if '<STR_LIT>' in config:<EOL><INDENT>config['<STR_LIT>'] = list(set(config['<STR_LIT>']).difference(config['<STR_LIT>']))<EOL><DEDENT>for path in paths:<EOL><INDENT>if os.path.isdir(path):<EOL><INDENT>for dirpath, dirnames, filenames in os.walk(path, topdown=True, followlinks=True):<EOL><INDENT>for dirname in list(dirnames):<EOL><INDENT>if file_should_be_skipped(dirname, config, dirpath):<EOL><INDENT>skipped.append(dirname)<EOL>dirnames.remove(dirname)<EOL><DEDENT><DEDENT>for filename in filenames:<EOL><INDENT>filepath = os.path.join(dirpath, filename)<EOL>if is_python_file(filepath):<EOL><INDENT>relative_file = os.path.relpath(filepath, path)<EOL>if file_should_be_skipped(relative_file, config, path):<EOL><INDENT>skipped.append(filename)<EOL><DEDENT>else:<EOL><INDENT>yield filepath<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>yield path<EOL><DEDENT><DEDENT> | Iterate over all Python source files defined in paths. | f13227:m2 |
def finalize_options(self) -> None: | self.arguments = {} <EOL>computed_settings = from_path(os.getcwd())<EOL>for key, value in computed_settings.items():<EOL><INDENT>self.arguments[key] = value<EOL><DEDENT> | Get options from config files. | f13227:c1:m1 |
def distribution_files(self) -> Iterator[str]: | <EOL>if self.distribution.packages:<EOL><INDENT>package_dirs = self.distribution.package_dir or {}<EOL>for package in self.distribution.packages:<EOL><INDENT>pkg_dir = package<EOL>if package in package_dirs:<EOL><INDENT>pkg_dir = package_dirs[package]<EOL><DEDENT>elif '<STR_LIT>' in package_dirs:<EOL><INDENT>pkg_dir = package_dirs['<STR_LIT>'] + os.path.sep + pkg_dir<EOL><DEDENT>yield pkg_dir.replace('<STR_LIT:.>', os.path.sep)<EOL><DEDENT><DEDENT>if self.distribution.py_modules:<EOL><INDENT>for filename in self.distribution.py_modules:<EOL><INDENT>yield "<STR_LIT>" % filename<EOL><DEDENT><DEDENT>yield "<STR_LIT>"<EOL> | Find distribution packages. | f13227:c1:m2 |
def get_output(command: str) -> bytes: | return subprocess.check_output(command.split())<EOL> | Run a command and return raw output
:param str command: the command to run
:returns: the stdout output of the command | f13228:m0 |
def get_lines(command: str) -> List[str]: | stdout = get_output(command)<EOL>return [line.strip().decode() for line in stdout.splitlines()]<EOL> | Run a command and return lines of output
:param str command: the command to run
:returns: list of whitespace-stripped lines output by command | f13228:m1 |
def git_hook(strict=False, modify=False): | <EOL>diff_cmd = "<STR_LIT>"<EOL>files_modified = get_lines(diff_cmd)<EOL>errors = <NUM_LIT:0><EOL>for filename in files_modified:<EOL><INDENT>if filename.endswith('<STR_LIT>'):<EOL><INDENT>staged_cmd = "<STR_LIT>" % filename<EOL>staged_contents = get_output(staged_cmd)<EOL>sort = SortImports(<EOL>file_path=filename,<EOL>file_contents=staged_contents.decode(),<EOL>check=True<EOL>)<EOL>if sort.incorrectly_sorted:<EOL><INDENT>errors += <NUM_LIT:1><EOL>if modify:<EOL><INDENT>SortImports(<EOL>file_path=filename,<EOL>file_contents=staged_contents.decode(),<EOL>check=False,<EOL>)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return errors if strict else <NUM_LIT:0><EOL> | Git pre-commit hook to check staged files for isort errors
:param bool strict - if True, return number of errors on exit,
causing the hook to fail. If False, return zero so it will
just act as a warning.
:param bool modify - if True, fix the sources if they are not
sorted properly. If False, only report result without
modifying anything.
:return number of errors if in strict mode, 0 otherwise. | f13228:m2 |
def allow(self, path: str) -> bool: | return path.endswith('<STR_LIT>')<EOL> | Determine if this path should be linted. | f13229:c0:m0 |
def run(self, path: str, **meta: Any) -> List[Dict[str, Any]]: | with open(os.devnull, '<STR_LIT:w>') as devnull:<EOL><INDENT>sys.stdout = devnull<EOL>if SortImports(path, check=True).incorrectly_sorted:<EOL><INDENT>return [{<EOL>'<STR_LIT>': <NUM_LIT:0>,<EOL>'<STR_LIT>': <NUM_LIT:0>,<EOL>'<STR_LIT:text>': '<STR_LIT>',<EOL>'<STR_LIT:type>': '<STR_LIT>'<EOL>}]<EOL><DEDENT>else:<EOL><INDENT>return []<EOL><DEDENT><DEDENT> | Lint the file. Return an array of error dicts if appropriate. | f13229:c0:m1 |
def nsorted(<EOL>to_sort: Iterable[str],<EOL>key: Optional[Callable[[str], Any]] = None<EOL>) -> List[str]: | if key is None:<EOL><INDENT>key_callback = _natural_keys<EOL><DEDENT>else:<EOL><INDENT>def key_callback(text: str) -> List[Any]:<EOL><INDENT>return _natural_keys(key(text)) <EOL><DEDENT><DEDENT>return sorted(to_sort, key=key_callback)<EOL> | Returns a naturally sorted list | f13230:m2 |
def _parse_known_pattern(self, pattern: str) -> List[str]: | if pattern.endswith(os.path.sep):<EOL><INDENT>patterns = [<EOL>filename<EOL>for filename in os.listdir(pattern)<EOL>if os.path.isdir(os.path.join(pattern, filename))<EOL>]<EOL><DEDENT>else:<EOL><INDENT>patterns = [pattern]<EOL><DEDENT>return patterns<EOL> | Expand pattern if identified as a directory and return found sub packages | f13233:c3:m1 |
@staticmethod<EOL><INDENT>def _load_mapping() -> Optional[Dict[str, str]]:<DEDENT> | if not pipreqs:<EOL><INDENT>return None<EOL><DEDENT>path = os.path.dirname(inspect.getfile(pipreqs))<EOL>path = os.path.join(path, '<STR_LIT>')<EOL>with open(path) as f:<EOL><INDENT>mappings = {} <EOL>for line in f:<EOL><INDENT>import_name, _, pypi_name = line.strip().partition("<STR_LIT::>")<EOL>mappings[pypi_name] = import_name<EOL><DEDENT>return mappings<EOL><DEDENT> | Return list of mappings `package_name -> module_name`
Example:
django-haystack -> haystack | f13233:c5:m3 |
def _load_names(self) -> List[str]: | names = []<EOL>for path in self._get_files():<EOL><INDENT>for name in self._get_names(path):<EOL><INDENT>names.append(self._normalize_name(name))<EOL><DEDENT><DEDENT>return names<EOL> | Return list of thirdparty modules from requirements | f13233:c5:m4 |
def _get_files(self) -> Iterator[str]: | path = os.path.abspath(self.path)<EOL>if os.path.isfile(path):<EOL><INDENT>path = os.path.dirname(path)<EOL><DEDENT>for path in self._get_parents(path):<EOL><INDENT>for file_path in self._get_files_from_dir(path):<EOL><INDENT>yield file_path<EOL><DEDENT><DEDENT> | Return paths to all requirements files | f13233:c5:m6 |
def _normalize_name(self, name: str) -> str: | if self.mapping:<EOL><INDENT>name = self.mapping.get(name, name)<EOL><DEDENT>return name.lower().replace('<STR_LIT:->', '<STR_LIT:_>')<EOL> | Convert package name to module name
Examples:
Django -> django
django-haystack -> django_haystack
Flask-RESTFul -> flask_restful | f13233:c5:m7 |
def _get_files_from_dir(self, path: str) -> Iterator[str]: | return RequirementsFinder._get_files_from_dir_cached(path)<EOL> | Return paths to requirements files from passed dir. | f13233:c6:m0 |
def _get_names(self, path: str) -> Iterator[str]: | for i in RequirementsFinder._get_names_cached(path):<EOL><INDENT>yield i<EOL><DEDENT> | Load required packages from path to requirements file | f13233:c6:m2 |
def file_should_be_skipped(<EOL>filename: str,<EOL>config: Mapping[str, Any],<EOL>path: str = '<STR_LIT>'<EOL>) -> bool: | os_path = os.path.join(path, filename)<EOL>normalized_path = os_path.replace('<STR_LIT:\\>', '<STR_LIT:/>')<EOL>if normalized_path[<NUM_LIT:1>:<NUM_LIT:2>] == '<STR_LIT::>':<EOL><INDENT>normalized_path = normalized_path[<NUM_LIT:2>:]<EOL><DEDENT>if path and config['<STR_LIT>']:<EOL><INDENT>check_exclude = '<STR_LIT:/>' + filename.replace('<STR_LIT:\\>', '<STR_LIT:/>') + '<STR_LIT:/>'<EOL>if path and os.path.basename(path) in ('<STR_LIT>', ):<EOL><INDENT>check_exclude = '<STR_LIT:/>' + os.path.basename(path) + check_exclude<EOL><DEDENT>if safety_exclude_re.search(check_exclude):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>for skip_path in config['<STR_LIT>']:<EOL><INDENT>if posixpath.abspath(normalized_path) == posixpath.abspath(skip_path.replace('<STR_LIT:\\>', '<STR_LIT:/>')):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>position = os.path.split(filename)<EOL>while position[<NUM_LIT:1>]:<EOL><INDENT>if position[<NUM_LIT:1>] in config['<STR_LIT>']:<EOL><INDENT>return True<EOL><DEDENT>position = os.path.split(position[<NUM_LIT:0>])<EOL><DEDENT>for glob in config['<STR_LIT>']:<EOL><INDENT>if fnmatch.fnmatch(filename, glob) or fnmatch.fnmatch('<STR_LIT:/>' + filename, glob):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>if not (os.path.isfile(os_path) or os.path.isdir(os_path) or os.path.islink(os_path)):<EOL><INDENT>return True<EOL><DEDENT>return False<EOL> | Returns True if the file and/or folder should be skipped based on the passed in settings. | f13234:m8 |
def exists_case_sensitive(path: str) -> bool: | result = os.path.exists(path)<EOL>if (sys.platform.startswith('<STR_LIT>') or sys.platform == '<STR_LIT>') and result:<EOL><INDENT>directory, basename = os.path.split(path)<EOL>result = basename in os.listdir(directory)<EOL><DEDENT>return result<EOL> | Returns if the given path exists and also matches the case on Windows.
When finding files that can be imported, it is important for the cases to match because while
file os.path.exists("module.py") and os.path.exists("MODULE.py") both return True on Windows, Python
can only import using the case of the real file. | f13235:m0 |
@contextmanager<EOL>def chdir(path: str) -> Iterator[None]: | curdir = os.getcwd()<EOL>os.chdir(path)<EOL>try:<EOL><INDENT>yield<EOL><DEDENT>finally:<EOL><INDENT>os.chdir(curdir)<EOL><DEDENT> | Context manager for changing dir and restoring previous workdir after exit. | f13235:m1 |
def union(a: Iterable[Any], b: Iterable[Any]) -> List[Any]: | u = [] <EOL>for item in a:<EOL><INDENT>if item not in u:<EOL><INDENT>u.append(item)<EOL><DEDENT><DEDENT>for item in b:<EOL><INDENT>if item not in u:<EOL><INDENT>u.append(item)<EOL><DEDENT><DEDENT>return u<EOL> | Return a list of items that are in `a` or `b` | f13235:m2 |
def difference(a: Iterable[Any], b: Container[Any]) -> List[Any]: | d = []<EOL>for item in a:<EOL><INDENT>if item not in b:<EOL><INDENT>d.append(item)<EOL><DEDENT><DEDENT>return d<EOL> | Return a list of items from `a` that are not in `b`. | f13235:m3 |
def sort_kate_imports(add_imports=(), remove_imports=()): | document = kate.activeDocument()<EOL>view = document.activeView()<EOL>position = view.cursorPosition()<EOL>selection = view.selectionRange()<EOL>sorter = SortImports(file_contents=document.text(), add_imports=add_imports, remove_imports=remove_imports,<EOL>settings_path=os.path.dirname(os.path.abspath(str(document.url().path()))))<EOL>document.setText(sorter.output)<EOL>position.setLine(position.line() + sorter.length_change)<EOL>if selection:<EOL><INDENT>start = selection.start()<EOL>start.setLine(start.line() + sorter.length_change)<EOL>end = selection.end()<EOL>end.setLine(end.line() + sorter.length_change)<EOL>selection.setRange(start, end)<EOL>view.setSelection(selection)<EOL><DEDENT>view.setCursorPosition(position)<EOL> | Sorts imports within Kate while maintaining cursor position and selection, even if length of file changes. | f13238:m0 |
@kate.action<EOL>def sort_imports(): | sort_kate_imports()<EOL> | Sort Imports | f13238:m1 |
@kate.action<EOL>def add_imports(): | text, ok = QtGui.QInputDialog.getText(None,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>')<EOL>if ok:<EOL><INDENT>sort_kate_imports(add_imports=text.split("<STR_LIT:;>"))<EOL><DEDENT> | Add Imports | f13238:m2 |
@kate.action<EOL>def remove_imports(): | text, ok = QtGui.QInputDialog.getText(None,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>')<EOL>if ok:<EOL><INDENT>sort_kate_imports(remove_imports=text.split("<STR_LIT:;>"))<EOL><DEDENT> | Remove Imports | f13238:m3 |
def sort_kate_imports(add_imports=(), remove_imports=()): | document = kate.activeDocument()<EOL>view = document.activeView()<EOL>position = view.cursorPosition()<EOL>selection = view.selectionRange()<EOL>sorter = SortImports(file_contents=document.text(), add_imports=add_imports, remove_imports=remove_imports,<EOL>settings_path=os.path.dirname(os.path.abspath(str(document.url().path()))))<EOL>document.setText(sorter.output)<EOL>position.setLine(position.line() + sorter.length_change)<EOL>if selection:<EOL><INDENT>start = selection.start()<EOL>start.setLine(start.line() + sorter.length_change)<EOL>end = selection.end()<EOL>end.setLine(end.line() + sorter.length_change)<EOL>selection.setRange(start, end)<EOL>view.setSelection(selection)<EOL><DEDENT>view.setCursorPosition(position)<EOL> | Sorts imports within Kate while maintaining cursor position and selection, even if length of file changes. | f13239:m0 |
def split_task_parameters(line): | if line is None:<EOL><INDENT>result = []<EOL><DEDENT>else:<EOL><INDENT>result = [parameter.strip() for parameter in line.split("<STR_LIT:U+002C>")]<EOL><DEDENT>return result<EOL> | Split a string of comma separated words. | f13241:m0 |
def find_tasks(lines): | tasks = []<EOL>linenumbers = []<EOL>pattern = re.compile(TASK_PATTERN)<EOL>for n, line in enumerate(lines):<EOL><INDENT>if "<STR_LIT:#>" in line and "<STR_LIT>" in line:<EOL><INDENT>m = pattern.match(line)<EOL>if m is not None:<EOL><INDENT>groupdict = m.groupdict()<EOL>linenumbers.append(n)<EOL>for key in groupdict:<EOL><INDENT>groupdict[key] = split_task_parameters(groupdict[key])<EOL>logging.debug(<EOL>"<STR_LIT>".format(key, "<STR_LIT:U+002CU+0020>".join(groupdict[key])))<EOL><DEDENT>tasks.append(groupdict)<EOL><DEDENT><DEDENT><DEDENT>linenumbers.append(len(lines))<EOL>return tasks, linenumbers<EOL> | Find task lines and corresponding line numbers in a list of lines. | f13241:m2 |
def create_environment(preamble): | environment = copy.deepcopy(os.environ)<EOL>for line in preamble:<EOL><INDENT>logging.debug(line)<EOL>if "<STR_LIT:=>" in line and not line.startswith("<STR_LIT:#>"):<EOL><INDENT>tmp = line.split("<STR_LIT:=>")<EOL>key = tmp[<NUM_LIT:0>].strip()<EOL>value = tmp[<NUM_LIT:1>].strip()<EOL>logging.debug(<EOL>"<STR_LIT>".format(key, value))<EOL>environment.update({key: value})<EOL><DEDENT><DEDENT>logging.debug("<STR_LIT>".format(environment))<EOL>return environment<EOL> | Create a dictionary of variables obtained from the preamble of
the task file and the environment the program is running on. | f13241:m3 |
def parse_input_file(text, variables=None): | text = find_includes(text)<EOL>lines = text.splitlines()<EOL>tasks, linenumbers = find_tasks(lines)<EOL>preamble = [line for line in lines[:linenumbers[<NUM_LIT:0>]]]<EOL>logging.debug("<STR_LIT>".format("<STR_LIT:\n>".join(preamble)))<EOL>if variables is not None:<EOL><INDENT>preamble += "<STR_LIT:\n>" + "<STR_LIT:\n>".join(variables)<EOL><DEDENT>environment = create_environment(preamble)<EOL>code_sections = []<EOL>for n in range(len(linenumbers) - <NUM_LIT:1>):<EOL><INDENT>code_sections.append((linenumbers[n], linenumbers[n+<NUM_LIT:1>]))<EOL><DEDENT>for n, task in zip(code_sections, tasks):<EOL><INDENT>task["<STR_LIT:code>"] = lines[n[<NUM_LIT:0>]: n[<NUM_LIT:1>]]<EOL>task["<STR_LIT>"] = environment<EOL><DEDENT>clean_tasks = []<EOL>for task in tasks:<EOL><INDENT>clean_tasks.append(Task(**task))<EOL><DEDENT>return clean_tasks<EOL> | Parser for a file with syntax somewhat similar to Drake. | f13241:m4 |
def check_inputs(self): | self.inputs = self.expand_filenames(self.inputs)<EOL>result = False<EOL>if len(self.inputs) == <NUM_LIT:0> or self.files_exist(self.inputs):<EOL><INDENT>result = True<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>return result<EOL> | Check for the existence of input files | f13242:c2:m2 |
def check_outputs(self): | self.outputs = self.expand_filenames(self.outputs)<EOL>result = False<EOL>if self.files_exist(self.outputs):<EOL><INDENT>if self.dependencies_are_newer(self.outputs, self.inputs):<EOL><INDENT>result = True<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL><DEDENT>elif self.force:<EOL><INDENT>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>result = True<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>result = True<EOL><DEDENT>return result<EOL> | Check for the existence of output files | f13242:c2:m3 |
def expand_variables(self): | self.environment["<STR_LIT>"] = "<STR_LIT:U+0020>".join(self.inputs)<EOL>self.environment["<STR_LIT>"] = "<STR_LIT:U+0020>".join(self.outputs)<EOL>for n, input_file in enumerate(self.inputs):<EOL><INDENT>self.environment["<STR_LIT>".format(n +<NUM_LIT:1>)] = input_file<EOL><DEDENT>for n, output_file in enumerate(self.outputs):<EOL><INDENT>self.environment["<STR_LIT>".format(n +<NUM_LIT:1>)] = output_file<EOL><DEDENT>for n, line in enumerate(self.code):<EOL><INDENT>match = self.__variable_pattern.findall(line)<EOL>if len(match) > <NUM_LIT:0>:<EOL><INDENT>for item in match:<EOL><INDENT>value = self.environment.get(item)<EOL>if value is not None:<EOL><INDENT>self.code[n] = self.code[n].replace("<STR_LIT>" + item + "<STR_LIT:]>", value)<EOL><DEDENT><DEDENT><DEDENT><DEDENT> | Expand variables in the task code.
Only variables who use the $[<variable name>] format are expanded.
Variables using the $<variable name> and ${<variable name>} formats
are expanded by the shell (in the cases where bash is the interpreter. | f13242:c2:m4 |
def expand_filenames(self, filenames): | results = []<EOL>for filename in filenames:<EOL><INDENT>result = filename<EOL>if "<STR_LIT:$>" in filename:<EOL><INDENT>template = Template(filename)<EOL>result = template.substitute(**self.environment)<EOL>logging.debug(<EOL>"<STR_LIT>".format(filename, result))<EOL><DEDENT>if any([pattern in result for pattern in "<STR_LIT>"]):<EOL><INDENT>expanded = glob.glob(result)<EOL>if len(expanded) > <NUM_LIT:0>:<EOL><INDENT>result = expanded<EOL><DEDENT>else:<EOL><INDENT>result = "<STR_LIT>"<EOL><DEDENT><DEDENT>if isinstance(result, list):<EOL><INDENT>results.extend(result)<EOL><DEDENT>else:<EOL><INDENT>results.append(result)<EOL><DEDENT><DEDENT>return sorted(list(set(results)))<EOL> | Expand a list of filenames using environment variables,
followed by expansion of shell-style wildcards. | f13242:c2:m5 |
def files_exist(self, filenames): | return all([os.path.exists(os.path.abspath(filename)) and os.path.isfile(os.path.abspath(filename))<EOL>for filename in filenames])<EOL> | Check if all files in a given list exist. | f13242:c2:m6 |
def dependencies_are_newer(self, files, dependencies): | dependency_mtimes = [<EOL>os.path.getmtime(filename) for filename in dependencies]<EOL>file_mtimes = [os.path.getmtime(filename) for filename in files]<EOL>result = False<EOL>for file_mtime in file_mtimes:<EOL><INDENT>for dependency_mtime in dependency_mtimes:<EOL><INDENT>if dependency_mtime > file_mtime:<EOL><INDENT>result = True<EOL><DEDENT><DEDENT><DEDENT>return result<EOL> | For two lists of files, check if any file in the
second list is newer than any file of the first. | f13242:c2:m7 |
def __call__(self): | print("<STR_LIT>".format(self.order, self))<EOL>if self.check_inputs() and self.check_outputs():<EOL><INDENT>self.expand_variables()<EOL>self.mktemp_file()<EOL>self.f.write("<STR_LIT:\n>".join(self.code) + "<STR_LIT:\n>")<EOL>self.f.close()<EOL>logging.debug("<STR_LIT>".format(self.environment))<EOL>print("<STR_LIT>".format(self.inputs))<EOL>print("<STR_LIT>".format(self.outputs))<EOL>start = dt.now()<EOL>try:<EOL><INDENT>out = subprocess.check_output([self.interpreter, self.f.name],<EOL>stderr=subprocess.STDOUT,<EOL>env=self.environment)<EOL><DEDENT>except subprocess.CalledProcessError as e:<EOL><INDENT>print("<STR_LIT>".format(self, e.returncode))<EOL>print("<STR_LIT>")<EOL>print(e.output)<EOL>raise TaskFailedException("<STR_LIT>".format(self))<EOL><DEDENT>end = dt.now()<EOL>logging.debug("<STR_LIT>".format(self.environment))<EOL>print("<STR_LIT>".format(str(end - start)))<EOL>print("<STR_LIT>".format(out))<EOL>self.outputs = self.expand_filenames(self.original_outputs)<EOL>if not(self.files_exist(self.outputs)):<EOL><INDENT>print("<STR_LIT>")<EOL>for filename in self.outputs:<EOL><INDENT>print("<STR_LIT>".format(filename, os.path.exists(filename)))<EOL><DEDENT>raise TaskFailedException("<STR_LIT>".format(self))<EOL><DEDENT><DEDENT> | Invoque an interpreter to execute the task's code. | f13242:c2:m8 |
def mktemp_file(self): | if not(os.path.exists(self.__dirname)):<EOL><INDENT>logging.debug("<STR_LIT>".format(self.__dirname))<EOL>os.mkdir(self.__dirname)<EOL><DEDENT>elif not(os.path.isdir(self.__dirname)):<EOL><INDENT>raise TempDirIsFileException(<EOL>"<STR_LIT>" %<EOL>self.__dirname)<EOL><DEDENT>self.f = tempfile.NamedTemporaryFile(dir=self.__dirname, delete=False, mode="<STR_LIT>")<EOL>logging.debug("<STR_LIT>".format(self.f.name))<EOL> | Create a temporary file in the '.faz' directory for
the code to feed to the interpreter. | f13242:c2:m9 |
def faz(input_file, variables=None): | logging.debug("<STR_LIT>".format(input_file))<EOL>tasks = parse_input_file(input_file, variables=variables)<EOL>print("<STR_LIT>".format(len(tasks)))<EOL>graph = DependencyGraph(tasks)<EOL>graph.show_tasks()<EOL>graph.execute()<EOL> | FAZ entry point. | f13243:m0 |
def _build_graph(self): | self._graph.add_nodes_from(self.tasks)<EOL>for node1 in self._graph.nodes:<EOL><INDENT>for node2 in self._graph.nodes:<EOL><INDENT>for input_file in node1.inputs:<EOL><INDENT>for output_file in node2.outputs:<EOL><INDENT>if output_file == input_file:<EOL><INDENT>self._graph.add_edge(node2, node1)<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>for order, task in enumerate(topological_sort(self._graph)):<EOL><INDENT>task.predecessors = self._graph.predecessors(task)<EOL>task.order = order<EOL><DEDENT> | Produce a dependency graph based on a list
of tasks produced by the parser. | f13245:c2:m1 |
def execute(self): | for task in self.tasks:<EOL><INDENT>print(<NUM_LIT> * "<STR_LIT:*>")<EOL>task()<EOL>print(<NUM_LIT> * "<STR_LIT:*>")<EOL><DEDENT> | Execute tasks in the graph (already in order). | f13245:c2:m3 |
def parse_error(self, response): | error_code = response.split('<STR_LIT:U+0020>')[<NUM_LIT:0>]<EOL>if error_code in self.EXCEPTION_CLASSES:<EOL><INDENT>response = response[len(error_code) + <NUM_LIT:1>:]<EOL>return self.EXCEPTION_CLASSES[error_code](response)<EOL><DEDENT>return ResponseError(response)<EOL> | Parse an error response | f13248:c1:m0 |
def on_connect(self, connection): | self._sock = connection._sock<EOL>self._buffer = SocketBuffer(self._sock, self.socket_read_size) <EOL>if connection.decode_responses:<EOL><INDENT>self.encoding = connection.encoding<EOL><DEDENT> | Called when the socket connects | f13248:c3:m2 |
def on_disconnect(self): | if self._sock is not None:<EOL><INDENT>self._sock.close()<EOL>self._sock = None<EOL><DEDENT>if self._buffer is not None:<EOL><INDENT>self._buffer.close()<EOL>self._buffer = None<EOL><DEDENT>self.encoding = None<EOL> | Called when the socket disconnects | f13248:c3:m3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.