001/*
002 *                    BioJava development code
003 *
004 * This code may be freely distributed and modified under the
005 * terms of the GNU Lesser General Public Licence.  This should
006 * be distributed with the code.  If you do not have a copy,
007 * see:
008 *
009 *      http://www.gnu.org/copyleft/lesser.html
010 *
011 * Copyright for this code is held jointly by the individual
012 * authors.  These should be listed in @author doc comments.
013 *
014 * For more information on the BioJava project and its aims,
015 * or to join the biojava-l mailing list, visit the home page
016 * at:
017 *
018 *      http://www.biojava.org/
019 *
020 */
021package org.biojava.nbio.structure.io.mmtf;
022
023import java.io.Serializable;
024import java.text.ParseException;
025import java.text.SimpleDateFormat;
026import java.util.ArrayList;
027import java.util.Collections;
028import java.util.Date;
029import java.util.HashMap;
030import java.util.LinkedHashMap;
031import java.util.List;
032import java.util.Map;
033
034import javax.vecmath.Matrix4d;
035
036import org.biojava.nbio.structure.AminoAcid;
037import org.biojava.nbio.structure.AminoAcidImpl;
038import org.biojava.nbio.structure.Atom;
039import org.biojava.nbio.structure.AtomImpl;
040import org.biojava.nbio.structure.BondImpl;
041import org.biojava.nbio.structure.Chain;
042import org.biojava.nbio.structure.ChainImpl;
043import org.biojava.nbio.structure.Element;
044import org.biojava.nbio.structure.EntityInfo;
045import org.biojava.nbio.structure.EntityType;
046import org.biojava.nbio.structure.Group;
047import org.biojava.nbio.structure.HetatomImpl;
048import org.biojava.nbio.structure.NucleotideImpl;
049import org.biojava.nbio.structure.PDBCrystallographicInfo;
050import org.biojava.nbio.structure.PDBHeader;
051import org.biojava.nbio.structure.PdbId;
052import org.biojava.nbio.structure.Structure;
053import org.biojava.nbio.structure.StructureImpl;
054import org.biojava.nbio.structure.StructureTools;
055import org.biojava.nbio.structure.chem.ChemComp;
056import org.biojava.nbio.structure.chem.PolymerType;
057import org.biojava.nbio.structure.chem.ResidueType;
058import org.biojava.nbio.structure.quaternary.BioAssemblyInfo;
059import org.biojava.nbio.structure.quaternary.BiologicalAssemblyTransformation;
060import org.biojava.nbio.structure.xtal.CrystalCell;
061import org.biojava.nbio.structure.xtal.SpaceGroup;
062import org.rcsb.mmtf.api.StructureAdapterInterface;
063import org.rcsb.mmtf.dataholders.MmtfStructure;
064import org.slf4j.Logger;
065import org.slf4j.LoggerFactory;
066
067
068/**
069 * A biojava specific structure inflator for MMTF.
070 * Should be ported to biojava code.
071 *
072 * @author Anthony Bradley
073 * @since 5.0
074 *
075 */
076public class MmtfStructureReader implements StructureAdapterInterface, Serializable {
077
078        /** The Constant serialVersionUID. */
079        private static final long serialVersionUID = 6772030485225130853L;
080
081        /** The logger */
082        private static final Logger logger = LoggerFactory.getLogger(MmtfStructureReader.class);
083
084        /** The structure. */
085        private Structure structure;
086
087        /** The model number. */
088        private int modelNumber;
089
090        /** The chain. */
091        private Chain chain;
092
093        /** The group. */
094        private Group group;
095
096        /** The atoms in a group. */
097        private List<Atom> atomsInGroup;
098
099        /** All the atoms. */
100        private Atom[] allAtoms;
101        private int atomCounter;
102
103        /** The list of EntityInformation */
104        private List<EntityInfo> entityInfoList;
105
106        /** All the chains */
107        private List<Chain> chainList;
108
109        /** All the chains as a list of maps */
110        private List<Map<String,Chain>> chainMap;
111
112        private List<double[]> transformList;
113
114        private int bioassIndex;
115
116        private Map<String,String> chainSequenceMap;
117
118        /**
119         * Instantiates a new bio java structure decoder.
120         */
121        public MmtfStructureReader() {
122                structure = new StructureImpl();
123                modelNumber = 0;
124                entityInfoList = new ArrayList<>();
125                chainList = new ArrayList<>();
126                chainMap = new ArrayList<>();
127                transformList = new ArrayList<>();
128                chainSequenceMap = new HashMap<>();
129        }
130
131        /**
132         * Gets the structure.
133         *
134         * @return the structure
135         */
136        public Structure getStructure() {
137                return structure;
138        }
139
140        @Override
141        public void finalizeStructure() {
142                // Number the remaining ones
143                int counter =0;
144                // Add the entity info
145                for (EntityInfo entityInfo : entityInfoList) {
146                        counter++;
147                        entityInfo.setMolId(counter);
148                }
149                structure.setEntityInfos(entityInfoList);
150                // Add the actual chains
151                for(int i=0; i<chainMap.size(); i++) {
152                        // Now add the chain information
153                        Map<String, Chain> modelChainMap = chainMap.get(i);
154                        for(Chain modelChain : modelChainMap.values()){
155                                structure.addChain(modelChain, i);
156                                String sequence = chainSequenceMap.get(modelChain.getId());
157                                if (sequence == null) {
158                                        logger.warn("Sequence is null for chain with asym_id {}. Most likely the chain is non-polymeric. Will not add seqres groups for it.", modelChain.getId());
159                                        continue;
160                                }
161                                MmtfUtils.addSeqRes(modelChain, sequence);
162                        }
163                }
164                StructureTools.cleanUpAltLocs(structure);
165        }
166
167        @Override
168        public void initStructure(int totalNumBonds, int totalNumAtoms, int totalNumGroups,
169                        int totalNumChains, int totalNumModels, String modelId) {
170                structure.setPdbId(new PdbId(modelId));
171                allAtoms = new Atom[totalNumAtoms];
172        }
173
174
175        /* (non-Javadoc)
176         * @see org.rcsb.mmtf.decoder.StructureDecoderInterface#setModelInfo(int, int)
177         */
178        @Override
179        public void setModelInfo(int inputModelNumber,
180                        int chainCount) {
181                modelNumber = inputModelNumber;
182                structure.addModel(new ArrayList<Chain>(chainCount));
183                chainMap.add(new LinkedHashMap<>());
184        }
185
186        /* (non-Javadoc)
187         * @see org.rcsb.mmtf.decoder.StructureDecoderInterface
188         * #setChainInfo(java.lang.String, int)
189         */
190        @Override
191        public void setChainInfo(String chainId, String chainName, int groupCount) {
192                // First check to see if the chain exists
193                Map<String, Chain> modelChainMap = chainMap.get(modelNumber);
194                if(modelChainMap.containsKey(chainId)){
195                        chain = modelChainMap.get(chainId);
196                }
197                // If we need to set a new chain do this
198                else{
199                        chain = new ChainImpl();
200                        chain.setId(chainId.trim());
201                        chain.setName(chainName);
202                        chain.setAtomGroups(new ArrayList<>(groupCount));
203                        modelChainMap.put(chainId, chain);
204                        chainList.add(chain);
205                }
206        }
207
208
209        /* (non-Javadoc)
210         * @see org.rcsb.mmtf.decoder.StructureDecoderInterface
211         * #setGroupInfo(java.lang.String, int, char, int, int)
212         */
213        @Override
214        public void setGroupInfo(String groupName, int groupNumber,
215                        char insertionCode, String chemCompType, int atomCount, int bondCount,
216                        char singleLetterCode, int sequenceIndexId, int secStructType) {
217                // Get the polymer type
218                ResidueType residueType = ResidueType.getResidueTypeFromString(chemCompType);
219                if (residueType == null)
220                        throw new IllegalStateException("Couldn't resolve residue type for "+ chemCompType);
221
222                int polymerType = getGroupTypIndicator(residueType.polymerType);
223                switch (polymerType) {
224                case 1:
225                        AminoAcid aa = new AminoAcidImpl();
226                        // Now set the one letter code
227                        aa.setAminoType(singleLetterCode);
228                        group = aa;
229                        break;
230                case 2:
231                        group = new NucleotideImpl();
232                        break;
233                default:
234                        group = new HetatomImpl();
235                        break;
236                }
237                atomsInGroup = new ArrayList<>();
238                ChemComp chemComp = new ChemComp();
239                chemComp.setOneLetterCode(String.valueOf(singleLetterCode));
240                chemComp.setType(chemCompType.toUpperCase());
241                chemComp.setResidueType(residueType);
242                chemComp.setPolymerType(residueType.polymerType);
243                group.setChemComp(chemComp);
244                group.setPDBName(groupName);
245                if (insertionCode == MmtfStructure.UNAVAILABLE_CHAR_VALUE) {
246                        group.setResidueNumber(chain.getName().trim(), groupNumber, null);
247                } else {
248                        group.setResidueNumber(chain.getName().trim(),
249                                        groupNumber, insertionCode);
250                }
251                group.setAtoms(new ArrayList<>(atomCount));
252                if (polymerType==1 || polymerType==2) {
253                        MmtfUtils.insertSeqResGroup(chain, group, sequenceIndexId);
254                }
255                if (atomCount > 0) {
256                        chain.addGroup(group);
257                }
258                MmtfUtils.setSecStructType(group, secStructType);
259        }
260
261        /**
262         *
263         * @return
264         */
265        private Group getGroupWithSameResNumButDiffPDBName() {
266                // If this chain already has this group number
267                for (Group g : chain.getAtomGroups() ) {
268                        if (g.getResidueNumber().equals(group.getResidueNumber())) {
269                                if( ! g.getPDBName().equals(group.getPDBName() )){
270                                        return g;
271                                }
272                        }
273                }
274                return null;
275        }
276
277        /* (non-Javadoc)
278         * @see org.rcsb.mmtf.decoder.StructureDecoderInterface#
279         * setAtomInfo(java.lang.String, int, char, float, float,
280         * float, float, float, java.lang.String, int)
281         */
282        @Override
283        public void setAtomInfo(String atomName,
284                        int serialNumber, char alternativeLocationId, float x,
285                        float y, float z, float occupancy,
286                        float temperatureFactor,
287                        String element, int charge) {
288                Atom atom = new AtomImpl();
289                Group altGroup = null;
290                atom.setPDBserial(serialNumber);
291                atom.setName(atomName.trim());
292                atom.setElement(Element.valueOfIgnoreCase(element));
293                if(alternativeLocationId==MmtfStructure.UNAVAILABLE_CHAR_VALUE){
294                        alternativeLocationId = ' ';
295                }
296                if (alternativeLocationId != ' ') {
297                        // Get the altGroup
298                        altGroup = getCorrectAltLocGroup(alternativeLocationId);
299                        atom.setAltLoc(alternativeLocationId);
300                } else {
301                        atom.setAltLoc(Character.valueOf(' '));
302                }
303                atom.setX(x);
304                atom.setY(y);
305                atom.setZ(z);
306                atom.setOccupancy(occupancy);
307                atom.setTempFactor(temperatureFactor);
308                atom.setCharge((short) charge);
309                if (altGroup == null) {
310                        group.addAtom(atom);
311                } else {
312                        altGroup.setChain(chain);
313                        altGroup.addAtom(atom);
314                }
315
316                // IF the main group doesn't have this atom
317                if (!group.hasAtom(atom.getName())) {
318
319                        // If it's not a microheterogenity case
320                        if (group.getPDBName().equals(atom.getGroup().getPDBName())) {
321                                // And it's not a deuterated case.  'nanoheterogenity'
322                                if(!StructureTools.hasNonDeuteratedEquiv(atom,group)){
323                                        group.addAtom(atom);
324                                }
325                        }
326                }
327                atomsInGroup.add(atom);
328                allAtoms[atomCounter] = atom;
329                atomCounter++;
330        }
331
332        /* (non-Javadoc)
333         * @see org.rcsb.mmtf.decoder.StructureDecoderInter
334         * face#setGroupBonds(int, int, int)
335         */
336        @Override
337        public void setGroupBond(int indOne, int indTwo, int bondOrder) {
338
339                // Get the atoms
340                Atom atomOne = atomsInGroup.get(indOne);
341                Atom atomTwo = atomsInGroup.get(indTwo);
342
343                // set the new bond
344                new BondImpl(atomOne, atomTwo, bondOrder);
345
346        }
347
348        /* (non-Javadoc)
349         * @see org.rcsb.mmtf.decoder.StructureDecoder
350         * Interface#setInterGroupBonds(int, int, int)
351         */
352        @Override
353        public void setInterGroupBond(int indOne, int indTwo, int bondOrder) {
354
355                // Get the atoms
356                Atom atomOne = allAtoms[indOne];
357                Atom atomTwo = allAtoms[indTwo];
358
359                // set the new bond (this
360                new BondImpl(atomOne, atomTwo, bondOrder);
361        }
362
363
364        /**
365         * Generates Alternate location groups.
366         *
367         * @param altLoc the alt loc
368         * @return the correct alt loc group
369         */
370        private Group getCorrectAltLocGroup(Character altLoc) {
371                // see if we know this altLoc already;
372                List<Atom> atoms = group.getAtoms();
373                if (atoms.size() > 0) {
374                        Atom a1 = atoms.get(0);
375                        // we are just adding atoms to the current group
376                        // probably there is a second group following later...
377                        if (a1.getAltLoc().equals(altLoc)) {
378                                return group;   }
379                }
380
381                // Get the altLocGroup
382                Group altLocgroup = group.getAltLocGroup(altLoc);
383                if (altLocgroup != null) {
384                        return altLocgroup;
385                }
386                // If the group already exists (microheterogenity).
387                Group oldGroup = getGroupWithSameResNumButDiffPDBName();
388                if (oldGroup!= null){
389                        Group altLocG = group;
390                        group = oldGroup;
391                        group.addAltLoc(altLocG);
392                        chain.getAtomGroups().remove(altLocG);
393                        return altLocG;
394                }
395                // no matching altLoc group found.
396                // build it up.
397                if (group.getAtoms().size() == 0) {
398                        return group;
399                }
400                Group altLocG = (Group) group.clone();
401                // drop atoms from cloned group...
402                // https://redmine.open-bio.org/issues/3307
403                altLocG.setAtoms(new ArrayList<Atom>());
404                altLocG.getAltLocs().clear();
405                group.addAltLoc(altLocG);
406                return altLocG;
407
408        }
409
410
411        /* (non-Javadoc)
412         * @see org.rcsb.mmtf.decoder.StructureDecoderInterface#
413         * setXtalInfo(java.lang.String, java.util.List)
414         */
415        @Override
416        public void setXtalInfo(String spaceGroupString, float[] unitCell, double[][] ncsOperMatrixList) {
417                // Now set the xtalographic information
418                PDBCrystallographicInfo pci = new PDBCrystallographicInfo();
419                SpaceGroup spaceGroup = SpaceGroup.parseSpaceGroup(spaceGroupString);
420                pci.setSpaceGroup(spaceGroup);
421                if (unitCell.length > 0) {
422                        CrystalCell cell = new CrystalCell(unitCell[0], unitCell[1],
423                                        unitCell[2], unitCell[3], unitCell[4], unitCell[5]);
424                        pci.setCrystalCell(cell);
425                        structure.setCrystallographicInfo(pci);
426                }
427
428                pci.setNcsOperators(MmtfUtils.getNcsAsMatrix4d(ncsOperMatrixList));
429        }
430
431
432        /**
433         * Get the type of group (0,1 or 2) depending on whether it is an amino aicd (1), nucleic acid (2) or ligand (0)
434         * @param polymerType
435         * @return The type of group. (0,1 or 2) depending on whether it is an amino aicd (1), nucleic acid (2) or ligand (0)
436         */
437        private int getGroupTypIndicator(PolymerType polymerType) {
438                if(PolymerType.PROTEIN_ONLY.contains(polymerType)){
439                        return 1;
440                }
441                if(PolymerType.POLYNUCLEOTIDE_ONLY.contains(polymerType)){
442                        return 2;
443                }
444                return 0;
445        }
446
447
448        @Override
449        public void setBioAssemblyTrans(int bioAssemblyId, int[] inputChainIndices, double[] inputTransform, String name) {
450                // Biojava uses this as a one indexed id.
451                bioAssemblyId++;
452                if(bioassIndex!=bioAssemblyId){
453                        transformList = new ArrayList<>();
454                        bioassIndex = bioAssemblyId;
455                }
456                PDBHeader pdbHeader = structure.getPDBHeader();
457                // Get the bioassembly data
458                Map<Integer, BioAssemblyInfo> bioAssemblies = pdbHeader.getBioAssemblies();
459                // Get the bioassembly itself (if it exists
460                BioAssemblyInfo bioAssInfo;
461                if (bioAssemblies.containsKey(bioAssemblyId)){
462                        bioAssInfo = bioAssemblies.get(bioAssemblyId);
463                }
464                else{
465                        bioAssInfo = new  BioAssemblyInfo();
466                        bioAssInfo.setTransforms(new ArrayList<BiologicalAssemblyTransformation>());
467                        bioAssemblies.put(bioAssemblyId, bioAssInfo);
468                        bioAssInfo.setId(bioAssemblyId);
469                }
470
471                for(int currChainIndex : inputChainIndices){
472                        BiologicalAssemblyTransformation bioAssTrans = new BiologicalAssemblyTransformation();
473                        Integer transId = transformList.indexOf(inputTransform)+1;
474                        if(transId==0){
475                                transformList.add(inputTransform);
476                                transId = transformList.indexOf(inputTransform)+1;
477                        }
478                        bioAssTrans.setId(transId.toString());
479                        // If it actually has an index - if it doesn't it is because the chain has no density.
480                        if (currChainIndex!=-1){
481                                bioAssTrans.setChainId(chainList.get(currChainIndex).getId());
482                        }
483                        else {
484                                continue;
485                        }
486                        // Now set matrix
487                        Matrix4d mat4d = new Matrix4d(inputTransform);
488                        bioAssTrans.setTransformationMatrix(mat4d);
489                        // Now add this
490                        bioAssInfo.getTransforms().add(bioAssTrans);
491                        // sort transformations into a unique order
492                        Collections.sort(bioAssInfo.getTransforms());
493                }
494        }
495
496        @Override
497        public void setEntityInfo(int[] chainIndices, String sequence, String description, String type) {
498                // First get the chains
499                EntityInfo entityInfo = new EntityInfo();
500                entityInfo.setDescription(description);
501                entityInfo.setType(EntityType.entityTypeFromString(type));
502                List<Chain> chains = new ArrayList<>();
503                // Now loop through the chain ids and make a list of them
504                for( int index : chainIndices) {
505                        chains.add(chainList.get(index));
506                        chainList.get(index).setEntityInfo(entityInfo);
507                        chainSequenceMap.put(chainList.get(index).getId(), sequence);
508                }
509                entityInfo.setChains(chains);
510                entityInfoList.add(entityInfo);
511        }
512
513        @Override
514        public void setHeaderInfo(float rFree, float rWork, float resolution, String title, String depositionDate,
515                        String releaseDate, String[] experimentalMethods) {
516                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
517                // Get the pdb header
518                PDBHeader pdbHeader = structure.getPDBHeader();
519                pdbHeader.setTitle(title);
520                pdbHeader.setResolution(resolution);
521                pdbHeader.setRfree(rFree);
522                pdbHeader.setRwork(rWork);
523                // Now loop through the techniques and add them in
524                if (experimentalMethods!=null) {
525                        for (String techniqueStr : experimentalMethods) {
526                                pdbHeader.setExperimentalTechnique(techniqueStr);
527                        }
528                }
529                // Set the dates
530                if(depositionDate!=null){
531                        try {
532                                Date depDate = formatter.parse(depositionDate);
533                                pdbHeader.setDepDate(depDate);
534                        } catch (ParseException e) {
535                                logger.warn("Could not parse date string '{}', depositon date will be unavailable", depositionDate);
536                        }
537                }
538                else{
539                        pdbHeader.setDepDate(new Date(0));
540                }
541                if(releaseDate!=null){
542                        try {
543                                Date relDate = formatter.parse(releaseDate);
544                                pdbHeader.setRelDate(relDate);
545                        } catch (ParseException e) {
546                                logger.warn("Could not parse date string '{}', release date will be unavailable", releaseDate);
547                        }
548                }
549                else{
550                        pdbHeader.setRelDate(new Date(0));
551                }
552        }
553}