diff --git a/.appveyor.yml b/.appveyor.yml index c779d98..87cd2ba 100644 --- a/.appveyor.yml +++ b/.appveyor.yml @@ -2,7 +2,7 @@ environment: # For Python versions available on Appveyor, see # https://www.appveyor.com/docs/windows-images-software/#python matrix: - - {APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015, PYTHON: "C:\\Python27"} + - {APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017, PYTHON: "C:\\Python36-x64"} - {APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019, PYTHON: "C:\\Python37-x64"} - {APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019, PYTHON: "C:\\Python38"} - {APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019, PYTHON: "C:\\Python38-x64"} diff --git a/.github/workflows/testpy.yml b/.github/workflows/testpy.yml index 9ff8f8f..9ca33ac 100644 --- a/.github/workflows/testpy.yml +++ b/.github/workflows/testpy.yml @@ -11,12 +11,8 @@ jobs: os: [ubuntu-latest] python-version: ['3.8', '3.9', '3.10', '3.11', '3.12', '3.13'] include: - - os: ubuntu-20.04 - python-version: '3.6' - os: macos-latest python-version: '3.10' - env: - PY2: ${{ startsWith(matrix.python-version, 2) && 'on' || 'off' }} runs-on: ${{ matrix.os }} steps: @@ -33,11 +29,7 @@ jobs: - name: Test run: | pytest --cov=modelcif --cov-branch --cov-report=xml --cov-append -v . - if [ "${{ env.PY2 }}" == "on" ]; then - flake8 --ignore E402,W503,W504 --exclude util/make-mmcif.py,examples/validate_mmcif.py - else - flake8 --ignore E402,W503,W504 - fi + flake8 --ignore E402,W503,W504 - uses: codecov/codecov-action@v4 env: CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} diff --git a/ChangeLog.rst b/ChangeLog.rst index 7cb3951..247740e 100644 --- a/ChangeLog.rst +++ b/ChangeLog.rst @@ -1,3 +1,24 @@ +1.4 - 2025-06-11 +================ + - Revision information and information on how the data in the file can + be used are now read from or written to mmCIF or BinaryCIF files. + See :attr:`System.revisions` and :attr:`System.data_usage` respectively. + - New classes have been added to :mod:`modelcif.alignment`, + :mod:`modelcif.qa_metric`, and :mod:`modelcif.protocol` to support + all sequence identity denominators (#47), QA metric types (#45), + and protocol step types (#44) respectively, as defined in the ModelCIF + dictionary. + - The new :class:`modelcif.alignment.Local` and + :class:`modelcif.alignment.Multiple` classes allow for both local + alignments and multiple sequence alignments to be described (#43). + - Bugfix: sequence identity and alignment score (``identity`` and ``score`` + arguments to :class:`modelcif.alignment.Pair`) are now optional, to + match the mmCIF dictionary (#49). + - Bugfix: information in ``_ma_template_non_poly.details`` is now read + from mmCIF or BinaryCIF files (#48). + - Bugfix: files containing empty or missing ``_ma_qa_metric.description`` + can now be read (#46). + 1.3 - 2025-01-14 ================ - The new :class:`modelcif.CustomTemplate` class allows for custom templates diff --git a/README.md b/README.md index 3676510..b023341 100644 --- a/README.md +++ b/README.md @@ -7,9 +7,9 @@ [![codecov](https://codecov.io/gh/ihmwg/python-modelcif/branch/main/graph/badge.svg)](https://codecov.io/gh/ihmwg/python-modelcif) This is a Python package to assist in handling [mmCIF](http://mmcif.wwpdb.org/) -and [BinaryCIF](https://github.com/dsehnal/BinaryCIF) files compliant with the +and [BinaryCIF](https://github.com/molstar/BinaryCIF) files compliant with the [ModelCIF](https://mmcif.wwpdb.org/dictionaries/mmcif_ma.dic/Index/) -extension. It works with Python 2.7 or Python 3. +extension. It works with Python 3.6 or later. Please [see the documentation](https://python-modelcif.readthedocs.org/) or some [worked examples](https://github.com/ihmwg/python-modelcif/tree/main/examples) @@ -38,7 +38,7 @@ pip install modelcif # Installation from source code To build and install from a clone of the GitHub repository, -first build and install version 1.7 or later of the +first build and install version 2.6 or later of the [python-ihm](https://github.com/ihmwg/python-ihm) module. Then run: ``` @@ -46,7 +46,7 @@ python setup.py build python setup.py install ``` -If you want to read or write [BinaryCIF](https://github.com/dsehnal/BinaryCIF) +If you want to read or write [BinaryCIF](https://github.com/molstar/BinaryCIF) files, you will also need the Python [msgpack](https://github.com/msgpack/msgpack-python) package. diff --git a/docs/alignment.rst b/docs/alignment.rst index c9f3619..cadcceb 100644 --- a/docs/alignment.rst +++ b/docs/alignment.rst @@ -14,6 +14,10 @@ The :mod:`modelcif.alignment` Python module .. autoclass:: AlignedPositionsIdentity +.. autoclass:: AlignedResiduePairsIdentity + +.. autoclass:: MeanSequenceIdentity + .. autoclass:: Pair :members: @@ -23,12 +27,18 @@ The :mod:`modelcif.alignment` Python module .. autoclass:: Global :members: +.. autoclass:: Local + :members: + .. autoclass:: AlignmentType :members: .. autoclass:: Pairwise :members: +.. autoclass:: Multiple + :members: + .. autoclass:: Score :members: diff --git a/docs/protocol.rst b/docs/protocol.rst index c61c579..d79626b 100644 --- a/docs/protocol.rst +++ b/docs/protocol.rst @@ -13,11 +13,26 @@ The :mod:`modelcif.protocol` Python module .. autoclass:: TemplateSearchStep :members: +.. autoclass:: TemplateSelectionStep + :members: + +.. autoclass:: TargetTemplateAlignmentStep + :members: + +.. autoclass:: CoevolutionMSAStep + :members: + +.. autoclass:: ContactPredictionStep + :members: + .. autoclass:: ModelingStep :members: .. autoclass:: ModelSelectionStep :members: +.. autoclass:: ModelRefinementStep + :members: + .. autoclass:: Protocol :members: diff --git a/docs/qa_metric.rst b/docs/qa_metric.rst index 7e97a48..347f57e 100644 --- a/docs/qa_metric.rst +++ b/docs/qa_metric.rst @@ -42,6 +42,16 @@ The :mod:`modelcif.qa_metric` Python module .. autoclass:: PLDDT +.. autoclass:: PLDDT01 + +.. autoclass:: PLDDTAllAtom + +.. autoclass:: PLDDTAllAtom01 + +.. autoclass:: PLDDTToPolymer + .. autoclass:: PTM .. autoclass:: IpTM + +.. autoclass:: Boolean diff --git a/examples/validate_mmcif.py b/examples/validate_mmcif.py index 3943921..32a5fba 100755 --- a/examples/validate_mmcif.py +++ b/examples/validate_mmcif.py @@ -1,7 +1,6 @@ # This example demonstrates the use of the Python IHM library's validator # to validate a user-provided input mmCIF file. -# This example requires Python 3. See validate_modbase.py for a more -# detailed example that also works with Python 2. +# See also validate_modbase.py for a more detailed example. import sys import ihm.dictionary diff --git a/examples/validate_modbase.py b/examples/validate_modbase.py index eae1e5b..1c80531 100644 --- a/examples/validate_modbase.py +++ b/examples/validate_modbase.py @@ -2,21 +2,18 @@ # A structure is downloaded from the ModBase database and checked against # the ModelCIF dictionary for compliance. This validator can be used # to perform basic integrity checking against any mmCIF dictionary. -# See also validate_mmcif.py for a simpler Python3 script to validate a +# See also validate_mmcif.py for a simpler script to validate a # user-provided mmCIF file. import io -import sys import ihm.dictionary -try: - import urllib.request as urllib2 # Python 3 -except ImportError: - import urllib2 # Python 2 +import urllib.request # Read in the ModelCIF dictionary from wwPDB as a Dictionary object. # Note that the ModelCIF dictionary also includes the PDBx dictionary, # so we don't need to read that in separately -fh = urllib2.urlopen('https://mmcif.wwpdb.org/dictionaries/ascii/mmcif_ma.dic') +fh = urllib.request.urlopen( + 'https://mmcif.wwpdb.org/dictionaries/ascii/mmcif_ma.dic') pdbx_mc = ihm.dictionary.read(fh) fh.close() @@ -25,18 +22,15 @@ # will result in a ValidatorError Python exception. # Here, a structure from ModBase (which should be valid) is used. acc = 'P21812' -cif = urllib2.urlopen('https://salilab.org/modbase/retrieve' - '?databaseID=%s&format=mmcif' % acc).read() +cif = urllib.request.urlopen('https://salilab.org/modbase/retrieve' + '?databaseID=%s&format=mmcif' % acc).read() # The encoding for mmCIF files isn't strictly defined, so first try UTF-8 # and if that fails, strip out any non-ASCII characters. This ensures that # we handle accented characters in string fields correctly. -if sys.version_info[0] >= 3: - try: - fh = io.StringIO(cif.decode('utf-8')) - except UnicodeDecodeError: - fh = io.StringIO(cif.decode('ascii', errors='ignore')) -else: - fh = io.BytesIO(cif.decode('ascii', errors='ignore').encode('ascii')) +try: + fh = io.StringIO(cif.decode('utf-8')) +except UnicodeDecodeError: + fh = io.StringIO(cif.decode('ascii', errors='ignore')) pdbx_mc.validate(fh) diff --git a/make-release.sh b/make-release.sh index d4a927a..b697424 100755 --- a/make-release.sh +++ b/make-release.sh @@ -6,6 +6,8 @@ # - Update AuditConformDumper to match latest MA dictionary if necessary # - Run util/validate-outputs.py to make sure all example outputs validate # (cd util; PYTHONPATH=.. python3 ./validate-outputs.py) +# - Run util/check-db-entries.py to check against some real archive structures +# (cd util; PYTHONPATH=.. python3 check-db-entries.py) # - If we need a newer python-ihm, update the version requirement in # requirements.txt, setup.py, util/python-modelcif.spec, and README.md. # - Update ChangeLog.rst and util/python-modelcif.spec with the release number diff --git a/modelcif/__init__.py b/modelcif/__init__.py index 0b4ff33..bcc8daf 100644 --- a/modelcif/__init__.py +++ b/modelcif/__init__.py @@ -4,12 +4,11 @@ from ihm import Entity, AsymUnit, Software, Assembly, Residue # noqa: F401 from ihm import AsymUnitRange, _remove_identical # noqa: F401 import modelcif.data -import sys -__version__ = '1.3' +__version__ = '1.4' -class System(object): +class System: """Top-level class representing a complete modeled system. :param str title: Longer text description of the system. @@ -60,6 +59,12 @@ def __init__(self, title=None, id='model', database=None, #: the system itself. See :class:`ihm.Citation`. self.citations = [] + #: Revision/update history. See :class:`ihm.Revision`. + self.revisions = [] + + #: Information on usage of the data. See :class:`ihm.DataUsage`. + self.data_usage = [] + #: All groups of models. See :class:`~modelcif.model.ModelGroup`. self.model_groups = [] @@ -279,8 +284,7 @@ def _all_features(self): # Provide ma-specific docs for Entity -if sys.version_info[0] >= 3: - Entity.__doc__ = """Represent a unique molecular sequence. +Entity.__doc__ = """Represent a unique molecular sequence. This can be used both for template sequences (in which case the Entity is then used in a :class:`Template` object) or for target (model) sequences @@ -311,8 +315,7 @@ def _all_features(self): # Provide ma-specific docs for Software -if sys.version_info[0] >= 3: - Software.__doc__ = """Software used as part of the modeling protocol. +Software.__doc__ = """Software used as part of the modeling protocol. :param str name: The name of the software. :param str classification: The major function of the software, for @@ -334,8 +337,7 @@ def _all_features(self): """ # Provide ma-specific docs for Assembly -if sys.version_info[0] >= 3: - Assembly.__doc__ = """A collection of parts of the system that were modeled +Assembly.__doc__ = """A collection of parts of the system that were modeled together. :param sequence elements: Initial set of parts of the system. @@ -354,7 +356,7 @@ def _all_features(self): """ -class Database(object): +class Database: """Information about a System that is part of an official database. If a :class:`System` is part of an official database (e.g. SwissModel, @@ -396,7 +398,7 @@ def __init__(self, elements=(), parameters=None): self.parameters = [] if parameters is None else parameters -class SoftwareWithParameters(object): +class SoftwareWithParameters: """A piece of software and the parameters with which it was used. See :class:`SoftwareGroup`. @@ -420,7 +422,7 @@ def __init__(self, software, parameters=None): citation = property(lambda self: self.software.citation) -class SoftwareParameter(object): +class SoftwareParameter: """A single parameter given to software used in modeling. See :class:`SoftwareWithParameters`, :class:`SoftwareGroup`. @@ -440,7 +442,7 @@ def __repr__(self): % (self.name, self.value)) -class Transformation(object): +class Transformation: """Rotation and translation applied to an object. These objects are generally used to record the transformation that @@ -468,7 +470,7 @@ def identity(cls): return cls._identity_obj -class TemplateSegment(object): +class TemplateSegment: """An aligned part of a template (see :class:`modelcif.alignment.Pair`). Usually these objects are created from @@ -588,7 +590,7 @@ def __init__(self, entity, asym_id, model_num, transformation, self.atoms = [] -class TemplateAtom(object): +class TemplateAtom: """Coordinates of a single atom in a custom template. This provides the coordinates for a template that has not been @@ -687,7 +689,7 @@ def __init__(self, name, url, version=None, release_date=None): self.url, self.version, self.release_date = url, version, release_date -class Feature(object): +class Feature: """Base class for selecting parts of the system. This class should not be used itself; instead, see :class:`AtomFeature`, :class:`PolyResidueFeature`, diff --git a/modelcif/alignment.py b/modelcif/alignment.py index d9c87cb..9136a69 100644 --- a/modelcif/alignment.py +++ b/modelcif/alignment.py @@ -13,7 +13,7 @@ class Alignment(modelcif.alignment.Global, modelcif.alignment.Pairwise): import modelcif.data -class Identity(object): +class Identity: """Percent sequence identity between the template sequence and the target sequence being modeled. Use the correct subclass that corresponds to the denominator used @@ -59,7 +59,23 @@ class AlignedPositionsIdentity(Identity): denominator = "Number of aligned positions (including gaps)" -class Pair(object): +class AlignedResiduePairsIdentity(Identity): + """Sequence identity calculated using the number of aligned residue pairs + (not including gaps) as the denominator. + See :class:`Identity` for more information.""" + other_details = None + denominator = "Number of aligned residue pairs (not including the gaps)" + + +class MeanSequenceIdentity(Identity): + """Sequence identity calculated using the arithmetic mean of the sequence + lengths as the denominator. + See :class:`Identity` for more information.""" + other_details = None + denominator = "Arithmetic mean sequence length" + + +class Pair: """A single pairwise alignment between a single target and template chain. See :class:`AlignmentMode`. An alignment consists of one or more of these pairs. @@ -70,12 +86,13 @@ class Pair(object): :type template: :class:`modelcif.TemplateSegment` :param target: The target segment that is aligned. :type target: output from :meth:`ihm.AsymUnit.segment` - :param identity: The sequence identity between target and template. + :param identity: The sequence identity between target and template, + if known. :type identity: :class:`Identity` - :param score: A measure of the quality of the alignment. + :param score: A measure of the quality of the alignment, if known. :type score: :class:`Score` """ - def __init__(self, template, target, identity, score): + def __init__(self, template, target, identity=None, score=None): self.template, self.target, self.score = template, target, score self.identity = identity @@ -106,7 +123,13 @@ class Global(AlignmentMode): mode = "global" -class AlignmentType(object): +class Local(AlignmentMode): + """Base class for local alignments. See :class:`AlignmentMode` for + more details.""" + mode = "local" + + +class AlignmentType: """Base class for all alignment types. Actual alignments should derive from both a subclass of this class (e.g. :class:`Pairwise`) and a subclass of :class:`AlignmentMode`. @@ -121,7 +144,14 @@ class Pairwise(AlignmentType): other_details = None -class Score(object): +class Multiple(AlignmentType): + """A multiple sequence alignment between target and template. + See :class:`AlignmentType` for more details.""" + type = "target-template MSA" + other_details = None + + +class Score: """Base class for a quality score for a given target-template alignment. Usually a derived class such as :class:`BLASTEValue` is used, and passed to :class:`Pair` objects. diff --git a/modelcif/associated.py b/modelcif/associated.py index 50d5148..eae1163 100644 --- a/modelcif/associated.py +++ b/modelcif/associated.py @@ -7,7 +7,7 @@ import warnings -class Repository(object): +class Repository: """An online location where associated files can be found. These objects are typically added to :attr:`modelcif.System.repositories`. @@ -28,7 +28,7 @@ def get_url(self, f): return posixpath.join(self.url_root or '', f.path) -class File(object): +class File: """A single associated file. These objects can be added to a :class:`Repository` or a :class:`ZipFile`. diff --git a/modelcif/data.py b/modelcif/data.py index cba548f..c80bf73 100644 --- a/modelcif/data.py +++ b/modelcif/data.py @@ -4,7 +4,7 @@ """ -class Data(object): +class Data: """Some part of the system that is input or output by part of the modeling protocol, and/or stored in a file. diff --git a/modelcif/descriptor.py b/modelcif/descriptor.py index 4aae71f..285ebee 100644 --- a/modelcif/descriptor.py +++ b/modelcif/descriptor.py @@ -8,7 +8,7 @@ """ -class Descriptor(object): +class Descriptor: """Base class for all descriptors. This class is generally not used directly; instead, a subclass such as :class:`IUPACName` or :class:`InChI` is employed. diff --git a/modelcif/dumper.py b/modelcif/dumper.py index b3aa83a..2bad4b2 100644 --- a/modelcif/dumper.py +++ b/modelcif/dumper.py @@ -563,15 +563,25 @@ def dump_details(self, system, writer): "sequence_identity_denominator_other_details"]) as lp: for a in system.alignments: for s in a.pairs: - denom = s.identity.denominator - od = s.identity.other_details + if s.identity is None: + denom = od = identity = None + else: + denom = s.identity.denominator + od = s.identity.other_details + identity = s.identity.value + if s.score is None: + score_type = score_other_details = score_value = None + else: + score_type = s.score.type + score_other_details = s.score.other_details + score_value = s.score.value lp.write(ordinal_id=next(ordinal), alignment_id=a._id, template_segment_id=s.template._segment_id, target_asym_id=s.target.asym._id, - score_type=s.score.type, - score_type_other_details=s.score.other_details, - score_value=s.score.value, - percent_sequence_identity=s.identity.value, + score_type=score_type, + score_type_other_details=score_other_details, + score_value=score_value, + percent_sequence_identity=identity, sequence_identity_denominator=denom, sequence_identity_denominator_other_details=od) @@ -887,7 +897,7 @@ def dump_metric_feature_pairwise(self, system, writer): metric_id=m._id, metric_value=m.value) -class _CopyWriter(object): +class _CopyWriter: """Context manager to write loop or category to two mmCIF/BinaryCIF files""" def __init__(self, w1, w2): @@ -906,7 +916,7 @@ def __exit__(self, exc_type, exc_value, traceback): self.w2.__exit__(exc_type, exc_value, traceback) -class _SystemWriter(object): +class _SystemWriter: """Utility class which normally just passes through to the default ``base_writer``, but outputs selected categories to associated files.""" def __init__(self, base_writer, category_map, copy_category_map): @@ -960,8 +970,9 @@ class ModelCIFVariant(Variant): ihm.dumper._StructDumper, ihm.dumper._CommentDumper, _AuditConformDumper, _DatabaseDumper, ihm.dumper._CitationDumper, ihm.dumper._SoftwareDumper, _SoftwareGroupDumper, - ihm.dumper._AuditAuthorDumper, - ihm.dumper._GrantDumper, _ChemCompDumper, _ChemCompDescriptorDumper, + ihm.dumper._AuditAuthorDumper, ihm.dumper._AuditRevisionDumper, + ihm.dumper._DataUsageDumper, ihm.dumper._GrantDumper, + _ChemCompDumper, _ChemCompDescriptorDumper, ihm.dumper._EntityDumper, ihm.dumper._EntitySrcGenDumper, ihm.dumper._EntitySrcNatDumper, ihm.dumper._EntitySrcSynDumper, ihm.dumper._StructRefDumper, diff --git a/modelcif/model.py b/modelcif/model.py index 749e02a..6537f52 100644 --- a/modelcif/model.py +++ b/modelcif/model.py @@ -1,4 +1,3 @@ -import sys import ihm.representation from ihm.model import Atom, ModelGroup # noqa: F401 import modelcif.data @@ -6,8 +5,7 @@ # Provide ma-specific docs for Atom -if sys.version_info[0] >= 3: - Atom.__doc__ = """Coordinates of part of the model represented by an atom. +Atom.__doc__ = """Coordinates of part of the model represented by an atom. See :meth:`Model.get_atoms` for more details. @@ -27,8 +25,7 @@ """ # Provide ma-specific docs for ModelGroup -if sys.version_info[0] >= 3: - ModelGroup.__doc__ = """A set of related models. See :class:`Model`. +ModelGroup.__doc__ = """A set of related models. See :class:`Model`. It is implemented as a simple list of the models. These objects are typically stored directly in the system; see @@ -121,7 +118,7 @@ class AbInitioModel(Model): other_details = None -class NotModeledResidueRange(object): +class NotModeledResidueRange: """A range of residues that were explicitly not modeled. See :attr:`Model.not_modeled_residue_ranges`. These ranges are not explicitly stored in the mmCIF file, diff --git a/modelcif/protocol.py b/modelcif/protocol.py index bb9c700..6a3cfd3 100644 --- a/modelcif/protocol.py +++ b/modelcif/protocol.py @@ -2,7 +2,7 @@ """ -class Step(object): +class Step: """A single step in a :class:`Protocol`. This class describes a generic step in a modeling protocol. In most @@ -41,6 +41,30 @@ class TemplateSearchStep(Step): method_type = "template search" +class TemplateSelectionStep(Step): + """A modeling protocol step that selects one or more templates. + See :class:`Step` for more details.""" + method_type = "template selection" + + +class TargetTemplateAlignmentStep(Step): + """A modeling protocol step that creates a target-template alignment. + See :class:`Step` for more details.""" + method_type = "target-template alignment" + + +class CoevolutionMSAStep(Step): + """A modeling protocol step that creates a coevolution multiple sequence + alignment. See :class:`Step` for more details.""" + method_type = "coevolution MSA" + + +class ContactPredictionStep(Step): + """A modeling protocol step that predicts contacts. + See :class:`Step` for more details.""" + method_type = "contact prediction" + + class ModelingStep(Step): """A modeling protocol step that generates model coordinates. See :class:`Step` for more details.""" @@ -53,7 +77,13 @@ class ModelSelectionStep(Step): method_type = "model selection" -class Protocol(object): +class ModelRefinementStep(Step): + """A modeling protocol step that refines models. + See :class:`Step` for more details.""" + method_type = "model refinement" + + +class Protocol: """A modeling protocol. Each protocol consists of a number of protocol steps.""" def __init__(self): diff --git a/modelcif/qa_metric.py b/modelcif/qa_metric.py index 40b22e2..633d13e 100644 --- a/modelcif/qa_metric.py +++ b/modelcif/qa_metric.py @@ -22,7 +22,7 @@ class MyScore(modelcif.qa_metric.Global, modelcif.qa_metric.Distance): """ -class MetricMode(object): +class MetricMode: """Base class for the mode of a quality metric. Use a derived class such as :class:`Global`, :class:`Local`, :class:`LocalPairwise`, :class:`Feature`, or :class:`FeaturePairwise` @@ -140,7 +140,7 @@ def __repr__(self): _all_features = property(lambda self: (self.feature1, self.feature2)) -class MetricType(object): +class MetricType: """Base class for the type of a quality metric. Generally a derived class such as :class:`ZScore` or :class:`Distance` is used to declare a new score, but a custom type can also be declared @@ -218,6 +218,35 @@ class PLDDT(MetricType): other_details = None +class PLDDT01(MetricType): + """Predicted lDDT-CA score in [0,1] (higher score, means better + accuracy). See :class:`MetricType` for more information.""" + type = "pLDDT in [0,1]" + other_details = None + + +class PLDDTAllAtom(MetricType): + """Predicted lDDT all atom score in [0,100] (higher score, means better + accuracy). See :class:`MetricType` for more information.""" + type = "pLDDT all-atom" + other_details = None + + +class PLDDTAllAtom01(MetricType): + """Predicted lDDT all atom score in [0,1] (higher score, means better + accuracy). See :class:`MetricType` for more information.""" + type = "pLDDT all-atom in [0,1]" + other_details = None + + +class PLDDTToPolymer(MetricType): + """Predicted lDDT with distances from each atom to CA or C1' of nearby + polymer residues [0,100] (higher score, means better accuracy). + See :class:`MetricType` for more information.""" + type = "pLDDT to polymer" + other_details = None + + class PTM(MetricType): """Predicted TM-score in [0,1] (higher value means higher confidence). See :class:`MetricType` for more information.""" @@ -230,3 +259,10 @@ class IpTM(MetricType): See :class:`MetricType` for more information.""" type = "ipTM" other_details = None + + +class Boolean(MetricType): + """0 or 1 depending on whether a check passed. + See :class:`MetricType` for more information.""" + type = "boolean" + other_details = None diff --git a/modelcif/reader.py b/modelcif/reader.py index 14190a0..1aabd62 100644 --- a/modelcif/reader.py +++ b/modelcif/reader.py @@ -94,7 +94,7 @@ def _update_old_object(self, obj, newcls=None): obj.asym_units = [] -class _SystemReader(object): +class _SystemReader: def __init__(self, model_class, starting_model_class, system=None): self.system = system or modelcif.System() @@ -106,6 +106,10 @@ def __init__(self, model_class, starting_model_class, system=None): self.citations = IDMapper(self.system.citations, ihm.Citation, *(None,) * 8) + #: Mapping from ID to :class:`ihm.Revision` objects + self.revisions = IDMapper(self.system.revisions, ihm.Revision, + *(None,) * 4) + #: Mapping from ID to :class:`ihm.Entity` objects self.entities = IDMapper(self.system.entities, _make_new_entity) @@ -270,7 +274,11 @@ class _TemplatePolyHandler(Handler): def __init__(self, sysr): super(_TemplatePolyHandler, self).__init__(sysr) - # Use python-ihm's _EntityPolyHandler to do most of the work here + # Use python-ihm's _EntityPolyHandler to do most of the work here. + # Note that we use Entity objects to store the sequence of the + # templates, but template Entities are *not* stored in the mmCIF + # file, so the 'entity ID' here is actually template_id and we + # don't look the Entity object up with sysr.entities.get_by_id(). self._eph = ihm.reader._EntityPolyHandler(sysr) def __call__(self, template_id, seq_one_letter_code, @@ -306,10 +314,10 @@ def _get_seq(codes, codes_can): class _TemplateNonPolyHandler(Handler): category = '_ma_template_non_poly' - def __call__(self, template_id, comp_id): + def __call__(self, template_id, comp_id, details): template = self.sysr.templates.get_by_id(template_id) seq = (self.sysr.chem_comps.get_by_id(comp_id),) - template.entity = ihm.Entity(sequence=seq) + template.entity = ihm.Entity(sequence=seq, description=details) class _SoftwareGroupHandler(Handler): @@ -393,7 +401,7 @@ def __call__(self, data_id, name, location_url, version, release_date): d._data_id = data_id -class _EnumerationMapper(object): +class _EnumerationMapper: """Map an mmCIF enumerated value to the corresponding Python class""" def __init__(self, module, base_class, attr="name"): self._base_class = base_class @@ -449,24 +457,25 @@ def __init__(self, *args): modelcif.reference.TargetReference) def __call__(self, target_entity_id, db_name, db_name_other_details, - db_code, db_accession, seq_db_isoform, seq_db_align_begin, - seq_db_align_end, ncbi_taxonomy_id, organism_scientific, + db_code, db_accession, seq_db_isoform, + seq_db_align_begin: int, seq_db_align_end: int, + ncbi_taxonomy_id, organism_scientific, seq_db_sequence_version_date, seq_db_sequence_checksum, - is_primary): + is_primary: bool): e = self.sysr.entities.get_by_id(target_entity_id) typ = self.type_map.get(db_name, db_name_other_details) with warnings.catch_warnings(): warnings.simplefilter("ignore") ref = typ(code=db_code, accession=db_accession, - align_begin=self.get_int(seq_db_align_begin), - align_end=self.get_int(seq_db_align_end), + align_begin=seq_db_align_begin, + align_end=seq_db_align_end, isoform=seq_db_isoform, ncbi_taxonomy_id=ncbi_taxonomy_id, organism_scientific=organism_scientific, sequence_version_date=_get_date( seq_db_sequence_version_date), sequence_crc64=seq_db_sequence_checksum, - is_primary=self.get_bool(is_primary)) + is_primary=is_primary) e.references.append(ref) def finalize(self): @@ -520,7 +529,7 @@ class _TemplateDetailsHandler(Handler): def __call__(self, template_id, template_trans_matrix_id, template_data_id, target_asym_id, template_label_asym_id, - template_label_entity_id, template_model_num, + template_label_entity_id, template_model_num: int, template_auth_asym_id, template_origin): newcls = None if template_origin and template_origin.lower() == 'customized': @@ -533,7 +542,7 @@ def __call__(self, template_id, template_trans_matrix_id, template.entity = ihm.Entity([]) template.entity_id = template_label_entity_id template.asym_id = template_label_asym_id - template.model_num = self.get_int(template_model_num) + template.model_num = template_model_num template._strand_id = template_auth_asym_id self.sysr.data_by_id[template_data_id] = template template._data_id = template_data_id @@ -582,22 +591,19 @@ class _TemplateCoordHandler(Handler): category = '_ma_template_coord' def __call__(self, template_id, group_pdb, type_symbol, label_atom_id, - label_seq_id, auth_seq_id, auth_atom_id, auth_comp_id, - cartn_x, cartn_y, cartn_z, occupancy, b_iso_or_equiv, - formal_charge): + label_seq_id: int, auth_seq_id: int, auth_atom_id, + auth_comp_id, cartn_x: float, cartn_y: float, cartn_z: float, + occupancy: float, b_iso_or_equiv: float, + formal_charge: float): template = self.sysr.templates.get_by_id(template_id, modelcif.CustomTemplate) atom = modelcif.TemplateAtom( het=group_pdb is not None and group_pdb != 'ATOM', type_symbol=type_symbol, atom_id=label_atom_id, - seq_id=self.get_int(label_seq_id), - auth_seq_id=self.get_int(auth_seq_id), - auth_atom_id=auth_atom_id, - auth_comp_id=auth_comp_id, - x=float(cartn_x), y=float(cartn_y), z=float(cartn_z), - occupancy=self.get_float(occupancy), - biso=self.get_float(b_iso_or_equiv), - charge=self.get_float(formal_charge)) + seq_id=label_seq_id, auth_seq_id=auth_seq_id, + auth_atom_id=auth_atom_id, auth_comp_id=auth_comp_id, + x=cartn_x, y=cartn_y, z=cartn_z, occupancy=occupancy, + biso=b_iso_or_equiv, charge=formal_charge) template.atoms.append(atom) @@ -694,15 +700,23 @@ def __init__(self, *args): modelcif.alignment, modelcif.alignment.Score, attr='type') def __call__(self, alignment_id, template_segment_id, target_asym_id, - score_type, score_type_other_details, score_value, - percent_sequence_identity, sequence_identity_denominator, + score_type, score_type_other_details, score_value: float, + percent_sequence_identity: float, + sequence_identity_denominator, sequence_identity_denominator_other_details): - score_class = self._score_map.get(score_type, score_type_other_details) - score = score_class(self.get_float(score_value)) - ident_class = self._ident_map.get( - sequence_identity_denominator, - sequence_identity_denominator_other_details) - ident = ident_class(self.get_float(percent_sequence_identity)) + if score_type: + score_class = self._score_map.get(score_type, + score_type_other_details) + score = score_class(score_value) + else: + score = None + if sequence_identity_denominator: + ident_class = self._ident_map.get( + sequence_identity_denominator, + sequence_identity_denominator_other_details) + ident = ident_class(percent_sequence_identity) + else: + ident = None template = self.sysr.template_segments.get_by_id(template_segment_id) asym = self.sysr.asym_units.get_by_id(target_asym_id) # We don't know the target segment yet (will be filled in at finalize @@ -721,10 +735,9 @@ class _TargetTemplatePolyMappingHandler(Handler): category = '_ma_target_template_poly_mapping' def __call__(self, template_segment_id, target_asym_id, - target_seq_id_begin, target_seq_id_end): + target_seq_id_begin: int, target_seq_id_end: int): k = (template_segment_id, target_asym_id) - rng = (self.get_int(target_seq_id_begin), - self.get_int(target_seq_id_end)) + rng = (target_seq_id_begin, target_seq_id_end) # Remember for now and we'll add in finalize() of AlignmentInfoHandler self.sysr.target_template_poly_mapping[k] = rng @@ -974,12 +987,11 @@ def __call__(self, feature_id, atom_id): class _PolyResidueFeatureHandler(Handler): category = '_ma_poly_residue_feature' - def __call__(self, feature_id, label_seq_id, label_asym_id): + def __call__(self, feature_id, label_seq_id: int, label_asym_id): f = self.sysr.features.get_by_id( feature_id, modelcif.PolyResidueFeature) asym = self.sysr.asym_units.get_by_id(label_asym_id) - seq_id = self.get_int(label_seq_id) - f.residues.append(asym.residue(seq_id)) + f.residues.append(asym.residue(label_seq_id)) class _EntityInstanceFeatureHandler(Handler): @@ -996,7 +1008,7 @@ def _make_qa_class(type_class, mode_class, p_name, p_description, p_software): """Create and return a new class to represent a QA metric""" class QA(type_class, mode_class): name = p_name - __doc__ = p_description + __doc__ = description = p_description software = p_software QA.__name__ = p_name return QA @@ -1032,65 +1044,59 @@ def __call__(self, id, name, description, type, mode, type_other_details, class _QAMetricGlobalHandler(Handler): category = '_ma_qa_metric_global' - def __call__(self, model_id, metric_id, metric_value): + def __call__(self, model_id, metric_id, metric_value: float): model = self.sysr.models.get_by_id(model_id) metric_class = self.sysr.qa_by_id[metric_id] - model.qa_metrics.append(metric_class(self.get_float(metric_value))) + model.qa_metrics.append(metric_class(metric_value)) class _QAMetricLocalHandler(Handler): category = '_ma_qa_metric_local' - def __call__(self, model_id, label_asym_id, label_seq_id, metric_id, - metric_value): + def __call__(self, model_id, label_asym_id, label_seq_id: int, metric_id, + metric_value: float): model = self.sysr.models.get_by_id(model_id) asym = self.sysr.asym_units.get_by_id(label_asym_id) - seq_id = self.get_int(label_seq_id) - residue = asym.residue(seq_id) + residue = asym.residue(label_seq_id) metric_class = self.sysr.qa_by_id[metric_id] - model.qa_metrics.append(metric_class(residue, - self.get_float(metric_value))) + model.qa_metrics.append(metric_class(residue, metric_value)) class _QAMetricPairwiseHandler(Handler): category = '_ma_qa_metric_local_pairwise' - def __call__(self, model_id, label_asym_id_1, label_seq_id_1, - label_asym_id_2, label_seq_id_2, metric_id, metric_value): + def __call__(self, model_id, label_asym_id_1, label_seq_id_1: int, + label_asym_id_2, label_seq_id_2: int, metric_id, + metric_value: float): model = self.sysr.models.get_by_id(model_id) asym1 = self.sysr.asym_units.get_by_id(label_asym_id_1) - seq_id1 = self.get_int(label_seq_id_1) - residue1 = asym1.residue(seq_id1) + residue1 = asym1.residue(label_seq_id_1) asym2 = self.sysr.asym_units.get_by_id(label_asym_id_2) - seq_id2 = self.get_int(label_seq_id_2) - residue2 = asym2.residue(seq_id2) + residue2 = asym2.residue(label_seq_id_2) metric_class = self.sysr.qa_by_id[metric_id] - model.qa_metrics.append(metric_class(residue1, residue2, - self.get_float(metric_value))) + model.qa_metrics.append(metric_class(residue1, residue2, metric_value)) class _QAMetricFeatureHandler(Handler): category = '_ma_qa_metric_feature' - def __call__(self, model_id, feature_id, metric_id, metric_value): + def __call__(self, model_id, feature_id, metric_id, metric_value: float): model = self.sysr.models.get_by_id(model_id) feature = self.sysr.features.get_by_id(feature_id) metric_class = self.sysr.qa_by_id[metric_id] - model.qa_metrics.append(metric_class(feature, - self.get_float(metric_value))) + model.qa_metrics.append(metric_class(feature, metric_value)) class _QAMetricFeaturePairwiseHandler(Handler): category = '_ma_qa_metric_feature_pairwise' def __call__(self, model_id, feature_id_1, feature_id_2, metric_id, - metric_value): + metric_value: float): model = self.sysr.models.get_by_id(model_id) feature1 = self.sysr.features.get_by_id(feature_id_1) feature2 = self.sysr.features.get_by_id(feature_id_2) metric_class = self.sysr.qa_by_id[metric_id] - model.qa_metrics.append(metric_class(feature1, feature2, - self.get_float(metric_value))) + model.qa_metrics.append(metric_class(feature1, feature2, metric_value)) class ModelCIFVariant(Variant): @@ -1101,6 +1107,11 @@ class ModelCIFVariant(Variant): _handlers = [ ihm.reader._StructHandler, ihm.reader._SoftwareHandler, ihm.reader._CitationHandler, ihm.reader._AuditAuthorHandler, + ihm.reader._AuditRevisionHistoryHandler, + ihm.reader._AuditRevisionDetailsHandler, + ihm.reader._AuditRevisionGroupHandler, + ihm.reader._AuditRevisionCategoryHandler, + ihm.reader._AuditRevisionItemHandler, ihm.reader._DataUsageHandler, ihm.reader._GrantHandler, ihm.reader._CitationAuthorHandler, _ChemCompHandler, _ChemCompDescriptorHandler, ihm.reader._EntityHandler, diff --git a/modelcif/reference.py b/modelcif/reference.py index a3fd770..1655c78 100644 --- a/modelcif/reference.py +++ b/modelcif/reference.py @@ -103,7 +103,7 @@ class UniProt(TargetReference): other_details = None -class TemplateReference(object): +class TemplateReference: """Point to the structure of a :class:`modelcif.Template` in a structure database. diff --git a/requirements.txt b/requirements.txt index 33385e4..9645aa3 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1 +1 @@ -ihm >= 1.7 +ihm >= 2.6 diff --git a/setup.py b/setup.py index cde78b1..4b1d60f 100755 --- a/setup.py +++ b/setup.py @@ -6,7 +6,7 @@ from distutils.core import setup import sys -VERSION = "1.3" +VERSION = "1.4" copy_args = sys.argv[1:] @@ -23,9 +23,8 @@ author_email='ben@salilab.org', url='https://github.com/ihmwg/python-modelcif', packages=['modelcif', 'modelcif.util'], - install_requires=['ihm>=1.7'], + install_requires=['ihm>=2.6'], classifiers=[ - "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", diff --git a/test/test_alignment.py b/test/test_alignment.py index 5802527..5f0a903 100644 --- a/test/test_alignment.py +++ b/test/test_alignment.py @@ -15,6 +15,8 @@ def test_identity(self): self.assertIsNone(ident.other_details) self.assertAlmostEqual(ident.value, 42.0, delta=1e-4) ident = modelcif.alignment.AlignedPositionsIdentity(42.0) + ident = modelcif.alignment.AlignedResiduePairsIdentity(42.0) + ident = modelcif.alignment.MeanSequenceIdentity(42.0) # generic "other" identity ident = modelcif.alignment.Identity(42.0) diff --git a/test/test_dumper.py b/test/test_dumper.py index b135acf..ae2333c 100644 --- a/test/test_dumper.py +++ b/test/test_dumper.py @@ -3,17 +3,11 @@ import utils import os import unittest -import sys -if sys.version_info[0] >= 3: - from io import StringIO -else: - from io import BytesIO as StringIO -msgpack = None -if sys.version_info[0] >= 3: - try: - import msgpack - except ImportError: - pass +from io import StringIO +try: + import msgpack +except ImportError: + msgpack = None TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) utils.set_search_paths(TOPDIR) @@ -79,7 +73,7 @@ def test_database_dumper(self): def test_software_group_dumper(self): """Test SoftwareGroupDumper""" - class MockObject(object): + class MockObject: pass p1 = modelcif.SoftwareParameter(name='foo', value=42) p2 = modelcif.SoftwareParameter(name='bar', value=True) @@ -268,7 +262,7 @@ def test_qa_metric_dumper(self): version=1, location='http://test.org') s1._group_id = 1 - class MockObject(object): + class MockObject: pass class CustomMetricType(modelcif.qa_metric.MetricType): @@ -408,7 +402,7 @@ def test_feature_dumper(self): """Test FeatureDumper""" system = modelcif.System() - class MockObject(object): + class MockObject: pass class TestScore(modelcif.qa_metric.Feature, modelcif.qa_metric.ZScore): @@ -503,7 +497,7 @@ class TestScore(modelcif.qa_metric.Feature, modelcif.qa_metric.ZScore): def test_protocol_dumper(self): """Test ProtocolDumper""" - class MockObject(object): + class MockObject: pass indat = MockObject() indat._data_group_id = 1 @@ -758,6 +752,10 @@ class Alignment(modelcif.alignment.Global, modelcif.alignment.Pairwise): pass + class LocalAlignment(modelcif.alignment.Local, + modelcif.alignment.Multiple): + pass + system = modelcif.System() tmp_e = modelcif.Entity('ACG') tgt_e = modelcif.Entity('ACE') @@ -788,16 +786,20 @@ class Alignment(modelcif.alignment.Global, aln._data_id = 100 system.alignments.append(aln) # The same alignment using HHblits e-value - p = modelcif.alignment.Pair( + p1 = modelcif.alignment.Pair( template=p.template, target=p.target, score=modelcif.alignment.HHblitsEValue("1e-14"), identity=p.identity) - aln = Alignment(name='testaln', pairs=[p]) + # The same alignment with missing score and identity + p2 = modelcif.alignment.Pair( + template=p.template, + target=p.target) + aln = Alignment(name='testaln', pairs=[p1, p2]) aln._data_id = 101 system.alignments.append(aln) - # Alignment with no pairs - aln2 = Alignment(name='testaln2', pairs=[]) + # Local alignment with no pairs + aln2 = LocalAlignment(name='testaln2', pairs=[]) aln2._data_id = 102 system.alignments.append(aln2) system._before_write() # populate system.templates @@ -820,6 +822,7 @@ class Alignment(modelcif.alignment.Global, _ma_template_details.template_auth_asym_id 1 1 'reference database' polymer 42 99 A H . 1 Z 2 1 'reference database' polymer 42 99 A H . 1 Z +3 1 'reference database' polymer 42 99 A H . 1 Z # # loop_ @@ -857,6 +860,7 @@ class Alignment(modelcif.alignment.Global, _ma_target_template_poly_mapping.target_seq_id_end 1 1 A 1 3 2 1 A 1 3 +3 1 A 1 3 # # loop_ @@ -868,7 +872,7 @@ class Alignment(modelcif.alignment.Global, _ma_alignment_info.alignment_mode 1 100 . 4 'target-template pairwise alignment' global 2 101 . 4 'target-template pairwise alignment' global -3 102 . . 'target-template pairwise alignment' global +3 102 . . 'target-template MSA' local # # loop_ @@ -884,6 +888,7 @@ class Alignment(modelcif.alignment.Global, _ma_alignment_details.sequence_identity_denominator_other_details 1 1 1 A 'BLAST e-value' . 1e-15 42.000 'Length of the shorter sequence' . 2 2 1 A 'HHblits e-value' . 1e-14 42.000 'Length of the shorter sequence' . +3 2 1 A . . . . . . # # loop_ @@ -895,6 +900,8 @@ class Alignment(modelcif.alignment.Global, 2 1 2 AC-G 3 2 1 ACE- 4 2 2 AC-G +5 2 1 ACE- +6 2 2 AC-G # """) @@ -1337,7 +1344,7 @@ def test_write_associated_binary(self): def test_system_writer(self): """Test _SystemWriter utility class""" - class BaseWriter(object): + class BaseWriter: def flush(self): return 'flush called' @@ -1447,7 +1454,7 @@ def test_chem_comp_dumper_bad_ccd(self): def test_chem_comp_descriptor_dumper(self): """Test ChemCompDescriptorDumper""" - class MockObject(object): + class MockObject: pass system = modelcif.System() diff --git a/test/test_edit.py b/test/test_edit.py index 28b8caa..148eefc 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -1,11 +1,7 @@ import utils import os import unittest -import sys -if sys.version_info[0] >= 3: - from io import StringIO -else: - from io import BytesIO as StringIO +import io TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) utils.set_search_paths(TOPDIR) @@ -16,7 +12,7 @@ class Tests(unittest.TestCase): def test_model_with_assembly(self): """Test read of Model with Assembly followed by write""" - sin = StringIO(""" + sin = io.StringIO(""" loop_ _entity.id _entity.type @@ -83,12 +79,12 @@ def test_model_with_assembly(self): ATOM 1 C CA . ALA 1 1 ? A 1.000 2.000 3.000 . 1 A . 1 """) s, = modelcif.reader.read(sin) - sout = StringIO() + sout = io.StringIO() modelcif.dumper.write(sout, [s]) def test_model_without_assembly(self): """Test read of Model without Assembly followed by write""" - sin = StringIO(""" + sin = io.StringIO(""" loop_ _entity.id _entity.type @@ -146,7 +142,7 @@ def test_model_without_assembly(self): ATOM 1 C CA . ALA 1 1 ? A 1.000 2.000 3.000 . 1 A . 1 """) s, = modelcif.reader.read(sin) - sout = StringIO() + sout = io.StringIO() modelcif.dumper.write(sout, [s]) diff --git a/test/test_examples.py b/test/test_examples.py index 75eac69..53e75a3 100644 --- a/test/test_examples.py +++ b/test/test_examples.py @@ -34,8 +34,6 @@ def test_validate_modbase_example(self): subprocess.check_call([sys.executable, get_example_path("validate_modbase.py")]) - @unittest.skipIf(sys.version_info[0] < 3, - "validate_mmcif.py needs Python 3") @unittest.skipIf('APPVEYOR' in os.environ, "AppVeyor environments have old SSL certs") @unittest.skipIf('GITHUB_ACTIONS' in os.environ, @@ -48,8 +46,6 @@ def test_validate_mmcif_example(self): get_example_path("input/ligands.cif")], cwd=tmpdir) - @unittest.skipIf(sys.version_info[0] < 3, - "associated.py needs Python 3") def test_associated_example(self): """Test associated example""" subprocess.check_call([sys.executable, diff --git a/test/test_make_mmcif.py b/test/test_make_mmcif.py index 6ea2549..8ce837a 100644 --- a/test/test_make_mmcif.py +++ b/test/test_make_mmcif.py @@ -14,7 +14,6 @@ class Tests(unittest.TestCase): - @unittest.skipIf(sys.version_info[0] < 3, "make_mmcif.py needs Python 3") def test_simple(self): """Simple test of make_mmcif utility script""" incif = utils.get_input_file_name(TOPDIR, 'struct_only.cif') @@ -26,7 +25,6 @@ def test_simple(self): 'of transcription regulation by Gdown1') os.unlink('output.cif') - @unittest.skipIf(sys.version_info[0] < 3, "make_mmcif.py needs Python 3") def test_non_default_output(self): """Simple test of make_mmcif with non-default output name""" incif = utils.get_input_file_name(TOPDIR, 'struct_only.cif') @@ -39,7 +37,6 @@ def test_non_default_output(self): 'of transcription regulation by Gdown1') os.unlink('non-default-output.cif') - @unittest.skipIf(sys.version_info[0] < 3, "make_mmcif.py needs Python 3") def test_no_title(self): """Check that make_mmcif adds missing title""" incif = utils.get_input_file_name(TOPDIR, 'no_title.cif') @@ -49,20 +46,17 @@ def test_no_title(self): self.assertEqual(s.title, 'Auto-generated system') os.unlink('output.cif') - @unittest.skipIf(sys.version_info[0] < 3, "make_mmcif.py needs Python 3") def test_bad_usage(self): """Bad usage of make_mmcif utility script""" ret = subprocess.call([sys.executable, MAKE_MMCIF]) self.assertEqual(ret, 2) - @unittest.skipIf(sys.version_info[0] < 3, "make_mmcif.py needs Python 3") def test_same_file(self): """Check that make_mmcif fails if input and output are the same""" incif = utils.get_input_file_name(TOPDIR, 'struct_only.cif') ret = subprocess.call([sys.executable, MAKE_MMCIF, incif, incif]) self.assertEqual(ret, 1) - @unittest.skipIf(sys.version_info[0] < 3, "make_mmcif.py needs Python 3") def test_not_modeled(self): """Check addition of not-modeled residue information""" incif = utils.get_input_file_name(TOPDIR, 'not_modeled.cif') diff --git a/test/test_reader.py b/test/test_reader.py index f44129f..112f239 100644 --- a/test/test_reader.py +++ b/test/test_reader.py @@ -1,12 +1,9 @@ from datetime import date -import sys import unittest import utils import os -if sys.version_info[0] >= 3: - from io import StringIO -else: - from io import BytesIO as StringIO +import datetime +from io import StringIO TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) utils.set_search_paths(TOPDIR) @@ -391,7 +388,7 @@ def test_template_details_handler_nonpoly(self): _ma_template_non_poly.template_id _ma_template_non_poly.comp_id _ma_template_non_poly.details -1 HEM Heme +1 HEM "Template Heme" """ s, = modelcif.reader.read(StringIO(cif)) t, = s.templates @@ -400,6 +397,7 @@ def test_template_details_handler_nonpoly(self): self.assertEqual(t.asym_id, 'B') self.assertEqual(t.strand_id, 'Z') self.assertEqual(len(s.alignments), 0) + self.assertEqual(t.entity.description, 'Template Heme') a, = s.asym_units self.assertIsInstance(a, modelcif.NonPolymerFromTemplate) self.assertIs(a.template, t) @@ -934,24 +932,31 @@ def test_protocol_handler(self): _ma_protocol_step.input_data_group_id _ma_protocol_step.output_data_group_id 1 1 1 'template search' 'ModPipe Seq-Prf (0001)' . 1 1 2 -2 1 2 modeling . . 2 2 1 -3 1 3 'model selection' . . 1 1 1 -4 1 4 other testname testdetails 42 99 66 +2 1 2 'template selection' . . . . . +3 1 3 'target-template alignment' . . . . . +4 1 4 modeling . . 2 2 1 +5 1 5 'model selection' . . 1 1 1 +6 1 6 'model refinement' . . . . . +7 1 7 other testname testdetails 42 99 66 """ s, = modelcif.reader.read(StringIO(cif)) p, = s.protocols - self.assertEqual(len(p.steps), 4) - s1, s2, s3, s4 = p.steps + self.assertEqual(len(p.steps), 7) + s1, s2, s3, s4, s5, s6, s7 = p.steps self.assertIsInstance(s1, modelcif.protocol.TemplateSearchStep) - self.assertIsInstance(s2, modelcif.protocol.ModelingStep) - self.assertIsInstance(s3, modelcif.protocol.ModelSelectionStep) - self.assertIsInstance(s4, modelcif.protocol.Step) - self.assertEqual(s4.method_type, "other") - self.assertEqual(s4.name, "testname") - self.assertEqual(s4.details, "testdetails") - self.assertEqual(s4.input_data._id, '99') - self.assertEqual(s4.output_data._id, '66') - self.assertEqual(s4.software._id, '42') + self.assertIsInstance(s2, modelcif.protocol.TemplateSelectionStep) + self.assertIsInstance(s3, + modelcif.protocol.TargetTemplateAlignmentStep) + self.assertIsInstance(s4, modelcif.protocol.ModelingStep) + self.assertIsInstance(s5, modelcif.protocol.ModelSelectionStep) + self.assertIsInstance(s6, modelcif.protocol.ModelRefinementStep) + self.assertIsInstance(s7, modelcif.protocol.Step) + self.assertEqual(s7.method_type, "other") + self.assertEqual(s7.name, "testname") + self.assertEqual(s7.details, "testdetails") + self.assertEqual(s7.input_data._id, '99') + self.assertEqual(s7.output_data._id, '66') + self.assertEqual(s7.software._id, '42') def test_target_entity_handler(self): """Test _TargetEntityHandler""" @@ -993,8 +998,7 @@ def test_qa_metric_global_handler(self): 'composite score, values >1.1 are considered reliable' 1 2 zDOPE 'Normalized DOPE' zscore global . 2 3 'TSVMod RMSD' 'TSVMod predicted RMSD (MSALL)' distance global . . -4 'TSVMod NO35' 'TSVMod predicted native overlap (MSALL)' 'normalized score' -global . . +4 'TSVMod NO35' . 'normalized score' global . . # loop_ _ma_qa_metric_global.ordinal_id @@ -1029,6 +1033,8 @@ def test_qa_metric_global_handler(self): self.assertIsInstance(q4, modelcif.qa_metric.Global) self.assertIsInstance(q4, modelcif.qa_metric.NormalizedScore) + self.assertIsNone(q4.description) + self.assertIsNone(q4.__doc__) def test_qa_metric_local_handler(self): """Test _QAMetricLocalHandler""" @@ -1295,7 +1301,7 @@ def test_alignment_info_details_handler(self): _ma_alignment_info.alignment_mode 1 3 1 . 'target-template pairwise alignment' global 2 4 1 . 'target-template pairwise alignment' global -3 5 1 . 'target-template pairwise alignment' global +3 5 1 . 'target-template MSA' local # # loop_ @@ -1310,7 +1316,8 @@ def test_alignment_info_details_handler(self): _ma_alignment_details.sequence_identity_denominator _ma_alignment_details.sequence_identity_denominator_other_details 1 1 1 A 'BLAST e-value' . 1.0 45.000 'Length of the shorter sequence' . -2 3 1 A 'HHblits e-value' . 2.0 45.000 'Length of the shorter sequence' . +2 2 1 A . . . . . . +3 3 1 A 'HHblits e-value' . 2.0 45.000 'Arithmetic mean sequence length' . # loop_ _ma_alignment.ordinal_id @@ -1336,7 +1343,6 @@ def test_alignment_info_details_handler(self): self.assertIs(a1.__class__, a2.__class__) self.assertIsInstance(a1, modelcif.alignment.Global) self.assertIsInstance(a1, modelcif.alignment.Pairwise) - self.assertEqual(len(a2.pairs), 0) p, = a1.pairs self.assertIsInstance(p.score, modelcif.alignment.BLASTEValue) self.assertAlmostEqual(p.score.value, 1.0, delta=1e-6) @@ -1350,9 +1356,16 @@ def test_alignment_info_details_handler(self): self.assertEqual(p.target.asym._id, 'A') self.assertEqual(p.target.gapped_sequence, 'DSYV-ETLD') self.assertEqual(p.target.seq_id_range, (1, 8)) + self.assertIsInstance(a3, modelcif.alignment.Local) + self.assertIsInstance(a3, modelcif.alignment.Multiple) + p, = a2.pairs + self.assertIsNone(p.score) + self.assertIsNone(p.identity) p, = a3.pairs self.assertIsInstance(p.score, modelcif.alignment.HHblitsEValue) self.assertAlmostEqual(p.score.value, 2.0, delta=1e-6) + self.assertIsInstance(p.identity, + modelcif.alignment.MeanSequenceIdentity) def test_associated_files(self): """Test _AssociatedHandler and _AssociatedArchiveHandler""" @@ -1605,6 +1618,42 @@ def test_add_to_system(self): self.assertEqual(s.asym_units[0].id, 'A') self.assertIs(s.asym_units[0].entity, e) + def test_audit_revision_handler(self): + """Test AuditRevisionHistoryHandler""" + # We leverage the support in python-ihm, so only a basic test here + cif = """ +loop_ +_pdbx_audit_revision_history.ordinal +_pdbx_audit_revision_history.data_content_type +_pdbx_audit_revision_history.major_revision +_pdbx_audit_revision_history.minor_revision +_pdbx_audit_revision_history.revision_date +40 'Structure model' 1 0 ? +41 'Structure model' 1 0 . +42 'Structure model' 2 0 1979-05-03 +""" + s, = modelcif.reader.read(StringIO(cif)) + r1, r2, r3 = s.revisions + self.assertEqual(r3.major, 2) + self.assertEqual(r3.minor, 0) + self.assertEqual(r3.date, datetime.date(1979, 5, 3)) + + def test_data_usage_handler(self): + """Test DataUsageHandler""" + # We leverage the support in python-ihm, so only a basic test here + cif = """ +loop_ +_pdbx_data_usage.id +_pdbx_data_usage.type +_pdbx_data_usage.details +_pdbx_data_usage.url +_pdbx_data_usage.name +1 license 'some license' someurl somename +""" + s, = modelcif.reader.read(StringIO(cif)) + d1, = s.data_usage + self.assertEqual(d1.details, "some license") + if __name__ == '__main__': unittest.main() diff --git a/test/utils.py b/test/utils.py index ae589fd..050eaab 100644 --- a/test/utils.py +++ b/test/utils.py @@ -3,14 +3,6 @@ import tempfile import contextlib import shutil -import unittest - - -# Allow using assertWarns unittest method even in Python 2 -if not hasattr(unittest.TestCase, 'assertWarns'): - def assertWarns(self, warning, f, *args, **keys): # noqa: N802 - f(*args, **keys) - unittest.TestCase.assertWarns = assertWarns def set_search_paths(topdir): diff --git a/util/check-db-entries.py b/util/check-db-entries.py new file mode 100644 index 0000000..7b53e19 --- /dev/null +++ b/util/check-db-entries.py @@ -0,0 +1,43 @@ +import unittest +import modelcif.reader +import modelcif.dumper +import urllib.request +import os + + +class Tests(unittest.TestCase): + def _read_cif(self, url): + with urllib.request.urlopen(url) as fh: + s, = modelcif.reader.read(fh) + return s + + def _write_cif(self, s, check=True): + with open('test.cif', 'w') as fh: + modelcif.dumper.write(fh, [s], check=check) + os.unlink('test.cif') + + def test_modbase(self): + """Test ModBase structure without errors""" + model_id = '3c79945a94ec00cac8a03104e853ca50' + modbase_top = 'https://salilab.org/modbase/retrieve/modbase' + url = '%s/?modelID=%s&format=mmcif' % (modbase_top, model_id) + s = self._read_cif(url) + self._write_cif(s) + + def test_swiss_model(self): + """Test SWISS-MODEL structure without errors""" + model_id = '680335e5cca47f7d2b00afc1' + url = 'https://swissmodel.expasy.org/repository/%s.cif' % model_id + s = self._read_cif(url) + self._write_cif(s) + + def test_alpha_fold(self): + """Test AlphaFold structure without errors""" + model_id = 'AF-B4GKE9-F1-model_v4' + url = 'https://alphafold.ebi.ac.uk/files/%s.cif' % model_id + s = self._read_cif(url) + self._write_cif(s) + + +if __name__ == '__main__': + unittest.main() diff --git a/util/python-modelcif.spec b/util/python-modelcif.spec index 291f62e..cf54593 100644 --- a/util/python-modelcif.spec +++ b/util/python-modelcif.spec @@ -1,19 +1,22 @@ Name: python3-modelcif License: MIT Group: Applications/Engineering -Version: 1.3 +Version: 1.4 Release: 1%{?dist} Summary: Package for handling ModelCIF mmCIF and BinaryCIF files Packager: Ben Webb URL: https://pypi.python.org/pypi/modelcif Source: modelcif-%{version}.tar.gz -BuildRequires: python3-devel, python3-setuptools, python3-ihm >= 1.7 -Requires: python3-ihm >= 1.7 +BuildRequires: python3-devel, python3-setuptools, python3-ihm >= 2.6 +Requires: python3-ihm >= 2.6 BuildArch: noarch +%if 0%{?fedora} >= 42 +BuildRequires: python3-pytest +%endif %description This is a Python package to assist in handling mmCIF and BinaryCIF files -compliant with the ModelCIF extension. It works with Python 2.7 or Python 3. +compliant with the ModelCIF extension. It works with Python 3.6 or later. %prep %setup -n modelcif-%{version} @@ -22,12 +25,19 @@ compliant with the ModelCIF extension. It works with Python 2.7 or Python 3. %{__python3} setup.py install --root=${RPM_BUILD_ROOT} --record=INSTALLED_FILES %check +%if 0%{?fedora} >= 42 +%pytest modelcif/test.py +%else %{__python3} setup.py test +%endif %files -f INSTALLED_FILES %defattr(-,root,root) %changelog +* Wed Jun 11 2025 Ben Webb 1.4-1 +- Update to latest upstream. + * Tue Jan 14 2025 Ben Webb 1.3-1 - Update to latest upstream.