Пример #1
0
def make_gaussian_cube_atoms(session):
    from chimerax.map import Volume
    from chimerax.map_data.gaussian.gaussian_grid import GaussianGrid
    glist = [m.data for m in session.models
             if isinstance(m, Volume) and isinstance(m.data, GaussianGrid)]
    slist = []
    for g in glist:
        atoms = g.gc.atoms
        if atoms:
            from chimerax.atomic import AtomicStructure, Element
            s = AtomicStructure(session)
            r = s.new_residue('UNK', 'A', 1)
            for i, (n,q,x,y,z) in enumerate(atoms):
                e = Element.get_element(n)
                a = s.new_atom(e.name, e)
                b = bohr_radius = 0.5291772108      # Angstroms
                a.coord = (b*x,b*y,b*z)
                a.serial_number = i
                r.add_atom(a)
            s.connect_structure()
            slist.append(s)

    session.models.add(slist)
    session.logger.info('Created %d atomic models for %d Gaussian Cube files'
                        % (len(slist), len(glist)))
Пример #2
0
def duplicate(session, selection, newModel=True):
    # dict for unique models, residues, and atoms
    models = {}
    # dict for just models and atoms
    atom_list = {}
    for atom in selection:
        if atom.structure not in models:
            models[atom.structure] = {}
            atom_list[atom.structure] = []

        if atom.residue not in models[atom.structure]:
            models[atom.structure][atom.residue] = []

        models[atom.structure][atom.residue].append(atom)
        atom_list[atom.structure].append(atom)

    for model in models:
        if newModel:
            struc = AtomicStructure(session,
                                    name="copy of %s" % model.atomspec)
        else:
            struc = model
            offset = len(model.atoms)
        for res in models[model]:
            residue = struc.new_residue(res.name, res.chain_id, res.number)
            for atom in models[model][res]:
                dup_atom = struc.new_atom(atom.name, atom.element)
                dup_atom.coord = atom.coord
                dup_atom.serial_number = len(struc.atoms)
                res.add_atom(dup_atom)

        for i, atom1 in enumerate(atom_list[model]):
            atom1.selected = False
            if newModel:
                struc.atoms[i].selected = True
                struc.atoms[i].color = atom1.color
                struc.atoms[i].radius = atom1.radius
                struc.atoms[i].draw_mode = atom1.draw_mode
            else:
                struc.atoms[i + offset].selected = True
                struc.atoms[i + offset].color = atom1.color
                struc.atoms[i + offset].radius = atom1.radius
                struc.atoms[i + offset].draw_mode = atom1.draw_mode

            for j, atom2 in enumerate(atom_list[model][:i]):
                if atom2 in atom1.neighbors:
                    if newModel:
                        struc.new_bond(struc.atoms[i], struc.atoms[j])
                    else:
                        struc.new_bond(struc.atoms[i + offset],
                                       struc.atoms[j + offset])

        if newModel:
            session.models.add([struc])

    session.triggers.activate_trigger(SELECTION_CHANGED, None)
Пример #3
0
def _read_block(session, stream):
    # First line should be an integer count of the number of
    # atoms in the block.  Each block gets turned into an
    # AtomicStructure instance.
    count_line = stream.readline()
    if not count_line:
        return None
    try:
        count = int(count_line)
    except ValueError:
        # XXX: Should emit an error message
        return None
    from chimerax.atomic import AtomicStructure
    s = AtomicStructure(session)

    # Next line is a comment line
    s.comment = stream.readline().strip()

    # There should be "count" lines of atoms.
    from numpy import array, float64
    residue = s.new_residue("UNK", 'A', 1)
    element_count = {}
    for n in range(count):
        atom_line = stream.readline()
        if not atom_line:
            # XXX: Should emit an error message
            return None
        parts = atom_line.split()
        if len(parts) != 4:
            # XXX: Should emit an error message
            return None
        # Extract available data
        element = parts[0]
        xyz = [float(v) for v in parts[1:]]

        # Convert to required initializers
        # XXX: May need to convert element to usable form
        n = element_count.get(element, 0) + 1
        name = element + str(n)
        element_count[element] = n

        # Create atom
        atom = s.new_atom(name, element)
        atom.coord = array(xyz, dtype=float64)
        residue.add_atom(atom)
    s.connect_structure()
    s.new_atoms()  # tell structure it needs to update
    return s
Пример #4
0
def _prep_add(session,
              structures,
              unknowns_info,
              template,
              need_all=False,
              **prot_schemes):
    global _serial
    _serial = None
    atoms = []
    type_info_for_atom = {}
    naming_schemas = {}
    idatm_type = {}  # need this later; don't want a recomp
    hydrogen_totals = {}

    # add missing OXTs of "real" C termini;
    # delete hydrogens of "fake" N termini after protonation
    # and add a single "HN" back on, using same dihedral as preceding residue;
    # delete extra hydrogen of "fake" C termini after protonation
    logger = session.logger
    real_N, real_C, fake_N, fake_C = determine_termini(session, structures)
    logger.info("Chain-initial residues that are actual N"
                " termini: %s" % ", ".join([str(r) for r in real_N]))
    logger.info("Chain-initial residues that are not actual N"
                " termini: %s" % ", ".join([str(r) for r in fake_N]))
    logger.info("Chain-final residues that are actual C"
                " termini: %s" % ", ".join([str(r) for r in real_C]))
    logger.info("Chain-final residues that are not actual C"
                " termini: %s" % ", ".join([str(r) for r in fake_C]))
    for rc in real_C:
        complete_terminal_carboxylate(session, rc)

    # ensure that N termini are protonated as N3+ (since Npl will fail)
    from chimerax.atomic import Sequence
    for nter in real_N + fake_N:
        n = nter.find_atom("N")
        if not n:
            continue
        # if residue wasn't templated, leave atom typing alone
        if Sequence.protein3to1(n.residue.name) == 'X':
            continue
        if not (n.residue.name == "PRO" and n.num_bonds >= 2):
            n.idatm_type = "N3+"

    coordinations = {}
    for struct in structures:
        pbg = struct.pseudobond_group(struct.PBG_METAL_COORDINATION,
                                      create_type=None)
        if not pbg:
            continue
        for pb in pbg.pseudobonds:
            for a in pb.atoms:
                if not need_all and a.structure not in structures:
                    continue
                if not a.element.is_metal:
                    coordinations.setdefault(a, []).append(pb.other_atom(a))

    remaining_unknowns = {}
    type_info_class = type_info['H'].__class__
    from chimerax.atomic import Residue
    for struct in structures:
        for atom in struct.atoms:
            if atom.element.number == 0:
                res = atom.residue
                struct.delete_atom(atom)
        idatm_lookup = {}
        if template:
            template_lookup = {}
            from chimerax.atomic import TmplResidue
            get_template = TmplResidue.get_template
            for res in struct.residues:
                if get_template(res.name):
                    continue
                try:
                    exemplar = template_lookup[res.name]
                except KeyError:
                    from chimerax.mmcif import find_template_residue
                    tmpl = find_template_residue(session, res.name)
                    if not tmpl:
                        continue
                    from chimerax.atomic import AtomicStructure
                    s = AtomicStructure(session)
                    r = exemplar = template_lookup[res.name] = s.new_residue(
                        res.name, 'A', 1)
                    atom_map = {}
                    for ta in tmpl.atoms:
                        if ta.element.number > 1:
                            a = s.new_atom(ta.name, ta.element)
                            a.coord = ta.coord
                            r.add_atom(a)
                            atom_map[ta] = a
                            for tnb in ta.neighbors:
                                if tnb in atom_map:
                                    s.new_bond(a, atom_map[tnb])
                for a in res.atoms:
                    ea = exemplar.find_atom(a.name)
                    if ea:
                        a.idatm_type = ea.idatm_type
            for r in template_lookup.values():
                r.structure.delete()
            template_lookup.clear()

        for atom in struct.atoms:
            atom_type = atom.idatm_type
            idatm_type[atom] = atom_type
            if atom_type in type_info:
                # don't want to ask for idatm_type in middle
                # of hydrogen-adding loop (since that will
                # force a recomp), so remember here
                type_info_for_atom[atom] = type_info[atom_type]
                # if atom is in standard residue but has missing bonds to
                # heavy atoms, skip it instead of incorrectly protonating
                # (or possibly throwing an error if e.g. it's planar)
                # also
                # UNK/N residues will be missing some or all of their side-chain atoms, so
                # skip atoms that would otherwise be incorrectly protonated due to their
                # missing neighbors
                truncated = \
                        atom.is_missing_heavy_template_neighbors(no_template_okay=True) \
                    or \
                        (atom.residue.name in ["UNK", "N"] and atom.residue.polymer_type != Residue.PT_NONE
                        and unk_atom_truncated(atom)) \
                    or \
                        (atom.residue.polymer_type == Residue.PT_NUCLEIC and atom.name == "P"
                        and atom.num_explicit_bonds < 4)

                if truncated:
                    session.logger.warning(
                        "Not adding hydrogens to %s because it is missing heavy-atom"
                        " bond partners" % atom)
                    type_info_for_atom[atom] = type_info_class(
                        4, atom.num_bonds, atom.name)
                else:
                    atoms.append(atom)
                # sulfonamide nitrogens coordinating a metal
                # get an additional hydrogen stripped
                if coordinations.get(atom, []) and atom.element.name == "N":
                    if "Son" in [nb.idatm_type for nb in atom.neighbors]:
                        orig_ti = type_info[atom_type]
                        type_info_for_atom[atom] = orig_ti.__class__(
                            orig_ti.geometry, orig_ti.substituents - 1,
                            orig_ti.description)
                continue
            if atom in unknowns_info:
                type_info_for_atom[atom] = unknowns_info[atom]
                atoms.append(atom)
                continue
            remaining_unknowns.setdefault(atom.residue.name,
                                          set()).add(atom.name)
            # leave remaining unknown atoms alone
            type_info_for_atom[atom] = type_info_class(4, atom.num_bonds,
                                                       atom.name)

        for rname, atom_names in remaining_unknowns.items():
            names_text = ", ".join([nm for nm in atom_names])
            atom_text, obj_text = ("atoms",
                                   "them") if len(atom_names) > 1 else ("atom",
                                                                        "it")
            logger.warning(
                "Unknown hybridization for %s (%s) of residue type %s;"
                " not adding hydrogens to %s" %
                (atom_text, names_text, rname, obj_text))
        naming_schemas.update(
            determine_naming_schemas(struct, type_info_for_atom))

    if need_all:
        from chimerax.atomic import AtomicStructure
        for struct in [
                m for m in session.models if isinstance(m, AtomicStructure)
        ]:
            if struct in structures:
                continue
            for atom in struct.atoms:
                idatm_type[atom] = atom.idatm_type
                if atom.idatm_type in type_info:
                    type_info_for_atom[atom] = type_info[atom.idatm_type]

    for atom in atoms:
        if atom not in type_info_for_atom:
            continue
        bonding_info = type_info_for_atom[atom]
        total_hydrogens = bonding_info.substituents - atom.num_bonds
        for bonded in atom.neighbors:
            if bonded.element.number == 1:
                total_hydrogens += 1
        hydrogen_totals[atom] = total_hydrogens

    schemes = {}
    # HIS and CYS treated as 'unspecified'; use built-in typing
    for scheme_type, res_names, res_check, typed_atoms in [
        ('his', ["HID", "HIE", "HIP"], None, []),
        ('asp', asp_res_names, _asp_check, asp_prot_names),
        ('glu', glu_res_names, _glu_check, glu_prot_names),
        ('lys', ["LYS", "LYN"], _lys_check, ["NZ"]),
        ('cys', ["CYM"], _cys_check, ["SG"])
    ]:
        scheme = prot_schemes.get(scheme_type + '_scheme', None)
        if scheme is None:
            by_name = True
            scheme = {}
        else:
            by_name = False
        if not scheme:
            for s in structures:
                for r in s.residues:
                    if r.name in res_names and res_check and res_check(r):
                        if by_name:
                            scheme[r] = r.name
                        elif scheme_type != 'his':
                            scheme[r] = res_names[0]
                        # unset any explicit typing...
                        for ta in typed_atoms:
                            a = r.find_atom(ta)
                            if a:
                                a.idatm_type = None
        else:
            for r in scheme.keys():
                if res_check and not res_check(r, scheme[r]):
                    del scheme[r]
        schemes[scheme_type] = scheme
    # create dictionary keyed on histidine residue with value of another
    # dictionary keyed on the nitrogen atoms with boolean values: True
    # equals should be protonated
    his_Ns = {}
    for r, protonation in schemes["his"].items():
        delta = r.find_atom("ND1")
        epsilon = r.find_atom("NE2")
        if delta is None or epsilon is None:
            # find the ring, etc.
            rings = r.structure.rings()
            for ring in rings:
                if r in rings.atoms.residues:
                    break
            else:
                continue
            # find CG by locating CB-CG bond
            ring_bonds = ring.bonds
            for ra in ring.atoms:
                if ra.element.name != "C":
                    continue
                for ba, b in zip(ra.neighbors, ra.bonds):
                    if ba.element.name == "C" and b not in ring_bonds:
                        break
                else:
                    continue
                break
            else:
                continue
            nitrogens = [a for a in ring.atoms if a.element.name == "N"]
            if len(nitrogens) != 2:
                continue
            if ra in nitrogens[0].neighbors:
                delta, epsilon = nitrogens
            else:
                epsilon, delta = nitrogens
        if protonation == "HID":
            his_Ns.update({delta: True, epsilon: False})
        elif protonation == "HIE":
            his_Ns.update({delta: False, epsilon: True})
        elif protonation == "HIP":
            his_Ns.update({delta: True, epsilon: True})
        else:
            continue
    for n, do_prot in his_Ns.items():
        if do_prot:
            type_info_for_atom[n] = type_info["Npl"]
            n.idatm_type = idatm_type[n] = "Npl"
        else:
            type_info_for_atom[n] = type_info["N2"]
            n.idatm_type = idatm_type[n] = "N2"

    for r, protonation in schemes["asp"].items():
        _handle_acid_protonation_scheme_item(r, protonation, asp_res_names,
                                             asp_prot_names, type_info,
                                             type_info_for_atom)

    for r, protonation in schemes["glu"].items():
        _handle_acid_protonation_scheme_item(r, protonation, glu_res_names,
                                             glu_prot_names, type_info,
                                             type_info_for_atom)

    for r, protonation in schemes["lys"].items():
        nz = r.find_atom("NZ")
        if protonation == "LYS":
            it = 'N3+'
        else:
            it = 'N3'
        ti = type_info[it]
        if nz is not None:
            type_info_for_atom[nz] = ti
            # avoid explicitly setting type if possible
            if nz.idatm_type != it:
                nz.idatm_type = it

    for r, protonation in schemes["cys"].items():
        sg = r.find_atom("SG")
        if protonation == "CYS":
            it = 'S3'
        else:
            it = 'S3-'
        ti = type_info[it]
        if sg is not None:
            type_info_for_atom[sg] = ti
            # avoid explicitly setting type if possible
            if sg.idatm_type != it:
                sg.idatm_type = it

    return atoms, type_info_for_atom, naming_schemas, idatm_type, \
            hydrogen_totals, his_Ns, coordinations, fake_N, fake_C
Пример #5
0
class MolecularDynamicsTool(HtmlToolInstance):
    '''
     # Properties for the tool
    '''
    SESSION_ENDURING = False
    SESSION_SAVE = False
    CUSTOM_SCHEME = "kmd"

    def __init__(self, session, tool_name):
        super().__init__(session,
                         tool_name,
                         size_hint=(500, 500),
                         show_http_in_help=False)
        self.display_name = DISPLAY_NAME
        self._build_ui()

        self.atomStruct = None
        self.atomLocation = []
        self.surfacePositions = []
        self.attributeFile = False

    # Loads the html view to be shown
    def _build_ui(self):
        html_file = os.path.join(os.path.dirname(__file__), "dynamics.html")
        self.html_view.setUrl(pathlib.Path(html_file).as_uri())

    # This is to delete the model from the view
    def delete(self):
        super(HtmlToolInstance, self).delete()
        self.deleteModel()

    '''
     # This handles when a window.location becomes kmd:<command>
     #
     # @param url - The command
    '''

    def handle_scheme(self, url):
        command = url.path()

        if command.startswith("log"):
            self.session.logger.info(command[len("log_"):])
        elif command == "Open":
            self.openFile()
        elif command.startswith("FrameChange"):
            frame = int(command[len("FrameChange_T_"):])
            self.changeModel(frame, command[12] == 'T')
        elif command == "MovieDone":
            movie_encode(self.session, output=[self.movieName], format="h264")
        elif command == "MovieStart":
            fileName, filt = QFileDialog.getSaveFileName(
                caption="Save Movie", filter="MP4 File (*.mp4)")

            if fileName == "":
                return

            if fileName[-4:] != ".mp4":
                fileName = fileName + ".mp4"

            self.movieName = fileName
            movie_record(self.session)
            self.html_view.runJavaScript("startMovie()")
        elif command == "Attribute":
            self.loadAttributeFile()
        else:
            self.session.logger.info("Unknown Command: " + str(url))

    def loadAttributeFile(self):
        fileName, filt = QFileDialog.getOpenFileName(
            caption="Open Attribute File", filter="Attribute File (*.dat)")

        if fileName == "":
            return

        fileObj = open(fileName)
        lines = fileObj.readlines()[3:]
        fileObj.close()
        mapVals = {}

        for line in lines:
            parts = line.split('\t')[1:]
            mapVals[int(parts[0][1:])] = float(parts[1])

        maxValue = max(mapVals.values())
        minValue = min(mapVals.values())
        midValue = (maxValue + minValue) / 2

        # Color from min (blue) to mid (white) to max (red)

        for key in mapVals.keys():
            value = mapVals[key]
            per = (value - minValue) / (midValue - minValue) - 1
            color = abs(per) * 255
            colorSet = [255, 255 - color, 255 - color, 255
                        ] if per > 0 else [255 - color, 255 - color, 255, 255]
            colorSet = array(colorSet)

            self.atomStruct.residues[key - 1].ribbon_color = colorSet
            self.atomStruct.residues[key - 1].atoms.colors = colorSet

        js = "attributeName = '" + fileName.split(
            "/")[-1] + "';updateDisplay()"
        self.html_view.runJavaScript(js)
        self.attributeFile = True

        if self.atomStruct.surfaces() != []:
            run(self.session,
                "color #" + self.atomStruct.surfaces()[0].id_string +
                " fromatoms",
                log=False)

    # This is to remove model for changing
    def deleteModel(self):
        if self.atomStruct == None:
            return

        if self.atomStruct.deleted:
            return

        if self.atomStruct.surfaces() != []:
            self.session.models.remove([self.atomStruct.surfaces()[0]])

        self.session.models.remove([self.atomStruct])
        self.attributeFile = False
        self.atomStruct = None
        self.atomLocation = []
        self.surfacePositions = []
        js = "modelName = null; frameCount = 0; reset();"
        self.html_view.runJavaScript(js)

    # This is to move the atoms
    def changeModel(self, frame, surf):
        locs = self.atomLocation[frame]
        atms = self.atomStruct.atoms

        atms.coords = locs

        if surf:
            ### Need to recalculate the surfce here
            if self.atomStruct.surfaces() == []:
                surface(self.session, atoms=self.atomStruct.atoms)
            else:
                surfPos = self.surfacePositions[frame]

                if surfPos is None:
                    self.session.models.remove([self.atomStruct.surfaces()[0]])
                    surface(self.session, atoms=self.atomStruct.atoms)
                    self.surfacePositions[frame] = self.atomStruct.surfaces(
                    )[0]
                else:
                    self.session.models.remove([self.atomStruct.surfaces()[0]])
                    self.atomStruct.add([surfPos])
            ###
            run(self.session,
                "color #" + self.atomStruct.surfaces()[0].id_string +
                " fromatoms",
                log=False)
        elif self.atomStruct.surfaces() != []:
            self.session.models.remove([self.atomStruct.surfaces()[0]])

    # This opens a file
    def openFile(self):
        fileName, filt = QFileDialog.getOpenFileName(
            caption="Open PDB Trajectory File", filter="PDB File (*.pdb)")

        if fileName == "":
            return

        if self.atomStruct != None:
            self.deleteModel()

        # This create a simple Oxygen atom
        # Need to get this to display
        self.atomStruct = AtomicStructure(self.session)

        myFile = open(fileName)

        coords = []
        prevRes = None
        res = None
        modelNum = -1

        for line in myFile:
            if line.startswith("MODEL"):
                modelNum = modelNum + 1
                coords = []
                prevRes = None
                res = None
            elif line.startswith("ENDMDL"):
                self.atomLocation.append(array(coords))
            elif line.startswith("ATOM"):
                x = float(line[30:38].strip())
                y = float(line[38:46].strip())
                z = float(line[46:54].strip())

                name = line[12:16].strip()
                resName = line[17:20].strip()
                chain = line[21]
                resSeq = line[22:26].strip()
                element = line[76:78].strip()

                if element == "H":
                    continue

                coords.append([x, y, z])

                if modelNum != 0:
                    continue

                if resName + resSeq != prevRes:
                    prevRes = resName + resSeq
                    res = self.atomStruct.new_residue(resName, chain,
                                                      int(resSeq))

                atom = self.atomStruct.new_atom(name, element)
                atom.coord = array([x, y, z], dtype=float64)
                res.add_atom(atom)

        myFile.close()
        self.atomStruct.connect_structure()

        self.session.models.add([self.atomStruct])

        for i in range(len(self.atomLocation)):
            self.surfacePositions.append(None)

        self.atomStruct.atoms.coords = self.atomLocation[0]
        fileName = fileName.split("/")[-1]

        js = "modelName = '" + fileName + "'; frameCount = " + str(
            len(self.atomLocation)) + "; reset();"
        self.html_view.runJavaScript(js)
        run(self.session, "lighting full", log=False)
Пример #6
0
def _read_block(session, stream, line_number):
    # XYZ files are stored in blocks, with each block representing
    # a set of atoms.  This function reads a single block
    # and builds a ChimeraX AtomStructure instance containing
    # the atoms listed in the block.

    # First line should be an integer count of the number of
    # atoms in the block.
    count_line = stream.readline()
    if not count_line:
        # Reached EOF, normal termination condition
        return None, line_number
    line_number += 1
    try:
        count = int(count_line)
    except ValueError:
        session.logger.error("line %d: atom count missing" % line_number)
        return None, line_number

    # Create the AtomicStructure instance for atoms in this block.
    # All atoms in the structure are placed in one residue
    # since XYZ format does not partition atoms into groups.
    from chimerax.atomic import AtomicStructure
    from numpy import array, float64
    s = AtomicStructure(session)
    residue = s.new_residue("UNK", 'A', 1)

    # XYZ format supplies the atom element type only, but
    # ChimeraX keeps track of both the element type and
    # a unique name for each atom.  To construct the unique
    # atom name, the # 'element_count' dictionary is used
    # to track the number of atoms of each element type so far,
    # and the current count is used to build unique atom names.
    element_count = {}

    # Next line is a comment line
    s.comment = stream.readline().strip()
    line_number += 1

    # There should be "count" lines of atoms.
    for n in range(count):
        atom_line = stream.readline()
        if not atom_line:
            session.logger.error("line %d: atom data missing" % line_number)
            return None, line_number
        line_number += 1

        # Extract available data
        parts = atom_line.split()
        if len(parts) != 4:
            session.logger.error("line %d: atom data malformatted" %
                                 line_number)
            return None, line_number

        # Convert to required parameters for creating atom.
        # Since XYZ format only required atom element, we
        # create a unique atom name by putting a number after
        # the element name.
        xyz = [float(v) for v in parts[1:]]
        element = parts[0]
        n = element_count.get(element, 0) + 1
        name = element + str(n)
        element_count[element] = n

        # Create atom in AtomicStructure instance 's',
        # set its coordinates, and add to residue
        atom = s.new_atom(name, element)
        atom.coord = array(xyz, dtype=float64)
        residue.add_atom(atom)

    # Use AtomicStructure method to add bonds based on interatomic distances
    s.connect_structure()

    # Updating state such as atom types while adding atoms iteratively
    # is unnecessary (and generally incorrect for partial structures).
    # When all atoms have been added, the instance is notified to
    # tell it to update internal state.
    s.new_atoms()

    # Return AtomicStructure instance and current line number
    return s, line_number
Пример #7
0
    def _make_structure(self, block):
        from numpy import array
        from .maestro import IndexAttribute
        if self.atomic:
            from chimerax.atomic import AtomicStructure as SC
        else:
            from chimerax.atomic import Structure as SC
        from chimerax.atomic import Element
        atoms = block.get_sub_block("m_atom")
        if atoms is None:
            print("No m_atom block found")
            return None
        bonds = block.get_sub_block("m_bond")
        s = SC(self.session, auto_style=self.auto_style)
        SC.register_attr(self.session, "viewdockx_data", "ViewDockX")

        residue_map = {}
        atom_map = {}
        for row in range(atoms.size):
            attrs = atoms.get_attribute_map(row)
            index = attrs[IndexAttribute]

            # Get residue data and create if necessary
            res_seq = attrs["i_m_residue_number"]
            insert_code = attrs.get("s_m_insertion_code", None)
            if not insert_code:
                insert_code = ' '
            chain_id = attrs.get("s_m_chain_name", ' ')
            res_key = (chain_id, res_seq, insert_code)
            try:
                r = residue_map[res_key]
            except KeyError:
                res_name = attrs.get("s_m_pdb_residue_name", "UNK")
                r = s.new_residue(res_name, chain_id, res_seq, insert_code)
                residue_map[res_key] = r
            rgb = attrs.get("s_m_ribbon_color_rgb", None)
            if rgb:
                r.ribbon_color = self._get_color(rgb)

            # Get atom data and create
            try:
                name = attrs["s_m_pdb_atom_name"]
            except KeyError:
                name = attrs.get("s_m_atom_name", "")
            name = name.strip()
            atomic_number = attrs.get("i_m_atomic_number", 6)
            element = Element.get_element(atomic_number)
            if not name:
                name = element.name
            a = s.new_atom(name, element)
            a.coord = array([atoms.get_attribute("r_m_x_coord", row),
                             atoms.get_attribute("r_m_y_coord", row),
                             atoms.get_attribute("r_m_z_coord", row)])
            try:
                a.bfactor = attrs["r_m_pdb_tfactor"]
            except (KeyError, TypeError):
                a.bfactor = 0.0
            try:
                a.occupancy = attrs["r_m_pdb_occupancy"]
            except (KeyError, TypeError):
                a.occupancy = 1.0
            rgb = attrs.get("s_m_color_rgb", None)
            if rgb:
                a.color = self._get_color(rgb)

            # Add atom to residue and to atom map for bonding later
            r.add_atom(a)
            atom_map[index] = a
        if bonds is None or bonds.size == 0:
            s.connect_structure()
        else:
            for row in range(bonds.size):
                attrs = bonds.get_attribute_map(row)
                fi = attrs["i_m_from"]
                ti = attrs["i_m_to"]
                if ti < fi:
                    # Bonds are reported in both directions. We only need one.
                    continue
                afi = atom_map[fi]
                ati = atom_map[ti]
                b = s.new_bond(afi, ati)
                b.order = attrs["i_m_order"]
        return s
Пример #8
0
 def _make_structure(self):
     """Build ChimeraX structure and reset structure data cache"""
     try:
         if self._molecule is None:
             return
         if self.atomic:
             from chimerax.atomic import AtomicStructure as SC
         else:
             from chimerax.atomic import Structure as SC
         # Create structure
         s = SC(self.session, auto_style=self.auto_style)
         s.name = self._molecule.mol_name
         SC.register_attr(self.session, "viewdockx_data", "ViewDockX")
         s.viewdockx_data = self._data
         if self._molecule.charge_type:
             s.charge_model = self._molecule.charge_type
         if self._molecule.mol_type:
             s.mol2_type = self._molecule.mol_type
         if self._molecule.mol_comment:
             s.mol2_comment = self._molecule.mol_comment
         # Create residues
         substid2residue = {}
         for subst_data in self._substs:
             # ChimeraX limitation: 4-letter residue type
             name = subst_data.subst_name[:4]
             chain = subst_data.chain
             if chain is None or chain == "****":
                 chain = ''
             residue = s.new_residue(name, chain, subst_data.subst_id)
             substid2residue[subst_data.subst_id] = residue
         # Create atoms
         atomid2atom = {}
         from numpy import array, float64
         for atom_data in self._atoms:
             name = atom_data.atom_name
             element = atom_data.atom_type
             if '.' in element:
                 element = element.split('.')[0]
             atom = s.new_atom(name, element)
             atom.coord = array([atom_data.x, atom_data.y, atom_data.z],
                                dtype=float64)
             if atom_data.charge is not None:
                 atom.charge = atom_data.charge
             try:
                 residue = substid2residue[atom_data.subst_id]
             except KeyError:
                 # Must not have been a substructure section
                 residue = s.new_residue("UNK", '', atom_data.subst_id)
                 substid2residue[atom_data.subst_id] = residue
             residue.add_atom(atom)
             atomid2atom[atom_data.atom_id] = atom
         # Create bonds
         for bond_data in self._bonds:
             try:
                 origin = atomid2atom[bond_data.origin_atom_id]
                 target = atomid2atom[bond_data.target_atom_id]
             except KeyError:
                 self.session.logger.warning("bad atom index in bond")
             else:
                 s.new_bond(origin, target)
         self.structures.append(s)
     finally:
         self._reset_structure()
Пример #9
0
class MolecularDynamicsTool(HtmlToolInstance):
    '''
     # Properties for the tool
    '''
    SESSION_ENDURING = False
    SESSION_SAVE = False
    CUSTOM_SCHEME = "kmd"

    def __init__(self, session, tool_name):
        super().__init__(session,
                         tool_name,
                         size_hint=(500, 500),
                         show_http_in_help=False)
        self.display_name = DISPLAY_NAME
        self._build_ui()

        self.atomStruct = None
        self.atomLocation = []
        self.surfacePositions = []
        self.attributeFile = False

    # Loads the html view to be shown
    def _build_ui(self):
        html_file = os.path.join(os.path.dirname(__file__), "dynamics.html")
        self.html_view.setUrl(pathlib.Path(html_file).as_uri())

    # This is to delete the model from the view
    def delete(self):
        super(HtmlToolInstance, self).delete()
        self.deleteModel()

    '''
     # This handles when a window.location becomes kmd:<command>
     #
     # @param url - The command
    '''

    def handle_scheme(self, url):
        command = url.path()

        if command.startswith("log"):
            self.session.logger.info(command[len("log_"):])
        elif command == "Open":
            self.openFile()
        elif command.startswith("FrameChange"):
            frame = int(command[len("FrameChange_T_"):])
            self.changeModel(frame, command[12] == 'T')
        elif command == "MovieDone":
            movie_encode(self.session, output=[self.movieName], format="h264")
        elif command == "MovieStart":
            fileName, filt = QFileDialog.getSaveFileName(
                caption="Save Movie", filter="MP4 File (*.mp4)")

            if fileName == "":
                return

            if fileName[-4:] != ".mp4":
                fileName = fileName + ".mp4"

            self.movieName = fileName
            movie_record(self.session)
            self.html_view.runJavaScript("startMovie()")
        elif command == "Attribute":
            self.loadAttributeFile()
        else:
            self.session.logger.info("Unknown Command: " + str(url))

    def loadAttributeFile(self):
        fileName, filt = QFileDialog.getOpenFileName(
            caption="Open Attribute File", filter="Attribute File (*.dat)")

        if fileName == "":
            return

        fileObj = open(fileName)
        lines = fileObj.readlines()[3:]
        fileObj.close()
        mapVals = {}

        for line in lines:
            parts = line.split('\t')[1:]
            mapVals[int(parts[0][1:])] = float(parts[1])

        maxValue = max(mapVals.values())
        minValue = min(mapVals.values())
        midValue = (maxValue + minValue) / 2

        # Color from min (blue) to mid (white) to max (red)

        for key in mapVals.keys():
            value = mapVals[key]
            per = (value - minValue) / (midValue - minValue) - 1
            color = abs(per) * 255
            colorSet = [255, 255 - color, 255 - color, 255
                        ] if per > 0 else [255 - color, 255 - color, 255, 255]
            colorSet = array(colorSet)

            self.atomStruct.residues[key - 1].ribbon_color = colorSet
            self.atomStruct.residues[key - 1].atoms.colors = colorSet

        js = "attributeName = '" + fileName.split(
            "/")[-1] + "';updateDisplay()"
        self.html_view.runJavaScript(js)
        self.attributeFile = True

        if self.atomStruct.surfaces() != []:
            run(self.session,
                "color #" + self.atomStruct.surfaces()[0].id_string +
                " fromatoms",
                log=False)

    # This is to remove model for changing
    def deleteModel(self):
        if self.atomStruct == None:
            return

        if self.atomStruct.deleted:
            return

        if self.atomStruct.surfaces() != []:
            self.session.models.remove([self.atomStruct.surfaces()[0]])

        self.session.models.remove([self.atomStruct])
        self.attributeFile = False
        self.atomStruct = None
        self.atomLocation = []
        self.surfacePositions = []
        js = "modelName = null; frameCount = 0; reset();"
        self.html_view.runJavaScript(js)

    # This is to move the atoms
    def changeModel(self, frame, surf):
        locs = self.atomLocation[frame]
        atms = self.atomStruct.atoms

        atms.coords = locs

        if surf:
            ### Need to recalculate the surfce here
            if self.atomStruct.surfaces() == []:
                surface(self.session, atoms=self.atomStruct.atoms)
            else:
                surfPos = self.surfacePositions[frame]

                if surfPos is None:
                    self.session.models.remove([self.atomStruct.surfaces()[0]])
                    surface(self.session, atoms=self.atomStruct.atoms)
                    self.surfacePositions[frame] = self.atomStruct.surfaces(
                    )[0]
                else:
                    self.session.models.remove([self.atomStruct.surfaces()[0]])
                    self.atomStruct.add([surfPos])
            ###
            run(self.session,
                "color #" + self.atomStruct.surfaces()[0].id_string +
                " fromatoms",
                log=False)
        elif self.atomStruct.surfaces() != []:
            self.session.models.remove([self.atomStruct.surfaces()[0]])

    # This opens a file
    def openFile(self):
        fileName, filt = QFileDialog.getOpenFileName(caption="Open Trajectory File",
                                                     filter="PDB File (*.pdb);;" \
                                                            "H5 Trajectory File (*.h5);;" \
                                                            "HDF5 Trajectory File (*.hdf5)" \
                                                            "GRO Topology File (*.gro)"
                                                     )
        print(fileName)
        print(filt)

        if fileName == "":
            return

        if filt == "(*.gro)":
            gro_fileName = fileName
            fileName, filt = QFileDialog.getOpenFileName(caption="Open Trajectory File",
                                                         filter="XTC Trajectory File (*.xtc);;" \
                                                                "TRR Trajectory File (*.trr);;" \
                                                         )
            print(fileName)
            print(filt)
        else:
            gro_fileName = None

        if self.atomStruct != None:
            self.deleteModel()

        # This create a simple Oxygen atom
        # Need to get this to display
        self.atomStruct = AtomicStructure(self.session)

        if filt in ["(*.xtc)", "(*.trr)"]:
            trj = mdtraj.load(fileName, topology=gro_fileName)
        else:
            trj = mdtraj.load(fileName)
        trj.atom_slice(trj.topology.select("not element H"))

        table, bond_table = trj.topology.to_dataframe()
        table.rename(columns={
            "name": "atomname",
            "resName": "residue_name",
            "chainID": "chain_id",
            "resSeq": "pos"
        },
                     inplace=True)
        table["pos"] = table["pos"].astype(int)
        xyz = trj.xyz[0]
        table["loc"] = [array(x, dtype=float64) for x in xyz]
        res_infos = table[["residue_name", "chain_id", "pos"
                           ]].drop_duplicates(keep="first").to_dict("records")
        for res in res_infos:
            residue = self.atomStruct.new_residue(**res)
            qry = ' and '.join(
                ['{} == {}'.format(k, v) for k, v in res.items()])
            res_atoms = table.query(qry)[["name", "element",
                                          "loc"]].to_dict("records")
            for a in res_atoms:
                atom = self.atomStruct.new_atom({
                    "name": a["name"],
                    "element": a["element"]
                })
                atom.coord = a["loc"]
                residue.add_atom(atom)

        for frame in range(1, trj.n_frames):
            xyz = trj.xyz[frame]
            self.atomLocation.append(array(xyz, dtype=float64))

        self.atomStruct.connect_structure()
        self.session.models.add([self.atomStruct])

        for i in range(len(self.atomLocation)):
            self.surfacePositions.append(None)

        self.atomStruct.atoms.coords = self.atomLocation[0]
        fileName = fileName.split("/")[-1]

        js = "modelName = '" + fileName + "'; frameCount = " + str(
            len(self.atomLocation)) + "; reset();"
        self.html_view.runJavaScript(js)
        run(self.session, "lighting full", log=False)