Example #1
0
def export_to_cluster_file(cells,
                           cluster_file,
                           neighbours=None,
                           neighbours_kwargs={},
                           new_cell=Translocations,
                           distributed_kwargs={},
                           **kwargs):
    not_2D = ValueError('data are not 2D')
    if isinstance(cells, Distributed):
        if cells.dim != 2:
            raise not_2D
        zones = cells
    else:
        if cells.tessellation._cell_centers.shape[1] != 2:
            raise not_2D
        zones = distributed(cells, new_cell=new_cell, **distributed_kwargs)
    if neighbours is None:
        neighbours = neighbours_per_axis
    with open(cluster_file, 'w') as f:
        for i in zones:
            zone = zones[i]
            f.write('ZONE: {}\n'.format(i + 1))
            f.write('NUMBER_OF_TRANSLOCATIONS: {}\n'.format(len(zone)))
            f.write('X-CENTRE: {}\n'.format(zone.center[0]))
            f.write('Y-CENTRE: {}\n'.format(zone.center[1]))
            #area = np.prod(np.max(zone.span, axis=0) - np.min(zone.span, axis=0))
            area = zone.volume
            f.write('AREA: {}\n'.format(area))
            f.write('AREA_CONVHULL: {}\n'.format(area))
            below, above = neighbours(i, zones, **neighbours_kwargs)
            _neighbours = zones.adjacency[i].indices
            _neighbours = OrderedDict(
                left=_neighbours[below[0]],
                right=_neighbours[above[0]],
                top=_neighbours[above[1]],
                bottom=_neighbours[below[1]],
            )
            for side in _neighbours:
                f.write('NUMBER_OF_{}_NEIGHBOURS: {}\n'.format(
                    side.upper(), _neighbours[side].size))
                if _neighbours[side].size:
                    f.write('{}_NEIGHBOURS: '.format(side.upper()))
                    for j in _neighbours[side]:
                        f.write('{}\t'.format(j + 1))
                    f.write('\n')
            f.write('DX\tDY\tDT\n')
            for dx, dy, dt in np.hstack((zone.dr, zone.dt[:, np.newaxis])):
                f.write('{}\t{}\t{}\n'.format(dx, dy, dt))
            f.write('\n\n')
Example #2
0
def truth(cells,
          t=None,
          diffusivity=None,
          force=None,
          potential=None,
          **kwargs):
    """
    Generate maps for the true diffusivity/force distribution.

    If `cells` is a :class:`~tramway.tessellation.base.CellStats` object,
    :func:`~tramway.inference.base.distributed` is called on `cells` and with the trailing
    keyword arguments to build a :class:`~tramway.inference.base.Distributed` object.

    Arguments:

        cells (CellStats or Distributed): distributed data ready for inference

        t (float): time as understood by `diffusivity` and `force`

        diffusivity (callable): admits the coordinates of a single location (array-like)
            and time (float, if `t` is defined) and returns the local diffusivity (float)

        force (callable): admits the coordinates of a single location (array-like)
            and time (float, if `t` is defined) and returns the local force (array-like)

        potential (callable): admits the coordinates of a single location (array-like)
            and time (float, if `t` is defined) and returns the local potential energy (float)

    Returns:

        pandas.DataFrame: diffusivity/force maps
    """
    try:
        cells.cells
    except AttributeError:
        import tramway.inference as ti
        cells = ti.distributed(cells, **kwargs)
    I, DVF = [], []
    for i in cells.cells:
        cell = cells.cells[i]
        if not I:
            dim = cell.center.size
        I.append(i)
        if diffusivity is None:
            D = []
        elif t is None:
            D = [diffusivity(cell.center)]
        else:
            D = [diffusivity(cell.center, t)]
        if force is None:
            F = []
        elif t is None:
            F = force(cell.center)
        else:
            F = force(cell.center, t)
        if potential is None:
            V = []
        elif t is None:
            V = [potential(cell.center)]
        else:
            V = [potential(cell.center, t)]
        DVF.append(np.concatenate((D, V, F)))
    DVF = np.vstack(DVF)
    if diffusivity is None:
        columns = []
    else:
        columns = ['diffusivity']
    if potential is not None:
        columns.append('potential')
    if force is not None:
        columns += ['force x' + str(col + 1) for col in range(dim)]
    return pd.DataFrame(index=I, data=DVF, columns=columns)
Example #3
0
def export_to_vmesh_file(cells,
                         maps,
                         vmesh_file,
                         cluster_file=None,
                         auto=False,
                         new_cell=Translocations,
                         distributed_kwargs={},
                         **kwargs):
    not_2D = ValueError('data are not 2D')
    if isinstance(cells, Distributed):
        if cells.dim != 2:
            raise not_2D
        zones = cells
    else:
        if cells.tessellation._cell_centers.shape[1] != 2:
            raise not_2D
        zones = distributed(cells, new_cell=new_cell, **distributed_kwargs)
    with open(vmesh_file, 'w') as f:
        # Input File
        if cluster_file is None and auto:
            dirname, basename = os.path.split(vmesh_file)
            cluster_files = [
                fn for fn in os.listdir(dirname if dirname else '.')
                if fn.endswith('.cluster') and basename.startswith(fn[:8])
            ]
            if cluster_files:
                if cluster_files[1:]:
                    print('multiple cluster files match:')
                    for fn in cluster_files:
                        print('\t' + fn)
                cluster_file = cluster_files[0]
            else:
                cluster_file = ''
        if cluster_file is not None:
            f.write('Input File: {}\n'.format(cluster_file))
        # Inference Mode
        mode = maps.mode.upper()
        if mode is None and auto:
            if 'potential' in maps.features:
                mode = 'DV'
            elif 'force' in maps.features:
                mode = 'DF'
            elif 'drift' in maps.features:
                mode = 'DD'
            else:
                mode = 'D'
        if mode is not None:
            f.write('Inference Mode: {}\n'.format(mode))
        # Localization Error
        err = maps.localization_error
        if err is None and auto:
            err = .03
        if err is not None:
            f.write('Localization Error: {:f} [nm]\n'.format(err * 1e3))
        # Number of Zones
        f.write('Number of Zones: {}\n'.format(len(zones)))
        # Diffusion Prior
        dp = maps.diffusivity_prior
        if dp is None and auto:
            dp = 0.
        if dp is not None:
            f.write('Diffusion Prior: {:f}\n'.format(dp))
        # Potential Prior
        vp = maps.potential_prior
        if vp is None and auto:
            vp = 0.
        if vp is not None:
            f.write('Potential Prior: {:f}\n'.format(vp))
        # Jeffreys' Prior
        jp = maps.jeffreys_prior
        if jp is None and auto:
            jp = 0
        if jp is not None:
            f.write("Jeffreys' Prior: {:d}\n".format(jp))
        # table header
        f.write('\nZone ID\tTranslocations\tx-Centre\ty-Centre')
        na = np.isnan(maps.maps.values) | np.isinf(maps.maps.values)
        ok = ~np.all(na, axis=1)
        data0 = [[i, len(zones[i]), zones[i].center]
                 for i in maps.maps.index[ok]]
        data1 = []
        nvars = 0
        if 'diffusivity' in maps.features:
            f.write('\tDiffusion')
            data1.append(maps['diffusivity'].values[ok])
            nvars += 1
        if 'force' in maps.features:
            f.write('\tx-Force\ty-Force')
            data1.append(maps['force'].values[ok])
            nvars += 2
        if 'potential' in maps.features:
            f.write('\tPotential')
            data1.append(maps['potential'].values[ok])
            nvars += 1
        # table data
        data1 = np.hstack(data1)
        fmt0 = '\n{:d}\t{:d}\t{:f}\t{:f}'
        for r, s in zip(data0, data1):
            i, n, r = r
            s = ['NA' if np.isnan(x) or np.isinf(x) else x for x in s]
            fmt1 = '\t{' + '}\t{'.join('' if x is 'NA' else ':f'
                                       for x in s) + '}'
            f.write((fmt0 + fmt1).format(i, n, *(r.tolist() + s)))
Example #4
0
def export_to_vmesh_file(cells,
                         maps,
                         vmesh_file,
                         cluster_file=None,
                         auto=False,
                         new_cell=Translocations,
                         distributed_kwargs={},
                         **kwargs):
    not_2D = ValueError("data are not 2D")
    if isinstance(cells, Distributed):
        if cells.dim != 2:
            raise not_2D
        zones = cells
    else:
        if cells.tessellation._cell_centers.shape[1] != 2:
            raise not_2D
        zones = distributed(cells, new_cell=new_cell, **distributed_kwargs)
    with open(vmesh_file, "w") as f:
        # Input File
        if cluster_file is None and auto:
            dirname, basename = os.path.split(vmesh_file)
            cluster_files = [
                fn for fn in os.listdir(dirname if dirname else ".")
                if fn.endswith(".cluster") and basename.startswith(fn[:8])
            ]
            if cluster_files:
                if cluster_files[1:]:
                    print("multiple cluster files match:")
                    for fn in cluster_files:
                        print("\t" + fn)
                cluster_file = cluster_files[0]
            else:
                cluster_file = ""
        if cluster_file is not None:
            f.write("Input File: {}\n".format(cluster_file))
        # Inference Mode
        mode = maps.mode.upper()
        if mode is None and auto:
            if "potential" in maps.features:
                mode = "DV"
            elif "force" in maps.features:
                mode = "DF"
            elif "drift" in maps.features:
                mode = "DD"
            else:
                mode = "D"
        if mode is not None:
            f.write("Inference Mode: {}\n".format(mode))
        # Localization Error
        err = maps.localization_error
        if err is None and auto:
            err = 0.03
        if err is not None:
            f.write("Localization Error: {:f} [nm]\n".format(err * 1e3))
        # Number of Zones
        f.write("Number of Zones: {}\n".format(len(zones)))
        # Diffusion Prior
        dp = maps.diffusivity_prior
        if dp is None and auto:
            dp = 0.0
        if dp is not None:
            f.write("Diffusion Prior: {:f}\n".format(dp))
        # Potential Prior
        vp = maps.potential_prior
        if vp is None and auto:
            vp = 0.0
        if vp is not None:
            f.write("Potential Prior: {:f}\n".format(vp))
        # Jeffreys' Prior
        jp = maps.jeffreys_prior
        if jp is None and auto:
            jp = 0
        if jp is not None:
            f.write("Jeffreys' Prior: {:d}\n".format(jp))
        # table header
        f.write("\nZone ID\tTranslocations\tx-Centre\ty-Centre")
        na = np.isnan(maps.maps.values) | np.isinf(maps.maps.values)
        ok = ~np.all(na, axis=1)
        data0 = [[i, len(zones[i]), zones[i].center]
                 for i in maps.maps.index[ok]]
        data1 = []
        nvars = 0
        if "diffusivity" in maps.features:
            f.write("\tDiffusion")
            data1.append(maps["diffusivity"].values[ok])
            nvars += 1
        if "force" in maps.features:
            f.write("\tx-Force\ty-Force")
            data1.append(maps["force"].values[ok])
            nvars += 2
        if "potential" in maps.features:
            f.write("\tPotential")
            data1.append(maps["potential"].values[ok])
            nvars += 1
        # table data
        data1 = np.hstack(data1)
        fmt0 = "\n{:d}\t{:d}\t{:f}\t{:f}"
        for r, s in zip(data0, data1):
            i, n, r = r
            s = ["NA" if np.isnan(x) or np.isinf(x) else x for x in s]
            fmt1 = "\t{" + "}\t{".join("" if x == "NA" else ":f"
                                       for x in s) + "}"
            f.write((fmt0 + fmt1).format(i, n, *(r.tolist() + s)))