def print_attrs(data_file, node_name='<STR_LIT:/>', which='<STR_LIT:user>', compress=False):

node = data_file.get_node(node_name)<EOL>print ('<STR_LIT>' % node)<EOL>for attr in node._v_attrs._f_list():<EOL><INDENT>print ('<STR_LIT>' % attr)<EOL>attr_content = repr(node._v_attrs[attr])<EOL>if compress:<EOL><INDENT>attr_content = attr_content.split('<STR_LIT:\n>')[<NUM_LIT:0>]<EOL><DEDENT>print ("<STR_LIT>" % attr_content)<EOL><DEDENT>

Print the HDF5 attributes for `node_name`.

    Parameters:
        data_file (pytables HDF5 file object): the data file to print
        node_name (string): name of the path inside the file to be printed.
            Can be either a group or a leaf-node. Default: '/', the root node.
        which (string): Valid values are 'user' for user-defined attributes,
            'sys' for pytables-specific attributes and 'all' to print both
            groups of attributes. Default 'user'.
        compress (bool): if True displays at most a line for each attribute.
            Default False.


base = data_file.get_node(group)<EOL>print ('<STR_LIT>' % base)<EOL>for node in base._f_walk_groups():<EOL><INDENT>if node is not base:<EOL><INDENT>print ('<STR_LIT>' % node)<EOL><DEDENT><DEDENT>print ('<STR_LIT>' % group)<EOL>for node in base._v_leaves.itervalues():<EOL><INDENT>info = node.shape<EOL>if len(info) == <NUM_LIT:0>:<EOL><INDENT>info = node.read()<EOL><DEDENT>print ('<STR_LIT>' % (node.name, info))<EOL>if len(node.title) > <NUM_LIT:0>:<EOL><INDENT>print ('<STR_LIT>' % node.title)<EOL><DEDENT><DEDENT>

Print all the sub-groups in `group` and leaf-nodes children of `group`.

    Parameters:
        data_file (pytables HDF5 file object): the data file to print
        group (string): path name of the group to be printed.
            Default: '/', the root node.


last_chunksize = int(np.mod(num_samples, chunksize))<EOL>chunksize = int(chunksize)<EOL>for _ in range(int(num_samples) // chunksize):<EOL><INDENT>yield chunksize<EOL><DEDENT>if last_chunksize > <NUM_LIT:0>:<EOL><INDENT>yield last_chunksize<EOL><DEDENT>

Iterator used to iterate in chunks over an array of size `num_samples`.
    At each iteration returns `chunksize` except for the last iteration.


i = <NUM_LIT:0><EOL>for c_size in iter_chunksize(num_samples, chunksize):<EOL><INDENT>yield slice(i, i + c_size)<EOL>i += c_size<EOL><DEDENT>

Iterator used to iterate in chunks over an array of size `num_samples`.

    At each iteration returns a slice of size `chunksize`. In the last
    iteration the slice may be smaller.


i = <NUM_LIT:0><EOL>for c_size in iter_chunksize(num_samples, chunksize):<EOL><INDENT>yield i, i + c_size<EOL>i += c_size<EOL><DEDENT>

Iterator used to iterate in chunks over an array of size `num_samples`.

    At each iteration returns a start and stop index for a slice of size
    `chunksize`. In the last iteration the slice may be smaller.


res = []<EOL>for slice in iter_chunk_slice(array.shape[-<NUM_LIT:1>], array.chunkshape[-<NUM_LIT:1>]):<EOL><INDENT>res.append(func(array[..., slice]))<EOL><DEDENT>return func(res)<EOL>

Reduce with `func`, chunk by chunk, the passed pytable `array`.


for slice in iter_chunk_slice(array.shape[-<NUM_LIT:1>], array.chunkshape[-<NUM_LIT:1>]):<EOL><INDENT>out_array.append(func(array[..., slice]))<EOL><DEDENT>return out_array<EOL>

Map with `func`, chunk by chunk, the input pytable `array`.
    The result is stored in the output pytable array `out_array`.


if os.path.exists(fname) or os.path.exists(fname + '<STR_LIT>'):<EOL><INDENT>return loadmat(fname)['<STR_LIT:data>']<EOL><DEDENT>else:<EOL><INDENT>raise IOError("<STR_LIT>" % fname)<EOL><DEDENT>

Load the array `data` in the .mat file `fname`.


def convert_PSFLab_xz(data, x_step=<NUM_LIT:0.5>, z_step=<NUM_LIT:0.5>, normalize=False):

z_len, x_len = data.shape<EOL>hdata = data[:, (x_len - <NUM_LIT:1>) // <NUM_LIT:2>:]<EOL>x = np.arange(hdata.shape[<NUM_LIT:1>]) * x_step<EOL>z = np.arange(-(z_len - <NUM_LIT:1>) / <NUM_LIT:2>, (z_len - <NUM_LIT:1>) / <NUM_LIT:2> + <NUM_LIT:1>) * z_step<EOL>if normalize:<EOL><INDENT>hdata /= hdata.max()  <EOL><DEDENT>return x, z, hdata, hdata[:, <NUM_LIT:0>].argmax()<EOL>

Process a 2D array (from PSFLab .mat file) containing a x-z PSF slice.

    The input data is the raw array saved by PSFLab. The returned array has
    the x axis cut in half (only positive x) to take advantage of the
    rotational symmetry around z. Pysical dimensions (`x_step` and `z_step)
    are also assigned.

    If `nomalize` is True the peak is normalized to 1.

    Returns:
    x, z: (1D array) the X and Z axis in pysical units
    hdata: (2D array) the PSF intesity
    izm: (float) the index of PSF max along z (axis 0) for x=0 (axis 1)


def __init__(self, xc=<NUM_LIT:0>, yc=<NUM_LIT:0>, zc=<NUM_LIT:0>, sx=<NUM_LIT:1>, sy=<NUM_LIT:1>, sz=<NUM_LIT:1>):

self.xc, self.yc, self.zc = xc, yc, zc<EOL>self.rc = np.array([xc, yc, zc])<EOL>self.sx, self.sy, self.sz = sx, sy, sz<EOL>self.s = np.array([sx, sy, sz])<EOL>self.kind = "<STR_LIT>"<EOL>

Create a Gaussian PSF object with given center and sigmas.
        `xc`, `yc`, `zc`: position of hte center of the gaussian
        `sx`, `sy`, `sz`: sigmas of the gaussian function.


xc, yc, zc = self.rc<EOL>sx, sy, sz = self.s<EOL>def arg(s):<EOL><INDENT>return "<STR_LIT>" % (s, s, s)<EOL><DEDENT>return NE.evaluate("<STR_LIT>" %<EOL>(arg("<STR_LIT:x>"), arg("<STR_LIT:y>"), arg("<STR_LIT:z>")))<EOL>


def __init__(self, fname='<STR_LIT>',<EOL>dir_=None, x_step=<NUM_LIT:0.5> / <NUM_LIT:8>, z_step=<NUM_LIT:0.5> / <NUM_LIT:8>,<EOL>psf_pytables=None):

if psf_pytables is not None:<EOL><INDENT>self.psflab_psf_raw = psf_pytables[:]<EOL>for name in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>setattr(self, name, psf_pytables.get_attr(name))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.fname = fname<EOL>if dir_ is None:<EOL><INDENT>dir_ = pkg_resources.resource_filename('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>self.dir_ = dir_<EOL>self.x_step, self.z_step = x_step, z_step<EOL>self.psflab_psf_raw = load_PSFLab_file('<STR_LIT:/>'.join([dir_, fname]))<EOL><DEDENT>xi, zi, hdata, zm = convert_PSFLab_xz(self.psflab_psf_raw,<EOL>x_step=x_step, z_step=z_step,<EOL>normalize=True)<EOL>self._fun_um = SI.RectBivariateSpline(xi, zi, hdata.T, kx=<NUM_LIT:1>, ky=<NUM_LIT:1>)<EOL>self.xi, self.zi, self.hdata, self.zm = xi, zi, hdata, zm<EOL>self.x_step, self.z_step = xi[<NUM_LIT:1>] - xi[<NUM_LIT:0>], zi[<NUM_LIT:1>] - zi[<NUM_LIT:0>]<EOL>self.kind = '<STR_LIT>'<EOL>

Create a PSF object for interpolation from numeric data.

        `dir_+fname`: should be a valid path

        If `dir_` is None use the "system" folder where the PSF shipped with
        pybromo are placed.


return self._fun_um.ev(x * <NUM_LIT>, z * <NUM_LIT>)<EOL>

Evaluate the function in (x, z) (micro-meters).
        The function is rotationally symmetric around z.


ro = np.sqrt(x**<NUM_LIT:2> + y**<NUM_LIT:2>)<EOL>zs, xs = ro.shape<EOL>v = self.eval_xz(ro.ravel(), z.ravel())<EOL>return v.reshape(zs, xs)<EOL>

Evaluate the function in (x, y, z).
        The function is rotationally symmetric around z.


def to_hdf5(self, file_handle, parent_node='<STR_LIT:/>'):

tarray = file_handle.create_array(parent_node, name=self.fname,<EOL>obj=self.psflab_psf_raw,<EOL>title='<STR_LIT>')<EOL>for name in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>file_handle.set_node_attr(tarray, name, getattr(self, name))<EOL><DEDENT>return tarray<EOL>

Store the PSF data in `file_handle` (pytables) in `parent_node`.

        The raw PSF array name is stored with same name as the original fname.
        Also, the following attribues are set: fname, dir_, x_step, z_step.


hash_list = []<EOL>for key, value in sorted(self.__dict__.items()):<EOL><INDENT>if not callable(value):<EOL><INDENT>if isinstance(value, np.ndarray):<EOL><INDENT>hash_list.append(value.tostring())<EOL><DEDENT>else:<EOL><INDENT>hash_list.append(str(value))<EOL><DEDENT><DEDENT><DEDENT>return hashlib.md5(repr(hash_list).encode()).hexdigest()<EOL>

Return an hash string computed on the PSF data.


def get_bromo_fnames_da(d_em_kHz, d_bg_kHz, a_em_kHz, a_bg_kHz,<EOL>ID='<STR_LIT>', t_tot='<STR_LIT>', num_p='<STR_LIT>', pM='<STR_LIT>',<EOL>t_step=<NUM_LIT>, D=<NUM_LIT>, dir_='<STR_LIT>'):

clk_p = t_step/<NUM_LIT> <EOL>E_sim = <NUM_LIT:1.>*a_em_kHz/(a_em_kHz + d_em_kHz)<EOL>FRET_val = <NUM_LIT>*E_sim<EOL>print("<STR_LIT>" % FRET_val)<EOL>d_em_kHz_str = "<STR_LIT>" % d_em_kHz<EOL>a_em_kHz_str = "<STR_LIT>" % a_em_kHz<EOL>d_bg_kHz_str = "<STR_LIT>" % d_bg_kHz<EOL>a_bg_kHz_str = "<STR_LIT>" % a_bg_kHz<EOL>print("<STR_LIT>" % (d_em_kHz_str, d_bg_kHz_str))<EOL>print("<STR_LIT>" % (a_em_kHz_str, a_bg_kHz_str))<EOL>fname_d = ('<STR_LIT>'<EOL>'<STR_LIT>').format(<EOL>em=d_em_kHz_str, bg=d_bg_kHz_str, t_tot=t_tot, pM=pM,<EOL>np=num_p, ID=ID, ts_us=t_step*<NUM_LIT>, D=D)<EOL>fname_a = ('<STR_LIT>'<EOL>'<STR_LIT>').format(<EOL>em=a_em_kHz_str, bg=a_bg_kHz_str, t_tot=t_tot, pM=pM,<EOL>np=num_p, ID=ID, ts_us=t_step*<NUM_LIT>, D=D)<EOL>print(fname_d)<EOL>print(fname_a)<EOL>name = ('<STR_LIT>'<EOL>'<STR_LIT>').format(FRET_val, d_bg_kHz, a_bg_kHz, d_em_kHz)<EOL>return dir_+fname_d, dir_+fname_a, name, clk_p, E_sim<EOL>

Get filenames for donor and acceptor timestamps for the given parameters


def parallel_gen_timestamps(dview, max_em_rate, bg_rate):

dview.execute('<STR_LIT>'<EOL>'<STR_LIT>' % (max_em_rate, bg_rate))<EOL>dview.execute('<STR_LIT>')<EOL>dview.execute('<STR_LIT>')<EOL>Times = dview['<STR_LIT>']<EOL>Times_par = dview['<STR_LIT>']<EOL>t_max = dview['<STR_LIT>'][<NUM_LIT:0>]<EOL>t_tot = np.sum(dview['<STR_LIT>'])<EOL>dview.execute("<STR_LIT>")<EOL>sim_name = dview['<STR_LIT>'][<NUM_LIT:0>]<EOL>times_all, times_par_all = merge_ph_times(Times, Times_par,<EOL>time_block=t_max)<EOL>return times_all, times_par_all, t_tot, sim_name<EOL>

Generate timestamps from a set of remote simulations in `dview`.
    Assumes that all the engines have an `S` object already containing
    an emission trace (`S.em`). The "photons" timestamps are generated
    from these emission traces and merged into a single array of timestamps.
    `max_em_rate` and `bg_rate` are passed to `S.sim_timetrace()`.


def merge_ph_times(times_list, times_par_list, time_block):

offsets = np.arange(len(times_list)) * time_block<EOL>cum_sizes = np.cumsum([ts.size for ts in times_list])<EOL>times = np.zeros(cum_sizes[-<NUM_LIT:1>])<EOL>times_par = np.zeros(cum_sizes[-<NUM_LIT:1>], dtype='<STR_LIT>')<EOL>i1 = <NUM_LIT:0><EOL>for i2, ts, ts_par, offset in zip(cum_sizes, times_list, times_par_list,<EOL>offsets):<EOL><INDENT>times[i1:i2] = ts + offset<EOL>times_par[i1:i2] = ts_par<EOL>i1 = i2<EOL><DEDENT>return times, times_par<EOL>

Build an array of timestamps joining the arrays in `ph_times_list`.
    `time_block` is the duration of each array of timestamps.


ph_times = np.hstack([ph_times_d, ph_times_a])<EOL>a_em = np.hstack([np.zeros(ph_times_d.size, dtype=np.bool),<EOL>np.ones(ph_times_a.size, dtype=np.bool)])<EOL>index_sort = ph_times.argsort()<EOL>return ph_times[index_sort], a_em[index_sort]<EOL>

Returns a merged timestamp array for Donor+Accept. and bool mask for A.


<EOL>P = reduce(lambda x, y: x + y, [Si.particles for Si in SS])<EOL>s = SS[<NUM_LIT:0>]<EOL>S = ParticlesSimulation(t_step=s.t_step, t_max=s.t_max,<EOL>particles=P, box=s.box, psf=s.psf)<EOL>S.em = np.zeros(s.em.shape, dtype=np.float64)<EOL>for Si in SS:<EOL><INDENT>S.em += Si.em<EOL><DEDENT>return S<EOL>

Returns a sim object summing the emissions and particles in SS (list).


def __init__(self, fig, page_step=<NUM_LIT:1>):

<EOL>self.fig = fig<EOL>self.page_step = page_step <EOL>self.xmin, self.xmax = fig.axes[<NUM_LIT:0>].get_xlim()<EOL>self.width = min(<NUM_LIT:1>, self.xmax-self.xmin) <EOL>self.pos = <NUM_LIT:0>   <EOL>self.scale = <NUM_LIT> <EOL>self.ax = self.fig.axes[<NUM_LIT:0>]<EOL>self.draw = self.fig.canvas.draw<EOL>QMainWin = fig.canvas.parent()<EOL>toolbar = QtGui.QToolBar(QMainWin)<EOL>QMainWin.addToolBar(QtCore.Qt.BottomToolBarArea, toolbar)<EOL>self.set_slider(toolbar)<EOL>self.set_spinbox(toolbar)<EOL>self.ax.set_xlim(self.pos,self.pos+self.width)<EOL>self.draw()<EOL>

Make a scrolling x axis on figure `fig`.
        `page_step` is the multiplier for page-step scrolling.


return (year % <NUM_LIT:4> == <NUM_LIT:0> and year % <NUM_LIT:100> != <NUM_LIT:0>) or (year % <NUM_LIT> == <NUM_LIT:0>)<EOL>

returns True for leap year and False otherwise

:param int year: calendar year
:return bool:


return <NUM_LIT> if is_leap_year(year) else <NUM_LIT><EOL>

returns number of days in the given calendar year

:param int year: calendar year
:return int:


eom = _days_per_month[month - <NUM_LIT:1>]<EOL>if is_leap_year(year) and month == <NUM_LIT:2>:<EOL><INDENT>eom += <NUM_LIT:1><EOL><DEDENT>return eom<EOL>

returns number of days for the given year and month

:param int year: calendar year
:param int month: calendar month
:return int:


return <NUM_LIT:1> <= month <= <NUM_LIT:12> and <NUM_LIT:1> <= day <= days_in_month(year, month) and year >= <NUM_LIT><EOL>

return True if (year,month, day) can be represented in Excel-notation
(number of days since 30.12.1899) for calendar days, otherwise False

:param int year: calendar year
:param int month: calendar month
:param int day: calendar day
:return bool:


int_date = int(floor(excel_int))<EOL>int_date -= <NUM_LIT:1>  if excel_int > <NUM_LIT> else <NUM_LIT:0><EOL>year = (int_date - <NUM_LIT:1>) // <NUM_LIT><EOL>rest_days = int_date - <NUM_LIT> * year - (year + <NUM_LIT:3>) // <NUM_LIT:4> + (year + <NUM_LIT>) // <NUM_LIT:100> - (year + <NUM_LIT>) // <NUM_LIT><EOL>year += <NUM_LIT><EOL>while rest_days <= <NUM_LIT:0>:<EOL><INDENT>year -= <NUM_LIT:1><EOL>rest_days += days_in_year(year)<EOL><DEDENT>month = <NUM_LIT:1><EOL>if is_leap_year(year) and rest_days == <NUM_LIT>:<EOL><INDENT>month = <NUM_LIT:2><EOL>day = <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>if is_leap_year(year) and rest_days > <NUM_LIT>:<EOL><INDENT>rest_days -= <NUM_LIT:1><EOL><DEDENT>while rest_days > _cum_month_days[month]:<EOL><INDENT>month += <NUM_LIT:1><EOL><DEDENT>day = rest_days - _cum_month_days[month - <NUM_LIT:1>]<EOL><DEDENT>return year, month, day<EOL>

converts date in Microsoft Excel representation style and returns `(year, month, day)` tuple

:param int excel_int: date as int (days since 1899-12-31)
:return tuple(int, int, int):


def from_ymd_to_excel(year, month, day):

if not is_valid_ymd(year, month, day):<EOL><INDENT>raise ValueError("<STR_LIT>".format(year, month, day))<EOL><DEDENT>days = _cum_month_days[month - <NUM_LIT:1>] + day<EOL>days += <NUM_LIT:1> if (is_leap_year(year) and month > <NUM_LIT:2>) else <NUM_LIT:0><EOL>years_distance = year - <NUM_LIT><EOL>days += years_distance * <NUM_LIT> +(years_distance + <NUM_LIT:3>) // <NUM_LIT:4> - (years_distance + <NUM_LIT>) // <NUM_LIT:100> + (years_distance + <NUM_LIT>) // <NUM_LIT><EOL>days += <NUM_LIT:1> if (year, month, day) > (<NUM_LIT>, <NUM_LIT:2>, <NUM_LIT>) else <NUM_LIT:0><EOL>return days<EOL>

converts date as `(year, month, day)` tuple into Microsoft Excel representation style

:param tuple(int, int, int): int tuple `year, month, day`
:return int:


return BaseDateFloat.to_ymd(self)[<NUM_LIT:2>]<EOL>


return BaseDateFloat.to_ymd(self)[<NUM_LIT:1>]<EOL>


return BaseDateFloat.to_ymd(self)[<NUM_LIT:0>]<EOL>


@staticmethod<EOL><INDENT>def from_ymd(year, month, day):<DEDENT>

return BaseDate(from_ymd_to_excel(year, month, day))<EOL>

creates date for year, month and day
:param int year:
:param int month:
:param int day:
:return BaseDate:


return from_excel_to_ymd(d)<EOL>

returns date represented as tuple `year, month, day`
:param BaseDateFloat d:
:return tuple(int, int, int):


return BaseDateFloat(super(BaseDate, d).__add__(days_int))<EOL>

adds number of days to a date
:param BaseDateFloat d: date to add days to
:param int days_int: number of days to add
:return BaseDate: resulting date


y, m, d = BaseDate.to_ymd(d)<EOL>if not is_leap_year(years_int) and m == <NUM_LIT:2>:<EOL><INDENT>d = min(<NUM_LIT>, d)<EOL><DEDENT>return BaseDateFloat.from_ymd(y + years_int, m, d)<EOL>

adds number of years to a date
:param BaseDateFloat d: date to add years to
:param int years_int: number of years to add
:return BaseDate: resulting date


return super(BaseDateFloat, end).__sub__(start)<EOL>

returns distance of two dates as number of days
:param BaseDateFloat start: start date
:param BaseDateFloat end: end date
:return float: difference between end date and start date in days


return BaseDateFloat.diff_in_days(start, end) / DAYS_IN_YEAR<EOL>

calculate difference between given dates in years. The difference corresponds to Act/365.25 year fraction

:param BaseDateFloat start: state date
:param BaseDateFloat end: end date
:return float: difference between end date and start date in years


return BaseDateDatetimeDate(year, month, day)<EOL>

converts date as `(year, month, day)` tuple into Microsoft Excel representation style

:param tuple(int, int, int): int tuple `year, month, day`
:return BaseDatetimeDate:


return d.year, d.month, d.day<EOL>

returns date represented as tuple `year, month, day`
:param BaseDateDatetimeDate d:
:return tuple(int, int, int):


n = date(d.year, d.month, d.day) + timedelta(days_int)<EOL>return BaseDateDatetimeDate(n.year, n.month, n.day)<EOL>

addition of a number of days

:param BaseDateDatetimeDate d:
:param int days_int:
:return BaseDatetimeDate:


y, m, d = BaseDateDatetimeDate.to_ymd(d)<EOL>y += years_int<EOL>if not is_leap_year(y) and m == <NUM_LIT:2>:<EOL><INDENT>d = min(<NUM_LIT>, d)<EOL><DEDENT>return BaseDateDatetimeDate.from_ymd(y, m, d)<EOL>

addition of a number of years

:param BaseDateDatetimeDate d:
:param int years_int:
:return BaseDatetimeDate:


diff = date(end.year, end.month, end.day) - date(start.year, start.month, start.day)<EOL>return float(diff.days)<EOL>

calculate difference between given dates in days

:param BaseDateDatetimeDate start: state date
:param BaseDateDatetimeDate end: end date
:return float: difference between end date and start date in days


return BaseDateDatetimeDate.diff_in_days(start, end) / DAYS_IN_YEAR<EOL>

calculate difference between given dates in years. The difference corresponds to Act/365.25 year fraction

:param BaseDateDatetimeDate start: state date
:param BaseDateDatetimeDate end: end date
:return float: difference between end date and start date in years


new = super(BaseDateTuple, cls).__new__(cls)<EOL>if BaseDateTuple._is_valid_args(args):<EOL><INDENT>if isinstance(args[<NUM_LIT:0>], BaseDateTuple):<EOL><INDENT>new.date = args[<NUM_LIT:0>].date<EOL><DEDENT>else:<EOL><INDENT>new.date = (args[<NUM_LIT:0>], args[<NUM_LIT:1>], args[<NUM_LIT:2>])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>msg = str(args) + "<STR_LIT>"<EOL>raise ValueError(msg)<EOL><DEDENT>return new<EOL>

:param args: should be three ints (year, month, day)


n = from_ymd_to_excel(*date_obj.date) + days_int<EOL>return BaseDateTuple(*from_excel_to_ymd(n))<EOL>

addition of a number of days

:param BaseDateTuple d:
:param int days_int:
:return BaseDatetimeDate:


y, m, d = BaseDateTuple.to_ymd(date_obj)<EOL>y += years_int<EOL>if not is_leap_year(y) and m == <NUM_LIT:2>:<EOL><INDENT>d = min(<NUM_LIT>, d)<EOL><DEDENT>return BaseDateTuple.from_ymd(y, m, d)<EOL>

addition of a number of years

:param BaseDateTuple d:
:param int years_int:
:return BaseDatetimeDate:


diff = from_ymd_to_excel(*end.date)-from_ymd_to_excel(*start.date)<EOL>return float(diff)<EOL>

calculate difference between given dates in days

:param BaseDateTuple start: state date
:param BaseDateTuple end: end date
:return float: difference between end date and start date in days


return BaseDateTuple.diff_in_days(start, end) / DAYS_IN_YEAR<EOL>


<EOL>y = year<EOL>g = y % <NUM_LIT><EOL>e = <NUM_LIT:0><EOL>c = y // <NUM_LIT:100><EOL>h = (c - c // <NUM_LIT:4> - (<NUM_LIT:8> * c + <NUM_LIT>) // <NUM_LIT> + <NUM_LIT> * g + <NUM_LIT:15>) % <NUM_LIT:30><EOL>i = h - (h // <NUM_LIT>) * (<NUM_LIT:1> - (h // <NUM_LIT>) * (<NUM_LIT> // (h + <NUM_LIT:1>)) * ((<NUM_LIT> - g) // <NUM_LIT:11>))<EOL>j = (y + y // <NUM_LIT:4> + i + <NUM_LIT:2> - c + c // <NUM_LIT:4>) % <NUM_LIT:7><EOL>p = i - j + e<EOL>d = <NUM_LIT:1> + (p + <NUM_LIT> + (p + <NUM_LIT:6>) // <NUM_LIT>) % <NUM_LIT><EOL>m = <NUM_LIT:3> + (p + <NUM_LIT>) // <NUM_LIT:30><EOL>return BusinessDate.from_ymd(int(y), int(m), int(d))<EOL>

This method was ported from the work done by GM Arts,
on top of the algorithm by Claus Tondering, which was
based in part on the algorithm of Ouding (1940), as
quoted in "Explanatory Supplement to the Astronomical
Almanac", P.  Kenneth Seidelmann, editor.

More about the algorithm may be found at:

http://users.chariot.net.au/~gmarts/eastalg.htm

and

http://www.tondering.dk/claus/calendar.html


if iterable:<EOL><INDENT>super(BusinessHolidays, self).__init__(BusinessDate(iterable))<EOL><DEDENT>else:<EOL><INDENT>super(BusinessHolidays, self).__init__()<EOL><DEDENT>

:param iterable iterable: sequence of holiday dates


if date_value is None:<EOL><INDENT>new_date = BusinessDate(BASE_DATE)<EOL><DEDENT>elif isinstance(date_value, BaseDateFloat):<EOL><INDENT>return super(BusinessDate, cls).__new__(cls, float(date_value))<EOL><DEDENT>elif isinstance(date_value, (BaseDateDatetimeDate, BaseDateTuple)):<EOL><INDENT>return super(BusinessDate, cls).__new__(cls, date_value.year, date_value.month, date_value.day)<EOL><DEDENT>elif isinstance(date_value, (int, float)):<EOL><INDENT>if date_value >= <NUM_LIT>:<EOL><INDENT>new_date = BusinessDate.from_string(str(date_value))<EOL><DEDENT>elif <NUM_LIT:1> < date_value < <NUM_LIT:200> * <NUM_LIT>:<EOL><INDENT>new_date = BusinessDate.from_excel(date_value)<EOL><DEDENT>else:<EOL><INDENT>new_date = BusinessDate.from_ordinal(date_value)<EOL><DEDENT><DEDENT>elif isinstance(date_value, (str, unicode)):<EOL><INDENT>new_date = BusinessDate.from_string(str(date_value))<EOL><DEDENT>elif isinstance(date_value, (date, datetime)):<EOL><INDENT>new_date = BusinessDate.from_date(date_value)<EOL><DEDENT>elif isinstance(date_value, list):<EOL><INDENT>new_date = [BusinessDate(d) for d in date_value]<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % str(type(date_value)))<EOL><DEDENT>return new_date<EOL>

r"""
        fundamental date class

        :param date_value: input value to create BusinessDate instance
        :type date_value: int, float, string or datetime.date
        :return: BusinessDate

        creates new BusinessDate either from `int`, `float`, `string`, `datetime.date`
        therefore the following will create the same

        .. code-block:: python

            BusinessDate(datetime.date(2015, 12, 31))
            BusinessDate(20151231)
            BusinessDate(2015-12-31)
            BusinessDate(31.12.2015)
            BusinessDate(12/31/2015)
            BusinessDate(42369)
            BusinessDate(42369.0)
            BusinessDate(735963)
            BusinessDate(735963.0)
            BusinessDate()

        **caution:** recommended is the use of class methods BusinessDate.from_string, from_date etc.


if isinstance(other, BusinessPeriod):<EOL><INDENT>return self.add_period(other)<EOL><DEDENT>elif BusinessPeriod.is_businessperiod(other):<EOL><INDENT>return self + BusinessPeriod(other)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>' % type(other))<EOL><DEDENT>

addition of BusinessDate.

:param BusinessDate or BusinessPeriod or str other: can be BusinessPeriod or
any thing that might be casted to it.


if isinstance(other, BusinessDate):<EOL><INDENT>y, m, d = self.diff(other)<EOL>return BusinessPeriod(years=y, months=m, days=d)<EOL><DEDENT>elif isinstance(other, BusinessPeriod):<EOL><INDENT>return self.add_period(-<NUM_LIT:1> * other)<EOL><DEDENT>elif BusinessDate.is_businessdate(other):<EOL><INDENT>return self - BusinessDate(other)<EOL><DEDENT>elif BusinessPeriod.is_businessperiod(other):<EOL><INDENT>return self - BusinessPeriod(other)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>' % type(other))<EOL><DEDENT>

subtraction of BusinessDate.

:param object other: can be other BusinessDate, BusinessPeriod or any thing that might be casted to those.


return copy(d)<EOL>

copy constructor

:param BusinessDate d:
:return bankdate:


return BusinessDate.from_ymd(datetime_date.year, datetime_date.month, datetime_date.day)<EOL>

construct BusinessDate instance from datetime.date instance,
raise ValueError exception if not possible

:param datetime.date datetime_date: calendar day
:return bool:


if date_str.count('<STR_LIT:->'):<EOL><INDENT>str_format = '<STR_LIT>'<EOL><DEDENT>elif date_str.count('<STR_LIT:.>'):<EOL><INDENT>str_format = '<STR_LIT>'<EOL><DEDENT>elif date_str.count('<STR_LIT:/>'):<EOL><INDENT>str_format = '<STR_LIT>'<EOL><DEDENT>elif len(date_str) == <NUM_LIT:8>:<EOL><INDENT>str_format = '<STR_LIT>'<EOL><DEDENT>elif len(date_str) == <NUM_LIT:4>:<EOL><INDENT>year = ord(date_str[<NUM_LIT:0>]) * <NUM_LIT> + ord(date_str[<NUM_LIT:1>])<EOL>month = ord(date_str[<NUM_LIT:2>])<EOL>day = ord(date_str[<NUM_LIT:3>])<EOL>return BusinessDate.from_ymd(year, month, day)<EOL><DEDENT>else:<EOL><INDENT>msg = "<STR_LIT>" + date_str + "<STR_LIT>"<EOL>raise ValueError(msg)<EOL><DEDENT>d = datetime.strptime(date_str, str_format)<EOL>return BusinessDate.from_ymd(d.year, d.month, d.day)<EOL>

construction from the following string patterns
'%Y-%m-%d'
'%d.%m.%Y'
'%m/%d/%Y'
'%Y%m%d'

:param str date_str:
:return BusinessDate:


y, m, d = self.to_ymd()<EOL>return date(y, m, d)<EOL>

construct datetime.date instance represented calendar date of BusinessDate instance

:return datetime.date:


return self.to_date().strftime(date_format)<EOL>

return BusinessDate as 'date.strftime(DATE_FORMAT)'

:return string:


return is_leap_year(year)<EOL>

returns True for leap year and False otherwise

:param int year: calendar year
:return bool:


return days_in_year(year)<EOL>

returns number of days in the given calendar year

:param int year: calendar year
:return int:


return days_in_month(year, month)<EOL>

returns number of days for the given year and month

:param int year: calendar year
:param int month: calendar month
:return int:


<EOL>if not isinstance(in_date, BaseDate):<EOL><INDENT>try:  <EOL><INDENT>in_date = BusinessDate(in_date)<EOL><DEDENT>except:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>y, m, d, = in_date.to_ymd()<EOL>return is_valid_ymd(y, m, d)<EOL>

checks whether the provided date is a date
:param BusinessDate, int or float in_date:
:return bool:


y, m, d = BusinessDate.to_ymd(self)<EOL>if weekday(y, m, d) > FRIDAY:<EOL><INDENT>return False<EOL><DEDENT>holiday_list = holiday_obj if holiday_obj is not None else DEFAULT_HOLIDAYS<EOL>if self in holiday_list:<EOL><INDENT>return False<EOL><DEDENT>elif date(y, m, d) in holiday_list:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>

:param list holiday_obj : datetime.date list defining business holidays
:return: bool

method to check if a date falls neither on weekend nor is holiday


def add_period(self, p, holiday_obj=None):

if isinstance(p, (list, tuple)):<EOL><INDENT>return [BusinessDate.add_period(self, pd) for pd in p]<EOL><DEDENT>elif isinstance(p, str):<EOL><INDENT>period = BusinessPeriod(p)<EOL><DEDENT>else:<EOL><INDENT>period = p<EOL><DEDENT>res = self<EOL>res = BusinessDate.add_months(res, period.months)<EOL>res = BusinessDate.add_years(res, period.years)<EOL>res = BusinessDate.add_days(res, period.days)<EOL>if period.businessdays:<EOL><INDENT>if holiday_obj:<EOL><INDENT>res = BusinessDate.add_business_days(res, period.businessdays, holiday_obj)<EOL><DEDENT>else:<EOL><INDENT>res = BusinessDate.add_business_days(res, period.businessdays, period.holiday)<EOL><DEDENT><DEDENT>return res<EOL>

addition of a period object

:param BusinessDate d:
:param p:
:type p: BusinessPeriod or str
:param list holiday_obj:
:return bankdate:


month_int += self.month<EOL>while month_int > <NUM_LIT:12>:<EOL><INDENT>self = BusinessDate.add_years(self, <NUM_LIT:1>)<EOL>month_int -= <NUM_LIT:12><EOL><DEDENT>while month_int < <NUM_LIT:1>:<EOL><INDENT>self = BusinessDate.add_years(self, -<NUM_LIT:1>)<EOL>month_int += <NUM_LIT:12><EOL><DEDENT>l = monthrange(self.year, month_int)[<NUM_LIT:1>]<EOL>return BusinessDate.from_ymd(self.year, month_int, min(l, self.day))<EOL>

addition of a number of months

:param BusinessDate d:
:param int month_int:
:return bankdate:


def add_business_days(self, days_int, holiday_obj=None):

res = self<EOL>if days_int >= <NUM_LIT:0>:<EOL><INDENT>count = <NUM_LIT:0><EOL>while count < days_int:<EOL><INDENT>res = BusinessDate.add_days(res, <NUM_LIT:1>)<EOL>if BusinessDate.is_business_day(res, holiday_obj):<EOL><INDENT>count += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>count = <NUM_LIT:0><EOL>while count > days_int:<EOL><INDENT>res = BusinessDate.add_days(res, -<NUM_LIT:1>)<EOL>if BusinessDate.is_business_day(res, holiday_obj):<EOL><INDENT>count -= <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>return res<EOL>

private method for the addition of business days, used in the addition of a BusinessPeriod only

:param BusinessDate d:
:param int days_int:
:param list holiday_obj:
:return: BusinessDate


if end_date < self:<EOL><INDENT>y, m, d = BusinessDate.diff(end_date, self)<EOL>return -y, -m, -d<EOL><DEDENT>y = end_date.year - self.year<EOL>m = end_date.month - self.month<EOL>while m < <NUM_LIT:0>:<EOL><INDENT>y -= <NUM_LIT:1><EOL>m += <NUM_LIT:12><EOL><DEDENT>while m > <NUM_LIT:12>:<EOL><INDENT>y += <NUM_LIT:1><EOL>m -= <NUM_LIT:12><EOL><DEDENT>s = BusinessDate.add_years(BusinessDate.add_months(self, m), y)<EOL>d = BusinessDate.diff_in_days(s, end_date)<EOL>if d < <NUM_LIT:0>:<EOL><INDENT>m -= <NUM_LIT:1><EOL>if m < <NUM_LIT:0>:<EOL><INDENT>y -= <NUM_LIT:1><EOL>m += <NUM_LIT:12><EOL><DEDENT>s = BusinessDate.add_years(BusinessDate.add_months(self, m), y)<EOL><DEDENT>d = BusinessDate.diff_in_days(s, end_date)<EOL>return -int(y), -int(m), -int(d)<EOL>

difference expressed as a tuple of years, months, days
(see also the python lib dateutils.relativedelta)

:param BusinessDate start_date:
:param BusinessDate end_date:
:return (int, int, int):


start_day = min(self.day, <NUM_LIT:30>)<EOL>end_day = <NUM_LIT:30> if (start_day == <NUM_LIT:30> and end.day == <NUM_LIT>) else end.day<EOL>return (<NUM_LIT> * (end.year - self.year) + <NUM_LIT:30> * (end.month - self.month) + (end_day - start_day)) / <NUM_LIT><EOL>

implements 30/360 Day Count Convention (4.16(f) 2006 ISDA Definitions)


return BusinessDate.diff_in_days(self, end) / <NUM_LIT><EOL>

implements Act/365.25 Day Count Convention


implements Act/365 day count convention (4.16(d) 2006 ISDA Definitions)


implements Act/360 day count convention (4.16(e) 2006 ISDA Definitions)


<EOL>if end.year - self.year == <NUM_LIT:0>:<EOL><INDENT>if BusinessDate.is_leap_year(self.year):<EOL><INDENT>return BusinessDate.diff_in_days(self, end) / <NUM_LIT>  <EOL><DEDENT>else:<EOL><INDENT>return BusinessDate.diff_in_days(self, end) / <NUM_LIT>  <EOL><DEDENT><DEDENT>else:<EOL><INDENT>rest_year1 = BusinessDate.diff_in_days(self, BusinessDate(<EOL>date(self.year, <NUM_LIT:12>, <NUM_LIT>))) + <NUM_LIT:1>  <EOL>rest_year2 = abs(BusinessDate.diff_in_days(end, BusinessDate(<EOL>date(end.year, <NUM_LIT:1>, <NUM_LIT:1>))))  <EOL>years_in_between = end.year - self.year - <NUM_LIT:1><EOL>return years_in_between + rest_year1 / (<NUM_LIT> if is_leap_year(self.year) else <NUM_LIT>) + rest_year2 / (<EOL><NUM_LIT> if is_leap_year(end.year) else <NUM_LIT>)<EOL><DEDENT>

implements Act/Act day count convention (4.16(b) 2006 ISDA Definitions)


y1, m1, d1 = self.to_ymd()<EOL>y2, m2, d2 = end.add_days(<NUM_LIT:0>).to_ymd()<EOL>d1 = min(d1, <NUM_LIT:30>)<EOL>d2 = min(d2, <NUM_LIT:30>)<EOL>return (<NUM_LIT> * (y2 - y1) + <NUM_LIT:30> * (m2 - m1) + (d2 - d1)) / <NUM_LIT><EOL>

implements the 30E/360 Day Count Convention (4.16(g) 2006 ISDA Definitons)


y1, m1, d1 = self.to_ymd()<EOL>y2, m2, d2 = end.add_days(<NUM_LIT:0>).to_ymd()<EOL>if (m1 == <NUM_LIT:2> and d1 >= <NUM_LIT>) or d1 == <NUM_LIT>:<EOL><INDENT>d1 = <NUM_LIT:30><EOL><DEDENT>if (m2 == <NUM_LIT:2> and d2 >= <NUM_LIT>) or d2 == <NUM_LIT>:<EOL><INDENT>d2 = <NUM_LIT:30><EOL><DEDENT>return (<NUM_LIT> * (y2 - y1) + <NUM_LIT:30> * (m2 - m1) + (d2 - d1)) / <NUM_LIT><EOL>

implements the 30E/360 (ISDA) Day Count Convention (4.16(h) 2006 ISDA Definitions)
:param end:
:return:


while not BusinessDate.is_business_day(self, holidays_obj):<EOL><INDENT>self = BusinessDate.add_days(self, -<NUM_LIT:1>)<EOL><DEDENT>return self<EOL>

adjusts to Business Day Convention "Preceding" (4.12(a) (iii) 2006 ISDA Definitions).


while not BusinessDate.is_business_day(self, holidays_obj):<EOL><INDENT>self = BusinessDate.add_days(self, <NUM_LIT:1>)<EOL><DEDENT>return self<EOL>

adjusts to Business Day Convention "Following" (4.12(a) (i) 2006 ISDA Definitions).


month = self.month<EOL>new = BusinessDate.adjust_follow(self, holidays_obj)<EOL>if month != new.month:<EOL><INDENT>new = BusinessDate.adjust_previous(self, holidays_obj)<EOL><DEDENT>self = new<EOL>return self<EOL>

adjusts to Business Day Convention "Modified [Following]" (4.12(a) (ii) 2006 ISDA Definitions).


month = self.month<EOL>new = BusinessDate.adjust_previous(self, holidays_obj)<EOL>if month != new.month:<EOL><INDENT>new = BusinessDate.adjust_follow(self, holidays_obj)<EOL><DEDENT>self = new<EOL>return self<EOL>

ajusts to Business Day Convention "Modified Preceding" (not in 2006 ISDA Definitons).


def __init__(self, period_in='<STR_LIT>', holiday=None, years=<NUM_LIT:0>, months=<NUM_LIT:0>, days=<NUM_LIT:0>, businessdays=<NUM_LIT:0>):

super(BusinessPeriod, self).__init__()<EOL>if isinstance(period_in, BusinessPeriod):<EOL><INDENT>years = period_in.years<EOL>months = period_in.months<EOL>days = period_in.days<EOL>businessdays = period_in.businessdays<EOL><DEDENT>elif isinstance(period_in, timedelta):<EOL><INDENT>days += timedelta.days<EOL><DEDENT>elif isinstance(period_in, (list, tuple)):<EOL><INDENT>if len(period_in) == <NUM_LIT:2>:<EOL><INDENT>y, m, d = BusinessDate.diff(period_in[<NUM_LIT:0>], period_in[<NUM_LIT:1>])<EOL>years += y<EOL>months += m<EOL>days += d<EOL><DEDENT><DEDENT>elif isinstance(period_in, (str, unicode)):<EOL><INDENT>period_in = str(period_in)<EOL>if period_in.startswith('<STR_LIT:->'):<EOL><INDENT>p = BusinessPeriod(period_in[<NUM_LIT:1>:])<EOL>years -= p.years<EOL>months -= p.months<EOL>days -= p.days<EOL>businessdays -= p.businessdays<EOL><DEDENT>elif period_in.upper() == '<STR_LIT>':<EOL><INDENT>businessdays += <NUM_LIT:1><EOL><DEDENT>elif period_in.upper() == '<STR_LIT>':<EOL><INDENT>businessdays += <NUM_LIT:2><EOL><DEDENT>elif period_in.upper() == '<STR_LIT>':<EOL><INDENT>businessdays += <NUM_LIT:3><EOL><DEDENT>elif period_in.upper().find('<STR_LIT:B>') > <NUM_LIT:0>:<EOL><INDENT>businessdays += int(period_in.upper().split('<STR_LIT:B>', <NUM_LIT:2>)[<NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>y, m, d = BusinessPeriod.parse(period_in)<EOL>years += y<EOL>months += m<EOL>days += d<EOL><DEDENT><DEDENT>if holiday is None:<EOL><INDENT>self.holiday = DEFAULT_HOLIDAYS<EOL><DEDENT>else:<EOL><INDENT>self.holiday = holiday<EOL><DEDENT>self.years = years<EOL>self.months = months<EOL>self.days = days<EOL>self.businessdays = businessdays<EOL>

class managing date periods like days, weeks, years etc.

:param period_in:
:param holiday:
:param years:
:param months:
:param days:
:param businessdays:

representation of a time BusinessPeriod, similar to dateutils.relativedelta, but with additional business day logic


try:  <EOL><INDENT>if str(in_period).upper() == '<STR_LIT>':<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>p = BusinessPeriod(str(in_period))<EOL>return not (p.days == <NUM_LIT:0> and p.months == <NUM_LIT:0> and p.years == <NUM_LIT:0> and p.businessdays == <NUM_LIT:0>)<EOL><DEDENT><DEDENT>except:<EOL><INDENT>return False<EOL><DEDENT>

:param in_period: object to be checked
:type in_period: object, str, timedelta
:return: True if cast works
:rtype: Boolean

checks is argument con becasted to BusinessPeriod


assert type(self) == type(other), "<STR_LIT>" % str((type(self), type(other)))<EOL>s = (self.years * <NUM_LIT:12> + self.months) * <NUM_LIT> + self.days<EOL>o = (other.years * <NUM_LIT:12> + other.months) * <NUM_LIT> + other.days<EOL>return s - o<EOL>

compare BusinessPeriods, comparison by (years*12+months)*31+days

        :param BusinessPeriod other:
        :return: int


def __init__(self, start, stop=None, step=None, rolling=None):

<EOL>start, stop, step, rolling = self._default_args(start, stop, step, rolling)<EOL>schedule = self._build_grid(start, stop, step, rolling)<EOL>super(BusinessRange, self).__init__(set(schedule))<EOL>self.sort()<EOL>

range like class to build date list

:param start: date to begin schedule, if stop not given, start will be used as stop and
    default in rolling to BusinessDate()
:type start: BusinessDate or int or str
:param stop: date to stop before, if not given, start will be used for stop instead
:type stop: BusinessDate or int or str
:param step: period to step schedule, if not given 1 year is default
:type step: BusinessPeriod or str
:param rolling: date to roll on (forward and backward) between start and stop,
    if not given default will be start
:type rolling: BusinessDate or int or str

range like class to build BusinessDate list from rolling date and BusinessPeriod

First, :code:`rolling` and :code:`step` defines a infinite grid of dates.
Second, this grid is sliced by :code:`start` (included , if meeting the grid) and
:code:`end` (excluded).


def __init__(self, start, end, step, roll=None):

if not roll:<EOL><INDENT>roll = end<EOL><DEDENT>if not isinstance(start, BusinessDate):<EOL><INDENT>if isinstance(start, BusinessPeriod):<EOL><INDENT>start = start.to_businessdate()<EOL><DEDENT>else:<EOL><INDENT>start = BusinessDate(start)<EOL><DEDENT><DEDENT>if not isinstance(end, BusinessDate):<EOL><INDENT>if isinstance(end, BusinessPeriod):<EOL><INDENT>end = end.to_businessdate()<EOL><DEDENT>else:<EOL><INDENT>end = BusinessDate(end)<EOL><DEDENT><DEDENT>super(BusinessSchedule, self).__init__(start, end, step, roll)<EOL>if start not in self:<EOL><INDENT>self.insert(<NUM_LIT:0>, start)<EOL><DEDENT>if end not in self:<EOL><INDENT>self.append(end)<EOL><DEDENT>

class to build date schedules incl. start and end date

:param BusinessDate start: start date of schedule
:param BusinessDate end: end date of schedule
:param BusinessPeriod step: period distance of two dates
:param BusinessDate roll: origin of schedule

convenient class to build date schedules
a schedule includes always start and end date
and rolls on roll, i.e. builds a sequence by
adding and/or substracting step to/from roll.
start and end slice the relevant dates.


self.id = classid  <EOL>self.name = None   <EOL>self.component = None   <EOL>self.D = None<EOL>


classid = str(self.id)<EOL>if quote: classid = '<STR_LIT:">'+classid+'<STR_LIT:">'<EOL>file.write('<STR_LIT>'+classid+'<STR_LIT>'+str(self.name)+'<STR_LIT:U+0020>'+optstring+'<STR_LIT:\n>')<EOL>

write the 'object' line; additional args are packed in string


return s * len(self.shape)<EOL>

Returns a string with as many repetitions of s as self
        has dimensions (derived from shape)


return [self.delta[d,d] * numpy.arange(self.shape[d]+<NUM_LIT:1>) + self.origin[d]- <NUM_LIT:0.5>*self.delta[d,d]     for d in range(self.rank)]<EOL>

Edges of the grid cells, origin at centre of 0,0,..,0 grid cell.

        Only works for regular, orthonormal grids.


def __init__(self, classid, array=None, type=None, typequote='<STR_LIT:">',<EOL>**kwargs):

if array is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>self.id = classid<EOL>self.name = '<STR_LIT>'<EOL>self.component = '<STR_LIT:data>'<EOL>if type is None:<EOL><INDENT>self.array = numpy.asarray(array)<EOL>try:<EOL><INDENT>self.type = self.np_types[self.array.dtype.name]<EOL><DEDENT>except KeyError:<EOL><INDENT>warnings.warn(("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>").format(<EOL>self.array.dtype.name))<EOL>self.type = self.array.dtype.name  <EOL><DEDENT><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>self.array = numpy.asarray(array, dtype=self.dx_types[type])<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueError(("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(type,<EOL>list(self.dx_types.values()))))<EOL><DEDENT>self.type = type<EOL><DEDENT>self.typequote = typequote<EOL>

Parameters
----------
classid : int
array : array_like
type : str (optional)
     Set the DX type in the output file and cast `array` to
     the closest numpy dtype.  `type` must be one of the
     allowed types in DX files as defined under `Array
     Objects`_.  The default ``None`` tries to set the type
     from the :class:`numpy.dtype` of `array`.

     .. versionadded:: 0.4.0

Raises
------
ValueError
     if `array` is not provided; or if `type` is not of the correct
     DX type


if self.type not in self.dx_types:<EOL><INDENT>raise ValueError(("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>").format(<EOL>self.type, list(self.dx_types.keys())))<EOL><DEDENT>typelabel = (self.typequote+self.type+self.typequote)<EOL>DXclass.write(self,file,<EOL>'<STR_LIT>'.format(<EOL>typelabel, self.array.size))<EOL>fmt_string = "<STR_LIT>"<EOL>if (self.array.dtype.kind == '<STR_LIT:f>' or self.array.dtype.kind == '<STR_LIT:c>'):<EOL><INDENT>precision = numpy.finfo(self.array.dtype).precision<EOL>fmt_string = "<STR_LIT>"+"<STR_LIT>".format(precision)+"<STR_LIT>"<EOL><DEDENT>values_per_line = <NUM_LIT:3><EOL>values = self.array.flat<EOL>while <NUM_LIT:1>:<EOL><INDENT>try:<EOL><INDENT>for i in range(values_per_line):<EOL><INDENT>file.write(fmt_string.format(next(values)) + "<STR_LIT:\t>")<EOL><DEDENT>file.write('<STR_LIT:\n>')<EOL><DEDENT>except StopIteration:<EOL><INDENT>file.write('<STR_LIT:\n>')<EOL>break<EOL><DEDENT><DEDENT>file.write('<STR_LIT>')<EOL>

Write the *class array* section.

        Parameters
        ----------
        file : file

        Raises
        ------
        ValueError
             If the `dxtype` is not a valid type, :exc:`ValueError` is
             raised.


if components is None:<EOL><INDENT>components = dict(positions=None,connections=None,data=None)<EOL><DEDENT>if comments is None:<EOL><INDENT>comments = ['<STR_LIT>',<EOL>'<STR_LIT>']<EOL><DEDENT>elif type(comments) is not list:<EOL><INDENT>comments = [str(comments)]<EOL><DEDENT>self.id = classid       <EOL>self.name = '<STR_LIT>'<EOL>self.component = None   <EOL>self.components = components<EOL>self.comments= comments<EOL>

OpenDX object, which is build from a list of components.

        Parameters
        ----------

        id : str
               arbitrary string
        components : dict
               dictionary of DXclass instances (no sanity check on the
               individual ids!) which correspond to

               * positions
               * connections
               * data

        comments : list
               list of strings; each string becomes a comment line
               prefixed with '#'. Avoid newlines.

        A field must have at least the components 'positions',
        'connections', and 'data'. Those components are associated
        with objects belonging to the field. When writing a dx file
        from the field, only the required objects are dumped to the file.

        (For a more general class that can use field:
        Because there could be more objects than components, we keep a
        separate object list. When dumping the dx file, first all
        objects are written and then the field object describes its
        components. Objects are referenced by their unique id.)

        .. Note:: uniqueness of the *id* is not checked.

        Example
        -------
        Create a new dx object::

           dx = OpenDX.field('density',[gridpoints,gridconnections,array])


<EOL>maxcol = <NUM_LIT><EOL>with open(filename,'<STR_LIT:w>') as outfile:<EOL><INDENT>for line in self.comments:<EOL><INDENT>comment = '<STR_LIT>'+str(line)<EOL>outfile.write(comment[:maxcol]+'<STR_LIT:\n>')<EOL><DEDENT>for component,object in self.sorted_components():<EOL><INDENT>object.write(outfile)<EOL><DEDENT>DXclass.write(self,outfile,quote=True)<EOL>for component,object in self.sorted_components():<EOL><INDENT>outfile.write('<STR_LIT>' % (component,str(object.id)))<EOL><DEDENT><DEDENT>

Write the complete dx object to the file.

        This is the simple OpenDX format which includes the data into
        the header via the 'object array ... data follows' statement.

        Only simple regular arrays are supported.

        The format should be compatible with VMD's dx reader plugin.


DXfield = self<EOL>p = DXParser(file)<EOL>p.parse(DXfield)<EOL>

Read DX field from file.

            dx = OpenDX.field.read(dxfile)

        The classid is discarded and replaced with the one from the file.


self[component] = DXobj<EOL>


self.comments.append(comment)<EOL>


for component, object insorted(self.components.items(),<EOL>key=lambda comp_obj: comp_obj[<NUM_LIT:1>].id):<EOL><INDENT>yield component, object<EOL><DEDENT>

iterator that returns (component,object) in id order


shape = self.components['<STR_LIT>'].shape<EOL>edges = self.components['<STR_LIT>'].edges()<EOL>hist = self.components['<STR_LIT:data>'].array.reshape(shape)<EOL>return (hist,edges)<EOL>

Return array data as (edges,grid), i.e. a numpy nD histogram.


if ascode is None:<EOL><INDENT>ascode = self.code<EOL><DEDENT>return self.cast[ascode](self.text)<EOL>

Return text cast to the correct type or the selected type


return self.DXclasses[self.type](self.id,**self.args)<EOL>

Initialize the corresponding DXclass from the data.

        class = DXInitObject.initialize()


self.filename = filename<EOL>self.field = field('<STR_LIT>',comments=['<STR_LIT>'+self.filename])<EOL>self.parsers = {'<STR_LIT>':self.__general,<EOL>'<STR_LIT>':self.__comment, '<STR_LIT:object>':self.__object,<EOL>'<STR_LIT>':self.__gridpositions,<EOL>'<STR_LIT>':self.__gridconnections,<EOL>'<STR_LIT>':self.__array, '<STR_LIT>':self.__field,<EOL>}<EOL>

Setup a parser for a simple DX file (from VMD)

        >>> DXfield_object = OpenDX.field(id)
        >>> p = DXparser('bulk.dx')
        >>> p.parse(DXfield_object)

        The field object will be completely rewritten (including the
        id if one is found in the input file. The input files
        component layout is currently ignored.

        Note that quotes are removed from quoted strings.


self.DXfield = DXfield              <EOL>self.currentobject = None           <EOL>self.objects = []                   <EOL>self.tokens = []                    <EOL>with open(self.filename,'<STR_LIT:r>') as self.dxfile:<EOL><INDENT>self.use_parser('<STR_LIT>')      <EOL><DEDENT>for o in self.objects:<EOL><INDENT>if o.type == '<STR_LIT>':<EOL><INDENT>DXfield.id = o.id<EOL>continue<EOL><DEDENT>c = o.initialize()<EOL>self.DXfield.add(c.component,c)<EOL><DEDENT>del self.currentobject, self.objects<EOL>

Parse the dx file and construct a DX field object with component classes.

        A :class:`field` instance *DXfield* must be provided to be
        filled by the parser::

           DXfield_object = OpenDX.field(*args)
           parse(DXfield_object)

        A tokenizer turns the dx file into a stream of tokens. A
        hierarchy of parsers examines the stream. The level-0 parser
        ('general') distinguishes comments and objects (level-1). The
        object parser calls level-3 parsers depending on the object
        found. The basic idea is that of a 'state machine'. There is
        one parser active at any time. The main loop is the general
        parser.

        * Constructing the dx objects with classtype and classid is
          not implemented yet.
        * Unknown tokens raise an exception.


while <NUM_LIT:1>:                            <EOL><INDENT>try:<EOL><INDENT>tok = self.__peek()         <EOL><DEDENT>except DXParserNoTokens:<EOL><INDENT>if self.currentobject and self.currentobject not in self.objects:<EOL><INDENT>self.objects.append(self.currentobject)<EOL><DEDENT>return                      <EOL><DEDENT>if tok.iscode('<STR_LIT>'):<EOL><INDENT>self.set_parser('<STR_LIT>')  <EOL><DEDENT>elif tok.iscode('<STR_LIT>') and tok.equals('<STR_LIT:object>'):<EOL><INDENT>self.set_parser('<STR_LIT:object>')   <EOL><DEDENT>elif self.__parser is self.__general:<EOL><INDENT>raise DXParseError('<STR_LIT>'+str(tok))<EOL><DEDENT>self.apply_parser()<EOL><DEDENT>

Level-0 parser and main loop.

        Look for a token that matches a level-1 parser and hand over control.


tok = self.__consume()<EOL>self.DXfield.add_comment(tok.value())<EOL>self.set_parser('<STR_LIT>')<EOL>

Level-1 parser for comments.

        pattern: #.*
        Append comment (with initial '# ' stripped) to all comments.


self.__consume()                    <EOL>classid = self.__consume().text<EOL>word = self.__consume().text<EOL>if word != "<STR_LIT:class>":<EOL><INDENT>raise DXParseError("<STR_LIT>" % word)<EOL><DEDENT>if self.currentobject:<EOL><INDENT>self.objects.append(self.currentobject)<EOL><DEDENT>classtype = self.__consume().text<EOL>self.currentobject = DXInitObject(classtype=classtype,classid=classid)<EOL>self.use_parser(classtype)<EOL>

Level-1 parser for objects.

        pattern: 'object' id 'class' type ...

        id ::=   integer|string|'"'white space string'"'
        type ::= string


try:<EOL><INDENT>tok = self.__consume()<EOL><DEDENT>except DXParserNoTokens:<EOL><INDENT>return<EOL><DEDENT>if tok.equals('<STR_LIT>'):<EOL><INDENT>shape = []<EOL>try:<EOL><INDENT>while True:<EOL><INDENT>self.__peek().value('<STR_LIT>')<EOL>tok = self.__consume()<EOL>shape.append(tok.value('<STR_LIT>'))<EOL><DEDENT><DEDENT>except (DXParserNoTokens, ValueError):<EOL><INDENT>pass<EOL><DEDENT>if len(shape) == <NUM_LIT:0>:<EOL><INDENT>raise DXParseError('<STR_LIT>')<EOL><DEDENT>self.currentobject['<STR_LIT>'] = shape<EOL><DEDENT>elif tok.equals('<STR_LIT>'):<EOL><INDENT>origin = []<EOL>try:<EOL><INDENT>while (self.__peek().iscode('<STR_LIT>') or<EOL>self.__peek().iscode('<STR_LIT>')):<EOL><INDENT>tok = self.__consume()<EOL>origin.append(tok.value())<EOL><DEDENT><DEDENT>except DXParserNoTokens:<EOL><INDENT>pass<EOL><DEDENT>if len(origin) == <NUM_LIT:0>:<EOL><INDENT>raise DXParseError('<STR_LIT>')<EOL><DEDENT>self.currentobject['<STR_LIT>'] = origin<EOL><DEDENT>elif tok.equals('<STR_LIT>'):<EOL><INDENT>d = []<EOL>try:<EOL><INDENT>while (self.__peek().iscode('<STR_LIT>') or<EOL>self.__peek().iscode('<STR_LIT>')):<EOL><INDENT>tok = self.__consume()<EOL>d.append(tok.value())<EOL><DEDENT><DEDENT>except DXParserNoTokens:<EOL><INDENT>pass<EOL><DEDENT>if len(d) == <NUM_LIT:0>:<EOL><INDENT>raise DXParseError('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>self.currentobject['<STR_LIT>'].append(d)<EOL><DEDENT>except KeyError:<EOL><INDENT>self.currentobject['<STR_LIT>'] = [d]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise DXParseError('<STR_LIT>'+str(tok)+'<STR_LIT>')<EOL><DEDENT>

Level-2 parser for gridpositions.

        pattern:
        object 1 class gridpositions counts 97 93 99
        origin -46.5 -45.5 -48.5
        delta 1 0 0
        delta 0 1 0
        delta 0 0 1


try:<EOL><INDENT>tok = self.__consume()<EOL><DEDENT>except DXParserNoTokens:<EOL><INDENT>return<EOL><DEDENT>if tok.equals('<STR_LIT>'):<EOL><INDENT>shape = []<EOL>try:<EOL><INDENT>while True:<EOL><INDENT>self.__peek().value('<STR_LIT>')<EOL>tok = self.__consume()<EOL>shape.append(tok.value('<STR_LIT>'))<EOL><DEDENT><DEDENT>except (DXParserNoTokens, ValueError):<EOL><INDENT>pass<EOL><DEDENT>if len(shape) == <NUM_LIT:0>:<EOL><INDENT>raise DXParseError('<STR_LIT>')<EOL><DEDENT>self.currentobject['<STR_LIT>'] = shape<EOL><DEDENT>else:<EOL><INDENT>raise DXParseError('<STR_LIT>'+str(tok)+'<STR_LIT>')<EOL><DEDENT>

Level-2 parser for gridconnections.

        pattern:
        object 2 class gridconnections counts 97 93 99


try:<EOL><INDENT>tok = self.__consume()<EOL><DEDENT>except DXParserNoTokens:<EOL><INDENT>return<EOL><DEDENT>if tok.equals('<STR_LIT:type>'):<EOL><INDENT>tok = self.__consume()<EOL>if not tok.iscode('<STR_LIT>'):<EOL><INDENT>raise DXParseError('<STR_LIT>'%tok.text)<EOL><DEDENT>self.currentobject['<STR_LIT:type>'] = tok.value()<EOL><DEDENT>elif tok.equals('<STR_LIT>'):<EOL><INDENT>tok = self.__consume()<EOL>try:<EOL><INDENT>self.currentobject['<STR_LIT>'] = tok.value('<STR_LIT>')<EOL><DEDENT>except ValueError:<EOL><INDENT>raise DXParseError('<STR_LIT>'%tok.text)<EOL><DEDENT><DEDENT>elif tok.equals('<STR_LIT>'):<EOL><INDENT>tok = self.__consume()<EOL>try:<EOL><INDENT>self.currentobject['<STR_LIT:size>'] = tok.value('<STR_LIT>')<EOL><DEDENT>except ValueError:<EOL><INDENT>raise DXParseError('<STR_LIT>'%tok.text)<EOL><DEDENT><DEDENT>elif tok.equals('<STR_LIT:data>'):<EOL><INDENT>tok = self.__consume()<EOL>if not tok.iscode('<STR_LIT>'):<EOL><INDENT>raise DXParseError('<STR_LIT>'%tok.text)<EOL><DEDENT>if tok.text != '<STR_LIT>':<EOL><INDENT>raise NotImplementedError('<STR_LIT>')<EOL><DEDENT>if not self.currentobject['<STR_LIT:size>']:<EOL><INDENT>raise DXParseError("<STR_LIT>")<EOL><DEDENT>self.currentobject['<STR_LIT>'] = []<EOL>while len(self.currentobject['<STR_LIT>']) <self.currentobject['<STR_LIT:size>']:<EOL><INDENT>self.currentobject['<STR_LIT>'].extend(self.dxfile.readline().strip().split())<EOL><DEDENT><DEDENT>elif tok.equals('<STR_LIT>'):<EOL><INDENT>attribute = self.__consume().value()<EOL>if not self.__consume().equals('<STR_LIT:string>'):<EOL><INDENT>raise DXParseError('<STR_LIT>')<EOL><DEDENT>value = self.__consume().value()<EOL><DEDENT>else:<EOL><INDENT>raise DXParseError('<STR_LIT>'+str(tok)+'<STR_LIT>')<EOL><DEDENT>

Level-2 parser for arrays.

        pattern:
        object 3 class array type double rank 0 items 12 data follows
        0 2 0
        0 0 3.6
        0 -2.0 1e-12
        +4.534e+01 .34534 0.43654
        attribute "dep" string "positions"


try:<EOL><INDENT>tok = self.__consume()<EOL><DEDENT>except DXParserNoTokens:<EOL><INDENT>return<EOL><DEDENT>if tok.equals('<STR_LIT>'):<EOL><INDENT>component = self.__consume().value()<EOL>if not self.__consume().equals('<STR_LIT:value>'):<EOL><INDENT>raise DXParseError('<STR_LIT>')<EOL><DEDENT>classid = self.__consume().value()<EOL>try:<EOL><INDENT>self.currentobject['<STR_LIT>'][component] = classid<EOL><DEDENT>except KeyError:<EOL><INDENT>self.currentobject['<STR_LIT>'] = {component:classid}<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise DXParseError('<STR_LIT>'+str(tok)+'<STR_LIT>')<EOL><DEDENT>

Level-2 parser for a DX field object.

        pattern:
        object "site map 1" class field
        component "positions" value 1
        component "connections" value 2
        component "data" value 3


self.__parser = self.parsers[parsername]<EOL>self.__parser()<EOL>

Set parsername as the current parser and apply it.


self.__parser = self.parsers[parsername]<EOL>


Apply the current parser to the token stream.


for m in self.dx_regex.finditer(string.strip()):<EOL><INDENT>code = m.lastgroup<EOL>text = m.group(m.lastgroup)<EOL>tok = Token(code,text)<EOL>if not tok.iscode('<STR_LIT>'):<EOL><INDENT>self.tokens.append(tok)<EOL><DEDENT><DEDENT>

Split s into tokens and update the token buffer.

        __tokenize(string)

        New tokens are appended to the token buffer, discarding white
        space.  Based on http://effbot.org/zone/xml-scanner.htm


if len(self.tokens) == <NUM_LIT:0>:<EOL><INDENT>self.__tokenize(self.dxfile.readline())<EOL><DEDENT>

Add a new tokenized line from the file to the token buffer.

        __refill_tokenbuffer()

        Only reads a new line if the buffer is empty. It is safe to
        call it repeatedly.

        At end of file, method returns empty strings and it is up to
        __peek and __consume to flag the end of the stream.


self.__refill_tokenbuffer()<EOL>try:<EOL><INDENT>return self.tokens.pop(<NUM_LIT:0>)  <EOL><DEDENT>except IndexError:<EOL><INDENT>raise DXParserNoTokens<EOL><DEDENT>

Get the next token from the buffer and remove it/them.

        try:
          while 1:
             token = __consume()
        except DXParserNoTokens:
          pass


<EOL>git_refnames = "<STR_LIT>"<EOL>git_full = "<STR_LIT>"<EOL>git_date = "<STR_LIT>"<EOL>keywords = {"<STR_LIT>": git_refnames, "<STR_LIT>": git_full, "<STR_LIT:date>": git_date}<EOL>return keywords<EOL>

Get the keywords needed to look up the version information.


<EOL>cfg = VersioneerConfig()<EOL>cfg.VCS = "<STR_LIT>"<EOL>cfg.style = "<STR_LIT>"<EOL>cfg.tag_prefix = "<STR_LIT>"<EOL>cfg.parentdir_prefix = "<STR_LIT>"<EOL>cfg.versionfile_source = "<STR_LIT>"<EOL>cfg.verbose = False<EOL>return cfg<EOL>

Create, populate and return the VersioneerConfig() object.


def decorate(f):<EOL><INDENT>"""<STR_LIT>"""<EOL>if vcs not in HANDLERS:<EOL><INDENT>HANDLERS[vcs] = {}<EOL><DEDENT>HANDLERS[vcs][method] = f<EOL>return f<EOL><DEDENT>return decorate<EOL>

Decorator to mark a method as the handler for a particular VCS.


def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,<EOL>env=None):

assert isinstance(commands, list)<EOL>p = None<EOL>for c in commands:<EOL><INDENT>try:<EOL><INDENT>dispcmd = str([c] + args)<EOL>p = subprocess.Popen([c] + args, cwd=cwd, env=env,<EOL>stdout=subprocess.PIPE,<EOL>stderr=(subprocess.PIPE if hide_stderr<EOL>else None))<EOL>break<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>e = sys.exc_info()[<NUM_LIT:1>]<EOL>if e.errno == errno.ENOENT:<EOL><INDENT>continue<EOL><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % dispcmd)<EOL>print(e)<EOL><DEDENT>return None, None<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % (commands,))<EOL><DEDENT>return None, None<EOL><DEDENT>stdout = p.communicate()[<NUM_LIT:0>].strip()<EOL>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>stdout = stdout.decode()<EOL><DEDENT>if p.returncode != <NUM_LIT:0>:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % dispcmd)<EOL>print("<STR_LIT>" % stdout)<EOL><DEDENT>return None, p.returncode<EOL><DEDENT>return stdout, p.returncode<EOL>


def versions_from_parentdir(parentdir_prefix, root, verbose):

rootdirs = []<EOL>for i in range(<NUM_LIT:3>):<EOL><INDENT>dirname = os.path.basename(root)<EOL>if dirname.startswith(parentdir_prefix):<EOL><INDENT>return {"<STR_LIT:version>": dirname[len(parentdir_prefix):],<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None, "<STR_LIT:date>": None}<EOL><DEDENT>else:<EOL><INDENT>rootdirs.append(root)<EOL>root = os.path.dirname(root)  <EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" %<EOL>(str(rootdirs), parentdir_prefix))<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL>

Try to determine the version from the parent directory name.

    Source tarballs conventionally unpack into a directory that includes both
    the project name and a version string. We will also support searching up
    two directory levels for an appropriately named parent directory


<EOL>keywords = {}<EOL>try:<EOL><INDENT>f = open(versionfile_abs, "<STR_LIT:r>")<EOL>for line in f.readlines():<EOL><INDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT:date>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT><DEDENT>f.close()<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT>return keywords<EOL>

Extract version information from the given file.


@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_versions_from_keywords(keywords, tag_prefix, verbose):

if not keywords:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>date = keywords.get("<STR_LIT:date>")<EOL>if date is not None:<EOL><INDENT>date = date.strip().replace("<STR_LIT:U+0020>", "<STR_LIT:T>", <NUM_LIT:1>).replace("<STR_LIT:U+0020>", "<STR_LIT>", <NUM_LIT:1>)<EOL><DEDENT>refnames = keywords["<STR_LIT>"].strip()<EOL>if refnames.startswith("<STR_LIT>"):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>refs = set([r.strip() for r in refnames.strip("<STR_LIT>").split("<STR_LIT:U+002C>")])<EOL>TAG = "<STR_LIT>"<EOL>tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])<EOL>if not tags:<EOL><INDENT>tags = set([r for r in refs if re.search(r'<STR_LIT>', r)])<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(refs - tags))<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(sorted(tags)))<EOL><DEDENT>for ref in sorted(tags):<EOL><INDENT>if ref.startswith(tag_prefix):<EOL><INDENT>r = ref[len(tag_prefix):]<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % r)<EOL><DEDENT>return {"<STR_LIT:version>": r,<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None,<EOL>"<STR_LIT:date>": date}<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": "<STR_LIT>", "<STR_LIT:date>": None}<EOL>

Get version information from git keywords.


@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):

GITS = ["<STR_LIT>"]<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>GITS = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root,<EOL>hide_stderr=True)<EOL>if rc != <NUM_LIT:0>:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % root)<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>describe_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>" % tag_prefix],<EOL>cwd=root)<EOL>if describe_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>describe_out = describe_out.strip()<EOL>full_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root)<EOL>if full_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>full_out = full_out.strip()<EOL>pieces = {}<EOL>pieces["<STR_LIT>"] = full_out<EOL>pieces["<STR_LIT>"] = full_out[:<NUM_LIT:7>]  <EOL>pieces["<STR_LIT:error>"] = None<EOL>git_describe = describe_out<EOL>dirty = git_describe.endswith("<STR_LIT>")<EOL>pieces["<STR_LIT>"] = dirty<EOL>if dirty:<EOL><INDENT>git_describe = git_describe[:git_describe.rindex("<STR_LIT>")]<EOL><DEDENT>if "<STR_LIT:->" in git_describe:<EOL><INDENT>mo = re.search(r'<STR_LIT>', git_describe)<EOL>if not mo:<EOL><INDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% describe_out)<EOL>return pieces<EOL><DEDENT>full_tag = mo.group(<NUM_LIT:1>)<EOL>if not full_tag.startswith(tag_prefix):<EOL><INDENT>if verbose:<EOL><INDENT>fmt = "<STR_LIT>"<EOL>print(fmt % (full_tag, tag_prefix))<EOL><DEDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% (full_tag, tag_prefix))<EOL>return pieces<EOL><DEDENT>pieces["<STR_LIT>"] = full_tag[len(tag_prefix):]<EOL>pieces["<STR_LIT>"] = int(mo.group(<NUM_LIT:2>))<EOL>pieces["<STR_LIT>"] = mo.group(<NUM_LIT:3>)<EOL><DEDENT>else:<EOL><INDENT>pieces["<STR_LIT>"] = None<EOL>count_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>cwd=root)<EOL>pieces["<STR_LIT>"] = int(count_out)  <EOL><DEDENT>date = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>cwd=root)[<NUM_LIT:0>].strip()<EOL>pieces["<STR_LIT:date>"] = date.strip().replace("<STR_LIT:U+0020>", "<STR_LIT:T>", <NUM_LIT:1>).replace("<STR_LIT:U+0020>", "<STR_LIT>", <NUM_LIT:1>)<EOL>return pieces<EOL>

Get version from 'git describe' in the root of the source tree.

    This only gets called if the git-archive 'subst' keywords were *not*
    expanded, and _version.py hasn't already been rewritten with a short
    version string, meaning we're inside a checked out source tree.


if "<STR_LIT:+>" in pieces.get("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>return "<STR_LIT:.>"<EOL><DEDENT>return "<STR_LIT:+>"<EOL>

Return a + if we don't already have one, else return a .


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % (pieces["<STR_LIT>"],<EOL>pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT>return rendered<EOL>

Build up version string, with post-release "local version identifier".

    Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
    get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty

    Exceptions:
    1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>

TAG[.post.devDISTANCE] -- No -dirty.

    Exceptions:
    1: no tags. 0.post.devDISTANCE


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>

TAG[.postDISTANCE[.dev0]+gHEX] .

    The ".dev0" means dirty. Note that .dev0 sorts backwards
    (a dirty tree will appear "older" than the corresponding clean one),
    but you shouldn't be releasing software with -dirty anyways.

    Exceptions:
    1: no tags. 0.postDISTANCE[.dev0]


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT>return rendered<EOL>

TAG[.postDISTANCE[.dev0]] .

    The ".dev0" means dirty.

    Eexceptions:
    1: no tags. 0.postDISTANCE[.dev0]


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>

TAG[-DISTANCE-gHEX][-dirty].

    Like 'git describe --tags --dirty --always'.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>

TAG-DISTANCE-gHEX[-dirty].

    Like 'git describe --tags --dirty --always -long'.
    The distance/hash is unconditional.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)


if pieces["<STR_LIT:error>"]:<EOL><INDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": pieces.get("<STR_LIT>"),<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": pieces["<STR_LIT:error>"],<EOL>"<STR_LIT:date>": None}<EOL><DEDENT>if not style or style == "<STR_LIT:default>":<EOL><INDENT>style = "<STR_LIT>"  <EOL><DEDENT>if style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_pre(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_post(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_old(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_git_describe(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_git_describe_long(pieces)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % style)<EOL><DEDENT>return {"<STR_LIT:version>": rendered, "<STR_LIT>": pieces["<STR_LIT>"],<EOL>"<STR_LIT>": pieces["<STR_LIT>"], "<STR_LIT:error>": None,<EOL>"<STR_LIT:date>": pieces.get("<STR_LIT:date>")}<EOL>

Render the given version pieces into the requested style.


<EOL>cfg = get_config()<EOL>verbose = cfg.verbose<EOL>try:<EOL><INDENT>return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,<EOL>verbose)<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>root = os.path.realpath(__file__)<EOL>for i in cfg.versionfile_source.split('<STR_LIT:/>'):<EOL><INDENT>root = os.path.dirname(root)<EOL><DEDENT><DEDENT>except NameError:<EOL><INDENT>return {"<STR_LIT:version>": "<STR_LIT>", "<STR_LIT>": None,<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": "<STR_LIT>",<EOL>"<STR_LIT:date>": None}<EOL><DEDENT>try:<EOL><INDENT>pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)<EOL>return render(pieces, cfg.style)<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>if cfg.parentdir_prefix:<EOL><INDENT>return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)<EOL><DEDENT><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>", "<STR_LIT>": None,<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": "<STR_LIT>", "<STR_LIT:date>": None}<EOL>

Get version information or return default if unable to do so.


if filename is not None:<EOL><INDENT>self.filename = filename<EOL><DEDENT>with open(self.filename, '<STR_LIT:rb>') as ccp4:<EOL><INDENT>h = self.header = self._read_header(ccp4)<EOL>nentries = h['<STR_LIT>'] * h['<STR_LIT>'] * h['<STR_LIT>']<EOL>datafmt = h['<STR_LIT>'] + str(nentries) + self._data_bintype<EOL>a = np.array(struct.unpack(datafmt, ccp4.read(struct.calcsize(datafmt))))<EOL><DEDENT>self.header['<STR_LIT:filename>'] = self.filename<EOL>order = '<STR_LIT:C>' if h['<STR_LIT>'] == '<STR_LIT:z>' else '<STR_LIT:F>'<EOL>self.array = a.reshape(h['<STR_LIT>'], h['<STR_LIT>'], h['<STR_LIT>'], order=order)<EOL>self.delta = self._delta()<EOL>self.origin = np.zeros(<NUM_LIT:3>)<EOL>self.rank = <NUM_LIT:3><EOL>

Populate the instance from the ccp4 file *filename*.


<EOL>return [self.delta[d, d] * np.arange(self.shape[d] + <NUM_LIT:1>) +<EOL>self.origin[d] - <NUM_LIT:0.5> * self.delta[d, d]<EOL>for d in range(self.rank)]<EOL>

Edges of the grid cells, origin at centre of 0,0,..,0 grid cell.

        Only works for regular, orthonormal grids.


bsaflag = None<EOL>ccp4file.seek(<NUM_LIT> * <NUM_LIT:4>)<EOL>mapbin = ccp4file.read(<NUM_LIT:4>)<EOL>for flag in '<STR_LIT>':<EOL><INDENT>mapstr = struct.unpack(flag + '<STR_LIT>', mapbin)[<NUM_LIT:0>].decode('<STR_LIT:utf-8>')<EOL>if mapstr.upper() == '<STR_LIT>':<EOL><INDENT>bsaflag = flag<EOL>break  <EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>")<EOL><DEDENT>ccp4file.seek(<NUM_LIT:0>)<EOL>return bsaflag<EOL>

Detect the byteorder of stream `ccp4file` and return format character.

        Try all endinaness and alignment options until we find
        something that looks sensible ("MAPS " in the first 4 bytes).

        (The ``machst`` field could be used to obtain endianness, but
        it does not specify alignment.)

        .. SeeAlso::

          :mod:`struct`


bsaflag = self._detect_byteorder(ccp4file)<EOL>nheader = struct.calcsize(self._headerfmt)<EOL>names = [r.key for r in self._header_struct]<EOL>bintopheader = ccp4file.read(<NUM_LIT> * <NUM_LIT:4>)<EOL>def decode_header(header, bsaflag='<STR_LIT:@>'):<EOL><INDENT>h = dict(zip(names, struct.unpack(bsaflag + self._headerfmt,<EOL>header)))<EOL>h['<STR_LIT>'] = bsaflag<EOL>return h<EOL><DEDENT>header = decode_header(bintopheader, bsaflag)<EOL>for rec in self._header_struct:<EOL><INDENT>if not rec.is_legal_dict(header):<EOL><INDENT>warnings.warn(<EOL>"<STR_LIT>" % (rec.key, header[rec.key]))<EOL><DEDENT><DEDENT>if (header['<STR_LIT>']):<EOL><INDENT>skewmatrix = np.fromfile(ccp4file, dtype=np.float32, count=<NUM_LIT:9>)<EOL>header['<STR_LIT>'] = skewmatrix.reshape((<NUM_LIT:3>, <NUM_LIT:3>))<EOL>header['<STR_LIT>'] = np.fromfile(ccp4file, dtype=np.float32, count=<NUM_LIT:3>)<EOL><DEDENT>else:<EOL><INDENT>header['<STR_LIT>'] = header['<STR_LIT>'] = None<EOL>ccp4file.seek(<NUM_LIT:12> * <NUM_LIT:4>, <NUM_LIT:1>)<EOL><DEDENT>ccp4file.seek(<NUM_LIT:15> * <NUM_LIT:4>, <NUM_LIT:1>)  <EOL>ccp4file.seek(<NUM_LIT:4>, <NUM_LIT:1>)  <EOL>endiancode = struct.unpack(bsaflag + '<STR_LIT>', ccp4file.read(<NUM_LIT:4>))<EOL>header['<STR_LIT>'] = '<STR_LIT>' if endiancode == (<NUM_LIT>, <NUM_LIT>, <NUM_LIT:0>, <NUM_LIT:0><EOL>) else '<STR_LIT>'<EOL>header['<STR_LIT>'] = struct.unpack(bsaflag + '<STR_LIT:f>', ccp4file.read(<NUM_LIT:4>))[<NUM_LIT:0>]<EOL>header['<STR_LIT>'] = struct.unpack(bsaflag + '<STR_LIT:I>', ccp4file.read(<NUM_LIT:4>))[<NUM_LIT:0>]<EOL>if header['<STR_LIT>']:<EOL><INDENT>binlabel = ccp4file.read(<NUM_LIT> * header['<STR_LIT>'])<EOL>flag = bsaflag + str(<NUM_LIT> * header['<STR_LIT>']) + '<STR_LIT:s>'<EOL>label = struct.unpack(flag, binlabel)[<NUM_LIT:0>]<EOL>header['<STR_LIT:label>'] = label.decode('<STR_LIT:utf-8>').rstrip('<STR_LIT:\x00>')<EOL><DEDENT>else:<EOL><INDENT>header['<STR_LIT:label>'] = None<EOL><DEDENT>ccp4file.seek(<NUM_LIT> * <NUM_LIT:4>)<EOL>return header<EOL>


return (self.array, self.edges)<EOL>

Return array data as (edges,grid), i.e. a numpy nD histogram.


from struct import calcsize, unpack<EOL>if not filename is None:<EOL><INDENT>self.filename = filename<EOL><DEDENT>with open(self.filename, '<STR_LIT:rb>') as plt:<EOL><INDENT>h = self.header = self._read_header(plt)<EOL>nentries = h['<STR_LIT>'] * h['<STR_LIT>'] * h['<STR_LIT>']<EOL>datafmt = h['<STR_LIT>']+str(nentries)+self._data_bintype<EOL>a = numpy.array(unpack(datafmt, plt.read(calcsize(datafmt))))<EOL><DEDENT>self.header['<STR_LIT:filename>'] = self.filename<EOL>self.array = a.reshape(h['<STR_LIT>'], h['<STR_LIT>'], h['<STR_LIT>']).transpose()  <EOL>self.delta = self._delta()<EOL>self.origin = numpy.array([h['<STR_LIT>'], h['<STR_LIT>'], h['<STR_LIT>']]) + <NUM_LIT:0.5>*numpy.diagonal(self.delta)<EOL>self.rank = h['<STR_LIT>']<EOL>

Populate the instance from the plt file *filename*.


return [self.delta[d,d] * numpy.arange(self.shape[d]+<NUM_LIT:1>) + self.origin[d]- <NUM_LIT:0.5>*self.delta[d,d]     for d in range(self.rank)]<EOL>


nheader = struct.calcsize(self._headerfmt)<EOL>names = [r.key for r in self._header_struct]<EOL>binheader = pltfile.read(nheader)<EOL>def decode_header(bsaflag='<STR_LIT:@>'):<EOL><INDENT>h = dict(zip(names, struct.unpack(bsaflag+self._headerfmt, binheader)))<EOL>h['<STR_LIT>'] = bsaflag<EOL>return h<EOL><DEDENT>for flag in '<STR_LIT>':<EOL><INDENT>header = decode_header(flag)<EOL>if header['<STR_LIT>'] == <NUM_LIT:3>:<EOL><INDENT>break   <EOL><DEDENT>header = None<EOL><DEDENT>if header is None:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>for rec in self._header_struct:<EOL><INDENT>if not rec.is_legal_dict(header):<EOL><INDENT>warnings.warn("<STR_LIT>" % (rec.key, header[rec.key]))<EOL><DEDENT><DEDENT>return header<EOL>

Read header bytes, try all possibilities for byte order/size/alignment.


return (self.array, self.edges)<EOL>


try:<EOL><INDENT>return x.grid<EOL><DEDENT>except AttributeError:<EOL><INDENT>return x<EOL><DEDENT>

Access the underlying ndarray of a Grid object or return the object itself


<EOL>arrs = tuple(arrs)<EOL>lens = list(map(len, arrs))<EOL>dim = len(arrs)<EOL>sz = <NUM_LIT:1><EOL>for s in lens:<EOL><INDENT>sz *= s<EOL><DEDENT>ans = []<EOL>for i, arr in enumerate(arrs):<EOL><INDENT>slc = [<NUM_LIT:1>] * dim<EOL>slc[i] = lens[i]<EOL>arr2 = numpy.asanyarray(arr).reshape(slc)<EOL>for j, sz in enumerate(lens):<EOL><INDENT>if j != i:<EOL><INDENT>arr2 = arr2.repeat(sz, axis=j)<EOL><DEDENT><DEDENT>ans.append(arr2)<EOL><DEDENT>return tuple(ans)<EOL>

Return a mesh grid for N dimensions.

    The input are N arrays, each of which contains the values along one axis of
    the coordinate system. The arrays do not have to have the same number of
    entries. The function returns arrays that can be fed into numpy functions
    so that they produce values for *all* points spanned by the axes *arrs*.

    Original from
    http://stackoverflow.com/questions/1827489/numpy-meshgrid-in-3d and fixed.

    .. SeeAlso: :func:`numpy.meshgrid` for the 2D case.


def __init__(self, grid=None, edges=None, origin=None, delta=None,<EOL>metadata={}, interpolation_spline_order=<NUM_LIT:3>):

<EOL>self._exporters = {<EOL>'<STR_LIT>': self._export_dx,<EOL>'<STR_LIT>': self._export_python,<EOL>'<STR_LIT>': self._export_python,  <EOL>'<STR_LIT>': self._export_python,  <EOL>}<EOL>self._loaders = {<EOL>'<STR_LIT>': self._load_cpp4,<EOL>'<STR_LIT>': self._load_dx,<EOL>'<STR_LIT>': self._load_plt,<EOL>'<STR_LIT>': self._export_python,<EOL>'<STR_LIT>': self._load_python,  <EOL>'<STR_LIT>': self._load_python,  <EOL>}<EOL>self.metadata = metadata<EOL>self.__interpolated = None  <EOL>self.__interpolation_spline_order = interpolation_spline_order<EOL>self.interpolation_cval = None  <EOL>if type(grid) is str:<EOL><INDENT>self.load(grid)<EOL><DEDENT>elif not (grid is None or edges is None):<EOL><INDENT>self.grid = numpy.asanyarray(grid)<EOL>self.edges = edges<EOL>self._update()<EOL><DEDENT>elif not (grid is None or origin is None or delta is None):<EOL><INDENT>origin = numpy.asanyarray(origin)<EOL>delta = numpy.asanyarray(delta)<EOL>if len(origin) != grid.ndim:<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>")<EOL><DEDENT>if delta.shape == () and numpy.isreal(delta):<EOL><INDENT>delta = numpy.ones(grid.ndim) * delta<EOL><DEDENT>elif delta.ndim > <NUM_LIT:1>:<EOL><INDENT>raise NotImplementedError(<EOL>"<STR_LIT>")<EOL><DEDENT>elif len(delta) != grid.ndim:<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>self.edges = [origin[dim] +<EOL>(numpy.arange(m + <NUM_LIT:1>) - <NUM_LIT:0.5>) * delta[dim]<EOL>for dim, m in enumerate(grid.shape)]<EOL>self.grid = numpy.asanyarray(grid)<EOL>self._update()<EOL><DEDENT>else:<EOL><INDENT>pass<EOL><DEDENT>

Create a Grid object from data.

From a numpy.histogramdd()::

  grid,edges = numpy.histogramdd(...)
  g = Grid(grid,edges=edges)

From an arbitrary grid::

  g = Grid(grid,origin=origin,delta=delta)

From a saved file::

  g = Grid(filename)

or ::

  g = Grid()
  g.load(filename)

:Arguments:
  grid
    histogram or density, defined on numpy nD array
  edges
    list of arrays, the lower and upper bin edges along the axes
    (both are output by numpy.histogramdd())
  origin
    cartesian coordinates of the center of grid[0,0,...,0]
  delta
    Either n x n array containing the cell lengths in each dimension,
    or n x 1 array for rectangular arrays.
  metadata
    a user defined dictionary of arbitrary values
    associated with the density; the class does not touch
    metadata[] but stores it with save()
  interpolation_spline_order
    order of interpolation function for resampling; cubic splines = 3 [3]


return self.__interpolation_spline_order<EOL>

Order of the B-spline interpolation of the data.

        3 = cubic; 4 & 5 are also supported

        Only choose values that are acceptable to
        :func:`scipy.ndimage.spline_filter`!

        See Also
        --------
        interpolated


self.__interpolation_spline_order = x<EOL>self._update()<EOL>

Setting the ``interpolation_spline_order`` updates :func:`interpolated`

        Because we cache the interpolation function, we need to rebuild the
        cache whenever the interpolation order changes: this is
        handled by :meth:`_update`


try:<EOL><INDENT>edges = edges.edges  <EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>midpoints = self._midpoints(edges)<EOL>coordinates = ndmeshgrid(*midpoints)<EOL>newgrid = self.interpolated(*coordinates)<EOL>return self.__class__(newgrid, edges)<EOL>

Resample data to a new grid with edges *edges*.

        This method creates a new grid with the data from the current
        grid resampled to a regular grid specified by *edges*.  The
        order of the interpolation is set by
        :attr:`Grid.interpolation_spline_order`: change the value
        *before* calling :meth:`resample`.

        Parameters
        ----------
        edges : tuple of arrays or Grid
             edges of the new grid or a :class:`Grid` instance that
             provides :attr:`Grid.edges`

        Returns
        -------
        Grid
             a new :class:`Grid` with the data interpolated over the
             new grid cells

        Examples
        --------

        Providing *edges* (a tuple of three arrays, indicating the
        boundaries of each grid cell)::

          g = grid.resample(edges)

        As a convenience, one can also supply another :class:`Grid` as
        the argument for this method ::

          g = grid.resample(othergrid)

        and the edges are taken from :attr:`Grid.edges`.


<EOL>newlengths = [(N - <NUM_LIT:1>) * float(factor) + <NUM_LIT:1> for N in self._len_edges()]<EOL>edges = [numpy.linspace(start, stop, num=int(N), endpoint=True)<EOL>for (start, stop, N) in<EOL>zip(self._min_edges(), self._max_edges(), newlengths)]<EOL>return self.resample(edges)<EOL>

Resample to a new regular grid.

        Parameters
        ----------
        factor : float
            The number of grid cells are scaled with `factor` in each
            dimension, i.e., ``factor * N_i`` cells along each
            dimension i.

        Returns
        -------
        Grid

        See Also
        --------
        resample


self.delta = numpy.array(list(<EOL>map(lambda e: (e[-<NUM_LIT:1>] - e[<NUM_LIT:0>]) / (len(e) - <NUM_LIT:1>), self.edges)))<EOL>self.midpoints = self._midpoints(self.edges)<EOL>self.origin = numpy.array(list(map(lambda m: m[<NUM_LIT:0>], self.midpoints)))<EOL>if self.__interpolated is not None:<EOL><INDENT>self.__interpolated = self._interpolationFunctionFactory()<EOL><DEDENT>

compute/update all derived data

        Can be called without harm and is idem-potent.

        Updates these attributes and methods:
           :attr:`origin`
              the center of the cell with index 0,0,0
           :attr:`midpoints`
              centre coordinate of each grid cell
           :meth:`interpolated`
              spline interpolation function that can generated a value for
              coordinate


if self.__interpolated is None:<EOL><INDENT>self.__interpolated = self._interpolationFunctionFactory()<EOL><DEDENT>return self.__interpolated<EOL>

B-spline function over the data grid(x,y,z).

        The :func:`interpolated` function allows one to obtain data
        values for any values of the coordinates::

           interpolated([x1,x2,...],[y1,y2,...],[z1,z2,...]) -> F[x1,y1,z1],F[x2,y2,z2],...

        The interpolation order is set in
        :attr:`Grid.interpolation_spline_order`.

        The interpolated function is computed once and is cached for better
        performance. Whenever :attr:`~Grid.interpolation_spline_order` is
        modified, :meth:`Grid.interpolated` is recomputed.

        The value for unknown data is set in :attr:`Grid.interpolation_cval`
        (TODO: also recompute when ``interpolation_cval`` value is changed.)

        Example
        -------
        Example usage for resampling::

           XX, YY, ZZ = numpy.mgrid[40:75:0.5, 96:150:0.5, 20:50:0.5]
           FF = interpolated(XX, YY, ZZ)

        Note
        ----
        Values are interpolated with a spline function. It is possible
        that the spline will generate values that would not normally
        appear in the data. For example, a density is non-negative but
        a cubic spline interpolation can generate negative values,
        especially at the boundary between 0 and high values.


def load(self, filename, file_format=None):

loader = self._get_loader(filename, file_format=file_format)<EOL>loader(filename)<EOL>

Load saved (pickled or dx) grid and edges from <filename>.pickle

           Grid.load(<filename>.pickle)
           Grid.load(<filename>.dx)

        The load() method calls the class's constructor method and
        completely resets all values, based on the loaded data.


ccp4 = CCP4.CCP4()<EOL>ccp4.read(filename)<EOL>grid, edges = ccp4.histogramdd()<EOL>self.__init__(grid=grid, edges=edges, metadata=self.metadata)<EOL>


dx = OpenDX.field(<NUM_LIT:0>)<EOL>dx.read(filename)<EOL>grid, edges = dx.histogramdd()<EOL>self.__init__(grid=grid, edges=edges, metadata=self.metadata)<EOL>


g = gOpenMol.Plt()<EOL>g.read(filename)<EOL>grid, edges = g.histogramdd()<EOL>self.__init__(grid=grid, edges=edges, metadata=self.metadata)<EOL>


def export(self, filename, file_format=None, type=None, typequote='<STR_LIT:">'):

exporter = self._get_exporter(filename, file_format=file_format)<EOL>exporter(filename, type=type, typequote=typequote)<EOL>

export density to file using the given format.

        The format can also be deduced from the suffix of the filename
        though the *format* keyword takes precedence.

        The default format for export() is 'dx'.  Use 'dx' for
        visualization.

        Implemented formats:

        dx
            :mod:`OpenDX`
        pickle
            pickle (use :meth:`Grid.load` to restore); :meth:`Grid.save`
            is simpler than ``export(format='python')``.

        Parameters
        ----------

        filename : str
            name of the output file

        file_format : {'dx', 'pickle', None} (optional)
            output file format, the default is "dx"

        type : str (optional)
            for DX, set the output DX array type, e.g., "double" or "float".
            By default (``None``), the DX type is determined from the numpy
            dtype of the array of the grid (and this will typically result in
            "double").

            .. versionadded:: 0.4.0

        typequote : str (optional)
            For DX, set the character used to quote the type string;
            by default this is a double-quote character, '"'.
            Custom parsers like the one from NAMD-GridForces (backend for MDFF)
            expect no quotes, and typequote='' may be used to appease them.

            .. versionadded:: 0.5.0


def _export_python(self, filename, **kwargs):

data = dict(grid=self.grid, edges=self.edges, metadata=self.metadata)<EOL>with open(filename, '<STR_LIT:wb>') as f:<EOL><INDENT>cPickle.dump(data, f, cPickle.HIGHEST_PROTOCOL)<EOL><DEDENT>

Pickle the Grid object

        The object is dumped as a dictionary with grid and edges: This
        is sufficient to recreate the grid object with __init__().


def _export_dx(self, filename, type=None, typequote='<STR_LIT:">', **kwargs):

root, ext = os.path.splitext(filename)<EOL>filename = root + '<STR_LIT>'<EOL>comments = [<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'<EOL>]<EOL>if self.metadata:<EOL><INDENT>comments.append('<STR_LIT>')<EOL><DEDENT>for k in self.metadata:<EOL><INDENT>comments.append('<STR_LIT:U+0020>' + str(k) + '<STR_LIT>' + str(self.metadata[k]))<EOL><DEDENT>comments.append(<EOL>'<STR_LIT>')<EOL>components = dict(<EOL>positions=OpenDX.gridpositions(<NUM_LIT:1>, self.grid.shape, self.origin,<EOL>self.delta),<EOL>connections=OpenDX.gridconnections(<NUM_LIT:2>, self.grid.shape),<EOL>data=OpenDX.array(<NUM_LIT:3>, self.grid, type=type, typequote=typequote),<EOL>)<EOL>dx = OpenDX.field('<STR_LIT>', components=components, comments=comments)<EOL>dx.write(filename)<EOL>

Export the density grid to an OpenDX file.

        The file format is the simplest regular grid array and it is
        also understood by VMD's and Chimera's DX reader; PyMOL
        requires the dx `type` to be set to "double".

        For the file format see
        http://opendx.sdsc.edu/docs/html/pages/usrgu068.htm#HDREDF


self.export(filename, file_format="<STR_LIT>")<EOL>

Save a grid object to <filename>.pickle

        Internally, this calls
        ``Grid.export(filename, format="python")``. A grid can be
        regenerated from the saved data with ::

           g = Grid(filename="grid.pickle")

        .. note::
           The pickle format depends on the Python version and
           therefore it is not guaranteed that a grid saved with, say,
           Python 2.7 can also be read with Python 3.5. The OpenDX format
           is a better alternative for portability.


for idx in numpy.ndindex(self.grid.shape):<EOL><INDENT>yield self.delta * numpy.array(idx) + self.origin<EOL><DEDENT>

Returns the coordinates of the centers of all grid cells as an
        iterator.


if not (numpy.isreal(other) or self == other):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>return True<EOL>

Check if *other* can be used in an arithmetic operation.

        1) *other* is a scalar
        2) *other* is a grid defined on the same edges

        :Raises: :exc:`TypeError` if not compatible.


def _interpolationFunctionFactory(self, spline_order=None, cval=None):

<EOL>import scipy.ndimage<EOL>if spline_order is None:<EOL><INDENT>spline_order = self.interpolation_spline_order<EOL><DEDENT>if cval is None:<EOL><INDENT>cval = self.interpolation_cval<EOL><DEDENT>data = self.grid<EOL>if cval is None:<EOL><INDENT>cval = data.min()<EOL><DEDENT>try:<EOL><INDENT>_data = data.filled(cval)<EOL><DEDENT>except AttributeError:<EOL><INDENT>_data = data<EOL><DEDENT>coeffs = scipy.ndimage.spline_filter(_data, order=spline_order)<EOL>x0 = self.origin<EOL>dx = self.delta<EOL>def _transform(cnew, c0, dc):<EOL><INDENT>return (numpy.atleast_1d(cnew) - c0) / dc<EOL><DEDENT>def interpolatedF(*coordinates):<EOL><INDENT>"""<STR_LIT>"""<EOL>_coordinates = numpy.array(<EOL>[_transform(coordinates[i], x0[i], dx[i]) for i in range(len(<EOL>coordinates))])<EOL>return scipy.ndimage.map_coordinates(coeffs,<EOL>_coordinates,<EOL>prefilter=False,<EOL>mode='<STR_LIT>',<EOL>cval=cval)<EOL><DEDENT>return interpolatedF<EOL>

Returns a function F(x,y,z) that interpolates any values on the grid.

        _interpolationFunctionFactory(self,spline_order=3,cval=None) --> F

        *cval* is set to :meth:`Grid.grid.min`. *cval* cannot be chosen too
        large or too small or NaN because otherwise the spline interpolation
        breaks down near that region and produces wild oscillations.

        .. Note:: Only correct for equally spaced values (i.e. regular edges with
                  constant delta).
        .. SeeAlso:: http://www.scipy.org/Cookbook/Interpolation


@staticmethod<EOL><INDENT>def show_clusters(sample, clusters, representatives, **kwargs):<DEDENT>

figure = kwargs.get('<STR_LIT>', None)<EOL>display = kwargs.get('<STR_LIT>', True)<EOL>offset = kwargs.get('<STR_LIT>', <NUM_LIT:0>)<EOL>visualizer = cluster_visualizer()<EOL>visualizer.append_clusters(clusters, sample, canvas=offset)<EOL>for cluster_index in range(len(clusters)):<EOL><INDENT>visualizer.append_cluster_attribute(offset, cluster_index, [representatives[cluster_index]], '<STR_LIT:*>', <NUM_LIT:10>)<EOL><DEDENT>return visualizer.show(figure=figure, display=display)<EOL>

!
        @brief Display BSAS clustering results.

        @param[in] sample (list): Dataset that was used for clustering.
        @param[in] clusters (array_like): Clusters that were allocated by the algorithm.
        @param[in] representatives (array_like): Allocated representatives correspond to clusters.
        @param[in] **kwargs: Arbitrary keyword arguments (available arguments: 'figure', 'display', 'offset').

        Keyword Args:

            - figure (figure): If 'None' then new is figure is created, otherwise specified figure is used for visualization.
            - display (bool): If 'True' then figure will be shown by the method, otherwise it should be shown manually using matplotlib function 'plt.show()'.
            - offset (uint): Specify axes index on the figure where results should be drawn (only if argument 'figure' is specified).

        @return (figure) Figure where clusters were drawn.


def __init__(self, data, maximum_clusters, threshold, ccore=True, **kwargs):

self._data = data;<EOL>self._amount = maximum_clusters;<EOL>self._threshold = threshold;<EOL>self._metric = kwargs.get('<STR_LIT>', distance_metric(type_metric.EUCLIDEAN));<EOL>self._ccore = ccore and self._metric.get_type() != type_metric.USER_DEFINED;<EOL>self._clusters = [];<EOL>self._representatives = [];<EOL>if self._ccore is True:<EOL><INDENT>self._ccore = ccore_library.workable();<EOL><DEDENT>

!
        @brief Creates classical BSAS algorithm.

        @param[in] data (list): Input data that is presented as list of points (objects), each point should be represented by list or tuple.
        @param[in] maximum_clusters: Maximum allowable number of clusters that can be allocated during processing.
        @param[in] threshold: Threshold of dissimilarity (maximum distance) between points.
        @param[in] ccore (bool): If True than DLL CCORE (C++ solution) will be used for solving.
        @param[in] **kwargs: Arbitrary keyword arguments (available arguments: 'metric').

        Keyword Args:

            - metric (distance_metric): Metric that is used for distance calculation between two points.


if self._ccore is True:<EOL><INDENT>self.__process_by_ccore();<EOL><DEDENT>else:<EOL><INDENT>self.__prcess_by_python();<EOL><DEDENT>

!
        @brief Performs cluster analysis in line with rules of BSAS algorithm.

        @remark Results of clustering can be obtained using corresponding get methods.

        @see get_clusters()
        @see get_representatives()


return self._clusters<EOL>

!
        @brief Returns list of allocated clusters, each cluster contains indexes of objects in list of data.

        @see process()
        @see get_representatives()


return self._representatives<EOL>

!
        @brief Returns list of representatives of allocated clusters.

        @see process()
        @see get_clusters()


return type_encoding.CLUSTER_INDEX_LIST_SEPARATION<EOL>

!
        @brief Returns clustering result representation type that indicate how clusters are encoded.

        @return (type_encoding) Clustering result representation.

        @see get_clusters()


index_cluster = -<NUM_LIT:1>;<EOL>nearest_distance = float('<STR_LIT>');<EOL>for index in range(len(self._representatives)):<EOL><INDENT>distance = self._metric(point, self._representatives[index]);<EOL>if distance < nearest_distance:<EOL><INDENT>index_cluster = index;<EOL>nearest_distance = distance;<EOL><DEDENT><DEDENT>return index_cluster, nearest_distance<EOL>

!
        @brief Find nearest cluster to the specified point.

        @param[in] point (list): Point from dataset.

        @return (uint, double) Index of nearest cluster and distance to it.


def _update_representative(self, index_cluster, point):

length = len(self._clusters[index_cluster]);<EOL>rep = self._representatives[index_cluster];<EOL>for dimension in range(len(rep)):<EOL><INDENT>rep[dimension] = ( (length - <NUM_LIT:1>) * rep[dimension] + point[dimension] ) / length;<EOL><DEDENT>

!
        @brief Update cluster representative in line with new cluster size and added point to it.

        @param[in] index_cluster (uint): Index of cluster whose representative should be updated.
        @param[in] point (list): Point that was added to cluster.


def __init__(self, data, amount_centers):

self.__data = data<EOL>self.__amount = amount_centers<EOL>self.__available_indexes = set(list(range(len(self.__data))))<EOL>if self.__amount <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if self.__amount > len(self.__data):<EOL><INDENT>raise ValueError("<STR_LIT>" % self.__amount)<EOL><DEDENT>

!
        @brief Creates instance of random center initializer.

        @param[in] data (list): List of points where each point is represented by list of coordinates.
        @param[in] amount_centers (unit): Amount of centers that should be initialized.


return_index = kwargs.get('<STR_LIT>', False)<EOL>if self.__amount == len(self.__data):<EOL><INDENT>if return_index:<EOL><INDENT>return list(range(len(self.__data)))<EOL><DEDENT>return self.__data[:]<EOL><DEDENT>return [self.__create_center(return_index) for _ in range(self.__amount)]<EOL>

!
        @brief Generates random centers in line with input parameters.

        @param[in] **kwargs: Arbitrary keyword arguments (available arguments: 'return_index').

        Keyword Args:

            - return_index (bool): If True then returns indexes of points from input data instead of points itself.

        @return (list) List of initialized initial centers.
                  If argument 'return_index' is False then returns list of points.
                  If argument 'return_index' is True then returns list of indexes.


random_index_point = random.randint(<NUM_LIT:0>, len(self.__data[<NUM_LIT:0>]))<EOL>if random_index_point not in self.__available_indexes:<EOL><INDENT>random_index_point = self.__available_indexes.pop()<EOL><DEDENT>else:<EOL><INDENT>self.__available_indexes.remove(random_index_point)<EOL><DEDENT>if return_index:<EOL><INDENT>return random_index_point<EOL><DEDENT>return self.__data[random_index_point]<EOL>

!
        @brief Generates and returns random center.

        @param[in] return_index (bool): If True then returns index of point from input data instead of point itself.


def __init__(self, data, amount_centers, amount_candidates = <NUM_LIT:1>):

self.__data = numpy.array(data)<EOL>self.__amount = amount_centers<EOL>self.__candidates = amount_candidates<EOL>self.__free_indexes = set(range(len(self.__data)))<EOL>self.__check_parameters()<EOL>

!
        @brief Creates K-Means++ center initializer instance.

        @param[in] data (array_like): List of points where each point is represented by list of coordinates.
        @param[in] amount_centers (uint): Amount of centers that should be initialized.
        @param[in] amount_candidates (uint): Amount of candidates that is considered as a center, if the farthest points (with the highest probability) should
                    be considered as centers then special constant should be used 'FARTHEST_CENTER_CANDIDATE'.

        @see FARTHEST_CENTER_CANDIDATE