Example #1
0
def get_covalent_chains(molecular_system,
                        chain=None,
                        selection='all',
                        syntaxis='MolSysMT',
                        check=True):

    if check:
        from molsysmt.tools.molecular_system import is_molecular_system
        if not is_molecular_system(molecular_system):
            raise MolecularSystemNeededError()

    from molsysmt.topology.get_bondgraph import get_bondgraph

    if selection is 'all':
        mask = None
    else:
        mask = select(molecular_system,
                      selection=selection,
                      syntaxis=syntaxis,
                      check=False)

    chain_atom_indices = []

    for sel_in_chain in chain:
        atom_indices = select(molecular_system,
                              selection=sel_in_chain,
                              mask=mask)
        chain_atom_indices.append(atom_indices)

    atom_indices = np.sort(np.unique(np.concatenate(chain_atom_indices)))

    graph = get_bondgraph(molecular_system,
                          selection=atom_indices,
                          nodes_name='atom_index',
                          check=False)

    n_slaves = len(chain_atom_indices)

    output = [[ii] for ii in chain_atom_indices[0]]
    for slave_index in range(n_slaves):
        chain_atom_indices[slave_index] = set(chain_atom_indices[slave_index])

    for slave_index in range(1, n_slaves):
        slave_preindex = slave_index - 1
        tmp_output = output.copy()
        output = []
        for chain in tmp_output:
            for ii in graph.neighbors(chain[slave_preindex]):
                if ii in chain_atom_indices[slave_index]:
                    new_chain = chain.copy()
                    new_chain.append(ii)
                    output.append(new_chain)
    del (graph)

    return np.array(output, dtype=int)
Example #2
0
def remove_solvent(molecular_system,
                   water=True,
                   ions=True,
                   cosolutes=True,
                   include_selection=None,
                   exclude_selection=None,
                   syntaxis='MolSysMT'):

    from molsysmt.basic import select, remove

    molecular_system = digest_molecular_system(molecular_system)
    syntaxis = digest_syntaxis(syntaxis)

    atom_indices_to_be_removed = []
    atom_indices_water = []
    atom_indices_ions = []
    atom_indices_cosolutes = []
    atom_indices_included = []
    atom_indices_excluded = []

    if water:
        atom_indices_water = select(molecular_system, 'group_type=="water"')

    if ions:
        atom_indices_ions = select(molecular_system, 'group_type=="ion"')

    if cosolutes:
        atom_indices_cosolutes = select(molecular_system,
                                        'group_type=="cosolute"')

    atom_indices_to_be_removed = list(
        (set(atom_indices_water) | set(atom_indices_ions)
         | set(atom_indices_cosolutes)))

    if include_selection is not None:
        atom_indices_included = select(molecular_system,
                                       selection=include_selection,
                                       syntaxis=syntaxis)
        atom_indices_to_be_removed = list(
            (set(atom_indices_to_be_removed) | set(atom_indices_included)))

    if exclude_selection is not None:
        atom_indices_excluded = select(molecular_system,
                                       selection=exclude_selection,
                                       syntaxis=syntaxis)
        atom_indices_to_be_removed = list(
            (set(atom_indices_to_be_removed) - set(atom_indices_excluded)))

    return remove(molecular_system, atom_indices_to_be_removed)
Example #3
0
def show_colored_cartoon_by_scalar_residue_values(view,
                                                  values,
                                                  selection='all',
                                                  cmap=None,
                                                  vmin=None,
                                                  vmax=None):

    from nglview.color import _ColorScheme
    from molsysmt.basic import select

    groups_selection = select(view,
                              target='group',
                              selection=selection,
                              to_syntaxis='NGLview')

    if vmin is None:
        vmin = min(values)
    if vmax is None:
        vmax = max(values)

    norm = Normalize(vmin=vmin, vmax=vmax)
    scheme = _ColorScheme(
        [[to_hex(cmap(norm(ii))), jj]
         for ii, jj in zip(values, groups_selection.split(' '))],
        label='user')
    view.add_cartoon(selection='protein', color=scheme)

    # It can also be done as:
    # nv.color.ColormakerRegistry.add_scheme('buried_factors',[['#'+ii[2:],str(jj)] for ii,jj in zip(colors, range(706))])
    # view.add_cartoon(selection='protein', color='buried_factors')

    pass
Example #4
0
def show_colored_surface_by_scalar_residue_values(view,
                                                  values,
                                                  selection='all',
                                                  cmap=None,
                                                  vmin=None,
                                                  vmax=None):

    from nglview.color import _ColorScheme
    from molsysmt.basic import select
    from matplotlib.colors import Normalize, to_hex

    groups_selection = select(view,
                              target='group',
                              selection=selection,
                              to_syntaxis='NGLview')

    if vmin is None:
        vmin = min(values)
    if vmax is None:
        vmax = max(values)

    norm = Normalize(vmin=vmin, vmax=vmax)
    scheme = _ColorScheme(
        [[to_hex(cmap(norm(ii))), jj]
         for ii, jj in zip(values, groups_selection.split(' '))],
        label='user')
    view.add_surface(selection='protein', color=scheme)

    pass
Example #5
0
def remove_ions (molecular_system, selection="all", include_selection=None, exclude_selection=None, syntaxis="MolSysMT"):

    from molsysmt.basic import select, remove

    molecular_system = digest_molecular_system(molecular_system)
    syntaxis = digest_syntaxis(syntaxis)

    atom_indices_to_be_removed = select(molecular_system, 'molecule_type=="ion"')

    if include_selection is not None:
        atom_indices_included = select(molecular_system, selection=include_selection, syntaxis=syntaxis)
        atom_indices_to_be_removed = list((set(atom_indices_to_be_removed) | set(atom_indices_included)))

    if exclude_selection is not None:
        atom_indices_excluded = select(molecular_system, selection=exclude_selection, syntaxis=syntaxis)
        atom_indices_to_be_removed = list((set(atom_indices_to_be_removed) - set(atom_indices_excluded)))

    return remove(molecular_system, atom_indices_to_be_removed)
Example #6
0
def remove_waters(molecular_system,
                  selection="all",
                  include_selection=None,
                  exclude_selection=None,
                  syntaxis="MolSysMT",
                  check=True):

    from molsysmt.basic import select, remove, is_molecular_system

    if check:

        if not is_molecular_system(molecular_system):
            raise NeedsSingleMolecularSystemError()

        try:
            syntaxis = digest_syntaxis(syntaxis)
        except:
            raise WrongSyntaxisError()

    atom_indices_to_be_removed = select(molecular_system,
                                        'molecule_type=="water"',
                                        check=False)

    if include_selection is not None:
        atom_indices_included = select(molecular_system,
                                       selection=include_selection,
                                       syntaxis=syntaxis,
                                       check=False)
        atom_indices_to_be_removed = list(
            (set(atom_indices_to_be_removed) | set(atom_indices_included)))

    if exclude_selection is not None:
        atom_indices_excluded = select(molecular_system,
                                       selection=exclude_selection,
                                       syntaxis=syntaxis,
                                       check=False)
        atom_indices_to_be_removed = list(
            (set(atom_indices_to_be_removed) - set(atom_indices_excluded)))

    return remove(molecular_system, atom_indices_to_be_removed)
Example #7
0
def get_center(molecular_system,
               selection='all',
               groups_of_atoms=None,
               weights=None,
               structure_indices='all',
               syntaxis='MolSysMT',
               engine='MolSysMT',
               parallel=False):

    molecular_system = digest_molecular_system(molecular_system)
    engine = digest_engine(engine)

    if engine == 'MolSysMT':

        if groups_of_atoms is None:
            atom_indices = select(molecular_system,
                                  selection=selection,
                                  syntaxis=syntaxis)
            groups_of_atoms = [atom_indices]

        groups_serialized = serialized_lists(groups_of_atoms, dtype='int64')

        if weights is None:
            weights = np.ones((groups_serialized.n_values))
        elif weights is 'masses':
            raise NotImplementedError

        coordinates = get(molecular_system,
                          target='system',
                          structure_indices=structure_indices,
                          coordinates=True)

        length_units = puw.get_unit(coordinates)
        coordinates = np.asfortranarray(puw.get_value(coordinates),
                                        dtype='float64')
        n_atoms = coordinates.shape[1]
        n_structures = coordinates.shape[0]

        com = libcom.center_of_mass(coordinates, groups_serialized.indices,
                                    groups_serialized.values,
                                    groups_serialized.starts, weights,
                                    n_structures, n_atoms,
                                    groups_serialized.n_indices,
                                    groups_serialized.n_values)

        del (coordinates, groups_serialized)

        return com * length_units

    else:

        raise NotImplementedError(NotImplementedMessage)
Example #8
0
def get_missing_heavy_atoms(molecular_system,
                            selection='all',
                            engine='PDBFixer',
                            syntaxis='MolSysMT'):

    engine = digest_engine(engine)

    output = {}

    if engine == "PDBFixer":

        from molsysmt.basic import convert, get_form, select

        correction_group_indices = False
        if selection is not 'all':
            group_indices_in_selection = select(molecular_system,
                                                target='group',
                                                selection=selection)
            correction_group_indices = True

        tmp_item = convert(molecular_system,
                           selection=selection,
                           to_form="pdbfixer.PDBFixer",
                           syntaxis=syntaxis)

        tmp_item.findMissingResidues()
        tmp_item.findMissingAtoms()
        missingAtoms = tmp_item.missingAtoms

        for group, atoms in missingAtoms.items():
            if correction_group_indices:
                group_index = group_indices_in_selection[group.index]
            else:
                group_index = group.index
            output[group_index] = []
            for atom in atoms:
                output[group_index].append(atom.name)

    else:

        raise NotImplementedError

    return output
Example #9
0
def get_sasa (molecular_system, target='atom', selection='all', structure_indices='all', syntaxis='MolSysMT',
          engine='MDTraj'):

    engine = digest_engine(engine)
    target = digest_target(target)

    if engine == 'MDTraj':

        from mdtraj import shrake_rupley

        tmp_item = convert(molecular_system, structure_indices=structure_indices, to_form='mdtraj.Trajectory')

        sasa_array = shrake_rupley(tmp_item, mode='atom') # tiene probe_radius y n_sphere_points

        if target=='atom':

            if selection is not 'all':

                atom_indices = select(molecular_system, selection=selection, syntaxis=syntaxis)
                sasa_array = sasa_array[:,atom_indices]

        else:

            sets_atoms = get(molecular_system, target=target, selection=selection, syntaxis=syntaxis, atom_index=True)

            n_sets = len(sets_atoms)
            n_structures = sasa_array.shape[0]

            new_sasa_array = np.empty([n_structures, n_sets], dtype='float')
            for ii in range(n_sets):
                new_sasa_array[:,ii] = sasa_array[:,sets_atoms[ii].astype(int)].sum(axis=1)
            sasa_array = new_sasa_array

        sasa_array = puw.quantity(sasa_array, 'nm**2')
        sasa_array = puw.standardize(sasa_array)

    else:

        raise NotImplementedError("Engine not implemented yet")

    return sasa_array
Example #10
0
def one_system(molecular_system=None,
               selection=None,
               structure_indices=None,
               form=None,
               syntaxis='MolSysMT'):

    from molsysmt.basic import convert, select

    atom_indices = None

    if form is not None:
        tmp_molecular_system = convert(molecular_system, form)
    else:
        tmp_molecular_system = item

    if selection is not None:
        atom_indices = select(molecular_system, selection, syntaxis=syntaxis)

    structure_indices = frameslist(tmp_molecular_system, structure_indices)

    return tmp_molecular_system, atom_indices, structure_indices
Example #11
0
def align(molecular_system,
          selection='backbone',
          structure_indices='all',
          reference_molecular_system=None,
          reference_selection='backbone',
          reference_frame_index=0,
          syntaxis='MolSysMT',
          parallel=True,
          method='sequence alignment and least rmsd fit',
          engine_sequence_alignment='biopython',
          engine_least_rmsd_fit='MolSysMT'):

    output = None

    if method == 'sequence alignment and least rmsd fit':

        from molsysmt.basic import select

        if engine_sequence_alignment == 'biopython':

            from molsysmt.topology import get_sequence_identity

            identity, identical_groups, reference_identical_groups = get_sequence_identity(
                molecular_system,
                selection=selection,
                reference_molecular_system=reference_molecular_system,
                reference_selection=reference_selection,
                engine='biopython')

        else:

            raise NotImplementedError

        aux_atoms_list = select(molecular_system,
                                target='atom',
                                selection='group_index==@identical_groups')
        selection_to_be_fitted = select(molecular_system,
                                        target='atom',
                                        selection=selection,
                                        mask=aux_atoms_list)

        aux_atoms_list = select(
            reference_molecular_system,
            target='atom',
            selection='group_index==@reference_identical_groups')
        reference_selection_to_be_fitted = select(
            reference_molecular_system,
            target='atom',
            selection=reference_selection,
            mask=aux_atoms_list)

        if engine_least_rmsd_fit == 'MolSysMT':

            from molsysmt.structure import fit

            output = fit(molecular_system=molecular_system,
                         selection=selection_to_be_fitted,
                         structure_indices=structure_indices,
                         reference_molecular_system=reference_molecular_system,
                         reference_selection=reference_selection_to_be_fitted,
                         reference_frame_index=reference_frame_index,
                         engine='MolSysMT',
                         parallel=parallel,
                         syntaxis=syntaxis)

    else:

        raise NotImplementedError

    return output
Example #12
0
def wrap_to_pbc(molecular_system,
                selection='all',
                structure_indices='all',
                center='[0,0,0] nanometers',
                center_of_selection=None,
                weights_for_center=None,
                recenter=True,
                keep_covalent_bonds=False,
                syntaxis='MolSysMT',
                engine='MolSysMT',
                in_place=False):

    engine = digest_engine(engine)
    structure_indices = digest_structure_indices(structure_indices)

    if engine == 'MolSysMT':

        from molsysmt.basic import select, get, set, extract, copy

        atom_indices = select(molecular_system,
                              selection=selection,
                              syntaxis=syntaxis)

        coordinates = get(molecular_system,
                          target='atom',
                          indices=atom_indices,
                          coordinates=True)
        length_units = puw.get_unit(coordinates)
        n_structures = coordinates.shape[0]
        n_atoms = coordinates.shape[1]
        box, box_shape = get(molecular_system,
                             target='system',
                             structure_indices=structure_indices,
                             box=True,
                             box_shape=True)
        box = puw.convert(box, to_unit=length_units)

        orthogonal = 0
        if box_shape is None:
            raise ValueError(
                "The system has no PBC box. The input argument 'pbc' can not be True."
            )
        elif box_shape == 'cubic':
            orthogonal = 1

        if center_of_selection is not None:

            from molsysmt.structure import get_center
            center = get_center(molecular_system,
                                selection=center_of_selection,
                                weights=weights_for_center,
                                structure_indices=structure_indices,
                                syntaxis=syntaxis,
                                engine='MolSysMT')

            center = puw.convert(center, to_unit=length_units)
            center = puw.get_value(center)

        else:

            center = puw.quantity(center)
            center = puw.convert(center, to_unit=length_units)
            center = puw.get_value(center)

            center_shape = np.shape(center)
            if len(center_shape) == 1 and center_shape[-1] == 3:
                center = np.tile(center, [n_structures, 1, 1])
            elif len(center_shape) == 2 and center_shape[
                    -1] == 3 and center_shape[0] == n_structures:
                center = np.expand_dims(center, axis=1)
            elif len(center_shape
                     ) == 2 and center_shape[-1] == 3 and center_shape[0] == 1:
                center = np.tile(center[0], [n_structures, 1, 1])
            elif len(center_shape
                     ) == 3 and center_shape[-1] == 3 and center_shape[
                         0] == n_structures and center_shape[1] == 1:
                center = np.array(center)
            else:
                raise ValueError('center needs the right shape')

        box = np.asfortranarray(puw.get_value(box), dtype='float64')
        coordinates = np.asfortranarray(puw.get_value(coordinates),
                                        dtype='float64')
        center = np.asfortranarray(center, dtype='float64')

        libbox.wrap_pbc(coordinates, center, box, orthogonal, n_atoms,
                        n_structures)

        if recenter:
            translation = np.tile(-center, (n_atoms, 1))
            coordinates += translation

        coordinates = np.ascontiguousarray(coordinates) * length_units

    else:

        raise NotImpementedEngineError()

    if in_place:

        set(molecular_system,
            target='atom',
            indices=atom_indices,
            structure_indices=structure_indices,
            syntaxis=syntaxis,
            coordinates=coordinates)

        pass

    else:

        tmp_molecular_system = copy(molecular_system)
        set(tmp_molecular_system,
            target='atom',
            indices=atom_indices,
            structure_indices=structure_indices,
            syntaxis=syntaxis,
            coordinates=coordinates)

        return tmp_molecular_system
Example #13
0
def get_rmsd(molecular_system,
             selection='backbone',
             structure_indices='all',
             reference_molecular_system=None,
             reference_selection=None,
             reference_frame_index=0,
             reference_coordinates=None,
             parallel=True,
             syntaxis='MolSysMT',
             engine='MolSysMT'):

    from molsysmt.basic import is_a_molecular_system

    if not is_a_molecular_system(molecular_system):
        raise SingleMolecularSystemNeededError()

    engine = digest_engine(engine)

    if engine == 'MolSysMT':

        from molsysmt.basic import select, get
        from molsysmt._private._digestion import digest_structure_indices

        n_atoms, n_structures = get(molecular_system,
                                    n_atoms=True,
                                    n_structures=True)
        atom_indices = select(molecular_system,
                              selection=selection,
                              syntaxis=syntaxis)
        n_atom_indices = atom_indices.shape[0]
        structure_indices = digest_structure_indices(structure_indices)
        if structure_indices is 'all':
            structure_indices = np.arange(n_structures)
        n_structure_indices = structure_indices.shape[0]

        if reference_coordinates is None:

            if reference_molecular_system is None:
                reference_molecular_system = molecular_system

            if reference_selection is None:
                reference_selection = selection

            reference_atom_indices = select(reference_molecular_system,
                                            selection=reference_selection,
                                            syntaxis=syntaxis)

            reference_coordinates = get(
                reference_molecular_system,
                target='atom',
                indices=reference_atom_indices,
                structure_indices=reference_frame_index,
                coordinates=True)

        coordinates = get(molecular_system,
                          coordinates=True,
                          structure_indices='all')
        units = puw.get_unit(coordinates)
        coordinates = np.asfortranarray(puw.get_value(coordinates),
                                        dtype='float64')
        reference_coordinates = np.asfortranarray(puw.get_value(
            reference_coordinates, to_unit=units),
                                                  dtype='float64')

        if reference_coordinates.shape[1] != n_atom_indices:
            raise ValueError(
                "reference selection and selection needs to have the same number of atoms"
            )

        rmsd_val = librmsd.rmsd(coordinates, atom_indices,
                                reference_coordinates, structure_indices,
                                n_atoms, n_structures, n_atom_indices,
                                n_structure_indices)

        rmsd_val = rmsd_val * units
        rmsd_val = puw.standardize(rmsd_val)
        del (coordinates, units)
        return rmsd_val

    elif engine == 'MDTraj':

        #from mdtraj import rmsd as mdtraj_rmsd
        #from molsysmt.basic import convert

        #tmp_molecular_system = convert(molecular_system, to_form='mdtraj.Trajectory')

        #rmsd_val = mdtraj_rmsd(tmp_molecular_system, ref_item, frame=ref_structure_indices,
        #                        ref_atom_indices=ref_atom_indices, atom_indices=atom_indices,
        #                        parallel=parallel, precentered=precentered)

        #rmsd_val = puw.standardize(rmsd_val)

        #return rmsd_val

        raise NotImplementedError

    else:

        raise NotImplementedError
Example #14
0
def buch(molecular_system,
         selection='all',
         selection_2=None,
         structure_indices='all',
         threshold='2.3 angstroms',
         acceptors=None,
         donors=None,
         pbc=False,
         optimize=False,
         output_form='dict',
         engine='MolSysMT',
         syntaxis='MolSysMT'):

    from molsysmt.hbonds.donors_and_acceptors import get_acceptor_atoms, get_donor_atoms
    from molsysmt.structure import get_neighbors

    molecular_system = digest_molecular_system(molecular_system)
    engine = digest_engine(engine)
    structure_indices = digest_structure_indices(structure_indices)

    output = None

    if selection_2 is None:

        if acceptors is None:
            acceptors_1 = get_acceptor_atoms(molecular_system,
                                             selection=selection,
                                             engine=engine,
                                             syntaxis=syntaxis)
        else:
            acceptors_1 = select(molecular_system,
                                 selection=selection,
                                 mask=acceptors,
                                 syntaxis=syntaxis)

        if donors is None:
            donors_1 = get_donor_atoms(molecular_system,
                                       selection=selection,
                                       engine=engine,
                                       syntaxis=syntaxis)
        else:
            donors_1 = select(molecular_system,
                              selection=selection,
                              mask=donors,
                              syntaxis=syntaxis)

        neighs, _ = get_neighbors(molecular_system,
                                  selection=acceptors_1,
                                  selection_2=donors_1[0],
                                  structure_indices=structure_indices,
                                  threshold=threshold,
                                  pbc=pbc,
                                  engine=engine,
                                  syntaxis=syntaxis)

        if output_form == 'dict':

            output = {}

            n_acceptors = len(acceptors_1)
            for frame_index in range(neighs.shape[0]):
                for ii in range(n_acceptors):
                    for donor_index in neighs[frame_index][ii]:
                        hbond_id = tuple(donors_1[donor_index].tolist() +
                                         [acceptors_1[ii]])
                        try:
                            output[hbond_id].append(frame_index)
                        except:
                            output[hbond_id] = [frame_index]

        else:

            raise NotImplementedError

    else:

        if acceptors is None:
            acceptors_1 = get_acceptor_atoms(molecular_system,
                                             selection=selection,
                                             engine=engine,
                                             syntaxis=syntaxis)
            acceptors_2 = get_acceptor_atoms(molecular_system,
                                             selection=selection_2,
                                             engine=engine,
                                             syntaxis=syntaxis)
        else:
            acceptors_1 = select(molecular_system,
                                 selection=selection,
                                 mask=acceptors,
                                 syntaxis=syntaxis)
            acceptors_2 = select(molecular_system,
                                 selection=selection_2,
                                 mask=acceptors,
                                 syntaxis=syntaxis)

        if donors is None:
            donors_1 = get_donor_atoms(molecular_system,
                                       selection=selection,
                                       engine=engine,
                                       syntaxis=syntaxis)
            donors_2 = get_donor_atoms(molecular_system,
                                       selection=selection_2,
                                       engine=engine,
                                       syntaxis=syntaxis)
        else:
            donors_1 = select(molecular_system,
                              selection=selection,
                              mask=donors,
                              syntaxis=syntaxis)
            donors_2 = select(molecular_system,
                              selection=selection_2,
                              mask=donors,
                              syntaxis=syntaxis)

        neighs, _ = get_neighbors(molecular_system,
                                  selection=acceptors_1,
                                  selection_2=donors_2[0],
                                  structure_indices=structure_indices,
                                  threshold=threshold,
                                  pbc=pbc,
                                  engine=engine,
                                  syntaxis=syntaxis)

        neighs_2, _ = get_neighbors(molecular_system,
                                    selection=acceptors_2,
                                    selection_2=donors_1[0],
                                    structure_indices=structure_indices,
                                    threshold=threshold,
                                    pbc=pbc,
                                    engine=engine,
                                    syntaxis=syntaxis)

        if output_form == 'dict':

            output = {}

            n_acceptors = len(acceptors_1)
            for frame_index in range(neighs.shape[0]):
                for ii in range(n_acceptors):
                    for donor_index in neighs[frame_index][ii]:
                        hbond_id = tuple(donors_2[donor_index].tolist() +
                                         [acceptors_1[ii]])
                        try:
                            output[hbond_id].append(frame_index)
                        except:
                            output[hbond_id] = [frame_index]

            n_acceptors = len(acceptors_2)
            for frame_index in range(neighs_2.shape[0]):
                for ii in range(n_acceptors):
                    for donor_index in neighs_2[frame_index][ii]:
                        hbond_id = tuple(donors_1[donor_index].tolist() +
                                         [acceptors_2[ii]])
                        try:
                            output[hbond_id].append(frame_index)
                        except:
                            output[hbond_id] = [frame_index]

        else:

            raise NotImplementedError()

    return output
Example #15
0
def fit(molecular_system=None,
        selection='backbone',
        structure_indices='all',
        reference_molecular_system=None,
        reference_selection=None,
        reference_frame_index=0,
        to_form=None,
        parallel=True,
        syntaxis='MolSysMT',
        method='least rmsd',
        engine='MolSysMT',
        check=True):

    from molsysmt.basic import select, get, set, convert, copy, is_molecular_system

    if check:
        if not is_molecular_system(molecular_system):
            raise MolecularSystemNeededError()

    engine = digest_engine(engine)

    if engine == 'MolSysMT':

        n_atoms, n_structures = get(molecular_system,
                                    n_atoms=True,
                                    n_structures=True,
                                    check=False)
        atom_indices = select(molecular_system,
                              selection=selection,
                              syntaxis=syntaxis,
                              check=False)
        n_atom_indices = atom_indices.shape[0]
        structure_indices = digest_structure_indices(structure_indices)
        if structure_indices is 'all':
            structure_indices = np.arange(n_structures)
        n_structure_indices = structure_indices.shape[0]

        if reference_molecular_system is None:
            reference_molecular_system = molecular_system

        if reference_selection is None:
            reference_selection = selection

        reference_atom_indices = select(reference_molecular_system,
                                        selection=reference_selection,
                                        syntaxis=syntaxis,
                                        check=False)

        reference_coordinates = get(reference_molecular_system,
                                    target='atom',
                                    indices=reference_atom_indices,
                                    structure_indices=reference_frame_index,
                                    coordinates=True,
                                    check=False)

        coordinates = get(molecular_system,
                          coordinates=True,
                          structure_indices='all',
                          check=False)
        units = puw.get_unit(coordinates)
        coordinates = np.asfortranarray(puw.get_value(coordinates),
                                        dtype='float64')
        reference_coordinates = np.asfortranarray(puw.get_value(
            reference_coordinates, to_unit=units),
                                                  dtype='float64')

        if reference_coordinates.shape[1] != n_atom_indices:
            raise ValueError(
                "reference selection and selection needs to have the same number of atoms"
            )

        librmsd.least_rmsd_fit(coordinates, atom_indices,
                               reference_coordinates, structure_indices,
                               n_atoms, n_structures, n_atom_indices,
                               n_structure_indices)

        coordinates = np.ascontiguousarray(coordinates) * units
        coordinates = puw.standardize(coordinates)

        if to_form is None:
            tmp_molecular_system = copy(molecular_system, check=False)
        else:
            tmp_molecular_system = convert(molecular_system,
                                           to_form=to_form,
                                           check=False)

        set(tmp_molecular_system,
            target='system',
            coordinates=coordinates,
            check=False)
        del (coordinates, units)
        return tmp_molecular_system

    elif engine == 'MDTraj':

        #tmp_item.superpose(tmp_ref_item,frame=ref_structure_indices,atom_indices=atom_indices,ref_atom_indices=ref_atom_indices,parallel=parallel)

        #if in_form==x_form:
        #    item=tmp_item
        #elif in_form=='molsysmt.Trajectory':
        #    item._import_mdtraj_data(tmp_item)
        #elif in_form=='molsysmt.MolSys':
        #    item.trajectory._import_mdtraj_data(tmp_item)
        #else:
        #    item=_convert(tmp_item, to_form=in_form)

        raise NotImplementedMethodError()

    else:

        raise NotImplementedMethodError()
Example #16
0
def standardize_view(view, atom_indices='all', structure_indices='all'):

    from molsysmt.basic import select, get, convert
    from molsysmt.build import is_solvated

    if atom_indices is not 'all':
        string_atom_indices = '@' + ','.join(map(str, atom_indices))
    else:
        string_atom_indices = 'all'

    tmp_topology = convert(view, to_form='molsysmt.Topology')

    sel_cartoon = select(
        tmp_topology,
        selection='molecule_type in ["protein", "dna", "rna"]',
        mask=atom_indices,
        to_syntaxis='NGLview')
    sel_balls = select(tmp_topology,
                       selection='molecule_type in ["ion"]',
                       mask=atom_indices,
                       to_syntaxis='NGLview')
    sel_licorice = select(
        tmp_topology,
        selection='molecule_type in ["lipid", "small molecule"]',
        mask=atom_indices,
        to_syntaxis='NGLview')

    peptide_indices = select(tmp_topology,
                             selection='molecule_type=="peptide"',
                             target='molecule')
    peptides_to_cartoon = []
    peptides_to_licorice = []
    for peptide_index in peptide_indices:
        n_aminoacids = get(tmp_topology,
                           target='molecule',
                           indices=peptide_index,
                           n_groups=True)[0]
        if n_aminoacids > 4:
            peptides_to_cartoon.append(peptide_index)
        else:
            peptides_to_licorice.append(peptide_index)
    sel_peptides_cartoon = select(
        tmp_topology,
        selection='molecule_index in @peptides_to_cartoon',
        mask=atom_indices,
        to_syntaxis='NGLview')
    sel_peptides_licorice = select(
        tmp_topology,
        selection='molecule_index in @peptides_to_licorice',
        mask=atom_indices,
        to_syntaxis='NGLview')

    view.clear()
    view.add_cartoon(selection=sel_cartoon)
    view.add_cartoon(selection=sel_peptides_cartoon)
    view.add_licorice(selection=sel_licorice, radius=0.4)
    view.add_licorice(selection=sel_peptides_licorice, radius=0.4)
    view.add_ball_and_stick(selection=sel_balls)

    n_waters = get(view, target="system", n_waters=True)
    n_selected_waters = get(view, target="system", n_waters=True)
    solvated = is_solvated(view)

    if (not solvated) or (n_selected_waters < n_waters):
        sel_water = select(tmp_topology,
                           selection='molecule_type in ["water"]',
                           mask=atom_indices,
                           to_syntaxis='NGLview')
        view.add_licorice(selection=sel_water)

    view.center(selection=string_atom_indices)

    pass
Example #17
0
def get_least_rmsd(molecular_system=None,
                   selection='backbone',
                   structure_indices='all',
                   reference_molecular_system=None,
                   reference_selection=None,
                   reference_frame_index=0,
                   reference_coordinates=None,
                   parallel=True,
                   syntaxis='MolSysMT',
                   engine='MolSysMT',
                   check=True):

    if check:
        from molsysmt.tools.molecular_system import is_molecular_system
        if not is_a_molecular_system(molecular_system):
            raise SingleMolecularSystemNeededError()

    engine = digest_engine(engine)

    if engine == 'MolSysMT':

        n_atoms, n_structures = get(molecular_system,
                                    n_atoms=True,
                                    n_structures=True,
                                    check=False)
        atom_indices = select(molecular_system,
                              selection=selection,
                              syntaxis=syntaxis,
                              check=False)
        n_atom_indices = atom_indices.shape[0]
        structure_indices = digest_structure_indices(structure_indices)
        if structure_indices is 'all':
            structure_indices = np.arange(n_structures)
        n_structure_indices = structure_indices.shape[0]

        if reference_coordinates is None:

            if reference_molecular_system is None:
                reference_molecular_system = molecular_system

            if reference_selection is None:
                reference_selection = selection

            reference_atom_indices = select(reference_molecular_system,
                                            selection=reference_selection,
                                            syntaxis=syntaxis,
                                            check=False)

            reference_coordinates = get(
                reference_molecular_system,
                target='atom',
                indices=reference_atom_indices,
                structure_indices=reference_frame_index,
                coordinates=True,
                check=False)

        coordinates = get(molecular_system,
                          coordinates=True,
                          structure_indices='all',
                          check=False)
        units = puw.get_unit(coordinates)
        coordinates = np.asfortranarray(puw.get_value(coordinates),
                                        dtype='float64')
        reference_coordinates = np.asfortranarray(puw.get_value(
            reference_coordinates, to_unit=units),
                                                  dtype='float64')

        if reference_coordinates.shape[1] != n_atom_indices:
            raise ValueError(
                "reference selection and selection needs to have the same number of atoms"
            )

        rmsd_val = librmsd.least_rmsd(coordinates, atom_indices,
                                      reference_coordinates, structure_indices,
                                      n_atoms, n_structures, n_atom_indices,
                                      n_structure_indices)

        rmsd_val = rmsd_val * units
        rmsd_val = puw.standardize(rmsd_val)
        del (coordinates, units)
        return rmsd_val

    elif engine == 'MDTraj':

        raise NotImplementedError

    else:
        raise NotImplementedError
Example #18
0
def comparison_two_systems(molecular_system_1=None,
                           selection_1=None,
                           structure_indices_1=None,
                           molecular_system_2=None,
                           selection_2=None,
                           structure_indices_2=None,
                           form=None,
                           syntaxis='MolSysMT'):

    from molsysmt.basic import convert, select

    single_molecular_system = False
    diff_selection = True
    atom_indices_1 = None
    atom_indices_2 = None

    if molecular_system1 is None and molecular_system_2 is None:
        raise BadCallError(BadCallMessage)

    if molecular_system_1 is None or molecular_system_2 is None:
        single_molecular_system = True
        if molecular_system_1 is None:
            molecular_system_1 = molecular_system_2
        else:
            molecular_system_2 = molecular_system_1

    if form is not None:
        tmp_molecular_system_1 = convert(molecular_system_1, form)
        tmp_molecular_system_2 = convert(molecular_system_2, form)
    else:
        tmp_molecular_system_1 = molecular_system_1
        tmp_molecular_system_2 = molecular_system_2

    if selection_1 is not None:
        atom_indices_1 = select(tmp_molecular_system_1,
                                selection_1,
                                syntaxis=syntaxis)

    if selection_2 is not None:
        atom_indices_2 = select(tmp_molecular_system_2,
                                selection_2,
                                syntaxis=syntaxis)

    if selection_1 is None and selection_2 is None:

        atom_indices_1 = None
        atom_indices_2 = None

    elif selection_1 is None or selection_2 is None:
        if single_molecular_system is True:
            diff_selection = False
            if selection_1 is None:
                atom_indices_1 = atom_indices_2
            else:
                atom_indices_2 = atom_indices_1
        else:
            if selection_1 is None:
                atom_indices_1 = select(tmp_molecular_system_1,
                                        selection_2,
                                        syntaxis=syntaxis)
            else:
                atom_indices_2 = select(tmp_molecular_system_2,
                                        selection_1,
                                        syntaxis=syntaxis)

    structure_indices_1 = frameslist(tmp_molecular_system_1,
                                     structure_indices_1)
    structure_indices_2 = frameslist(tmp_molecular_system_2,
                                     structure_indices_2)

    return tmp_molecular_system_1, atom_indices_1, structure_indices_1, \
           tmp_molecular_system_2, atom_indices_2, structure_indices_2, \
           single_molecular_system, diff_selection
Example #19
0
def add_terminal_cappings(molecular_system,
                          N_terminal=None,
                          C_terminal=None,
                          selection='all',
                          syntaxis='MolSysMT',
                          engine='PDBFixer'):

    from molsysmt.basic import get_form, convert, get, select

    form_in = get_form(molecular_system)

    if engine is 'PDBFixer':

        from pdbfixer.pdbfixer import Sequence

        tmp_molecular_system = convert(molecular_system,
                                       to_form='pdbfixer.PDBFixer')
        atom_indices_in_selection = select(tmp_molecular_system,
                                           selection=selection,
                                           syntaxis=syntaxis)
        atom_indices_in_components = get(
            tmp_molecular_system,
            target='component',
            selection='component_type in ["peptide", "protein"] \
                                         and atom_index in @atom_indices_in_selection',
            atom_index=True)

        for atom_indices_in_component in atom_indices_in_components:

            chain_id = get(
                tmp_molecular_system,
                target='chain',
                selection='atom_index in @atom_indices_in_component',
                chain_id=True)
            groups_sequence = get(
                tmp_molecular_system,
                target='group',
                selection='atom_index in @atom_indices_in_component',
                group_name=True)

            groups_sequence = list(groups_sequence)

            if N_terminal is not None:

                groups_sequence = [N_terminal] + groups_sequence

            if C_terminal is not None:

                groups_sequence = groups_sequence + [C_terminal]

            tmp_molecular_system.sequences.append(
                Sequence(chain_id, groups_sequence))

        tmp_molecular_system.findMissingResidues()
        tmp_molecular_system.findMissingAtoms()
        tmp_molecular_system.addMissingAtoms()

        n_hs = get(tmp_molecular_system,
                   target='atom',
                   selection='atom_type=="H"',
                   n_atoms=True)

        if n_hs > 0:

            tmp_molecular_system.addMissingHydrogens(pH=7.4)

        tmp_molecular_system = convert(tmp_molecular_system, to_form=form_in)

    else:

        raise NotImplementedError

    return tmp_molecular_system
Example #20
0
def get_sequence_identity(molecular_system,
                          selection='all',
                          reference_molecular_system=None,
                          reference_selection='all',
                          syntaxis='MolSysMT',
                          engine='biopython'):

    from molsysmt.topology.get_sequence_alignment import get_sequence_alignment
    from molsysmt.basic import select

    if engine == 'biopython':

        # This is code from ensembler.modeling.calculate_seq_identity
        # This should be implemented here importing the function but there is a conflict installing
        # ensembler: ensembler is only available for python 2.7
        # (https://github.com/choderalab/ensembler/blob/master/ensembler/modeling.py)

        group_indices = select(molecular_system,
                               target='group',
                               selection=selection)
        reference_group_indices = select(reference_molecular_system,
                                         target='group',
                                         selection=reference_selection)

        seq, seq_ref = get_sequence_alignment(
            molecular_system,
            selection=selection,
            reference_molecular_system=reference_molecular_system,
            reference_selection=reference_selection,
            syntaxis=syntaxis,
            engine=engine)

        intersect = []
        intersect_ref = []

        ii = 0
        ii_ref = 0

        for res, res_ref in zip(seq, seq_ref):

            if res != '-' and res_ref == '-':
                ii += 1
            elif res == '-' and res_ref != '-':
                ii_ref += 1
            elif res == res_ref:
                if res != '-' and res_ref != '-':
                    intersect.append(group_indices[ii])
                    intersect_ref.append(reference_group_indices[ii_ref])
                    ii += 1
                    ii_ref += 1
            else:
                ii += 1
                ii_ref += 1

    else:

        raise NotImplementedError

    identity = 100.0 * (len(intersect) / len(group_indices))

    return identity, intersect, intersect_ref
Example #21
0
def solvate(molecular_system,
            box_geometry="truncated octahedral",
            clearance='14.0 angstroms',
            anion='Cl-',
            num_anions="neutralize",
            cation='Na+',
            num_cations="neutralize",
            ionic_strength='0.0 molar',
            engine="LEaP",
            to_form=None,
            logfile=False,
            verbose=False):
    """solvate(item, geometry=None, water=None, engine=None)
    Methods and wrappers to create and solvate boxes
    Parameters
    ----------
    anion: 'Cl-', 'Br-', 'F-', and 'I-'
    num_anions: number of cations to add. integer or "neutralize"
    cation: "NA"  'Cs+', 'K+', 'Li+', 'Na+', and 'Rb+'
    num_cations: number of cations to add. integer or "neutralize"
    box_geometry: "cubic", "truncated_octahedral" or "rhombic_dodecahedron" (Default: "truncated_octahedral")
    Returns
    -------
    item : bla bla
        bla bla
    Examples
    --------
    See Also
    --------
    Notes
    -----
    """

    from molsysmt.basic import get_form, convert

    engine = digest_engine(engine)
    to_form = digest_to_form(to_form)
    if to_form is None:
        to_form = get_form(molecular_system)

    if engine == "OpenMM":

        from openmm import Vec3

        clearance = puw.convert(clearance, to_form='openmm.unit')
        ionic_strength = puw.convert(ionic_strength, to_form='openmm.unit')

        modeller = convert(molecular_system, to_form='openmm.Modeller')
        molecular_mechanics = convert(molecular_system,
                                      to_form='molsysmt.MolecularMechanics')
        parameters = molecular_mechanics.get_openmm_System_parameters()
        forcefield = molecular_mechanics.to_openmm_ForceField()

        solvent_model = None
        if molecular_mechanics.water_model == 'SPC':
            solvent_model = 'tip3p'
        elif molecular_mechanics.water_model in [
                'TIP3P', 'TIP3PFB', 'SPCE', 'TIP4PEW', 'TIP4PFB', 'TIP5P'
        ]:
            solvent_model = molecular_mechanics.water_model.lower()
        else:
            raise NotImplementedError()

        if box_geometry == "truncated octahedral":

            max_size = max(
                max((pos[i] for pos in modeller.positions)) -
                min((pos[i] for pos in modeller.positions)) for i in range(3))
            vectors = Vec3(1.0, 0,
                           0), Vec3(1.0 / 3.0, 2.0 * np.sqrt(2.0) / 3.0,
                                    0.0), Vec3(-1.0 / 3.0,
                                               np.sqrt(2.0) / 3.0,
                                               np.sqrt(6.0) / 3.0)
            box_vectors = [(max_size + clearance) * v for v in vectors]

            modeller.addSolvent(forcefield,
                                model=solvent_model,
                                boxVectors=box_vectors,
                                ionicStrength=ionic_strength,
                                positiveIon=cation,
                                negativeIon=anion)

        elif box_geometry == "rhombic dodecahedral":

            max_size = max(
                max((pos[i] for pos in modeller.positions)) -
                min((pos[i] for pos in modeller.positions)) for i in range(3))
            vectors = Vec3(1.0, 0.0,
                           0.0), Vec3(0.0, 1.0,
                                      0.0), Vec3(0.5, 0.5,
                                                 np.sqrt(2) / 2)
            box_vectors = [(max_size + clearance) * v for v in vectors]

            modeller.addSolvent(forcefield,
                                model=solvent_model,
                                boxVectors=box_vectors,
                                ionicStrength=ionic_strength,
                                positiveIon=cation,
                                negativeIon=anion)

        else:

            modeller.addSolvent(forcefield,
                                model=solvent_model,
                                padding=clearance,
                                ionicStrength=ionic_strength,
                                positiveIon=cation,
                                negativeIon=anion)

        tmp_item = convert(modeller, to_form=to_form)

        del (modeller)

        return tmp_item

    elif engine == "PDBFixer":

        from openmm import Vec3

        clearance = puw.convert(clearance, to_form='openmm.unit')
        ionic_strength = puw.convert(ionic_strength, to_form='openmm.unit')

        pdbfixer = convert(molecular_system, to_form='pdbfixer.PDBFixer')
        max_size = max(
            max((pos[i] for pos in pdbfixer.positions)) -
            min((pos[i] for pos in pdbfixer.positions)) for i in range(3))

        box_size = None
        box_vectors = None

        if box_geometry == "truncated octahedral":

            vectors = Vec3(1.0, 0,
                           0), Vec3(1.0 / 3.0, 2.0 * np.sqrt(2.0) / 3.0,
                                    0.0), Vec3(-1.0 / 3.0,
                                               np.sqrt(2.0) / 3.0,
                                               np.sqrt(6.0) / 3.0)

        elif box_geometry == "rhombic dodecahedral":

            vectors = Vec3(1.0, 0.0,
                           0.0), Vec3(0.0, 1.0,
                                      0.0), Vec3(0.5, 0.5,
                                                 np.sqrt(2) / 2)

        elif box_geometry == "cubic":

            vectors = Vec3(1.0, 0.0, 0.0), Vec3(0.0, 1.0,
                                                0.0), Vec3(0.0, 0.0, 1.0)

        box_vectors = [(max_size + clearance) * v for v in vectors]

        pdbfixer.addSolvent(boxVectors=box_vectors,
                            ionicStrength=ionic_strength,
                            positiveIon=cation,
                            negativeIon=anion)

        tmp_item = convert(pdbfixer, to_form=to_form)

        del (pdbfixer)

        return tmp_item

    elif engine == "LEaP":

        from molsysmt.thirds.tleap import TLeap
        from molsysmt._private.files_and_directories import temp_directory, temp_filename
        from molsysmt.tools.file_pdb import replace_HETATM_by_ATOM_in_terminal_cappings
        from shutil import rmtree, copyfile
        from os import getcwd, chdir
        from molsysmt.basic import set as _set, select
        from molsysmt.build import has_hydrogens, remove_hydrogens

        if has_hydrogens(molecular_system):
            raise ValueError(
                "A molecular system without hydrogen atoms is needed.")
            #molecular_system = remove_hydrogens(molecular_system)
            #if verbose:
            #    print("All Hydrogen atoms were removed to be added by LEaP\n\n")

        indices_NME_C = select(
            molecular_system,
            target='atom',
            selection='group_name=="NME" and atom_name=="C"')
        with_NME_C = (len(indices_NME_C) > 0)

        if with_NME_C:
            _set(molecular_system,
                 target='atom',
                 selection='group_name=="NME" and atom_name=="C"',
                 atom_name='CH3')

        current_directory = getcwd()
        working_directory = temp_directory()
        pdbfile_in = temp_filename(dir=working_directory, extension='pdb')
        _ = convert(molecular_system, to_form=pdbfile_in)
        #replace_HETATM_from_capping_atoms(pdbfile_in)

        tmp_prmtop = temp_filename(dir=working_directory, extension='prmtop')
        tmp_inpcrd = tmp_prmtop.replace('prmtop', 'inpcrd')
        tmp_logfile = tmp_prmtop.replace('prmtop', 'leap.log')

        molecular_mechanics = convert(molecular_system,
                                      to_form='molsysmt.MolecularMechanics')
        parameters = molecular_mechanics.get_leap_parameters()
        forcefield = parameters['forcefield']
        water = parameters['water_model']

        solvent_model = None
        if water == 'SPC':
            solvent_model = 'SPCBOX'
        elif water == 'TIP3P':
            solvent_model = 'TIP3PBOX'
        elif water == 'TIP4P':
            solvent_model = 'TIP4PBOX'

        if verbose:
            print('Working directory:', working_directory)

        tleap = TLeap()
        tleap.load_parameters(*forcefield)
        tleap.load_unit('MolecularSystem', pdbfile_in)
        tleap.check_unit('MolecularSystem')
        tleap.get_total_charge('MolecularSystem')
        tleap.solvate('MolecularSystem',
                      solvent_model,
                      clearance,
                      box_geometry=box_geometry)

        if num_anions != 0:
            if num_anions == 'neutralize':
                num_anions = 0
            tleap.add_ions('MolecularSystem',
                           anion,
                           num_ions=num_anions,
                           replace_solvent=True)

        if num_cations != 0:
            if num_cations == 'neutralize':
                num_cations = 0
            tleap.add_ions('MolecularSystem',
                           cation,
                           num_ions=num_cations,
                           replace_solvent=True)

        tleap.save_unit('MolecularSystem', tmp_prmtop)
        errors = tleap.run(working_directory=working_directory,
                           verbose=verbose)

        del (tleap)

        if logfile:
            copyfile(tmp_logfile, current_directory + '/build_peptide.log')

        tmp_item = convert([tmp_prmtop, tmp_inpcrd], to_form=to_form)

        if with_NME_C:
            _set(tmp_item,
                 target='atom',
                 selection='group_name=="NME" and atom_name=="CH3"',
                 atom_name='C')

        rmtree(working_directory)

        return tmp_item

    else:

        raise NotImplementedError
Example #22
0
def translate(molecular_system,
              translation=None,
              selection='all',
              structure_indices='all',
              syntaxis='MolSysMT',
              in_place=False,
              check=True):

    from molsysmt.basic import get, set, select, copy, is_molecular_system

    if check:
        if not is_molecular_system(molecular_system):
            raise MolecularSystemNeededError()

    atom_indices = select(molecular_system,
                          selection=selection,
                          syntaxis=syntaxis)
    coordinates = get(molecular_system,
                      target='atom',
                      indices=atom_indices,
                      structure_indices=structure_indices,
                      coordinates=True)

    length_units = puw.get_unit(coordinates)
    coordinates = puw.get_value(coordinates)
    translation = puw.get_value(translation, to_unit=length_units)
    n_atoms = coordinates.shape[1]

    if type(translation) in [list, tuple]:
        translation = np.array(translation)

    if type(translation) == np.ndarray:
        if len(translation.shape) == 1:
            if translation.shape[0] == 3:
                translation = np.tile(translation, (n_atoms, 1))
            else:
                raise ValueError('Wrong shape of translation vector')
        elif len(translation.shape) == 2:
            if translation.shape[1] != 3:
                raise ValueError('Wrong shape of translation vector')
        elif len(translation.shape) == 3:
            if translation.shape[2] != 3:
                raise ValueError('Wrong shape of translation vector')
            if translation.shape[1] == 1:
                translation = np.tile(translation, (n_atoms, 1))

    coordinates += translation
    coordinates = coordinates * length_units

    if in_place:
        return set(molecular_system,
                   target='atom',
                   indices=atom_indices,
                   structure_indices=structure_indices,
                   coordinates=coordinates)
    else:
        tmp_molecular_system = copy(molecular_system)
        set(tmp_molecular_system,
            target='atom',
            indices=atom_indices,
            structure_indices=structure_indices,
            coordinates=coordinates)
        return tmp_molecular_system
Example #23
0
def get_distances(molecular_system,
                  selection="all",
                  groups_of_atoms=None,
                  group_behavior=None,
                  structure_indices="all",
                  molecular_system_2=None,
                  selection_2=None,
                  groups_of_atoms_2=None,
                  group_behavior_2=None,
                  structure_indices_2=None,
                  pairs=False,
                  crossed_frames=False,
                  pbc=False,
                  parallel=False,
                  output_form='tensor',
                  output_atom_indices=False,
                  output_structure_indices=False,
                  engine='MolSysMT',
                  syntaxis='MolSysMT'):

    from molsysmt.structure.get_center_of_mass import get_center_of_mass
    from molsysmt.structure.get_geometric_center import get_geometric_center

    # group_behavior in
    # ['center_of_mass','geometric_center','minimum_distance','maximum_distance']
    # output_form in ['tensor','dict']

    # crossed_frames es para cuando queremos calcular lista de frames1 contra lista de frames 2
    # (todos con todos), si crossed_frames=False entonces es sólo el primer frame de lista 1 contra
    # el primer frame de lista 2, el segundo contra el segundo, etc.

    # selection groups está por si quiero distancias entre centros de masas, necesita
    # hacer un lista de listas frente a otra lista de listas.

    molecular_system = digest_molecular_system(molecular_system)

    if molecular_system_2 is None:
        same_system = True
        molecular_system_2 = molecular_system
    else:
        same_system = False
        molecular_system_2 = digest_molecular_system(molecular_system_2)

    engine = digest_engine(engine)
    structure_indices = digest_structure_indices(structure_indices)
    structure_indices_2 = digest_structure_indices(structure_indices_2)

    if group_behavior == 'minimum_distance' or group_behavior_2 == 'minimum_distance':
        if group_behavior == 'minimum_distance' and group_behavior_2 == 'minimum_distance':
            raise NotImplementedError(NotImplementedMessage)
            #num_groups_1=len(groups_of_atoms)
            #num_groups_2=len(groups_of_atoms_2)
            #structure_indices = _digest_structure_indices(item, structure_indices)
            #num_frames=len(structure_indices)
            #dists = np.zeros((num_frames, num_groups_1, num_groups_2),dtype=float)
            #for ii in range(num_groups_1):
            #    group1 = groups_of_atoms_2[ii]
            #    for jj in range(num_groups_2):
            #        group2 = groups_of_atoms_2[jj]
            #        _, min_dist = min_distances(molecular_system=molecular_system, selection=group1,
            #                                    structure_indices=structure_indices,
            #                                    selection_2=group2,
            #                                    pbc=pbc, parallel=parallel, engine=engine)
            #        dists[:,ii,jj]=min_dist
            #del(num_groups1,num_groups2,structure_indices,num_frames,group1,group2)
            #return dists
        else:
            raise NotImplementedError(NotImplementedMessage)

    if engine == 'MolSysMT':

        same_selection = False
        same_groups = False
        same_frames = False

        if groups_of_atoms is not None:
            selection = None

        if (selection is not None) and (selection_2 is None):
            if (groups_of_atoms_2 is None):
                selection_2 = selection
                same_selection = True

        if groups_of_atoms is not None:
            if (selection_2 is None) and (groups_of_atoms_2 is None):
                groups_of_atoms_2 = groups_of_atoms
                same_groups = True

        if structure_indices_2 is None:
            structure_indices_2 = structure_indices
            same_frames = True

        if selection is not None:

            if group_behavior == 'center_of_mass':
                coordinates_1 = get_center_of_mass(
                    molecular_system,
                    selection=selection,
                    structure_indices=structure_indices)
                atom_indices_1 = [0]
            elif group_behavior == 'geometric_center':
                coordinates_1 = get_geometric_center(
                    molecular_system,
                    selection=selection,
                    structure_indices=structure_indices)
                atom_indices_1 = [0]
            else:
                atom_indices_1 = select(molecular_system,
                                        selection=selection,
                                        syntaxis=syntaxis)
                coordinates_1 = get(molecular_system,
                                    target='atom',
                                    indices=atom_indices_1,
                                    structure_indices=structure_indices,
                                    coordinates=True)
        else:

            if group_behavior == 'center_of_mass':
                coordinates_1 = get_center_of_mass(
                    molecular_system,
                    groups_of_atoms=groups_of_atoms,
                    structure_indices=structure_indices)
                atom_indices_1 = np.range(coordinates_1.shape[1])
            elif group_behavior == 'geometric_center':
                coordinates_1 = get_geometric_center(
                    molecular_system,
                    groups_of_atoms=groups_of_atoms,
                    structure_indices=structure_indices)
                atom_indices_1 = np.arange(coordinates_1.shape[1])
            else:
                raise ValueError(
                    "Value of argument group_behavior not recognized.")

        if selection_2 is not None:

            if same_system and same_selection and same_frames:

                atom_indices_2 = atom_indices_1
                coordinates_2 = coordinates_1

            else:

                if group_behavior_2 == 'center_of_mass':
                    coordinates_2 = get_center_of_mass(
                        molecular_system_2,
                        selection=selection_2,
                        structure_indices=structure_indices_2)
                    atom_indices_2 = [0]
                elif group_behavior_2 == 'geometric_center':
                    coordinates_2 = get_geometric_center(
                        molecular_system_2,
                        selection=selection_2,
                        structure_indices=structure_indices_2)
                    atom_indices_2 = [0]
                else:
                    atom_indices_2 = select(molecular_system_2,
                                            selection=selection_2,
                                            syntaxis=syntaxis)
                    coordinates_2 = get(molecular_system_2,
                                        target='atom',
                                        indices=atom_indices_2,
                                        structure_indices=structure_indices_2,
                                        coordinates=True)

        else:

            if same_system and same_groups and same_frames:
                atom_indices_2 = atom_indices_1
                coordinates_2 = coordinates_1
            else:
                if group_behavior_2 == 'center_of_mass':
                    coordinates_2 = get_center_of_mass(
                        molecular_system_2,
                        groups_of_atoms=groups_of_atoms_2,
                        structure_indices=structure_indices_2)
                    atom_indices_2 = np.arange(coordinates_2.shape[1])
                elif group_behavior_2 == 'geometric_center':
                    coordinates_2 = get_geometric_center(
                        molecular_system_2,
                        groups_of_atoms=groups_of_atoms_2,
                        structure_indices=structure_indices_2)
                    atom_indices_2 = np.arange(coordinates_2.shape[1])
                else:
                    raise ValueError(
                        "Value of argument group_behavior_2 not recognized.")

        diff_set = not ((same_system and same_selection and same_frames) or
                        (same_system and same_groups and same_frames))

        length_units = puw.get_unit(coordinates_1)
        coordinates_1 = np.asfortranarray(puw.get_value(coordinates_1),
                                          dtype='float64')
        coordinates_2 = np.asfortranarray(puw.get_value(coordinates_2),
                                          dtype='float64')
        nframes_1 = coordinates_1.shape[0]
        nframes_2 = coordinates_2.shape[0]
        nelements1 = coordinates_1.shape[1]
        nelements2 = coordinates_2.shape[1]

        if pbc:

            box, box_shape = get(molecular_system,
                                 target='system',
                                 box=True,
                                 box_shape=True,
                                 structure_indices=structure_indices)

            orthogonal = 0
            if box_shape is None:
                raise ValueError(
                    "The system has no PBC box. The input argument 'pbc' can not be True."
                )
            elif box_shape == 'cubic':
                orthogonal = 1

        else:

            box = np.zeros([nframes_1, 3, 3]) * length_units
            orthogonal = 1

        box = np.asfortranarray(puw.get_value(box), dtype='float64')

        if crossed_frames is False:
            if nframes_1 != nframes_2:
                raise ValueError(
                    "Both structure_indices and structure_indices_2 need the same number of frames."
                )
            else:
                if pairs is False:
                    dists = libgeometry.distance(int(diff_set), coordinates_1,
                                                 coordinates_2, box,
                                                 orthogonal, int(pbc),
                                                 nelements1, nelements2,
                                                 nframes_1)
                else:
                    if nframes_1 != nframes_2:
                        raise ValueError(
                            "Both selection and selection_2 need the same number of atoms."
                        )
                    else:
                        dists = libgeometry.distance_pairs(
                            coordinates_1, coordinates_2, box, orthogonal,
                            int(pbc), nelements1, nelements2, nframes_1)
        else:
            raise NotImplementedError(NotImplementedMessage)

        del (coordinates_1, coordinates_2, box)

        dists = dists * length_units

        if output_form == 'tensor':
            if output_structure_indices:

                if structure_indices is 'all':
                    structure_indices = np.arange(nframes_1)
                if structure_indices_2 is 'all':
                    structure_indices_2 = np.arange(nframes_2)

                if output_atom_indices:
                    return atom_indices_1, structure_indices, atom_indices_2, structure_indices_2, dists
                else:
                    return structure_indices, structure_indices_2, dists

            elif output_atom_indices:
                return atom_indices_1, atom_indices_2, dists
            else:
                return dists

        elif output_form == 'dict':
            if structure_indices is 'all':
                structure_indices = np.arange(nframes_1)
            if structure_indices_2 is 'all':
                structure_indices_2 = np.arange(nframes_2)
            if pairs is False:
                if crossed_frames is False:
                    tmp_dict = {}
                    for ii in range(len(atom_indices_1)):
                        atom1 = atom_indices_1[ii]
                        tmp_dict[atom1] = {}
                        for jj in range(len(atom_indices_2)):
                            atom2 = atom_indices_2[jj]
                            tmp_dict[atom1][atom2] = {}
                            for kk in range(len(structure_indices)):
                                frame_index_1 = structure_indices[kk]
                                tmp_dict[atom1][atom2][frame_index_1] = dists[
                                    kk, ii, jj]
                    return tmp_dict
                else:
                    raise NotImplementedError(NotImplementedMessage)
            else:
                if crossed_frames is False:
                    tmp_dict = {}
                    for ii in range(len(atom_indices_1)):
                        atom1 = atom_indices_1[ii]
                        atom2 = atom_indices_2[ii]
                        if atom1 not in tmp_dict:
                            tmp_dict[atom1] = {}
                        if atom2 not in tmp_dict[atom1]:
                            tmp_dict[atom1][atom2] = {}
                        for kk in range(len(structure_indices)):
                            frame_index_1 = structure_indices[kk]
                            tmp_dict[atom1][atom2][frame_index_1] = dists[kk,
                                                                          ii]
                    return tmp_dict
                else:
                    raise NotImplementedError(NotImplementedMessage)

        else:
            raise NotImplementedError(NotImplementedMessage)

    elif engine == 'MDTraj':

        #tmp_item1, atom_indices1, structure_indices1, tmp_item2, atom_indices2, structure_indices2,\
        #single_item, single_selection = _digest_comparison_two_systems(item, selection, frame,\
        #                                                               item2, selection2, frame2,\
        #                                                               form='mdtraj.Trajectory')

        #if (group_behavior is None) and (group_behavior2 is None):
        #    if item2 is None:
        #        from mdtraj import compute_distances as _mdtraj_compute_distances
        #        tensor1_to_grid, tensor2_to_grid = np.meshgrid(atom_indices1,atom_indices2)
        #        pairs_list =np.vstack([tensor1_to_grid.ravel(), tensor2_to_grid.ravel()]).T
        #        dists = _mdtraj_compute_distances(tmp_item1,pairs_list,pbc)
        #        if output_form=='matrix':
        #            nframes=dists.shape[0]
        #            del(_mdtraj_compute_distances,pairs_list)
        #            return dists.reshape(len(atom_indices2),len(atom_indices1),nframes).T
        #        elif output_form=='dict':
        #            tmp_dict={}
        #            for kk in range(dists.shape[1]):
        #                ii=pairs_list[kk,0]
        #                jj=pairs_list[kk,1]
        #                try:
        #                    tmp_dict[ii][jj]=dists[:,kk]
        #                except:
        #                    tmp_dict[ii]={}
        #                    tmp_dict[ii][jj]=dists[:,kk]
        #            del(_mdtraj_compute_distances,pairs_list)
        #            return tmp_dict
        #        else:
        #            raise NotImplementedError(NotImplementedMessage)
        #    else:
        #        raise NotImplementedError(NotImplementedMessage)
        #else:
        #    raise NotImplementedError(NotImplementedMessage)

        raise NotImplementedError(NotImplementedMessage)
    else:
        raise NotImplementedError(NotImplementedMessage)