Exemple #1
0
def delete(atom_id=None):
    """Delete structural data.
    
    @keyword atom_id:   The molecule, residue, and atom identifier string.  This matches the spin ID string format.  If not given, then all structural data will be deleted.
    @type atom_id:      str or None
    """

    # Test if the current data pipe exists.
    pipes.test()

    # Run the object method.
    if hasattr(cdp, 'structure'):
        print("Deleting structural data from the current pipe.")
        cdp.structure.delete(atom_id=atom_id)
    else:
        print("No structures are present.")

    # Then remove any spin specific structural info.
    print("Deleting all spin specific structural info.")
    for spin in spin_loop(selection=atom_id):
        # Delete positional information.
        if hasattr(spin, 'pos'):
            del spin.pos

    # Then remove any interatomic vector structural info.
    print("Deleting all interatomic vectors.")
    for interatom in interatomic_loop(selection1=atom_id):
        # Delete bond vectors.
        if hasattr(interatom, 'vector'):
            del interatom.vector
Exemple #2
0
def set_errors(align_id=None, spin_id1=None, spin_id2=None, sd=None):
    """Set the RDC errors if not already present.

    @keyword align_id:  The optional alignment tensor ID string.
    @type align_id:     str
    @keyword spin_id1:  The optional spin ID string of the first spin.
    @type spin_id1:     None or str
    @keyword spin_id2:  The optional spin ID string of the second spin.
    @type spin_id2:     None or str
    @keyword sd:        The RDC standard deviation in Hz.
    @type sd:           float or int.
    """

    # Check the pipe setup.
    check_pipe_setup(sequence=True, rdc_id=align_id, rdc=True)

    # Convert the align IDs to an array, or take all IDs.
    if align_id:
        align_ids = [align_id]
    else:
        align_ids = cdp.rdc_ids

    # Loop over the interatomic data.
    for interatom in interatomic_loop(selection1=spin_id1, selection2=spin_id2):
        # No data structure.
        if not hasattr(interatom, 'rdc_err'):
            interatom.rdc_err = {}

        # Set the error.
        for id in align_ids:
            interatom.rdc_err[id] = sd
Exemple #3
0
    def test_rdc_load(self):
        """Test for the loading of some RDC data with the spin ID format."""

        # Create a data pipe.
        self.interpreter.pipe.create('test', 'N-state')

        # Data directory.
        dir = status.install_path + sep+'test_suite'+sep+'shared_data'+sep+'align_data'+sep

        # Load the spins.
        self.interpreter.sequence.read(file='tb.txt', dir=dir, spin_id_col=1)
        self.interpreter.sequence.attach_protons()
        self.interpreter.sequence.display()

        # Load the RDCs.
        self.interpreter.rdc.read(align_id='tb', file='tb.txt', dir=dir, spin_id1_col=1, spin_id2_col=2, data_col=3, error_col=4)
        self.interpreter.sequence.display()

        # The RDCs.
        rdcs = [ -26.2501958629, 9.93081766942, 7.26317614156, -1.24840526981, 5.31803314334, 14.0362909456, 1.33652530397, -1.6021670281]

        # Checks.
        self.assertEqual(count_spins(), 16)
        self.assertEqual(len(cdp.interatomic), 8)
        i = 0
        for interatom in interatomic_loop():
            self.assertAlmostEqual(rdcs[i], interatom.rdc['tb'])
            i += 1
Exemple #4
0
def base_data_types():
    """Determine all the base data types.

    The base data types can include::
        - 'rdc', residual dipolar couplings.
        - 'pcs', pseudo-contact shifts.

    @return:    A list of all the base data types.
    @rtype:     list of str
    """

    # Array of data types.
    list = []

    # RDC search.
    for interatom in interatomic_loop(selection1=domain_moving()):
        if hasattr(interatom, 'rdc'):
            list.append('rdc')
            break

    # PCS search.
    for spin in spin_loop(selection=domain_moving()):
        if hasattr(spin, 'pcs'):
            list.append('pcs')
            break

    # No data is present.
    if not list:
        raise RelaxError("Neither RDCs nor PCSs are present.")

    # Return the list.
    return list
Exemple #5
0
    def test_rdc_load(self):
        """Test for the loading of some RDC data with the spin ID format."""

        # Create a data pipe.
        self.interpreter.pipe.create('test', 'N-state')

        # Data directory.
        dir = status.install_path + sep+'test_suite'+sep+'shared_data'+sep+'align_data'+sep

        # Load the spins.
        self.interpreter.sequence.read(file='tb.txt', dir=dir, spin_id_col=1)
        self.interpreter.sequence.attach_protons()
        self.interpreter.sequence.display()

        # Load the RDCs.
        self.interpreter.rdc.read(align_id='tb', file='tb.txt', dir=dir, spin_id1_col=1, spin_id2_col=2, data_col=3, error_col=4)
        self.interpreter.sequence.display()

        # The RDCs.
        rdcs = [ -26.2501958629, 9.93081766942, 7.26317614156, -1.24840526981, 5.31803314334, 14.0362909456, 1.33652530397, -1.6021670281]

        # Checks.
        self.assertEqual(count_spins(), 16)
        self.assertEqual(len(cdp.interatomic), 8)
        i = 0
        for interatom in interatomic_loop():
            self.assertAlmostEqual(rdcs[i], interatom.rdc['tb'])
            i += 1
Exemple #6
0
def base_data_types():
    """Determine all the base data types.

    The base data types can include::
        - 'rdc', residual dipolar couplings.
        - 'pcs', pseudo-contact shifts.

    @return:    A list of all the base data types.
    @rtype:     list of str
    """

    # Array of data types.
    list = []

    # RDC search.
    for interatom in interatomic_loop(selection1=domain_moving()):
        if hasattr(interatom, 'rdc'):
            list.append('rdc')
            break

    # PCS search.
    for spin in spin_loop(selection=domain_moving()):
        if hasattr(spin, 'pcs'):
            list.append('pcs')
            break

    # No data is present.
    if not list:
        raise RelaxError("Neither RDCs nor PCSs are present.")

    # Return the list.
    return list
Exemple #7
0
    def test_calc_q_factors_no_tensor(self):
        """Test the operation of the rdc.calc_q_factors user function when no alignment tensor is present."""

        # Create a data pipe.
        self.interpreter.pipe.create('orig', 'N-state')

        # Data directory.
        dir = status.install_path + sep+'test_suite'+sep+'shared_data'+sep+'align_data'+sep

        # Load the spins.
        self.interpreter.sequence.read(file='tb.txt', dir=dir, spin_id_col=1)
        self.interpreter.sequence.attach_protons()
        self.interpreter.sequence.display()

        # Load the RDCs.
        self.interpreter.rdc.read(align_id='tb', file='tb.txt', dir=dir, spin_id1_col=1, spin_id2_col=2, data_col=3, error_col=4)
        self.interpreter.sequence.display()

        # Create back-calculated RDC values from the real values.
        for interatom in interatomic_loop():
            if hasattr(interatom, 'rdc'):
                if not hasattr(interatom, 'rdc_bc'):
                    interatom.rdc_bc = {}
                interatom.rdc_bc['tb'] = interatom.rdc['tb'] + 1.0

        # Q factors.
        self.interpreter.rdc.calc_q_factors()
Exemple #8
0
    def test_calc_q_factors_no_tensor(self):
        """Test the operation of the rdc.calc_q_factors user function when no alignment tensor is present."""

        # Create a data pipe.
        self.interpreter.pipe.create('orig', 'N-state')

        # Data directory.
        dir = status.install_path + sep+'test_suite'+sep+'shared_data'+sep+'align_data'+sep

        # Load the spins.
        self.interpreter.sequence.read(file='tb.txt', dir=dir, spin_id_col=1)
        self.interpreter.sequence.attach_protons()
        self.interpreter.sequence.display()

        # Load the RDCs.
        self.interpreter.rdc.read(align_id='tb', file='tb.txt', dir=dir, spin_id1_col=1, spin_id2_col=2, data_col=3, error_col=4)
        self.interpreter.sequence.display()

        # Create back-calculated RDC values from the real values.
        for interatom in interatomic_loop():
            if hasattr(interatom, 'rdc'):
                if not hasattr(interatom, 'rdc_bc'):
                    interatom.rdc_bc = {}
                interatom.rdc_bc['tb'] = interatom.rdc['tb'] + 1.0

        # Q factors.
        self.interpreter.rdc.calc_q_factors()
Exemple #9
0
    def test_align_tensor_with_mc_sims(self):
        """Test the loading of a relax state with an alignment tensor with MC simulation structures."""

        # The file.
        path = status.install_path + sep + 'test_suite' + sep + 'shared_data' + sep + 'saved_states' + sep + 'align_tensor_mc.bz2'

        # Load the state.
        self.interpreter.state.load(path)

        # The data.
        domains = ['Dy N-dom', 'Dy C-dom']
        rdc = {"Dy N-dom": [-6.41, -21.55], "Dy C-dom": [-21.55]}
        rdc_bc = {"Dy N-dom": [None, -20.87317257368743], "Dy C-dom": [None]}

        rdc_err = {"Dy N-dom": [1.0, 1.0], "Dy C-dom": [1.0]}

        # Check the data.
        for domain in domains:
            # Switch to the X-domain data pipe.
            self.interpreter.pipe.switch(domain)

            # Check the interatomic data.
            i = 0
            for interatom in interatomic_loop():
                # Check the RDC data.
                self.assertEqual(interatom.rdc[domain], rdc[domain][i])
                if rdc_bc[domain][i]:
                    self.assertEqual(interatom.rdc_bc[domain],
                                     rdc_bc[domain][i])
                if rdc_err[domain][i]:
                    self.assertEqual(interatom.rdc_err[domain],
                                     rdc_err[domain][i])

                # Increment the index.
                i += 1
Exemple #10
0
    def overfit_deselect(self, data_check=True, verbose=True):
        """Deselect spins which have insufficient data to support minimisation.

        @keyword data_check:    A flag to signal if the presence of base data is to be checked for.
        @type data_check:       bool
        @keyword verbose:       A flag which if True will allow printouts.
        @type verbose:          bool
        """

        # Nothing to do.
        if not data_check:
            return

        # Loop over spin data, checking for PCS data.
        ids = []
        for spin, spin_id in spin_loop(return_id=True, skip_desel=True):
            if not hasattr(spin, 'pcs'):
                spin.select = False
                ids.append(spin_id)
        if verbose and len(ids):
            warn(RelaxWarning("No PCS data is present, deselecting the spins %s." % ids))

        # Loop over the interatomic data containers, checking for RDC data.
        ids = []
        for interatom in interatomic_loop(selection1=domain_moving()):
            if not hasattr(interatom, 'rdc'):
                interatom.select = False
                ids.append("%s - %s" % (interatom.spin_id1, interatom.spin_id2))
        if verbose and len(ids):
            warn(RelaxWarning("No RDC data is present, deselecting the interatomic data containers between spin pairs %s." % ids))
Exemple #11
0
def write(align_id=None, file=None, dir=None, bc=False, force=False):
    """Display the RDC data corresponding to the alignment ID.

    @keyword align_id:  The alignment tensor ID string.
    @type align_id:     str
    @keyword file:      The file name or object to write to.
    @type file:         str or file object
    @keyword dir:       The name of the directory to place the file into (defaults to the current directory).
    @type dir:          str
    @keyword bc:        The back-calculation flag which if True will cause the back-calculated rather than measured data to be written.
    @type bc:           bool
    @keyword force:     A flag which if True will cause any pre-existing file to be overwritten.
    @type force:        bool
    """

    # Check the pipe setup.
    check_pipe_setup(sequence=True, rdc_id=align_id, rdc=True)

    # Open the file for writing.
    file = open_write_file(file, dir, force)

    # Loop over the interatomic data containers and collect the data.
    data = []
    for interatom in interatomic_loop():
        # Skip deselected containers.
        if not interatom.select:
            continue

        # Skip containers with no RDCs.
        if not bc and (not hasattr(interatom, 'rdc') or align_id not in interatom.rdc.keys()):
            continue
        elif bc and (not hasattr(interatom, 'rdc_bc') or align_id not in interatom.rdc_bc.keys()):
            continue

        # Append the spin data.
        data.append([])
        data[-1].append(interatom.spin_id1)
        data[-1].append(interatom.spin_id2)

        # Handle the missing rdc_data_types variable.
        data_type = None
        if hasattr(interatom, 'rdc_data_types'):
            data_type = interatom.rdc_data_types[align_id]

        # The value.
        if bc:
            data[-1].append(repr(convert(interatom.rdc_bc[align_id], data_type, align_id)))
        else:
            data[-1].append(repr(convert(interatom.rdc[align_id], data_type, align_id)))

        # The error.
        if hasattr(interatom, 'rdc_err') and align_id in interatom.rdc_err.keys():
            data[-1].append(repr(convert(interatom.rdc_err[align_id], data_type, align_id)))
        else:
            data[-1].append(repr(None))

    # Write out.
    write_data(out=file, headings=["Spin_ID1", "Spin_ID2", "RDCs", "RDC_error"], data=data)
Exemple #12
0
    def _pipe_setup(self):
        """Set up the main data pipe."""

        # Create a data pipe.
        self.interpreter.pipe.create('distribution', 'N-state')

        # Load the original PDB.
        self.interpreter.structure.read_pdb('1J7P_1st_NH.pdb', dir=self.path, set_mol_name='C-dom')

        # Set up the 15N and 1H spins.
        self.interpreter.structure.load_spins(spin_id='@N', ave_pos=False)
        self.interpreter.structure.load_spins(spin_id='@H', ave_pos=False)
        self.interpreter.spin.isotope(isotope='15N', spin_id='@N')
        self.interpreter.spin.isotope(isotope='1H', spin_id='@H')

        # Define the magnetic dipole-dipole relaxation interaction.
        self.interpreter.interatom.define(spin_id1='@N', spin_id2='@H', direct_bond=True)
        self.interpreter.interatom.set_dist(spin_id1='@N', spin_id2='@H', ave_dist=1.041 * 1e-10)
        self.interpreter.interatom.unit_vectors()

        # Init a rotation matrix and the frame order matrix.
        self.R = zeros((3, 3), float64)
        self.daeg = zeros((9, 9), float64)

        # Load the tensors.
        self._tensors = ['dy', 'tb', 'tm', 'er']
        self.interpreter.script(self.path+'tensors.py')

        # The alignment specific data.
        for tag in self._tensors:
            # The temperature and field strength.
            self.interpreter.spectrometer.temperature(id=tag, temp=303)
            self.interpreter.spectrometer.frequency(id=tag, frq=900e6)

            # Set 1 Hz errors on all RDC data.
            for interatom in interatomic_loop():
                if not hasattr(interatom, 'rdc_err'):
                    interatom.rdc_err = {}
                interatom.rdc_err[tag] = 1.0

            # Set 0.1 ppm errors on all PCS data.
            for spin in spin_loop():
                if not hasattr(spin, 'pcs_err'):
                    spin.pcs_err = {}
                spin.pcs_err[tag] = 0.1

        # Set up the IDs.
        cdp.rdc_ids = self._tensors
        cdp.pcs_ids = self._tensors

        # Set up the model.
        self.interpreter.n_state_model.select_model(model='fixed')
        self.interpreter.n_state_model.number_of_states(self.N)

        # Set the paramagnetic centre.
        self.interpreter.paramag.centre(pos=[35.934, 12.194, -4.206])
Exemple #13
0
    def _pipe_setup(self):
        """Set up the main data pipe."""

        # Create a data pipe.
        self.interpreter.pipe.create('distribution', 'N-state')

        # Load the original PDB.
        self.interpreter.structure.read_pdb('1J7P_1st_NH.pdb', dir=self.path, set_mol_name='C-dom')

        # Set up the 15N and 1H spins.
        self.interpreter.structure.load_spins(spin_id='@N', ave_pos=False)
        self.interpreter.structure.load_spins(spin_id='@H', ave_pos=False)
        self.interpreter.spin.isotope(isotope='15N', spin_id='@N')
        self.interpreter.spin.isotope(isotope='1H', spin_id='@H')

        # Define the magnetic dipole-dipole relaxation interaction.
        self.interpreter.interatom.define(spin_id1='@N', spin_id2='@H', direct_bond=True)
        self.interpreter.interatom.set_dist(spin_id1='@N', spin_id2='@H', ave_dist=1.041 * 1e-10)
        self.interpreter.interatom.unit_vectors()

        # Init a rotation matrix and the frame order matrix.
        self.R = zeros((3, 3), float64)
        self.daeg = zeros((9, 9), float64)

        # Load the tensors.
        self._tensors = ['dy', 'tb', 'tm', 'er']
        self.interpreter.script(self.path+'tensors.py')

        # The alignment specific data.
        for tag in self._tensors:
            # The temperature and field strength.
            self.interpreter.spectrometer.temperature(id=tag, temp=303)
            self.interpreter.spectrometer.frequency(id=tag, frq=900e6)

            # Set 1 Hz errors on all RDC data.
            for interatom in interatomic_loop():
                if not hasattr(interatom, 'rdc_err'):
                    interatom.rdc_err = {}
                interatom.rdc_err[tag] = 1.0

            # Set 0.1 ppm errors on all PCS data.
            for spin in spin_loop():
                if not hasattr(spin, 'pcs_err'):
                    spin.pcs_err = {}
                spin.pcs_err[tag] = 0.1

        # Set up the IDs.
        cdp.rdc_ids = self._tensors
        cdp.pcs_ids = self._tensors

        # Set up the model.
        self.interpreter.n_state_model.select_model(model='fixed')
        self.interpreter.n_state_model.number_of_states(self.N)

        # Set the paramagnetic centre.
        self.interpreter.paramag.centre(pos=[35.934, 12.194, -4.206])
Exemple #14
0
    def test_rdc_copy(self):
        """Test the operation of the rdc.copy user function."""

        # Create a data pipe.
        self.interpreter.pipe.create('orig', 'N-state')

        # Data directory.
        dir = status.install_path + sep + 'test_suite' + sep + 'shared_data' + sep + 'align_data' + sep

        # Load the spins.
        self.interpreter.sequence.read(file='tb.txt', dir=dir, spin_id_col=1)
        self.interpreter.sequence.attach_protons()
        self.interpreter.sequence.display()

        # Load the RDCs.
        self.interpreter.rdc.read(align_id='tb',
                                  file='tb.txt',
                                  dir=dir,
                                  spin_id1_col=1,
                                  spin_id2_col=2,
                                  data_col=3,
                                  error_col=4)
        self.interpreter.sequence.display()

        # The RDCs.
        rdcs = [
            -26.2501958629, 9.93081766942, 7.26317614156, -1.24840526981,
            5.31803314334, 14.0362909456, 1.33652530397, -1.6021670281
        ]

        # Create a new data pipe by copying the old, then switch to it.
        self.interpreter.pipe.copy(pipe_from='orig', pipe_to='new')
        self.interpreter.pipe.switch(pipe_name='new')

        # Delete the RDC data.
        self.interpreter.rdc.delete()

        # Copy the RDCs.
        self.interpreter.rdc.copy(pipe_from='orig', align_id='tb')

        # Checks.
        self.assert_(hasattr(cdp, 'align_ids'))
        self.assert_('tb' in cdp.align_ids)
        self.assert_(hasattr(cdp, 'rdc_ids'))
        self.assert_('tb' in cdp.rdc_ids)
        self.assertEqual(count_spins(), 16)
        self.assertEqual(len(cdp.interatomic), 8)
        i = 0
        for interatom in interatomic_loop():
            self.assertAlmostEqual(rdcs[i], interatom.rdc['tb'])
            i += 1
    def _backup_pos(self):
        """Back up the positional data prior to the rotations."""

        # Store and then reinitalise the atomic position.
        for spin in spin_loop():
            if hasattr(spin, 'pos'):
                spin.orig_pos = array(spin.pos, float16)
                spin.pos = zeros((self.N, 3), float16)

        # Store and then reinitalise the bond vector.
        for interatom in interatomic_loop():
            if hasattr(interatom, 'vector'):
                interatom.orig_vect = array(interatom.vector, float16)
                interatom.vector = zeros((self.N, 3), float16)
Exemple #16
0
def sel_interatom(spin_id1=None, spin_id2=None, boolean='OR', change_all=False):
    """Select specific interatomic data containers.

    @keyword spin_id1:              The spin ID string of the first spin of the pair.
    @type spin_id1:                 str or None
    @keyword spin_id2:              The spin ID string of the second spin of the pair.
    @type spin_id2:                 str or None
    @param boolean:                 The boolean operator used to select the spin systems with.  It can be one of 'OR', 'NOR', 'AND', 'NAND', 'XOR', or 'XNOR'.  This will be ignored if the change_all flag is set.
    @type boolean:                  str
    @keyword change_all:            A flag which if True will cause all spins not specified in the file to be deselected.  Only the boolean operator 'OR' is compatible with this flag set to True (all others will be ignored).
    @type change_all:               bool
    @raises RelaxNoSequenceError:   If no molecule/residue/spins sequence data exists.
    @raises RelaxError:             If the boolean operator is unknown.
    """

    # Test if the current data pipe exists.
    check_pipe()

    # Test if sequence data is loaded.
    if not exists_mol_res_spin_data():
        raise RelaxNoSequenceError

    # First deselect all interatom containers if the change_all flag is set.
    if change_all:
        # Interatomic data loop.
        for interatom in interatomic_loop(skip_desel=False):
            interatom.select = False

    # Interatomic data loop.
    for interatom in interatomic_loop(selection1=spin_id1, selection2=spin_id2, skip_desel=False):
        # Select just the specified containers.
        if change_all:
            interatom.select = True

        # Boolean selections.
        else:
            interatom.select = boolean_select(current=interatom.select, boolean=boolean)
Exemple #17
0
def sel_interatom(spin_id1=None, spin_id2=None, boolean='OR', change_all=False):
    """Select specific interatomic data containers.

    @keyword spin_id1:              The spin ID string of the first spin of the pair.
    @type spin_id1:                 str or None
    @keyword spin_id2:              The spin ID string of the second spin of the pair.
    @type spin_id2:                 str or None
    @param boolean:                 The boolean operator used to select the spin systems with.  It can be one of 'OR', 'NOR', 'AND', 'NAND', 'XOR', or 'XNOR'.  This will be ignored if the change_all flag is set.
    @type boolean:                  str
    @keyword change_all:            A flag which if True will cause all spins not specified in the file to be deselected.  Only the boolean operator 'OR' is compatible with this flag set to True (all others will be ignored).
    @type change_all:               bool
    @raises RelaxNoSequenceError:   If no molecule/residue/spins sequence data exists.
    @raises RelaxError:             If the boolean operator is unknown.
    """

    # Test if the current data pipe exists.
    pipes.test()

    # Test if sequence data is loaded.
    if not exists_mol_res_spin_data():
        raise RelaxNoSequenceError

    # First deselect all interatom containers if the change_all flag is set.
    if change_all:
        # Interatomic data loop.
        for interatom in interatomic_loop(skip_desel=False):
            interatom.select = False

    # Interatomic data loop.
    for interatom in interatomic_loop(selection1=spin_id1, selection2=spin_id2, skip_desel=False):
        # Select just the specified containers.
        if change_all:
            interatom.select = True

        # Boolean selections.
        else:
            interatom.select = boolean_select(current=interatom.select, boolean=boolean)
Exemple #18
0
def delete():
    """Delete all J coupling data."""

    # Check the pipe setup.
    check_pipe_setup(sequence=True, j=True)

    # The interatomic data.
    for interatom in interatomic_loop():
        # The data.
        if hasattr(interatom, 'j_coupling'):
            del interatom.j_coupling

        # The error.
        if hasattr(interatom, 'j_coupling_err'):
            del interatom.j_coupling_err
Exemple #19
0
def delete():
    """Delete all J coupling data."""

    # Check the pipe setup.
    check_pipe_setup(sequence=True, j=True)

    # The interatomic data.
    for interatom in interatomic_loop():
        # The data.
        if hasattr(interatom, 'j_coupling'):
            del interatom.j_coupling

        # The error.
        if hasattr(interatom, 'j_coupling_err'):
            del interatom.j_coupling_err
Exemple #20
0
def opt_uses_j_couplings():
    """Determine of J couplings are needed for optimisation.

    @return:    True if J couplings are required, False otherwise.
    @rtype:     bool
    """

    # Loop over the alignments.
    for align_id in cdp.align_ids:
        for interatom in interatomic_loop():
            if hasattr(interatom, 'rdc_data_types') and align_id in interatom.rdc_data_types and interatom.rdc_data_types[align_id] == 'T':
                return True

    # No J values required.
    return False
Exemple #21
0
def spheroid_frame():
    """Function for calculating the angle alpha of the XH vector within the spheroid frame."""

    # Loop over the interatomic info.
    for interatom in interatomic_loop():
        # Test if the vector exists.
        if not hasattr(interatom, 'vector'):
            # Throw a warning.
            warn(RelaxWarning("No angles could be calculated for the spin pair '%s' and '%s'." % (interatom.spin_id1, interatom.spin_id2)))

            # Skip the container.
            continue

        # Calculate alpha.
        interatom.alpha = acos(dot(cdp.diff_tensor.Dpar_unit, interatom.vector))
Exemple #22
0
    def base_data_loop(self):
        """Generator method for looping over the base data - RDCs and PCSs.

        This loop yields the following:

            - The RDC identification data for the interatomic data container and alignment.
            - The PCS identification data for the spin data container and alignment.

        @return:    The base data type ('rdc' or 'pcs'), the spin or interatomic data container information (either one or two spin hashes), and the alignment ID string.
        @rtype:     list of str
        """

        # Loop over the interatomic data containers for the moving domain (for the RDC data).
        for interatom in interatomic_loop(selection1=domain_moving()):
            # Skip deselected containers.
            if not interatom.select:
                continue

            # No RDC, so skip.
            if not hasattr(interatom, 'rdc'):
                continue

            # Loop over the alignment IDs.
            for align_id in cdp.rdc_ids:
                # Yield the info set.
                if align_id in interatom.rdc and interatom.rdc[
                        align_id] != None:
                    yield [
                        'rdc', interatom._spin_hash1, interatom._spin_hash2,
                        align_id
                    ]

        # Loop over the spin containers for the moving domain (for the PCS data).
        for spin, spin_id in spin_loop(selection=domain_moving(),
                                       return_id=True):
            # Skip deselected spins.
            if not spin.select:
                continue

            # No PCS, so skip.
            if not hasattr(spin, 'pcs'):
                continue

            # Loop over the alignment IDs.
            for align_id in cdp.pcs_ids:
                # Yield the info set.
                if align_id in spin.pcs and spin.pcs[align_id] != None:
                    yield ['pcs', spin_id, align_id]
Exemple #23
0
def write(file=None, dir=None, force=False):
    """Write the J coupling data to file.

    @keyword file:      The file name or object to write to.
    @type file:         str or file object
    @keyword dir:       The name of the directory to place the file into (defaults to the current directory).
    @type dir:          str
    @keyword force:     A flag which if True will cause any pre-existing file to be overwritten.
    @type force:        bool
    """

    # Check the pipe setup.
    check_pipe_setup(sequence=True, j=True)

    # Open the file for writing.
    file = open_write_file(file, dir, force)

    # Loop over the interatomic data containers and collect the data.
    data = []
    for interatom in interatomic_loop():
        # Skip deselected containers.
        if not interatom.select:
            continue

        # Skip containers with no J coupling.
        if not hasattr(interatom, 'j_coupling'):
            continue

        # Append the spin data.
        data.append([])
        data[-1].append(interatom.spin_id1)
        data[-1].append(interatom.spin_id2)

        # The value.
        data[-1].append(repr(interatom.j_coupling))

        # The error.
        if hasattr(interatom, 'j_coupling_err'):
            data[-1].append(repr(interatom.j_coupling_err))
        else:
            data[-1].append(repr(None))

    # Write out.
    write_data(out=file, headings=["Spin_ID1", "Spin_ID2", "J coupling", "J coupling"], data=data)
Exemple #24
0
def sel_domain(domain_id=None, boolean='OR', change_all=False):
    """Select all spins and interatomic data containers of the given domain.

    @keyword domain_id:     The domain ID string.
    @type domain_id:        str or None
    @param boolean:         The boolean operator used to select the spin systems with.  It can be one of 'OR', 'NOR', 'AND', 'NAND', 'XOR', or 'XNOR'. This will be ignored if the change_all flag is set.
    @type boolean:          str
    @keyword change_all:    A flag which if True will cause all spins and interatomic data containers outside of the domain to be deselected.
    @type change_all:       bool
    """

    # Test if the current data pipe exists.
    pipes.test()

    # Test if the domain is defined.
    if not hasattr(cdp, 'domain') or domain_id not in cdp.domain:
        raise RelaxNoDomainError(domain_id)

    # The domain selection object.
    domain = Selection(cdp.domain[domain_id])

    # Loop over the spins and select as required.
    for spin, mol_name, res_num, res_name in spin_loop(full_info=True):
        # Inside the domain.
        if domain.contains_spin(spin_name=spin.name, spin_num=spin.num, res_name=res_name, res_num=res_num, mol=mol_name):
            spin.select = boolean_select(current=spin.select, boolean=boolean)

        # Deselect spins outside of the domain.
        elif change_all:
            spin.select = False

    # Interatomic data loop.
    for interatom in interatomic_loop():
        # Decode the spin ids.
        mol_name1, res_num1, res_name1, spin_num1, spin_name1 = spin_id_to_data_list(interatom.spin_id1)
        mol_name2, res_num2, res_name2, spin_num2, spin_name2 = spin_id_to_data_list(interatom.spin_id2)

        # Inside the domain.
        if domain.contains_spin(spin_name=spin_name1, spin_num=spin_num1, res_name=res_name1, res_num=res_num1, mol=mol_name1) or domain.contains_spin(spin_name=spin_name2, spin_num=spin_num2, res_name=res_name2, res_num=res_num2, mol=mol_name2):
            interatom.select = boolean_select(current=interatom.select, boolean=boolean)

        # Deselect containers outside of the domain.
        elif change_all:
            interatom.select = False
Exemple #25
0
def write(file=None, dir=None, force=False):
    """Write the J coupling data to file.

    @keyword file:      The file name or object to write to.
    @type file:         str or file object
    @keyword dir:       The name of the directory to place the file into (defaults to the current directory).
    @type dir:          str
    @keyword force:     A flag which if True will cause any pre-existing file to be overwritten.
    @type force:        bool
    """

    # Check the pipe setup.
    check_pipe_setup(sequence=True, j=True)

    # Open the file for writing.
    file = open_write_file(file, dir, force)

    # Loop over the interatomic data containers and collect the data.
    data = []
    for interatom in interatomic_loop():
        # Skip deselected containers.
        if not interatom.select:
            continue

        # Skip containers with no J coupling.
        if not hasattr(interatom, 'j_coupling'):
            continue

        # Append the spin data.
        data.append([])
        data[-1].append(interatom.spin_id1)
        data[-1].append(interatom.spin_id2)

        # The value.
        data[-1].append(repr(interatom.j_coupling))

        # The error.
        if hasattr(interatom, 'j_coupling_err'):
            data[-1].append(repr(interatom.j_coupling_err))
        else:
            data[-1].append(repr(None))

    # Write out.
    write_data(out=file, headings=["Spin_ID1", "Spin_ID2", "J coupling", "J coupling"], data=data)
Exemple #26
0
def sel_domain(domain_id=None, boolean='OR', change_all=False):
    """Select all spins and interatomic data containers of the given domain.

    @keyword domain_id:     The domain ID string.
    @type domain_id:        str or None
    @param boolean:         The boolean operator used to select the spin systems with.  It can be one of 'OR', 'NOR', 'AND', 'NAND', 'XOR', or 'XNOR'. This will be ignored if the change_all flag is set.
    @type boolean:          str
    @keyword change_all:    A flag which if True will cause all spins and interatomic data containers outside of the domain to be deselected.
    @type change_all:       bool
    """

    # Test if the current data pipe exists.
    check_pipe()

    # Test if the domain is defined.
    if not hasattr(cdp, 'domain') or domain_id not in cdp.domain:
        raise RelaxNoDomainError(domain_id)

    # The domain selection object.
    domain = Selection(cdp.domain[domain_id])

    # Loop over the spins and select as required.
    for spin, mol_name, res_num, res_name in spin_loop(full_info=True):
        # Inside the domain.
        if domain.contains_spin(spin_name=spin.name, spin_num=spin.num, res_name=res_name, res_num=res_num, mol=mol_name):
            spin.select = boolean_select(current=spin.select, boolean=boolean)

        # Deselect spins outside of the domain.
        elif change_all:
            spin.select = False

    # Interatomic data loop.
    for interatom in interatomic_loop():
        # Decode the spin ids.
        mol_name1, res_num1, res_name1, spin_num1, spin_name1 = spin_id_to_data_list(interatom.spin_id1)
        mol_name2, res_num2, res_name2, spin_num2, spin_name2 = spin_id_to_data_list(interatom.spin_id2)

        # Inside the domain.
        if domain.contains_spin(spin_name=spin_name1, spin_num=spin_num1, res_name=res_name1, res_num=res_num1, mol=mol_name1) or domain.contains_spin(spin_name=spin_name2, spin_num=spin_num2, res_name=res_name2, res_num=res_num2, mol=mol_name2):
            interatom.select = boolean_select(current=interatom.select, boolean=boolean)

        # Deselect containers outside of the domain.
        elif change_all:
            interatom.select = False
Exemple #27
0
    def base_data_loop(self):
        """Generator method for looping over the base data - RDCs and PCSs.

        This loop yields the following:

            - The RDC identification data for the interatomic data container and alignment.
            - The PCS identification data for the spin data container and alignment.

        @return:    The base data type ('rdc' or 'pcs'), the spin or interatomic data container information (either one or two spin IDs), and the alignment ID string.
        @rtype:     list of str
        """

        # Loop over the interatomic data containers for the moving domain (for the RDC data).
        for interatom in interatomic_loop(selection1=domain_moving()):
            # Skip deselected containers.
            if not interatom.select:
                continue

            # No RDC, so skip.
            if not hasattr(interatom, 'rdc'):
                continue

            # Loop over the alignment IDs.
            for align_id in cdp.rdc_ids:
                # Yield the info set.
                if align_id in interatom.rdc and interatom.rdc[align_id] != None:
                    yield ['rdc', interatom.spin_id1, interatom.spin_id2, align_id]

        # Loop over the spin containers for the moving domain (for the PCS data).
        for spin, spin_id in spin_loop(selection=domain_moving(), return_id=True):
            # Skip deselected spins.
            if not spin.select:
                continue

            # No PCS, so skip.
            if not hasattr(spin, 'pcs'):
                continue

            # Loop over the alignment IDs.
            for align_id in cdp.pcs_ids:
                # Yield the info set.
                if align_id in spin.pcs and spin.pcs[align_id] != None:
                    yield ['pcs', spin_id, align_id]
Exemple #28
0
def setup_pseudoatom_rdc():
    """Make sure that the interatom system is properly set up for pseudo-atoms and RDCs.

    Interatomic data containers between the non-pseudo-atom and the pseudo-atom members will be deselected.
    """

    # Loop over all interatomic data containers.
    for interatom in interatomic_loop():
        # Get the spins.
        spin1 = return_spin(interatom.spin_id1)
        spin2 = return_spin(interatom.spin_id2)

        # Checks.
        flag1 = is_pseudoatom(spin1)
        flag2 = is_pseudoatom(spin2)

        # No pseudo-atoms, so do nothing.
        if not (flag1 or flag2):
            continue

        # Both are pseudo-atoms.
        if flag1 and flag2:
            warn(RelaxWarning("Support for both spins being in a dipole pair being pseudo-atoms is not implemented yet, deselecting the interatomic data container for the spin pair '%s' and '%s'." % (interatom.spin_id1, interatom.spin_id2)))
            interatom.select = False

        # Alias the pseudo and normal atoms.
        pseudospin = spin1
        base_spin_id = interatom.spin_id2
        pseudospin_id = interatom.spin_id1
        if flag2:
            pseudospin = spin2
            base_spin_id = interatom.spin_id1
            pseudospin_id = interatom.spin_id2

        # Loop over the atoms of the pseudo-atom.
        for spin, spin_id in pseudoatom_loop(pseudospin, return_id=True):
            # Get the corresponding interatomic data container.
            pseudo_interatom = return_interatom(spin_id1=spin_id, spin_id2=base_spin_id)

            # Deselect if needed.
            if pseudo_interatom.select:
                warn(RelaxWarning("Deselecting the interatomic data container for the spin pair '%s' and '%s' as it is part of the pseudo-atom system of the spin pair '%s' and '%s'." % (pseudo_interatom.spin_id1, pseudo_interatom.spin_id2, base_spin_id, pseudospin_id)))
                pseudo_interatom.select = False
Exemple #29
0
    def test_align_tensor_with_mc_sims(self):
        """Test the loading of a relax state with an alignment tensor with MC simulation structures."""

        # The file.
        path = status.install_path + sep+'test_suite'+sep+'shared_data'+sep+'saved_states'+sep+'align_tensor_mc.bz2'

        # Load the state.
        self.interpreter.state.load(path)

        # The data.
        domains = ['Dy N-dom', 'Dy C-dom']
        rdc = {
            "Dy N-dom" : [-6.41, -21.55],
            "Dy C-dom" : [-21.55]
        }
        rdc_bc = {
            "Dy N-dom" : [None, -20.87317257368743],
            "Dy C-dom" : [None]
        }

        rdc_err = {
            "Dy N-dom" : [1.0, 1.0],
            "Dy C-dom" : [1.0]
        }

        # Check the data.
        for domain in domains:
            # Switch to the X-domain data pipe.
            self.interpreter.pipe.switch(domain)

            # Check the interatomic data.
            i = 0
            for interatom in interatomic_loop():
                # Check the RDC data.
                self.assertEqual(interatom.rdc[domain], rdc[domain][i])
                if rdc_bc[domain][i]:
                    self.assertEqual(interatom.rdc_bc[domain], rdc_bc[domain][i])
                if rdc_err[domain][i]:
                    self.assertEqual(interatom.rdc_err[domain], rdc_err[domain][i])

                # Increment the index.
                i += 1
Exemple #30
0
def base_data_types():
    """Determine all the base data types.

    The base data types can include::
        - 'rdc', residual dipolar couplings.
        - 'pcs', pseudo-contact shifts.
        - 'noesy', NOE restraints.
        - 'tensor', alignment tensors.

    @return:    A list of all the base data types.
    @rtype:     list of str
    """

    # Array of data types.
    list = []

    # RDC search.
    for interatom in interatomic_loop():
        if hasattr(interatom, 'rdc'):
            list.append('rdc')
            break

    # PCS search.
    for spin in spin_loop():
        if hasattr(spin, 'pcs'):
            list.append('pcs')
            break

    # Alignment tensor search.
    if not ('rdc' in list or 'pcs' in list) and hasattr(cdp, 'align_tensors'):
        list.append('tensor')

    # NOESY data search.
    if hasattr(cdp, 'noe_restraints'):
        list.append('noesy')

    # No data is present.
    if not list:
        raise RelaxError("Neither RDC, PCS, NOESY nor alignment tensor data is present.")

    # Return the list.
    return list
Exemple #31
0
def base_data_types():
    """Determine all the base data types.

    The base data types can include::
        - 'rdc', residual dipolar couplings.
        - 'pcs', pseudo-contact shifts.
        - 'noesy', NOE restraints.
        - 'tensor', alignment tensors.

    @return:    A list of all the base data types.
    @rtype:     list of str
    """

    # Array of data types.
    list = []

    # RDC search.
    for interatom in interatomic_loop():
        if hasattr(interatom, 'rdc'):
            list.append('rdc')
            break

    # PCS search.
    for spin in spin_loop():
        if hasattr(spin, 'pcs'):
            list.append('pcs')
            break

    # Alignment tensor search.
    if not ('rdc' in list or 'pcs' in list) and hasattr(cdp, 'align_tensors'):
        list.append('tensor')

    # NOESY data search.
    if hasattr(cdp, 'noe_restraints'):
        list.append('noesy')

    # No data is present.
    if not list:
        raise RelaxError("Neither RDC, PCS, NOESY nor alignment tensor data is present.")

    # Return the list.
    return list
Exemple #32
0
    def test_rdc_copy(self):
        """Test the operation of the rdc.copy user function."""

        # Create a data pipe.
        self.interpreter.pipe.create('orig', 'N-state')

        # Data directory.
        dir = status.install_path + sep+'test_suite'+sep+'shared_data'+sep+'align_data'+sep

        # Load the spins.
        self.interpreter.sequence.read(file='tb.txt', dir=dir, spin_id_col=1)
        self.interpreter.sequence.attach_protons()
        self.interpreter.sequence.display()

        # Load the RDCs.
        self.interpreter.rdc.read(align_id='tb', file='tb.txt', dir=dir, spin_id1_col=1, spin_id2_col=2, data_col=3, error_col=4)
        self.interpreter.sequence.display()

        # The RDCs.
        rdcs = [ -26.2501958629, 9.93081766942, 7.26317614156, -1.24840526981, 5.31803314334, 14.0362909456, 1.33652530397, -1.6021670281]

        # Create a new data pipe by copying the old, then switch to it.
        self.interpreter.pipe.copy(pipe_from='orig', pipe_to='new')
        self.interpreter.pipe.switch(pipe_name='new')

        # Delete the RDC data.
        self.interpreter.rdc.delete()

        # Copy the RDCs.
        self.interpreter.rdc.copy(pipe_from='orig', align_id='tb')

        # Checks.
        self.assert_(hasattr(cdp, 'align_ids'))
        self.assert_('tb' in cdp.align_ids)
        self.assert_(hasattr(cdp, 'rdc_ids'))
        self.assert_('tb' in cdp.rdc_ids)
        self.assertEqual(count_spins(), 16)
        self.assertEqual(len(cdp.interatomic), 8)
        i = 0
        for interatom in interatomic_loop():
            self.assertAlmostEqual(rdcs[i], interatom.rdc['tb'])
            i += 1
Exemple #33
0
def weight(align_id=None, spin_id=None, weight=1.0):
    """Set optimisation weights on the RDC data.

    @keyword align_id:  The alignment tensor ID string.
    @type align_id:     str
    @keyword spin_id:   The spin ID string.
    @type spin_id:      None or str
    @keyword weight:    The optimisation weight.  The higher the value, the more importance the RDC will have.
    @type weight:       float or int.
    """

    # Check the pipe setup.
    check_pipe_setup(sequence=True, rdc_id=align_id, rdc=True)

    # Loop over the interatomic data.
    for interatom in interatomic_loop():
        # No data structure.
        if not hasattr(interatom, 'rdc_weight'):
            interatom.rdc_weight = {}

        # Set the weight.
        interatom.rdc_weight[align_id] = weight
Exemple #34
0
def delete(align_id=None):
    """Delete the RDC data corresponding to the alignment ID.

    @keyword align_id:  The alignment tensor ID string.  If not specified, all data will be deleted.
    @type align_id:     str or None
    """

    # Check the pipe setup.
    check_pipe_setup(sequence=True, rdc_id=align_id, rdc=True)

    # The IDs.
    if not align_id:
        ids = deepcopy(cdp.rdc_ids)
    else:
        ids = [align_id]

    # Loop over the alignments, removing all the corresponding data.
    for id in ids:
        # The RDC ID.
        cdp.rdc_ids.pop(cdp.rdc_ids.index(id))

        # The interatomic data.
        for interatom in interatomic_loop():
            # The data.
            if hasattr(interatom, 'rdc') and id in interatom.rdc:
                interatom.rdc.pop(id)

            # The error.
            if hasattr(interatom, 'rdc_err') and id in interatom.rdc_err:
                interatom.rdc_err.pop(id)

            # The data type.
            if hasattr(interatom, 'rdc_data_types') and id in interatom.rdc_data_types:
                interatom.rdc_data_types.pop(id)

        # Clean the global data.
        if not hasattr(cdp, 'pcs_ids') or id not in cdp.pcs_ids:
            cdp.align_ids.pop(cdp.align_ids.index(id))
Exemple #35
0
def check_pipe_setup(pipe=None, sequence=False, j=False):
    """Check that the current data pipe has been setup sufficiently.

    @keyword pipe:      The data pipe to check, defaulting to the current pipe.
    @type pipe:         None or str
    @keyword sequence:  A flag which when True will invoke the sequence data check.
    @type sequence:     bool
    @keyword j:         A flag which if True will check that J couplings exist.
    @type j:            bool
    """

    # The data pipe.
    if pipe == None:
        pipe = pipes.cdp_name()

    # Get the data pipe.
    dp = pipes.get_pipe(pipe)

    # Test if the current data pipe exists.
    check_pipe(pipe)

    # Test if sequence data exists.
    if sequence and not exists_mol_res_spin_data(pipe):
        raise RelaxNoSequenceError(pipe)

    # Test if J coupling data exists.
    if j:
        # Search for interatomic data.
        data = False
        for interatom in interatomic_loop():
            if hasattr(interatom, 'j_coupling'):
                data = True
                break

        # No data.
        if not data:
            raise RelaxNoJError()
Exemple #36
0
def check_pipe_setup(pipe=None, sequence=False, j=False):
    """Check that the current data pipe has been setup sufficiently.

    @keyword pipe:      The data pipe to check, defaulting to the current pipe.
    @type pipe:         None or str
    @keyword sequence:  A flag which when True will invoke the sequence data check.
    @type sequence:     bool
    @keyword j:         A flag which if True will check that J couplings exist.
    @type j:            bool
    """

    # The data pipe.
    if pipe == None:
        pipe = pipes.cdp_name()

    # Get the data pipe.
    dp = pipes.get_pipe(pipe)

    # Test if the current data pipe exists.
    pipes.test(pipe)

    # Test if sequence data exists.
    if sequence and not exists_mol_res_spin_data(pipe):
        raise RelaxNoSequenceError(pipe)

    # Test if J coupling data exists.
    if j:
        # Search for interatomic data.
        data = False
        for interatom in interatomic_loop():
            if hasattr(interatom, 'j_coupling'):
                data = True
                break

        # No data.
        if not data:
            raise RelaxNoJError()
Exemple #37
0
def num_data_points():
    """Determine the number of data points used in the model.

    @return:    The number, n, of data points in the model.
    @rtype:     int
    """

    # Determine the data type.
    data_types = base_data_types()

    # Init.
    n = 0

    # Spin loop.
    for spin in spin_loop(skip_desel=True):
        # PCS data (skipping array elements set to None).
        if 'pcs' in data_types:
            if hasattr(spin, 'pcs'):
                for id in spin.pcs:
                    if is_float(spin.pcs[id]):
                        n += 1

    # Interatomic data loop.
    for interatom in interatomic_loop(skip_desel=True):
        # RDC data (skipping array elements set to None).
        if 'rdc' in data_types:
            if hasattr(interatom, 'rdc'):
                for id in interatom.rdc:
                    if is_float(interatom.rdc[id]):
                        n += 1

    # Alignment tensors.
    if 'tensor' in data_types:
        n += 5*len(cdp.align_tensors)

    # Return the value.
    return n
Exemple #38
0
def num_data_points():
    """Determine the number of data points used in the model.

    @return:    The number, n, of data points in the model.
    @rtype:     int
    """

    # Determine the data type.
    data_types = base_data_types()

    # Init.
    n = 0

    # Spin loop.
    for spin in spin_loop(skip_desel=True):
        # PCS data (skipping array elements set to None).
        if 'pcs' in data_types:
            if hasattr(spin, 'pcs'):
                for id in spin.pcs:
                    if is_float(spin.pcs[id]):
                        n += 1

    # Interatomic data loop.
    for interatom in interatomic_loop(skip_desel=True):
        # RDC data (skipping array elements set to None).
        if 'rdc' in data_types:
            if hasattr(interatom, 'rdc'):
                for id in interatom.rdc:
                    if is_float(interatom.rdc[id]):
                        n += 1

    # Alignment tensors.
    if 'tensor' in data_types:
        n += 5*len(cdp.align_tensors)

    # Return the value.
    return n
Exemple #39
0
    def overfit_deselect(self, data_check=True, verbose=True):
        """Deselect spins which have insufficient data to support minimisation.

        @keyword data_check:    A flag to signal if the presence of base data is to be checked for.
        @type data_check:       bool
        @keyword verbose:       A flag which if True will allow printouts.
        @type verbose:          bool
        """

        # Nothing to do.
        if not data_check:
            return

        # Loop over spin data, checking for PCS data.
        ids = []
        for spin, spin_id in spin_loop(return_id=True, skip_desel=True):
            if not hasattr(spin, 'pcs'):
                spin.select = False
                ids.append(spin_id)
        if verbose and len(ids):
            warn(
                RelaxWarning(
                    "No PCS data is present, deselecting the spins %s." % ids))

        # Loop over the interatomic data containers, checking for RDC data.
        ids = []
        for interatom in interatomic_loop(selection1=domain_moving()):
            if not hasattr(interatom, 'rdc'):
                interatom.select = False
                ids.append("%s - %s" %
                           (interatom.spin_id1, interatom.spin_id2))
        if verbose and len(ids):
            warn(
                RelaxWarning(
                    "No RDC data is present, deselecting the interatomic data containers between spin pairs %s."
                    % ids))
Exemple #40
0
def minimise_bc_data(model, sim_index=None):
    """Extract and unpack the back calculated data.

    @param model:       The instantiated class containing the target function.
    @type model:        class instance
    @keyword sim_index: The optional Monte Carlo simulation index.
    @type sim_index:    None or int
    """

    # No alignment tensors, so nothing to do.
    if not hasattr(cdp, 'align_tensors'):
        return

    # Simulation flag.
    sim_flag = (sim_index != None)

    # Loop over each alignment.
    align_index = 0
    for i in range(len(cdp.align_ids)):
        # Skip non-optimised tensors.
        if not opt_uses_tensor(cdp.align_tensors[i]):
            continue

        # The alignment ID.
        align_id = cdp.align_ids[i]

        # Data flags
        rdc_flag = False
        if hasattr(cdp, 'rdc_ids') and align_id in cdp.rdc_ids:
            rdc_flag = True
        pcs_flag = False
        if hasattr(cdp, 'pcs_ids') and align_id in cdp.pcs_ids:
            pcs_flag = True

        # Spin loop.
        pcs_index = 0
        for spin in spin_loop():
            # Skip deselected spins.
            if not spin.select:
                continue

            # Spins with PCS data.
            if pcs_flag and hasattr(spin, 'pcs'):
                # Initialise the data structure if necessary.
                if sim_flag:
                    if not hasattr(spin, 'pcs_sim_bc'):
                        spin.pcs_sim_bc = {}
                    if align_id not in spin.pcs_sim_bc:
                        spin.pcs_sim_bc[align_id] = [None] * cdp.sim_number
                else:
                    if not hasattr(spin, 'pcs_bc'):
                        spin.pcs_bc = {}

                # Add the back calculated PCS (in ppm).
                if sim_flag:
                    spin.pcs_sim_bc[align_id][sim_index] = model.deltaij_theta[align_index, pcs_index] * 1e6
                else:
                    spin.pcs_bc[align_id] = model.deltaij_theta[align_index, pcs_index] * 1e6

                # Increment the data index if the spin container has data.
                pcs_index = pcs_index + 1

        # Interatomic data container loop.
        rdc_index = 0
        for interatom in interatomic_loop():
            # Get the spins.
            spin1 = return_spin(interatom.spin_id1)
            spin2 = return_spin(interatom.spin_id2)

            # RDC checks.
            if not check_rdcs(interatom):
                continue

            # Containers with RDC data.
            if rdc_flag and hasattr(interatom, 'rdc'):
                # Initialise the data structure if necessary.
                if sim_flag:
                    if not hasattr(interatom, 'rdc_sim_bc'):
                        interatom.rdc_sim_bc = {}
                    if align_id not in interatom.rdc_sim_bc:
                        interatom.rdc_sim_bc[align_id] = [0.0] * cdp.sim_number
                else:
                    if not hasattr(interatom, 'rdc_bc'):
                        interatom.rdc_bc = {}

                # Append the back calculated PCS.
                if sim_flag:
                    interatom.rdc_sim_bc[align_id][sim_index] = model.rdc_theta[align_index, rdc_index]
                else:
                    interatom.rdc_bc[align_id] = model.rdc_theta[align_index, rdc_index]

                # Increment the data index if the interatom container has data.
                rdc_index = rdc_index + 1

        # Increment the alignment index (for the optimised tensors).
        align_index += 1
Exemple #41
0
    def test_dasha(self):
        """Test a complete model-free analysis using the program 'Dasha'."""

        # Execute the script.
        self.script_exec(status.install_path + sep+'test_suite'+sep+'system_tests'+sep+'scripts'+sep+'dasha.py')

        # Check the global data.
        self.assertEqual(len(cdp.ri_ids), 3)
        for ri_id in cdp.ri_ids:
            self.assertEqual(cdp.spectrometer_frq[ri_id], 600000000.0)
        self.assertEqual(cdp.ri_type['R1_600'], 'R1')
        self.assertEqual(cdp.ri_type['R2_600'], 'R2')
        self.assertEqual(cdp.ri_type['NOE_600'], 'NOE')

        # The spin data.
        select = [True, True, False, False]
        fixed = [False, False, False, False]
        isotope = ['15N', '15N', '15N', '15N']
        model = ['m3', 'm3', 'm3', 'm3']
        equation = ['mf_orig', 'mf_orig', 'mf_orig', 'mf_orig']
        params = [['s2', 'rex'], ['s2', 'rex'], ['s2', 'rex'], ['s2', 'rex']]
        s2 = [0.71510, 0.64359, None, None]
        s2f = [None, None, None, None]
        s2s = [None, None, None, None]
        local_tm = [None, None, None, None]
        te = [None, None, None, None]
        tf = [None, None, None, None]
        ts = [None, None, None, None]
        rex_scale = 1.0 / (2.0 * pi * cdp.spectrometer_frq[cdp.ri_ids[0]]) ** 2
        rex = [4.32701*rex_scale, 4.29432*rex_scale, None, None]
        csa = [-172e-6, -172e-6, -172e-6, -172e-6]
        chi2 = [1.9657, 0.63673, None, None]
        ri_data = [{'R1_600': 1.0, 'R2_600': 15.0, 'NOE_600': 0.9},
                   {'R1_600': 0.9, 'R2_600': 13.9, 'NOE_600': 0.79},
                   {'R2_600': 12.0, 'NOE_600': 0.6},
                   None]
        ri_data_err = [{'R1_600': 0.05, 'R2_600': 0.5, 'NOE_600': 0.05},
                       {'R1_600': 0.05, 'R2_600': 0.8, 'NOE_600': 0.05},
                       {'R2_600': 0.5, 'NOE_600': 0.05},
                       None]

        # Check the spin data.
        i = 0
        for spin in spin_loop():
            # Protons.
            if spin.isotope == '1H':
                self.assertEqual(spin.select, False)
                continue

            # Check the data.
            self.assertEqual(spin.select, select[i])
            self.assertEqual(spin.fixed, fixed[i])
            self.assertEqual(spin.isotope, isotope[i])
            self.assertEqual(spin.model, model[i])
            self.assertEqual(spin.equation, equation[i])
            self.assertEqual(spin.params, params[i])
            self.assertEqual(spin.s2, s2[i])
            self.assertEqual(spin.s2f, s2f[i])
            self.assertEqual(spin.s2s, s2s[i])
            self.assertEqual(spin.local_tm, local_tm[i])
            self.assertEqual(spin.te, te[i])
            self.assertEqual(spin.tf, tf[i])
            self.assertEqual(spin.ts, ts[i])
            self.assertEqual(spin.rex, rex[i])
            self.assertAlmostEqual(spin.csa, csa[i])
            self.assertEqual(spin.chi2, chi2[i])
            if ri_data[i] == None:
                self.assert_(not hasattr(spin, 'ri_data'))
            else:
                for ri_id in cdp.ri_ids:
                    if ri_id in ri_data[i]:
                        self.assertEqual(spin.ri_data[ri_id], ri_data[i][ri_id])

            # Increment the spin index.
            i += 1

        # Check the interatomic data.
        r = [1.02e-10, 1.02e-10, 1.02e-10, 1.02e-10]
        i = 0
        for interatom in interatomic_loop():
            self.assertAlmostEqual(interatom.r, r[i])
            i += 1
Exemple #42
0
print("\nChi tensor 0:\n%s" % chi0)
print("\nChi tensor 2:\n%s" % chi2)

# RDCs.
#######

# Open the RDC files.
dy_500_rdc = open('dy_500_rdc', 'w')
dy_700_rdc = open('dy_700_rdc', 'w')
er_900_rdc = open('er_900_rdc', 'w')

# The dipolar constant.
d = -3.0 / (2.0 * pi) * mu0 / (4.0 * pi) * g1H * g15N * h_bar / r_nh**3

# Loop over the interatomic data containers and calculate RDCs.
for interatom in interatomic_loop():
    # Calculate the RDC at 500 MHz for the first tensor, and write out the data.
    A = chi0 / mag_constant(B0=500e6 * 2.0 * pi / g1H, T=303)
    rdc = d * dot(dot(interatom.vector, A), interatom.vector)
    dy_500_rdc.write("%-20s %-20s %20f\n" %
                     (repr(interatom.spin_id1), repr(interatom.spin_id2), rdc))

    # Calculate the RDC at 700 MHz for the first tensor, and write out the data.
    A = chi0 / mag_constant(B0=700e6 * 2.0 * pi / g1H, T=303)
    rdc = d * dot(dot(interatom.vector, A), interatom.vector)
    dy_700_rdc.write("%-20s %-20s %20f\n" %
                     (repr(interatom.spin_id1), repr(interatom.spin_id2), rdc))

    # Calculate the RDC at 900 MHz for the second tensor, and write out the data.
    A = chi2 / mag_constant(B0=900e6 * 2.0 * pi / g1H, T=303)
    rdc = d * dot(dot(interatom.vector, A), interatom.vector)
Exemple #43
0
    def test_corr_plot(self):
        """Test the operation of the rdc.corr_plot user function."""

        # Create a data pipe.
        self.interpreter.pipe.create('orig', 'N-state')

        # Data directory.
        dir = status.install_path + sep+'test_suite'+sep+'shared_data'+sep+'align_data'+sep

        # Load the spins.
        self.interpreter.sequence.read(file='tb.txt', dir=dir, spin_id_col=1)
        self.interpreter.sequence.attach_protons()
        self.interpreter.sequence.display()

        # Load the RDCs.
        self.interpreter.rdc.read(align_id='tb', file='tb.txt', dir=dir, spin_id1_col=1, spin_id2_col=2, data_col=3, error_col=4)
        self.interpreter.sequence.display()

        # Create back-calculated RDC values from the real values.
        for interatom in interatomic_loop():
            if hasattr(interatom, 'rdc'):
                if not hasattr(interatom, 'rdc_bc'):
                    interatom.rdc_bc = {}
                interatom.rdc_bc['tb'] = interatom.rdc['tb'] + 1.0

        # Correlation plot.
        ds.tmpfile_handle, ds.tmpfile = mkstemp()
        self.interpreter.rdc.corr_plot(format='grace', title='Test', subtitle='Test2', file=ds.tmpfile, dir=None, force=True)

        # The expected file contents.
        real_contents = [
            "@version 50121",
            "@page size 842, 595",
            "@with g0",
            "@    world -27.0, -27.0, 16.0, 16.0",
            "@    view 0.15, 0.15, 1.28, 0.85",
            "@    title \"Test\"",
            "@    subtitle \"Test2\"",
            "@    xaxis  label \"Back-calculated RDC (Hz)\"",
            "@    xaxis  label char size 1.00",
            "@    xaxis  tick major 10",
            "@    xaxis  tick major size 0.50",
            "@    xaxis  tick major linewidth 0.5",
            "@    xaxis  tick minor ticks 9",
            "@    xaxis  tick minor linewidth 0.5",
            "@    xaxis  tick minor size 0.25",
            "@    xaxis  ticklabel char size 0.70",
            "@    yaxis  label \"Measured RDC (Hz)\"",
            "@    yaxis  label char size 1.00",
            "@    yaxis  tick major 10",
            "@    yaxis  tick major size 0.50",
            "@    yaxis  tick major linewidth 0.5",
            "@    yaxis  tick minor ticks 9",
            "@    yaxis  tick minor linewidth 0.5",
            "@    yaxis  tick minor size 0.25",
            "@    yaxis  ticklabel char size 0.70",
            "@    legend on",
            "@    legend 1, 0.5",
            "@    legend box fill pattern 1",
            "@    legend char size 1.0",
            "@    frame linewidth 0.5",
            "@    s0 symbol 1",
            "@    s0 symbol size 0.45",
            "@    s0 symbol linewidth 0.5",
            "@    s0 errorbar size 0.5",
            "@    s0 errorbar linewidth 0.5",
            "@    s0 errorbar riser linewidth 0.5",
            "@    s0 line linestyle 2",
            "@    s1 symbol 2",
            "@    s1 symbol size 0.45",
            "@    s1 symbol linewidth 0.5",
            "@    s1 errorbar size 0.5",
            "@    s1 errorbar linewidth 0.5",
            "@    s1 errorbar riser linewidth 0.5",
            "@    s1 line linestyle 0",
            "@    s1 legend \"tb\"",
            "@target G0.S0",
            "@type xydy",
            "          -100.000000000000000           -100.000000000000000              0.000000000000000",
            "           100.000000000000000            100.000000000000000              0.000000000000000",
            "&",
            "@target G0.S1",
            "@type xydy",
            "           -25.250195862900000            -26.250195862900000              1.000000000000000    \"#CaM:5@N-#CaM:5@H\"",
            "            10.930817669420000              9.930817669420000              1.000000000000000    \"#CaM:6@N-#CaM:6@H\"",
            "             8.263176141559999              7.263176141560000              1.000000000000000    \"#CaM:7@N-#CaM:7@H\"",
            "            -0.248405269810000             -1.248405269810000              0.000000000000000    \"#CaM:8@N-#CaM:8@H\"",
            "             6.318033143340000              5.318033143340000              1.000000000000000    \"#CaM:9@N-#CaM:9@H\"",
            "            15.036290945599999             14.036290945599999              1.000000000000000    \"#CaM:10@N-#CaM:10@H\"",
            "             2.336525303970000              1.336525303970000              0.000000000000000    \"#CaM:11@N-#CaM:11@H\"",
            "            -0.602167028100000             -1.602167028100000              0.000000000000000    \"#CaM:12@N-#CaM:12@H\"",
            "&",
        ]

        # Check the data.
        print("\nChecking the Grace file contents.")
        file = open(ds.tmpfile)
        lines = file.readlines()
        file.close()
        print(real_contents)
        print(lines)
        self.assertEqual(len(real_contents), len(lines))
        for i in range(len(lines)):
            print(lines[i][:-1])
            self.assertEqual(real_contents[i], lines[i][:-1])
Exemple #44
0
    def _calculate_rdc(self):
        """Calculate the averaged RDC for all states."""

        # Open the output files.
        if self.ROT_FILE:
            rot_file = open_write_file('rotations', dir=self.save_path, compress_type=1, force=True)

        # Printout.
        sys.stdout.write("\n\nRotating %s states for the RDC:\n\n" % locale.format("%d", self.N**self.MODES, grouping=True))

        # Turn off the relax interpreter echoing to allow the progress meter to be shown correctly.
        self.interpreter.off()

        # Set up some data structures for faster calculations.
        interatoms = []
        vectors = []
        d = []
        for interatom in interatomic_loop():
            # Nothing to do.
            if not hasattr(interatom, 'vector'):
                continue

            # Initialise the RDC structure (as a 1D numpy.float128 array for speed and minimising truncation artifacts).
            interatom.rdc = {}
            for tag in self._tensors:
                interatom.rdc[tag] = zeros(1, float128)

            # Pack the interatomic containers and vectors.
            interatoms.append(interatom)
            vectors.append(interatom.vector)

            # Get the spins.
            spin1 = return_spin(spin_id=interatom.spin_id1)
            spin2 = return_spin(spin_id=interatom.spin_id2)

            # Gyromagnetic ratios.
            g1 = periodic_table.gyromagnetic_ratio(spin1.isotope)
            g2 = periodic_table.gyromagnetic_ratio(spin2.isotope)

            # Calculate the RDC dipolar constant (in Hertz, and the 3 comes from the alignment tensor), and append it to the list.
            d.append(3.0/(2.0*pi) * dipolar_constant(g1, g2, interatom.r))

        # Repackage the data for speed.
        vectors = transpose(array(vectors, float64))
        d = array(d, float64)
        num_interatoms = len(vectors)

        # Store the alignment tensors.
        A = []
        for i in range(len(self._tensors)):
            A.append(cdp.align_tensors[i].A)

        # Loop over each position.
        for global_index, mode_indices in self._state_loop():
            # The progress meter.
            self._progress(global_index)

            # Total rotation matrix (for construction of the frame order matrix).
            total_R = eye(3)

            # Data initialisation.
            new_vect = vectors

            # Loop over each motional mode.
            for motion_index in range(self.MODES):
                # Generate the distribution specific rotation.
                self.rotation(mode_indices[motion_index], motion_index=motion_index)

                # Rotate the NH vector.
                new_vect = dot(self.R, new_vect)

                # Decompose the rotation into Euler angles and store them.
                if self.ROT_FILE:
                    a, b, g = R_to_euler_zyz(self.R)
                    rot_file.write('Mode %i:  %10.7f %10.7f %10.7f\n' % (motion_index, a, b, g))

                # Contribution to the total rotation.
                total_R = dot(self.R, total_R)

            # Loop over each alignment.
            for i in range(len(self._tensors)):
                # Calculate the RDC as quickly as possible.
                rdcs = d * tensordot(transpose(new_vect), tensordot(A[i], new_vect, axes=1), axes=1)

                # Store the values.
                for j in range(len(interatoms)):
                    interatoms[j].rdc[self._tensors[i]][0] += rdcs[j, j]

            # The frame order matrix component.
            self.daeg += kron_prod(total_R, total_R)

        # Print out.
        sys.stdout.write('\n\n')

        # Frame order matrix averaging.
        self.daeg = self.daeg / self.N**self.MODES

        # Write out the frame order matrix.
        file = open(self.save_path+sep+'frame_order_matrix', 'w')
        print_frame_order_2nd_degree(self.daeg, file=file, places=8)

        # Reactive the interpreter echoing.
        self.interpreter.on()

        # Average the RDC and write the data.
        for tag in self._tensors:
            # Average.
            for interatom in interatomic_loop():
                interatom.rdc[tag] = interatom.rdc[tag][0] / self.N**self.MODES

            # Save.
            self.interpreter.rdc.write(align_id=tag, file='rdc_%s.txt'%tag, dir=self.save_path, force=True)
Exemple #45
0
    def test_dasha(self):
        """Test a complete model-free analysis using the program 'Dasha'."""

        # Test for the presence of the Dasha binary (skip the test if not present).
        try:
            test_binary('dasha')
        except:
            return

        # Execute the script.
        self.script_exec(status.install_path + sep+'test_suite'+sep+'system_tests'+sep+'scripts'+sep+'dasha.py')

        # Check the global data.
        self.assertEqual(len(cdp.ri_ids), 3)
        for ri_id in cdp.ri_ids:
            self.assertEqual(cdp.spectrometer_frq[ri_id], 600000000.0)
        self.assertEqual(cdp.ri_type['R1_600'], 'R1')
        self.assertEqual(cdp.ri_type['R2_600'], 'R2')
        self.assertEqual(cdp.ri_type['NOE_600'], 'NOE')

        # The spin data.
        select = [True, True, False, False]
        fixed = [False, False, False, False]
        isotope = ['15N', '15N', '15N', '15N']
        model = ['m3', 'm3', 'm3', 'm3']
        equation = ['mf_orig', 'mf_orig', 'mf_orig', 'mf_orig']
        params = [['s2', 'rex'], ['s2', 'rex'], ['s2', 'rex'], ['s2', 'rex']]
        s2 = [0.71510, 0.64359, None, None]
        s2f = [None, None, None, None]
        s2s = [None, None, None, None]
        local_tm = [None, None, None, None]
        te = [None, None, None, None]
        tf = [None, None, None, None]
        ts = [None, None, None, None]
        rex_scale = 1.0 / (2.0 * pi * cdp.spectrometer_frq[cdp.ri_ids[0]]) ** 2
        rex = [4.32701*rex_scale, 4.29432*rex_scale, None, None]
        csa = [-172e-6, -172e-6, -172e-6, -172e-6]
        chi2 = [1.9657, 0.63673, None, None]
        ri_data = [{'R1_600': 1.0, 'R2_600': 15.0, 'NOE_600': 0.9},
                   {'R1_600': 0.9, 'R2_600': 13.9, 'NOE_600': 0.79},
                   {'R2_600': 12.0, 'NOE_600': 0.6},
                   None]
        ri_data_err = [{'R1_600': 0.05, 'R2_600': 0.5, 'NOE_600': 0.05},
                       {'R1_600': 0.05, 'R2_600': 0.8, 'NOE_600': 0.05},
                       {'R2_600': 0.5, 'NOE_600': 0.05},
                       None]

        # Check the spin data.
        i = 0
        for spin in spin_loop():
            # Protons.
            if spin.isotope == '1H':
                self.assertEqual(spin.select, False)
                continue

            # Check the data.
            self.assertEqual(spin.select, select[i])
            self.assertEqual(spin.fixed, fixed[i])
            self.assertEqual(spin.isotope, isotope[i])
            self.assertEqual(spin.model, model[i])
            self.assertEqual(spin.equation, equation[i])
            self.assertEqual(spin.params, params[i])
            self.assertEqual(spin.s2, s2[i])
            self.assertEqual(spin.s2f, s2f[i])
            self.assertEqual(spin.s2s, s2s[i])
            self.assertEqual(spin.local_tm, local_tm[i])
            self.assertEqual(spin.te, te[i])
            self.assertEqual(spin.tf, tf[i])
            self.assertEqual(spin.ts, ts[i])
            self.assertEqual(spin.rex, rex[i])
            self.assertAlmostEqual(spin.csa, csa[i])
            self.assertEqual(spin.chi2, chi2[i])
            if ri_data[i] == None:
                self.assert_(not hasattr(spin, 'ri_data'))
            else:
                for ri_id in cdp.ri_ids:
                    if ri_id in ri_data[i].keys():
                        self.assertEqual(spin.ri_data[ri_id], ri_data[i][ri_id])

            # Increment the spin index.
            i += 1

        # Check the interatomic data.
        r = [1.02e-10, 1.02e-10, 1.02e-10, 1.02e-10]
        i = 0
        for interatom in interatomic_loop():
            self.assertAlmostEqual(interatom.r, r[i])
            i += 1
Exemple #46
0
    def test_rdc_copy_back_calc(self):
        """Test the operation of the rdc.copy user function for back-calculated values."""

        # Data directory.
        dir = status.install_path + sep+'test_suite'+sep+'shared_data'+sep+'align_data'+sep

        # Set up two data identical pipes.
        pipes = ['orig', 'new']
        delete = [':6', ':11']
        for i in range(2):
            # Create a data pipe.
            self.interpreter.pipe.create(pipes[i], 'N-state')

            # Load the spins.
            self.interpreter.sequence.read(file='tb.txt', dir=dir, spin_id_col=1)
            self.interpreter.spin.element('N')

            # Delete the residue.
            self.interpreter.residue.delete(delete[i])

            # Attach protons.
            self.interpreter.sequence.attach_protons()
            self.interpreter.sequence.display()

            # Create the interatomic data containers.
            self.interpreter.interatom.define(spin_id1='@N', spin_id2='@H')

        # Printout.
        print("\n\nInteratomic data containers for the 'orig' data pipe:")
        for interatom in interatomic_loop(pipe='orig'):
            print("'%s' '%s'" % (interatom.spin_id1, interatom.spin_id2))
        print("\nInteratomic data containers for the 'new' data pipe:")
        for interatom in interatomic_loop(pipe='new'):
            print("'%s' '%s'" % (interatom.spin_id1, interatom.spin_id2))

        # Load the RDCs into the first data pipe.
        self.interpreter.pipe.switch('orig')
        self.interpreter.rdc.read(align_id='tb', file='tb.txt', dir=dir, spin_id1_col=1, spin_id2_col=2, data_col=3, error_col=4)

        # Create back-calculated RDC values from the real values.
        for interatom in interatomic_loop():
            if hasattr(interatom, 'rdc'):
                if not hasattr(interatom, 'rdc_bc'):
                    interatom.rdc_bc = {}
                interatom.rdc_bc['tb'] = interatom.rdc['tb'] + 1.0

        # Copy the RDCs, including back-calculated values, into the second data pipe.
        self.interpreter.rdc.copy(pipe_from='orig', pipe_to='new', align_id='tb', back_calc=True)

        # Checks.
        rdcs = [
            [ -26.2501958629, 7.26317614156, -1.24840526981, 5.31803314334, 14.0362909456, 1.33652530397, -1.6021670281],
            [ -26.2501958629, 9.93081766942, 7.26317614156, -1.24840526981, 5.31803314334, 14.0362909456, -1.6021670281]
        ]
        for i in range(2):
            print("\nChecking data pipe '%s'." % pipes[i])

            # Metadata.
            self.assert_(hasattr(ds[pipes[i]], 'align_ids'))
            self.assert_('tb' in ds[pipes[i]].align_ids)
            self.assert_(hasattr(ds[pipes[i]], 'rdc_ids'))
            self.assert_('tb' in ds[pipes[i]].rdc_ids)

            # Spin data.
            self.assertEqual(count_spins(pipe=pipes[i]), 14)
            self.assertEqual(len(ds[pipes[i]].interatomic), 7)
            j = 0
            for interatom in interatomic_loop(pipe=pipes[i]):
                # Residue 6 in the 'new' data pipe has no RDCs.
                if i == 1 and j == 1:
                    self.assert_(not hasattr(interatom, 'rdc'))
                    self.assert_(not hasattr(interatom, 'rdc_data_types'))
                    self.assert_(not hasattr(interatom, 'absolute_rdc'))
                else:
                    self.assertAlmostEqual(rdcs[i][j], interatom.rdc['tb'])
                    self.assertAlmostEqual(rdcs[i][j]+1.0, interatom.rdc_bc['tb'])
                    self.assert_(hasattr(interatom, 'rdc_data_types'))
                    self.assert_('tb' in interatom.rdc_data_types)
                    self.assertEqual(interatom.rdc_data_types['tb'], 'D')
                    self.assert_(hasattr(interatom, 'absolute_rdc'))
                    self.assert_('tb' in interatom.absolute_rdc)
                    self.assertEqual(interatom.absolute_rdc['tb'], False)
                j += 1
Exemple #47
0
    def base_data_loop(self):
        """Loop over the base data of the spins - RDCs, PCSs, and NOESY data.

        This loop iterates for each data point (RDC, PCS, NOESY) for each spin or interatomic data container, returning the identification information.

        @return:            A list of the spin or interatomic data container, the data type ('rdc', 'pcs', 'noesy'), and the alignment ID if required.
        @rtype:             list of [SpinContainer instance, str, str] or [InteratomContainer instance, str, str]
        """

        # Loop over the interatomic data containers.
        for interatom in interatomic_loop():
            # Skip deselected data.
            if not interatom.select:
                continue

            # Re-initialise the data structure.
            data = [interatom, None, None]

            # RDC data.
            if hasattr(interatom, 'rdc'):
                data[1] = 'rdc'

                # Loop over the alignment IDs.
                for id in cdp.rdc_ids:
                    # Add the ID.
                    data[2] = id

                    # Yield the set.
                    yield data

            # NOESY data.
            if hasattr(interatom, 'noesy'):
                data[1] = 'noesy'

                # Loop over the alignment IDs.
                for id in cdp.noesy_ids:
                    # Add the ID.
                    data[2] = id

                    # Yield the set.
                    yield data

        # Loop over the spins.
        for spin in spin_loop():
            # Skip deselected data.
            if not spin.select:
                continue

            # Re-initialise the data structure.
            data = [spin, None, None]

            # PCS data.
            if hasattr(spin, 'pcs'):
                data[1] = 'pcs'

                # Loop over the alignment IDs.
                for id in cdp.pcs_ids:
                    # Add the ID.
                    data[2] = id

                    # Yield the set.
                    yield data
Exemple #48
0
def create_vector_dist(length=None,
                       symmetry=True,
                       file=None,
                       dir=None,
                       force=False):
    """Create a PDB representation of the vector distribution.

    @keyword length:    The length to set the vectors to in the PDB file.
    @type length:       float
    @keyword symmetry:  The symmetry flag which if set will create a second PDB chain 'B' which is the same as chain 'A' but with the vectors reversed.
    @type symmetry:     bool
    @keyword file:      The name of the PDB file to create.
    @type file:         str
    @keyword dir:       The name of the directory to place the PDB file into.
    @type dir:          str
    @keyword force:     Flag which if set will overwrite any pre-existing file.
    @type force:        bool
    """

    # Test if the current pipe exists.
    check_pipe()

    # Test if a structure has been loaded.
    if not hasattr(cdp, 'structure') or not cdp.structure.num_models() > 0:
        raise RelaxNoPdbError

    # Test if sequence data is loaded.
    if not exists_mol_res_spin_data():
        raise RelaxNoSequenceError

    # Test if unit vectors exist.
    vectors = False
    for interatom in interatomic_loop():
        if hasattr(interatom, 'vector'):
            vectors = True
            break
    if not vectors:
        raise RelaxNoVectorsError

    # Initialise.
    #############

    # Create the structural object.
    structure = Internal()

    # Add a structure.
    structure.add_molecule(name='vector_dist')

    # Alias the single molecule from the single model.
    mol = structure.structural_data[0].mol[0]

    # Initialise the residue and atom numbers.
    res_num = 1
    atom_num = 1

    # Centre of mass.
    #################

    # Calculate the centre of mass.
    R = pipe_centre_of_mass()

    # Increment the residue number.
    res_num = res_num + 1

    # The vectors.
    ##############

    # Loop over the interatomic data containers.
    for interatom in interatomic_loop():
        # Get the spins.
        spin1 = return_spin(spin_hash=interatom._spin_hash1)
        spin2 = return_spin(spin_hash=interatom._spin_hash2)

        # Skip deselected spin systems.
        if not spin1.select or not spin2.select:
            continue

        # Skip containers missing vectors.
        if not hasattr(interatom, 'vector'):
            continue

        # Scale the vector.
        vector = interatom.vector * length * 1e10

        # Add the first spin as the central atom.
        mol.atom_add(pdb_record='ATOM',
                     atom_num=atom_num,
                     atom_name=spin1.name,
                     res_name=spin1._res_name,
                     chain_id='A',
                     res_num=spin1._res_num,
                     pos=R,
                     segment_id=None,
                     element=spin1.element)

        # Add the second spin as the end atom.
        mol.atom_add(pdb_record='ATOM',
                     atom_num=atom_num + 1,
                     atom_name=spin2.name,
                     res_name=spin2._res_name,
                     chain_id='A',
                     res_num=spin2._res_num,
                     pos=R + vector,
                     segment_id=None,
                     element=spin2.element)

        # Connect the two atoms.
        mol.atom_connect(index1=atom_num - 1, index2=atom_num)

        # Increment the atom number.
        atom_num = atom_num + 2

    # Symmetry chain.
    if symmetry:
        # Loop over the interatomic data containers.
        for interatom in interatomic_loop():
            # Get the spins.
            spin1 = return_spin(spin_hash=interatom._spin_hash1)
            spin2 = return_spin(spin_hash=interatom._spin_hash2)

            # Skip deselected spin systems.
            if not spin1.select or not spin2.select:
                continue

            # Skip containers missing vectors.
            if not hasattr(interatom, 'vector'):
                continue

            # Scale the vector.
            vector = interatom.vector * length * 1e10

            # Add the first spin as the central atom.
            mol.atom_add(pdb_record='ATOM',
                         atom_num=atom_num,
                         atom_name=spin1.name,
                         res_name=spin1._res_name,
                         chain_id='B',
                         res_num=spin1._res_num,
                         pos=R,
                         segment_id=None,
                         element=spin1.element)

            # Add the second spin as the end atom.
            mol.atom_add(pdb_record='ATOM',
                         atom_num=atom_num + 1,
                         atom_name=spin2.name,
                         res_name=spin2._res_name,
                         chain_id='B',
                         res_num=spin2._res_num,
                         pos=R - vector,
                         segment_id=None,
                         element=spin2.element)

            # Connect the two atoms.
            mol.atom_connect(index1=atom_num - 1, index2=atom_num)

            # Increment the atom number.
            atom_num = atom_num + 2

    # Create the PDB file.
    ######################

    # Print out.
    print("\nGenerating the PDB file.")

    # Open the PDB file for writing.
    tensor_pdb_file = open_write_file(file, dir, force=force)

    # Write the data.
    structure.write_pdb(tensor_pdb_file)

    # Close the file.
    tensor_pdb_file.close()

    # Add the file to the results file list.
    if not hasattr(cdp, 'result_files'):
        cdp.result_files = []
    if dir == None:
        dir = getcwd()
    cdp.result_files.append([
        'vector_dist_pdb', 'Vector distribution PDB',
        get_file_path(file, dir)
    ])
    status.observers.result_file.notify()
Exemple #49
0
    def assemble_data(self):
        """Assemble the data required for the auto-analysis.

        See the docstring for auto_analyses.dauvernge_protocol for details.  All data is taken from the relax data store, so data upload from the GUI to there must have been previously performed.

        @return:    A container with all the data required for the auto-analysis.
        @rtype:     class instance, list of str
        """

        # The data container.
        data = Container()
        missing = []

        # The pipe name and bundle.
        data.pipe_name = self.data.pipe_name
        data.pipe_bundle = self.data.pipe_bundle

        # The model-free models (do not change these unless absolutely necessary).
        data.local_tm_models = self.local_tm_model_field.GetValue()
        data.mf_models = self.mf_model_field.GetValue()

        # Automatic looping over all rounds until convergence (must be a boolean value of True or False).
        data.conv_loop = True

        # Increment size.
        data.inc = gui_to_int(self.grid_inc.GetValue())
        if hasattr(self.data, 'diff_tensor_grid_inc'):
            data.diff_tensor_grid_inc = self.data.diff_tensor_grid_inc
        else:
            data.diff_tensor_grid_inc = {
                'sphere': 11,
                'prolate': 11,
                'oblate': 11,
                'ellipsoid': 6
            }

        # The number of Monte Carlo simulations to be used for error analysis at the end of the analysis.
        data.mc_sim_num = gui_to_int(self.mc_sim_num.GetValue())

        # Number of maximum iterations.
        data.max_iter = self.data.max_iter

        # Results directory.
        data.save_dir = self.data.save_dir

        # Check if sequence data is loaded
        if not exists_mol_res_spin_data():
            missing.append("Sequence data")

        # Relaxation data.
        if not hasattr(cdp, 'ri_ids') or len(cdp.ri_ids) == 0:
            missing.append("Relaxation data")

        # Insufficient data.
        if hasattr(cdp, 'ri_ids') and len(cdp.ri_ids) <= 3:
            missing.append(
                "Insufficient relaxation data, 4 or more data sets are essential for the execution of the dauvergne_protocol auto-analysis. Check that you have entered data for a least two spectrometer fields."
            )

        # Interatomic data containers.
        if not hasattr(cdp, 'interatomic') or len(cdp.interatomic) == 0:
            missing.append(
                "Interatomic data (for the dipole-dipole interaction)")

        # Get the mode.
        mode = gui_to_str(self.mode.GetValue())

        # Solve for all global models.
        if mode == 'Fully automated':
            # The global model list.
            data.global_models = [
                'local_tm', 'sphere', 'prolate', 'oblate', 'ellipsoid', 'final'
            ]

        # Any global model selected.
        else:
            data.global_models = [mode]

        # Check for vectors.
        vector_check = False
        if 'prolate' in data.global_models or 'oblate' in data.global_models or 'ellipsoid' in data.global_models:
            vector_check = True

        # Spin variables.
        for spin, spin_id in spin_loop(return_id=True):
            # Skip deselected spins.
            if not spin.select:
                continue

            # The message skeleton.
            msg = "Spin '%s' - %s (try the %s user function)." % (spin_id,
                                                                  "%s", "%s")

            # Test if the nuclear isotope type has been set.
            if not hasattr(spin, 'isotope') or spin.isotope == None:
                missing.append(msg % ("nuclear isotope data", "spin.isotope"))

            # Test if the CSA value has been set for the heteronuclei.
            if (hasattr(spin, 'isotope') and spin.isotope
                    in ['15N', '13C']) and (not hasattr(spin, 'csa')
                                            or spin.csa == None):
                missing.append(msg % ("CSA data", "value.set"))

        # Interatomic data container variables.
        for interatom in interatomic_loop():
            # Get the spin containers.
            spin1 = return_spin(spin_hash=interatom._spin_hash1)
            spin2 = return_spin(spin_hash=interatom._spin_hash2)

            # Skip deselected spins.
            if not spin1.select:
                continue
            if not spin2.select:
                continue

            # The message skeleton.
            msg = "Spin pair '%s' and '%s' - %s (try the %s user function)." % (
                interatom.spin_id1, interatom.spin_id2, "%s", "%s")

            # Test if the interatomic distance has been set.
            if not hasattr(interatom, 'r') or interatom.r == None:
                missing.append(msg % ("bond length data", "value.set"))

            # Test if the unit vectors have been loaded.
            if vector_check and (not hasattr(interatom, 'vector')
                                 or interatom.vector is None):
                missing.append(msg %
                               ("unit vectors", "interatom.unit_vectors"))

        # Return the container and list of missing data.
        return data, missing
Exemple #50
0
def q_factors(spin_id=None):
    """Calculate the Q-factors for the RDC data.

    @keyword spin_id:   The spin ID string used to restrict the Q-factor calculation to a subset of all spins.
    @type spin_id:      None or str
    """

    # Check the pipe setup.
    check_pipe_setup(sequence=True)

    # No RDCs, so no Q factors can be calculated.
    if not hasattr(cdp, 'rdc_ids') or not len(cdp.rdc_ids):
        warn(RelaxWarning("No RDC data exists, Q factors cannot be calculated."))
        return

    # Q-factor dictonaries.
    cdp.q_factors_rdc = {}
    cdp.q_factors_rdc_norm2 = {}

    # Loop over the alignments.
    for align_id in cdp.rdc_ids:
        # Init.
        D2_sum = 0.0
        sse = 0.0

        # Interatomic data loop.
        dj = None
        N = 0
        interatom_count = 0
        rdc_data = False
        rdc_bc_data = False
        norm2_flag = True
        for interatom in interatomic_loop():
            # Increment the counter.
            interatom_count += 1

            # Data checks.
            if hasattr(interatom, 'rdc') and align_id in interatom.rdc:
                rdc_data = True
            if hasattr(interatom, 'rdc_bc') and align_id in interatom.rdc_bc:
                rdc_bc_data = True
            j_flag = False
            if hasattr(interatom, 'rdc_data_types') and align_id in interatom.rdc_data_types and interatom.rdc_data_types[align_id] == 'T':
                j_flag = True
                if not hasattr(interatom, 'j_coupling'):
                    raise RelaxNoJError

            # Skip containers without RDC data.
            if not hasattr(interatom, 'rdc') or not hasattr(interatom, 'rdc_bc') or not align_id in interatom.rdc or interatom.rdc[align_id] == None or not align_id in interatom.rdc_bc or interatom.rdc_bc[align_id] == None:
                continue

            # Get the spins.
            spin1 = return_spin(interatom.spin_id1)
            spin2 = return_spin(interatom.spin_id2)

            # Sum of squares.
            sse = sse + (interatom.rdc[align_id] - interatom.rdc_bc[align_id])**2

            # Sum the RDCs squared (for one type of normalisation).
            if j_flag:
                D2_sum = D2_sum + (interatom.rdc[align_id] - interatom.j_coupling)**2
            else:
                D2_sum = D2_sum + interatom.rdc[align_id]**2

            # Gyromagnetic ratios.
            g1 = return_gyromagnetic_ratio(spin1.isotope)
            g2 = return_gyromagnetic_ratio(spin2.isotope)

            # Skip the 2Da^2(4 + 3R)/5 normalised Q factor if pseudo-atoms are present.
            if  norm2_flag and (is_pseudoatom(spin1) or is_pseudoatom(spin2)):
                warn(RelaxWarning("Pseudo-atoms are present, skipping the Q factor normalised with 2Da^2(4 + 3R)/5."))
                norm2_flag = False

            # Calculate the RDC dipolar constant (in Hertz, and the 3 comes from the alignment tensor), and append it to the list.
            if norm2_flag:
                dj_new = 3.0/(2.0*pi) * dipolar_constant(g1, g2, interatom.r)
                if dj != None and dj_new != dj:
                    warn(RelaxWarning("The dipolar constant is not the same for all RDCs, skipping the Q factor normalised with 2Da^2(4 + 3R)/5."))
                    norm2_flag = False
                else:
                    dj = dj_new

            # Increment the number of data sets.
            N = N + 1

        # Warnings (and then exit).
        if not interatom_count:
            warn(RelaxWarning("No interatomic data containers have been used in the calculation, skipping the RDC Q factor calculation."))
            return
        if not rdc_data:
            warn(RelaxWarning("No RDC data can be found for the alignment ID '%s', skipping the RDC Q factor calculation for this alignment." % align_id))
            continue
        if not rdc_bc_data:
            warn(RelaxWarning("No back-calculated RDC data can be found for the alignment ID '%s', skipping the RDC Q factor calculation for this alignment." % align_id))
            continue

        # Normalisation factor of 2Da^2(4 + 3R)/5.
        if norm2_flag:
            D = dj * cdp.align_tensors[cdp.align_ids.index(align_id)].A_diag
            Da = 1.0/3.0 * (D[2, 2] - (D[0, 0]+D[1, 1])/2.0)
            Dr = 1.0/3.0 * (D[0, 0] - D[1, 1])
            if Da == 0:
                R = nan
            else:
                R = Dr / Da
            norm = 2.0 * (Da)**2 * (4.0 + 3.0*R**2)/5.0
            if Da == 0.0:
                norm = 1e-15

            # The Q-factor for the alignment.
            cdp.q_factors_rdc[align_id] = sqrt(sse / N / norm)

        else:
            cdp.q_factors_rdc[align_id] = 0.0

        # The second Q-factor definition.
        cdp.q_factors_rdc_norm2[align_id] = sqrt(sse / D2_sum)

    # The total Q-factor.
    cdp.q_rdc = 0.0
    cdp.q_rdc_norm2 = 0.0
    for id in cdp.q_factors_rdc:
        cdp.q_rdc = cdp.q_rdc + cdp.q_factors_rdc[id]**2
    for id in cdp.q_factors_rdc_norm2:
        cdp.q_rdc_norm2 = cdp.q_rdc_norm2 + cdp.q_factors_rdc_norm2[id]**2
    cdp.q_rdc = sqrt(cdp.q_rdc / len(cdp.q_factors_rdc))
    cdp.q_rdc_norm2 = sqrt(cdp.q_rdc_norm2 / len(cdp.q_factors_rdc_norm2))
Exemple #51
0
def return_rdc_data(sim_index=None):
    """Set up the data structures for optimisation using RDCs as base data sets.

    @keyword sim_index: The index of the simulation to optimise.  This should be None if normal optimisation is desired.
    @type sim_index:    None or int
    @return:            The assembled data structures for using RDCs as the base data for optimisation.  These include:
                            - rdc, the RDC values.
                            - rdc_err, the RDC errors.
                            - rdc_weight, the RDC weights.
                            - vectors, the interatomic vectors (pseudo-atom dependent).
                            - rdc_const, the dipolar constants (pseudo-atom dependent).
                            - absolute, the absolute value flags (as 1's and 0's).
                            - T_flags, the flags for T = J+D type data (as 1's and 0's).
                            - j_couplings, the J coupling values if the RDC data type is set to T = J+D.
                            - pseudo_flags, the list of flags indicating if the interatomic data contains a pseudo-atom (as 1's and 0's).
    @rtype:             tuple of (numpy rank-2 float64 array, numpy rank-2 float64 array, numpy rank-2 float64 array, list of numpy rank-3 float64 arrays, list of lists of floats, numpy rank-2 int32 array, numpy rank-2 int32 array, numpy rank-2 float64 array, numpy rank-1 int32 array)
    """

    # Sort out pseudo-atoms first.  This only needs to be called once.
    setup_pseudoatom_rdc()

    # Initialise.
    rdc = []
    rdc_err = []
    rdc_weight = []
    unit_vect = []
    rdc_const = []
    absolute = []
    T_flags = []
    j_couplings = []
    pseudo_flags = []

    # The unit vectors, RDC constants, and J couplings.
    for interatom in interatomic_loop():
        # Get the spins.
        spin1 = return_spin(interatom.spin_id1)
        spin2 = return_spin(interatom.spin_id2)

        # RDC checks.
        if not check_rdcs(interatom):
            continue

        # Gyromagnetic ratios.
        g1 = return_gyromagnetic_ratio(spin1.isotope)
        g2 = return_gyromagnetic_ratio(spin2.isotope)

        # Pseudo atoms.
        if is_pseudoatom(spin1) and is_pseudoatom(spin2):
            raise RelaxError("Support for both spins being in a dipole pair being pseudo-atoms is not implemented yet.")
        if is_pseudoatom(spin1) or is_pseudoatom(spin2):
            # Set the flag.
            pseudo_flags.append(1)

            # Alias the pseudo and normal atoms.
            if is_pseudoatom(spin1):
                pseudospin = spin1
                base_spin = spin2
                pseudospin_id = interatom.spin_id1
                base_spin_id = interatom.spin_id2
            else:
                pseudospin = spin2
                base_spin = spin1
                pseudospin_id = interatom.spin_id2
                base_spin_id = interatom.spin_id1

            # Loop over the atoms of the pseudo-atom, storing the data.
            pseudo_unit_vect = []
            pseudo_rdc_const = []
            for spin, spin_id in pseudoatom_loop(pseudospin, return_id=True):
                # Get the corresponding interatomic data container.
                pseudo_interatom = return_interatom(spin_id1=spin_id, spin_id2=base_spin_id)

                # Check.
                if pseudo_interatom == None:
                    raise RelaxError("The interatomic data container between the spins '%s' and '%s' for the pseudo-atom '%s' is not defined." % (base_spin_id, spin_id, pseudospin_id))

                # Add the vectors.
                if is_float(interatom.vector[0]):
                    pseudo_unit_vect.append([pseudo_interatom.vector])
                else:
                    pseudo_unit_vect.append(pseudo_interatom.vector)

                # Calculate the RDC dipolar constant (in Hertz, and the 3 comes from the alignment tensor), and append it to the list.
                pseudo_rdc_const.append(3.0/(2.0*pi) * dipolar_constant(g1, g2, pseudo_interatom.r))

            # Reorder the unit vectors so that the structure and pseudo-atom dimensions are swapped.
            pseudo_unit_vect = transpose(array(pseudo_unit_vect, float64), (1, 0, 2))

            # Block append the pseudo-data.
            unit_vect.append(pseudo_unit_vect)
            rdc_const.append(pseudo_rdc_const)

        # Normal atom.
        else:
            # Set the flag.
            pseudo_flags.append(0)

            # Add the vectors.
            if is_float(interatom.vector[0]):
                unit_vect.append([interatom.vector])
            else:
                unit_vect.append(interatom.vector)

            # Calculate the RDC dipolar constant (in Hertz, and the 3 comes from the alignment tensor), and append it to the list.
            rdc_const.append(3.0/(2.0*pi) * dipolar_constant(g1, g2, interatom.r))

        # Store the measured J coupling.
        if opt_uses_j_couplings():
            j_couplings.append(interatom.j_coupling)

    # Fix the unit vector data structure.
    num = None
    for rdc_index in range(len(unit_vect)):
        # Convert to numpy structures.
        unit_vect[rdc_index] = array(unit_vect[rdc_index], float64)

        # Number of vectors.
        if num == None:
            if unit_vect[rdc_index] != None:
                num = len(unit_vect[rdc_index])
            continue

        # Check.
        if unit_vect[rdc_index] != None and len(unit_vect[rdc_index]) != num:
            raise RelaxError("The number of interatomic vectors for all no match:\n%s" % unit_vect[rdc_index])

    # Missing unit vectors.
    if num == None:
        raise RelaxError("No interatomic vectors could be found.")

    # Update None entries.
    for i in range(len(unit_vect)):
        if unit_vect[i] == None:
            unit_vect[i] = [[None, None, None]]*num

    # The RDC data.
    for i in range(len(cdp.align_ids)):
        # Alias the ID.
        align_id = cdp.align_ids[i]

        # Skip non-optimised data.
        if not opt_uses_align_data(align_id):
            continue

        # Append empty arrays to the RDC structures.
        rdc.append([])
        rdc_err.append([])
        rdc_weight.append([])
        absolute.append([])
        T_flags.append([])

        # Interatom loop.
        for interatom in interatomic_loop():
            # Get the spins.
            spin1 = return_spin(interatom.spin_id1)
            spin2 = return_spin(interatom.spin_id2)

            # RDC checks.
            if not check_rdcs(interatom):
                continue

            # T-type data.
            if align_id in interatom.rdc_data_types and interatom.rdc_data_types[align_id] == 'T':
                T_flags[-1].append(True)
            else:
                T_flags[-1].append(False)

            # Check for J couplings if the RDC data type is T = J+D.
            if T_flags[-1][-1] and not hasattr(interatom, 'j_coupling'):
                continue

            # Defaults of None.
            value = None
            error = None

            # Normal set up.
            if align_id in interatom.rdc.keys():
                # The RDC.
                if sim_index != None:
                    value = interatom.rdc_sim[align_id][sim_index]
                else:
                    value = interatom.rdc[align_id]

                # The error.
                if hasattr(interatom, 'rdc_err') and align_id in interatom.rdc_err.keys():
                    # T values.
                    if T_flags[-1][-1]:
                        error = sqrt(interatom.rdc_err[align_id]**2 + interatom.j_coupling_err**2)

                    # D values.
                    else:
                        error = interatom.rdc_err[align_id]

            # Append the RDCs to the list.
            rdc[-1].append(value)

            # Append the RDC errors.
            rdc_err[-1].append(error)

            # Append the weight.
            if hasattr(interatom, 'rdc_weight') and align_id in interatom.rdc_weight.keys():
                rdc_weight[-1].append(interatom.rdc_weight[align_id])
            else:
                rdc_weight[-1].append(1.0)

            # Append the absolute value flag.
            if hasattr(interatom, 'absolute_rdc') and align_id in interatom.absolute_rdc.keys():
                absolute[-1].append(interatom.absolute_rdc[align_id])
            else:
                absolute[-1].append(False)

    # Convert to numpy objects.
    rdc = array(rdc, float64)
    rdc_err = array(rdc_err, float64)
    rdc_weight = array(rdc_weight, float64)
    absolute = array(absolute, int32)
    T_flags = array(T_flags, int32)
    if not opt_uses_j_couplings():
        j_couplings = None
    pseudo_flags = array(pseudo_flags, int32)

    # Return the data structures.
    return rdc, rdc_err, rdc_weight, unit_vect, rdc_const, absolute, T_flags, j_couplings, pseudo_flags
Exemple #52
0
    def test_corr_plot(self):
        """Test the operation of the rdc.corr_plot user function."""

        # Create a data pipe.
        self.interpreter.pipe.create('orig', 'N-state')

        # Data directory.
        dir = status.install_path + sep+'test_suite'+sep+'shared_data'+sep+'align_data'+sep

        # Load the spins.
        self.interpreter.sequence.read(file='tb.txt', dir=dir, spin_id_col=1)
        self.interpreter.sequence.attach_protons()
        self.interpreter.sequence.display()

        # Load the RDCs.
        self.interpreter.rdc.read(align_id='tb', file='tb.txt', dir=dir, spin_id1_col=1, spin_id2_col=2, data_col=3, error_col=4)
        self.interpreter.sequence.display()

        # Create back-calculated RDC values from the real values.
        for interatom in interatomic_loop():
            if hasattr(interatom, 'rdc'):
                if not hasattr(interatom, 'rdc_bc'):
                    interatom.rdc_bc = {}
                interatom.rdc_bc['tb'] = interatom.rdc['tb'] + 1.0

        # Correlation plot.
        ds.tmpfile = mktemp()
        self.interpreter.rdc.corr_plot(format='grace', title='Test', subtitle='Test2', file=ds.tmpfile, dir=None, force=True)

        # The expected file contents.
        real_contents = [
            "@version 50121",
            "@page size 842, 595",
            "@with g0",
            "@    world -27.0, -27.0, 16.0, 16.0",
            "@    view 0.15, 0.15, 1.28, 0.85",
            "@    title \"Test\"",
            "@    subtitle \"Test2\"",
            "@    xaxis  label \"Back-calculated RDC (Hz)\"",
            "@    xaxis  label char size 1.00",
            "@    xaxis  tick major 10",
            "@    xaxis  tick major size 0.50",
            "@    xaxis  tick major linewidth 0.5",
            "@    xaxis  tick minor ticks 9",
            "@    xaxis  tick minor linewidth 0.5",
            "@    xaxis  tick minor size 0.25",
            "@    xaxis  ticklabel char size 0.70",
            "@    yaxis  label \"Measured RDC (Hz)\"",
            "@    yaxis  label char size 1.00",
            "@    yaxis  tick major 10",
            "@    yaxis  tick major size 0.50",
            "@    yaxis  tick major linewidth 0.5",
            "@    yaxis  tick minor ticks 9",
            "@    yaxis  tick minor linewidth 0.5",
            "@    yaxis  tick minor size 0.25",
            "@    yaxis  ticklabel char size 0.70",
            "@    legend on",
            "@    legend 1, 0.5",
            "@    legend box fill pattern 1",
            "@    legend char size 1.0",
            "@    frame linewidth 0.5",
            "@    s0 symbol 1",
            "@    s0 symbol size 0.45",
            "@    s0 symbol linewidth 0.5",
            "@    s0 errorbar size 0.5",
            "@    s0 errorbar linewidth 0.5",
            "@    s0 errorbar riser linewidth 0.5",
            "@    s0 line linestyle 2",
            "@    s1 symbol 2",
            "@    s1 symbol size 0.45",
            "@    s1 symbol linewidth 0.5",
            "@    s1 errorbar size 0.5",
            "@    s1 errorbar linewidth 0.5",
            "@    s1 errorbar riser linewidth 0.5",
            "@    s1 line linestyle 0",
            "@    s1 legend \"tb\"",
            "@target G0.S0",
            "@type xydy",
            "          -100.000000000000000           -100.000000000000000              0.000000000000000",
            "           100.000000000000000            100.000000000000000              0.000000000000000",
            "&",
            "@target G0.S1",
            "@type xydy",
            "           -25.250195862900000            -26.250195862900000              1.000000000000000    \"#CaM:5@N-#CaM:5@H\"",
            "            10.930817669420000              9.930817669420000              1.000000000000000    \"#CaM:6@N-#CaM:6@H\"",
            "             8.263176141559999              7.263176141560000              1.000000000000000    \"#CaM:7@N-#CaM:7@H\"",
            "            -0.248405269810000             -1.248405269810000              0.000000000000000    \"#CaM:8@N-#CaM:8@H\"",
            "             6.318033143340000              5.318033143340000              1.000000000000000    \"#CaM:9@N-#CaM:9@H\"",
            "            15.036290945599999             14.036290945599999              1.000000000000000    \"#CaM:10@N-#CaM:10@H\"",
            "             2.336525303970000              1.336525303970000              0.000000000000000    \"#CaM:11@N-#CaM:11@H\"",
            "            -0.602167028100000             -1.602167028100000              0.000000000000000    \"#CaM:12@N-#CaM:12@H\"",
            "&",
        ]

        # Check the data.
        print("\nChecking the Grace file contents.")
        file = open(ds.tmpfile)
        lines = file.readlines()
        file.close()
        print(real_contents)
        print(lines)
        self.assertEqual(len(real_contents), len(lines))
        for i in range(len(lines)):
            print(lines[i][:-1])
            self.assertEqual(real_contents[i], lines[i][:-1])
Exemple #53
0
def minimise_bc_data(model, sim_index=None):
    """Extract and unpack the back calculated data.

    @param model:       The instantiated class containing the target function.
    @type model:        class instance
    @keyword sim_index: The optional Monte Carlo simulation index.
    @type sim_index:    None or int
    """

    # No alignment tensors, so nothing to do.
    if not hasattr(cdp, 'align_tensors'):
        return

    # Simulation flag.
    sim_flag = (sim_index != None)

    # Loop over each alignment.
    align_index = 0
    for i in range(len(cdp.align_ids)):
        # Skip non-optimised tensors.
        if not opt_uses_tensor(cdp.align_tensors[i]):
            continue

        # The alignment ID.
        align_id = cdp.align_ids[i]

        # Data flags
        rdc_flag = False
        if hasattr(cdp, 'rdc_ids') and align_id in cdp.rdc_ids:
            rdc_flag = True
        pcs_flag = False
        if hasattr(cdp, 'pcs_ids') and align_id in cdp.pcs_ids:
            pcs_flag = True

        # Spin loop.
        pcs_index = 0
        for spin in spin_loop():
            # Skip deselected spins.
            if not spin.select:
                continue

            # Spins with PCS data.
            if pcs_flag and hasattr(spin, 'pcs'):
                # Initialise the data structure if necessary.
                if sim_flag:
                    if not hasattr(spin, 'pcs_sim_bc'):
                        spin.pcs_sim_bc = {}
                    if align_id not in spin.pcs_sim_bc:
                        spin.pcs_sim_bc[align_id] = [None] * cdp.sim_number
                else:
                    if not hasattr(spin, 'pcs_bc'):
                        spin.pcs_bc = {}

                # Add the back calculated PCS (in ppm).
                if sim_flag:
                    spin.pcs_sim_bc[align_id][sim_index] = model.deltaij_theta[
                        align_index, pcs_index] * 1e6
                else:
                    spin.pcs_bc[align_id] = model.deltaij_theta[
                        align_index, pcs_index] * 1e6

                # Increment the data index if the spin container has data.
                pcs_index = pcs_index + 1

        # Interatomic data container loop.
        rdc_index = 0
        for interatom in interatomic_loop():
            # Get the spins.
            spin1 = return_spin(spin_hash=interatom._spin_hash1)
            spin2 = return_spin(spin_hash=interatom._spin_hash2)

            # RDC checks.
            if not check_rdcs(interatom):
                continue

            # Containers with RDC data.
            if rdc_flag and hasattr(interatom, 'rdc'):
                # Initialise the data structure if necessary.
                if sim_flag:
                    if not hasattr(interatom, 'rdc_sim_bc'):
                        interatom.rdc_sim_bc = {}
                    if align_id not in interatom.rdc_sim_bc:
                        interatom.rdc_sim_bc[align_id] = [0.0] * cdp.sim_number
                else:
                    if not hasattr(interatom, 'rdc_bc'):
                        interatom.rdc_bc = {}

                # Append the back calculated PCS.
                if sim_flag:
                    interatom.rdc_sim_bc[align_id][
                        sim_index] = model.rdc_theta[align_index, rdc_index]
                else:
                    interatom.rdc_bc[align_id] = model.rdc_theta[align_index,
                                                                 rdc_index]

                # Increment the data index if the interatom container has data.
                rdc_index = rdc_index + 1

        # Increment the alignment index (for the optimised tensors).
        align_index += 1
Exemple #54
0
    def test_rdc_copy_back_calc(self):
        """Test the operation of the rdc.copy user function for back-calculated values."""

        # Data directory.
        dir = status.install_path + sep+'test_suite'+sep+'shared_data'+sep+'align_data'+sep

        # Set up two data identical pipes.
        pipes = ['orig', 'new']
        delete = [':6', ':11']
        for i in range(2):
            # Create a data pipe.
            self.interpreter.pipe.create(pipes[i], 'N-state')

            # Load the spins.
            self.interpreter.sequence.read(file='tb.txt', dir=dir, spin_id_col=1)
            self.interpreter.spin.element('N')

            # Delete the residue.
            self.interpreter.residue.delete(delete[i])

            # Attach protons.
            self.interpreter.sequence.attach_protons()
            self.interpreter.sequence.display()

            # Create the interatomic data containers.
            self.interpreter.interatom.define(spin_id1='@N', spin_id2='@H')

        # Printout.
        print("\n\nInteratomic data containers for the 'orig' data pipe:")
        for interatom in interatomic_loop(pipe='orig'):
            print("'%s' '%s'" % (interatom.spin_id1, interatom.spin_id2))
        print("\nInteratomic data containers for the 'new' data pipe:")
        for interatom in interatomic_loop(pipe='new'):
            print("'%s' '%s'" % (interatom.spin_id1, interatom.spin_id2))

        # Load the RDCs into the first data pipe.
        self.interpreter.pipe.switch('orig')
        self.interpreter.rdc.read(align_id='tb', file='tb.txt', dir=dir, spin_id1_col=1, spin_id2_col=2, data_col=3, error_col=4)

        # Create back-calculated RDC values from the real values.
        for interatom in interatomic_loop():
            if hasattr(interatom, 'rdc'):
                if not hasattr(interatom, 'rdc_bc'):
                    interatom.rdc_bc = {}
                interatom.rdc_bc['tb'] = interatom.rdc['tb'] + 1.0

        # Copy the RDCs, including back-calculated values, into the second data pipe.
        self.interpreter.rdc.copy(pipe_from='orig', pipe_to='new', align_id='tb', back_calc=True)

        # Checks.
        rdcs = [
            [ -26.2501958629, 7.26317614156, -1.24840526981, 5.31803314334, 14.0362909456, 1.33652530397, -1.6021670281],
            [ -26.2501958629, 9.93081766942, 7.26317614156, -1.24840526981, 5.31803314334, 14.0362909456, -1.6021670281]
        ]
        for i in range(2):
            print("\nChecking data pipe '%s'." % pipes[i])

            # Metadata.
            self.assert_(hasattr(ds[pipes[i]], 'align_ids'))
            self.assert_('tb' in ds[pipes[i]].align_ids)
            self.assert_(hasattr(ds[pipes[i]], 'rdc_ids'))
            self.assert_('tb' in ds[pipes[i]].rdc_ids)

            # Spin data.
            self.assertEqual(count_spins(pipe=pipes[i]), 14)
            self.assertEqual(len(ds[pipes[i]].interatomic), 7)
            j = 0
            for interatom in interatomic_loop(pipe=pipes[i]):
                # Residue 6 in the 'new' data pipe has no RDCs.
                if i == 1 and j == 1:
                    self.assert_(not hasattr(interatom, 'rdc'))
                    self.assert_(not hasattr(interatom, 'rdc_data_types'))
                    self.assert_(not hasattr(interatom, 'absolute_rdc'))
                else:
                    self.assertAlmostEqual(rdcs[i][j], interatom.rdc['tb'])
                    self.assertAlmostEqual(rdcs[i][j]+1.0, interatom.rdc_bc['tb'])
                    self.assert_(hasattr(interatom, 'rdc_data_types'))
                    self.assert_('tb' in interatom.rdc_data_types)
                    self.assertEqual(interatom.rdc_data_types['tb'], 'D')
                    self.assert_(hasattr(interatom, 'absolute_rdc'))
                    self.assert_('tb' in interatom.absolute_rdc)
                    self.assertEqual(interatom.absolute_rdc['tb'], False)
                j += 1