示例#1
0
    def test_delete(self):
        """Test the relax_data.delete user function, replicating U{bug #19785<https://gna.org/bugs/?19785>}."""

        # Execute the script.
        self.interpreter.run(script_file=status.install_path + sep+'test_suite'+sep+'system_tests'+sep+'scripts'+sep+'bug_19785_relax_data_delete.py')

        # Switch to the first pipe.
        self.interpreter.pipe.switch('delete 1')

        # Checks.
        self.assertEqual(cdp.ri_ids, ['R1_900', 'NOE_900', 'R1_500', 'R2_500', 'NOE_500'])
        self.assert_(not 'R2_900' in cdp.spectrometer_frq)
        self.assert_(not 'R2_900' in cdp.ri_type)
        for spin in spin_loop():
            # Protons.
            if spin.name in ['H', 'HE1']:
                self.assert_(not hasattr(spin, 'ri_data'))

            # Nitrogens.
            else:
                self.assert_(not 'R2_900' in spin.ri_data)
                self.assert_(not 'R2_900' in spin.ri_data_err)

        # Switch to the second pipe.
        self.interpreter.pipe.switch('delete 2')

        # Checks.
        self.assert_(not hasattr(cdp, 'ri_ids'))
        self.assert_(not hasattr(cdp, 'spectrometer_frq'))
        self.assert_(not hasattr(cdp, 'ri_type'))
        for spin in spin_loop():
            self.assert_(not hasattr(spin, 'ri_data'))
            self.assert_(not hasattr(spin, 'ri_data_err'))
示例#2
0
def compare_sequence(pipe1=None, pipe2=None, fail=True):
    """Compare the sequence in two data pipes.

    @keyword pipe1:     The name of the first data pipe.
    @type pipe1:        str
    @keyword pipe2:     The name of the second data pipe.
    @type pipe2:        str
    @keyword fail:      A flag which if True causes a RelaxError to be raised.
    @type fail:         bool
    @return:            1 if the sequence is the same, 0 if different.
    @rtype:             int
    @raises RelaxError: If the sequence is different and the fail flag is True.
    """

    # Failure status.
    status = 1

    # Molecule number.
    if count_molecules(pipe=pipe1) != count_molecules(pipe=pipe2):
        status = 0
        if fail:
            raise RelaxDiffMolNumError(pipe1, pipe2)

    # Residue number.
    if count_residues(pipe=pipe1) != count_residues(pipe=pipe2):
        status = 0
        if fail:
            raise RelaxDiffResNumError(pipe1, pipe2)

    # Spin number.
    if count_spins(pipe=pipe1) != count_spins(pipe=pipe2):
        status = 0
        if fail:
            raise RelaxDiffSpinNumError(pipe1, pipe2)

    # Create a string representation of the 2 sequences.
    seq1 = ''
    seq2 = ''
    for spin, spin_id in spin_loop(return_id=True, pipe=pipe1):
        seq1 = seq1 + spin_id + '\n'
    for spin, spin_id in spin_loop(return_id=True, pipe=pipe2):
        seq2 = seq2 + spin_id + '\n'

    # Sequence check.
    if seq1 != seq2:
        status = 0
        if fail:
            raise RelaxDiffSeqError(pipe1, pipe2)

    # Return the status.
    return status
示例#3
0
def compare_sequence(pipe1=None, pipe2=None, fail=True):
    """Compare the sequence in two data pipes.

    @keyword pipe1:     The name of the first data pipe.
    @type pipe1:        str
    @keyword pipe2:     The name of the second data pipe.
    @type pipe2:        str
    @keyword fail:      A flag which if True causes a RelaxError to be raised.
    @type fail:         bool
    @return:            1 if the sequence is the same, 0 if different.
    @rtype:             int
    @raises RelaxError: If the sequence is different and the fail flag is True.
    """

    # Failure status.
    status = 1

    # Molecule number.
    if count_molecules(pipe=pipe1) != count_molecules(pipe=pipe2):
        status = 0
        if fail:
            raise RelaxDiffMolNumError(pipe1, pipe2)

    # Residue number.
    if count_residues(pipe=pipe1) != count_residues(pipe=pipe2):
        status = 0
        if fail:
            raise RelaxDiffResNumError(pipe1, pipe2)

    # Spin number.
    if count_spins(pipe=pipe1) != count_spins(pipe=pipe2):
        status = 0
        if fail:
            raise RelaxDiffSpinNumError(pipe1, pipe2)

    # Create a string representation of the 2 sequences.
    seq1 = ''
    seq2 = ''
    for spin, spin_id in spin_loop(return_id=True, pipe=pipe1):
        seq1 = seq1 + spin_id + '\n'
    for spin, spin_id in spin_loop(return_id=True, pipe=pipe2):
        seq2 = seq2 + spin_id + '\n'

    # Sequence check.
    if seq1 != seq2:
        status = 0
        if fail:
            raise RelaxDiffSeqError(pipe1, pipe2)

    # Return the status.
    return status
示例#4
0
    def _has_errors_spin(self):
        """Testing if errors exist for the current data pipe (spin system specific).

        @return:    The answer to the question of whether errors exist.
        @rtype:     bool
        """

        # Diffusion tensor errors.
        if hasattr(cdp, 'diff'):
            for object_name in dir(cdp.diff):
                # The object error name.
                object_error = object_name + '_err'

                # Error exists.
                if hasattr(cdp.diff, object_error):
                    return True

        # Loop over the sequence.
        for spin in spin_loop():
            # Parameter errors.
            for object_name in dir(spin):
                # The object error name.
                object_error = object_name + '_err'

                # Error exists.
                if hasattr(spin, object_error):
                    return True

        # No errors found.
        return False
示例#5
0
    def test_read_sparky(self):
        """Test the reading of chemical shifts from a Sparky peak list."""

        # Create the sequence data, and name the spins.
        for res_num in [3, 4, 5, 6, 40]:
            self.interpreter.spin.create(res_num=res_num, spin_name='N')
            self.interpreter.spin.create(res_num=res_num, spin_name='HN')
        self.interpreter.spin.create(res_num=40, spin_name='NE1')
        self.interpreter.spin.create(res_num=40, spin_name='HE1')

        # Load the peak list.
        path = status.install_path + sep + 'test_suite' + sep + 'shared_data' + sep + 'peak_lists'
        self.interpreter.chemical_shift.read(file='ref_ave.list', dir=path)

        # Test the data.
        cs = [
            122.454, 8.397, 111.978, 8.720, 115.069, 8.177, 120.910, 8.813,
            123.335, 8.005, 130.204, 10.294
        ]
        i = 0
        for spin in spin_loop():
            # No data.
            if i > 12:
                self.assert_(not hasattr(spin, 'chemical_shift'))

            # Check the shift.
            self.assertEqual(spin.chemical_shift, cs[i])

            # Increment the index.
            i += 1
示例#6
0
    def test_read_xeasy(self):
        """Test the reading of chemical shifts from a XEasy peak list."""

        # Create the sequence data, and name the spins.
        for res_num in [21, 96, 104, 110]:
            self.interpreter.spin.create(res_num=res_num, spin_name='N')
            self.interpreter.spin.create(res_num=res_num, spin_name='HN')
        self.interpreter.spin.create(res_num=79, spin_name='NE1')
        self.interpreter.spin.create(res_num=79, spin_name='HE1')

        # Load the peak list.
        path = status.install_path + sep+'test_suite'+sep+'shared_data'+sep+'peak_lists'
        self.interpreter.chemical_shift.read(file='xeasy_r1_20ms.text', dir=path)

        # Test the data.
        cs = [134.221, 10.014, 118.450, 8.364, 127.582, 9.211, 129.041, 9.882, 132.592, 10.481]
        i = 0
        for spin in spin_loop():
            # No data.
            if i > 10:
                self.assert_(not hasattr(spin, 'chemical_shift'))

            # Check the shift.
            self.assertEqual(spin.chemical_shift, cs[i])

            # Increment the index.
            i += 1
示例#7
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
示例#8
0
文件: bruker.py 项目: bopopescu/relax
    def test_bug_13_T2_read_fail(self):
        """Test catching U{bug #13<https://sourceforge.net/p/nmr-relax/tickets/13/>}, the failure reading a Bruker DC T2 file as submitted by Stefano Ciurli."""

        # The data ID.
        ri_id = 'T2_500'

        # The data path.
        dir = path.join(status.install_path, 'test_suite', 'shared_data',
                        'bruker_files')

        # Create a data pipe, read the sequence, and read the Bruker DC file to trigger the bug.
        self.interpreter.pipe.create('bug_13', 'mf')
        self.interpreter.sequence.read(file='bug_13_sequence',
                                       dir=dir,
                                       res_num_col=2,
                                       res_name_col=1)
        self.interpreter.bruker.read(ri_id=ri_id,
                                     file='bug_13_APO_T2_500_trunc.txt',
                                     dir=dir)

        # Check the data in the relax data store.
        self.assertEqual(cdp.ri_ids, [ri_id])
        self.assertEqual(cdp.spectrometer_frq[ri_id], 500.125 * 1e6)
        self.assertEqual(cdp.ri_type[ri_id], 'R2')

        # The R1 values and errors.
        r2 = [15.517992, 15.604246, 15.371578]
        r2_err = [0.2379555, 0.2386264, 0.3294271]
        i = 0
        for spin in spin_loop():
            self.assertAlmostEqual(spin.ri_data[ri_id], r2[i])
            self.assertAlmostEqual(spin.ri_data_err[ri_id], r2_err[i])
            i += 1
示例#9
0
    def check_curve_fitting_manual(self):
        """Check the results of the curve-fitting."""

        # Data.
        relax_times = [0.0176, 0.0176, 0.0352, 0.0704, 0.0704, 0.1056, 0.1584, 0.1584, 0.1936, 0.1936]
        chi2 = [2.916952651567855, 5.4916923952919632, 16.21182245065274, 4.3591263759462926, 9.8925377583244316, 6.0238341559877782]
        rx = [8.0814894819820662, 8.6478971039559642, 9.5710638183013845, 10.716551838066295, 11.143793935455122, 12.82875370075309]
        i0 = [1996050.9679875025, 2068490.9458927638, 1611556.5194095275, 1362887.2331948928, 1877670.5623875158, 897044.17382064369]

        # Some checks.
        self.assertEqual(cdp.curve_type, 'exp')
        self.assertEqual(cdp.int_method, ds.int_type)
        self.assertEqual(len(cdp.relax_times), 10)
        cdp_relax_times = sorted(cdp.relax_times.values())
        for i in range(10):
            self.assertEqual(cdp_relax_times[i], relax_times[i])

        # Check the errors.
        for key in cdp.sigma_I:
            self.assertAlmostEqual(cdp.sigma_I[key], 10578.039482421433, 6)
            self.assertAlmostEqual(cdp.var_I[key], 111894919.29166669)

        # Spin data check.
        i = 0
        for spin in spin_loop(skip_desel=True):
            self.assertAlmostEqual(spin.chi2, chi2[i])
            self.assertAlmostEqual(spin.rx, rx[i])
            self.assertAlmostEqual(spin.i0/1e6, i0[i]/1e6)

            # Increment the spin index.
            i = i + 1
示例#10
0
文件: data.py 项目: pombredanne/relax
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
示例#11
0
文件: bruker.py 项目: bopopescu/relax
    def test_bug_13_T1_read_fail(self):
        """Test catching U{bug #13<https://sourceforge.net/p/nmr-relax/tickets/13/>}, the failure reading a Bruker DC T1 file as submitted by Stefano Ciurli."""

        # The data ID.
        ri_id = 'T1_500'

        # The data path.
        dir = path.join(status.install_path, 'test_suite', 'shared_data',
                        'bruker_files')

        # Create a data pipe, read the sequence, and read the Bruker DC file to trigger the bug.
        self.interpreter.pipe.create('bug_13', 'mf')
        self.interpreter.sequence.read(file='bug_13_sequence',
                                       dir=dir,
                                       res_num_col=2,
                                       res_name_col=1)
        self.interpreter.bruker.read(ri_id=ri_id,
                                     file='bug_13_APO_T1_500_trunc.txt',
                                     dir=dir)

        # Check the data in the relax data store.
        self.assertEqual(cdp.ri_ids, [ri_id])
        self.assertEqual(cdp.spectrometer_frq[ri_id], 500.125 * 1e6)
        self.assertEqual(cdp.ri_type[ri_id], 'R1')

        # The R1 values and errors.
        r1 = [1.830269, 1.729287, 1.623507]
        r1_err = [0.0228767, 0.0210908, 0.0239931]
        i = 0
        for spin in spin_loop():
            self.assertAlmostEqual(spin.ri_data[ri_id], r1[i])
            self.assertAlmostEqual(spin.ri_data_err[ri_id], r1_err[i])
            i += 1
示例#12
0
def ellipsoid_frame():
    """Calculate the spherical angles of the bond vector in the ellipsoid frame."""

    # Get the unit vectors Dx, Dy, and Dz of the diffusion tensor axes.
    Dx, Dy, Dz = diffusion_tensor.unit_axes()

    # Spin loop.
    for spin, mol_name, res_num, res_name in spin_loop(full_info=True):
        # Test if the vector exists.
        if not hasattr(spin, 'xh_vect'):
            # Get the spin id string.
            spin_id = generate_spin_id(mol_name=mol_name, res_num=res_num, res_name=res_name, spin_num=spin.num, spin_name=spin.name)

            # Throw a warning.
            warn(RelaxWarning("No angles could be calculated for the spin " + repr(spin_id) + "."))

            # Skip the spin.
            continue

        # dz and dx direction cosines.
        dz = dot(Dz, spin.xh_vect)
        dx = dot(Dx, spin.xh_vect)

        # Calculate the polar angle theta.
        spin.theta = acos(dz)

        # Calculate the azimuthal angle phi.
        spin.phi = acos(dx / sin(spin.theta))
示例#13
0
文件: pcs.py 项目: pombredanne/relax
    def test_load_multi_col_data2(self):
        """Test the loading of PCS data from a file with different columns for each spin type."""

        # Create a data pipe for all the data.
        self.interpreter.pipe.create('CaM N-dom', 'N-state')

        # Create some spins.
        self.interpreter.spin.create(spin_name='N', spin_num=1, res_name='Gly', res_num=3, mol_name='CaM')
        self.interpreter.spin.create(spin_name='H', spin_num=2, res_name='Gly', res_num=3, mol_name='CaM')
        self.interpreter.spin.create(spin_name='N', spin_num=3, res_name='Gly', res_num=4, mol_name='CaM')
        self.interpreter.spin.create(spin_name='H', spin_num=4, res_name='Gly', res_num=4, mol_name='CaM')
        self.interpreter.sequence.display()

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

        # PCSs.
        self.interpreter.pcs.read(align_id='dy', file='pcs_dy_200911.txt', dir=dir, res_num_col=1, data_col=2, error_col=4, spin_id='@N')
        self.interpreter.pcs.read(align_id='dy', file='pcs_dy_200911.txt', dir=dir, res_num_col=1, data_col=3, error_col=4, spin_id='@H')

        # The data.
        pcs_data = {
            '#CaM:3@N': 0.917,
            '#CaM:3@H': 0.843,
            '#CaM:4@N': 1.131,
            '#CaM:4@H': 1.279,
        }

        # Check the PCS data.
        print("\n")
        for spin, spin_id in spin_loop(return_id=True):
            print("Checking the PCS data of spin '%s'." % spin_id)
            self.assert_(hasattr(spin, 'pcs'))
            self.assertEqual(spin.pcs['dy'], pcs_data[spin_id])
            self.assertEqual(spin.pcs_err['dy'], 0.1)
示例#14
0
    def test_back_calc(self):
        """Test the back calculation of relaxation data from model-free results (U{bug #14941<https://gna.org/bugs/?14941>})."""

        # Load the original state.
        self.interpreter.state.load(state='sphere_trunc', dir=status.install_path + sep+'test_suite'+sep+'shared_data'+sep+'model_free'+sep+'bug_14941_local_tm_global_selection')

        # Back calculate the relaxation data.
        self.interpreter.relax_data.back_calc()

        # The actual data.
        ri_data_bc = [{'R2_600': 4.7159538829340821, 'R1_500': 2.4779663389365068, 'NOE_500': 0.51989421750722165, 'R2_500': 4.3440970032224548, 'R1_600': 2.2831801922968129, 'NOE_600': 0.63592506242171432},
                      {'R2_600': 4.7211287713315739, 'R1_500': 2.5267468751446214, 'NOE_500': 0.57703969243842634, 'R2_500': 4.6185111669453738, 'R1_600': 2.2320234021052801, 'NOE_600': 0.66505178335932991}]

        # Loop over the spins.
        index = 0
        for spin in spin_loop():
            # Skip deselected protons.
            if not spin.select:
                continue

            # Check the back calculated data.
            self.assertEqual(spin.ri_data_bc, ri_data_bc[index])

            # Increment.
            index += 1
示例#15
0
    def test_back_calc_specific(self):
        """Test the back calculation of specific relaxation data from model-free results (U{bug #14941<https://gna.org/bugs/?14941>})."""

        # Load the original state.
        self.interpreter.state.load(state='sphere_trunc', dir=status.install_path + sep+'test_suite'+sep+'shared_data'+sep+'model_free'+sep+'bug_14941_local_tm_global_selection')

        # Back calculate the relaxation data.
        self.interpreter.relax_data.back_calc('NOE_500')

        # The actual data.
        ri_data_bc = [{'NOE_500': 0.51989421750722165},
                      {'NOE_500': 0.57703969243842634}]

        # Loop over the spins.
        index = 0
        for spin in spin_loop():
            # Skip deselected protons.
            if not spin.select:
                continue

            # Check the back calculated data.
            self.assertEqual(spin.ri_data_bc, ri_data_bc[index])

            # Increment.
            index += 1
示例#16
0
    def test_back_calc_specific(self):
        """Test the back calculation of specific relaxation data from model-free results (U{bug #14941<https://web.archive.org/web/https://gna.org/bugs/?14941>})."""

        # Load the original state.
        self.interpreter.state.load(state='sphere_trunc',
                                    dir=status.install_path + sep +
                                    'test_suite' + sep + 'shared_data' + sep +
                                    'model_free' + sep +
                                    'bug_14941_local_tm_global_selection')

        # Back calculate the relaxation data.
        self.interpreter.relax_data.back_calc('NOE_500')

        # The actual data.
        ri_data_bc = [{
            'NOE_500': 0.51989421750722165
        }, {
            'NOE_500': 0.57703969243842634
        }]

        # Loop over the spins.
        index = 0
        for spin in spin_loop():
            # Skip deselected protons.
            if not spin.select:
                continue

            # Check the back calculated data.
            self.assertEqual(spin.ri_data_bc, ri_data_bc[index])

            # Increment.
            index += 1
示例#17
0
    def test_select_sn_ratio_any(self):
        """Test the select.sn_ratio for signal to noise ratios, where any ID should evaluate to True.
        """

        # Setup data.
        self.setup_signal_noise_ratio()

        # Calculate the signal to noise ratio calculation.
        self.interpreter.spectrum.sn_ratio()

        # First deselect all spins.
        self.interpreter.deselect.all()

        # Select spins.
        self.interpreter.select.sn_ratio(ratio=200.0, operation='<', all_sn=False)

        # Test
        spin_ids_sel = []
        spin_ids_desel = []

        # Collect spin ids which are selected.
        for cur_spin, cur_spin_id in spin_loop(return_id=True, skip_desel=False):
            if cur_spin.select:
                spin_ids_sel.append(cur_spin_id)
            else:
                spin_ids_desel.append(cur_spin_id)

        # Make the test:
        self.assertEqual(spin_ids_sel, [':4@N', ':5@N', ':6@N'])
        self.assertEqual(spin_ids_desel, [':3@N'])
示例#18
0
    def test_read_sparky(self):
        """Test the reading of chemical shifts from a Sparky peak list."""

        # Create the sequence data, and name the spins.
        for res_num in [3, 4, 5, 6, 40]:
            self.interpreter.spin.create(res_num=res_num, spin_name='N')
            self.interpreter.spin.create(res_num=res_num, spin_name='HN')
        self.interpreter.spin.create(res_num=40, spin_name='NE1')
        self.interpreter.spin.create(res_num=40, spin_name='HE1')

        # Load the peak list.
        path = status.install_path + sep+'test_suite'+sep+'shared_data'+sep+'peak_lists'
        self.interpreter.chemical_shift.read(file='ref_ave.list', dir=path)

        # Test the data.
        cs = [122.454, 8.397, 111.978, 8.720, 115.069, 8.177, 120.910, 8.813, 123.335, 8.005, 130.204, 10.294]
        i = 0
        for spin in spin_loop():
            # No data.
            if i > 12:
                self.assert_(not hasattr(spin, 'chemical_shift'))

            # Check the shift.
            self.assertEqual(spin.chemical_shift, cs[i])

            # Increment the index.
            i += 1
示例#19
0
def errors():
    """Function for generating relaxation data errors."""

    # Loop over the sequence.
    for spin in spin_loop():
        # Loop over the relaxation data.
        for ri_id in cdp.ri_ids:
            # No data.
            if spin.ri_data_bc[ri_id] == None:
                continue

            # Set up the error relaxation data structure if needed.
            if not hasattr(spin, "ri_data_err"):
                spin.ri_data_err = {}

            # 600 MHz NOE.
            if ri_id == "NOE_600":
                spin.ri_data_err[ri_id] = 0.04

            # 500 MHz NOE.
            elif ri_id == "NOE_500":
                spin.ri_data_err[ri_id] = 0.05

            # All other data.
            else:
                spin.ri_data_err[ri_id] = spin.ri_data_bc[ri_id] * 0.02
示例#20
0
文件: data.py 项目: tlinnet/relax
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
示例#21
0
    def _has_errors_spin(self):
        """Testing if errors exist for the current data pipe (spin system specific).

        @return:    The answer to the question of whether errors exist.
        @rtype:     bool
        """

        # Diffusion tensor errors.
        if hasattr(cdp, "diff"):
            for object_name in dir(cdp.diff):
                # The object error name.
                object_error = object_name + "_err"

                # Error exists.
                if hasattr(cdp.diff, object_error):
                    return True

        # Loop over the sequence.
        for spin in spin_loop():
            # Parameter errors.
            for object_name in dir(spin):
                # The object error name.
                object_error = object_name + "_err"

                # Error exists.
                if hasattr(spin, object_error):
                    return True

        # No errors found.
        return False
示例#22
0
    def test_back_calc_new(self):
        """Test the back calculation of new relaxation data from model-free results (U{bug #14941<https://gna.org/bugs/?14941>})."""

        # Load the original state.
        self.interpreter.state.load(state='sphere_trunc', dir=status.install_path + sep+'test_suite'+sep+'shared_data'+sep+'model_free'+sep+'bug_14941_local_tm_global_selection')

        # Back calculate the relaxation data.
        self.interpreter.relax_data.back_calc('NOE_500.001', ri_type='NOE', frq=500.001e6)

        # The actual data.
        ri_data_bc = [{'NOE_500.001': 0.52064607759431081},
                      {'NOE_500.001': 0.57759452179767434}]

        # Loop over the spins.
        index = 0
        for spin in spin_loop():
            # Skip deselected protons.
            if not spin.select:
                continue

            # Check the back calculated data.
            self.assertEqual(spin.ri_data_bc, ri_data_bc[index])

            # Increment.
            index += 1
示例#23
0
def __deselect_spins():
    """Deselect spins with no or too little data, that are overfitting, etc."""

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

    # Is structural data required?
    need_vect = False
    if hasattr(cdp, 'diff_tensor') and (cdp.diff_tensor.type == 'spheroid' or cdp.diff_tensor.type == 'ellipsoid'):
        need_vect = True

    # Loop over the sequence.
    for spin in spin_loop():
        # Relaxation data must exist!
        if not hasattr(spin, 'ri_data'):
            spin.select = False

        # Require 3 or more relaxation data points.
        elif len(spin.ri_data) < 3:
            spin.select = False

        # Require at least as many data points as params to prevent over-fitting.
        elif hasattr(spin, 'params') and spin.params and len(spin.params) > len(spin.ri_data):
            spin.select = False
示例#24
0
def back_calc():
    """Back calculate the peak intensities.

    The simple two parameter exponential curve (Rx, I0) is assumed.
    """

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

        # The parameter vector.
        param_vector = array([spin.rx, spin.i0], float64)

        # Initialise the relaxation fit functions.
        setup(num_params=len(spin.params),
              num_times=len(cdp.relax_times),
              values=spin.ave_intensities,
              sd=cdp.sd,
              relax_times=cdp.relax_times,
              scaling_matrix=identity(2, float64))

        # Make a single function call.  This will cause back calculation and the data will be stored in the C module.
        func(param_vector)

        # Get the data and store it in the spin specific data structure.
        spin.fit_int = back_calc_I()
示例#25
0
def baseplane_rmsd(error=0.0, spectrum_id=None, spin_id=None):
    """Set the peak intensity errors, as defined as the baseplane RMSD.

    @param error:           The peak intensity error value defined as the RMSD of the base plane
                            noise.
    @type error:            float
    @keyword spectrum_id:   The spectrum id.
    @type spectrum_id:      str
    @param spin_id:         The spin identification string.
    @type spin_id:          str
    """

    # Data checks.
    check_pipe()
    check_mol_res_spin_data()
    check_spectrum_id(spectrum_id)

    # The scaling by NC_proc.
    if hasattr(cdp, 'ncproc') and spectrum_id in cdp.ncproc:
        scale = 1.0 / 2**cdp.ncproc[spectrum_id]
    else:
        scale = 1.0

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

        # Initialise or update the baseplane_rmsd data structure as necessary.
        if not hasattr(spin, 'baseplane_rmsd'):
            spin.baseplane_rmsd = {}

        # Set the error.
        spin.baseplane_rmsd[spectrum_id] = float(error) * scale
示例#26
0
    def error_analysis(self):
        """Perform an error analysis of the peak intensities for each field strength separately."""

        # Printout.
        section(file=sys.stdout, text="Error analysis", prespace=2)

        # Check if intensity errors have already been calculated by the user.
        precalc = True
        for spin in spin_loop(skip_desel=True):
            # No structure.
            if not hasattr(spin, 'peak_intensity_err'):
                precalc = False
                break

            # Determine if a spectrum ID is missing from the list.
            for id in cdp.spectrum_ids:
                if id not in spin.peak_intensity_err:
                    precalc = False
                    break

        # Skip.
        if precalc:
            print(
                "Skipping the error analysis as it has already been performed."
            )
            return

        # Perform the error analysis.
        self.interpreter.spectrum.error_analysis_per_field()
示例#27
0
文件: pcs.py 项目: pombredanne/relax
    def test_pcs_load(self):
        """Test for the loading of some PCS 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='pcs.txt', dir=dir, spin_name_col=1)
        self.interpreter.sequence.display()

        # Load the PCSs.
        self.interpreter.pcs.read(align_id='tb', file='pcs.txt', dir=dir, spin_name_col=1, data_col=2)
        self.interpreter.sequence.display()

        # The PCSs.
        pcs = [0.004, 0.008, 0.021, 0.029, 0.016, 0.010, 0.008, 0.003, 0.006, 0.003, 0.007, 0.005, 0.001, 0.070, None, 0.025, 0.098, 0.054, 0.075, 0.065, None, 0.070, 0.015, 0.098, 0.060, 0.120]

        # Checks.
        self.assertEqual(count_spins(), 26)
        self.assertEqual(len(cdp.interatomic), 0)
        i = 0
        for spin in spin_loop():
            self.assertEqual(pcs[i], spin.pcs['tb'])
            i += 1
示例#28
0
文件: uf.py 项目: tlinnet/relax
def model_setup(model=None, equation=None, params=None, spin_id=None):
    """Function for updating various data structures depending on the model selected.

    @param model:       The name of the model.
    @type model:        str
    @param equation:    The equation type to use.  The 3 allowed types are:  'mf_orig' for the original model-free equations with parameters {s2, te}; 'mf_ext' for the extended model-free equations with parameters {s2f, tf, s2, ts}; and 'mf_ext2' for the extended model-free equations with parameters {s2f, tf, s2s, ts}.
    @type equation:     str
    @param params:      A list of the parameters to include in the model.  The allowed parameter names includes those for the equation type as well as chemical exchange 'rex', the bond length 'r', and the chemical shift anisotropy 'csa'.
    @type params:       list of str
    @param spin_id:     The spin identification string.
    @type spin_id:      str
    """

    # Test that no diffusion tensor exists if local tm is a parameter in the model.
    if params:
        for param in params:
            if param == 'local_tm' and hasattr(pipes.get_pipe(),
                                               'diff_tensor'):
                raise RelaxTensorError('diffusion')

    # Loop over the sequence.
    for spin, spin_id in spin_loop(spin_id, return_id=True):
        # Initialise the data structures (if needed).
        api_model_free.data_init(spin_id)

        # Model-free model, equation, and parameter types.
        spin.model = model
        spin.equation = equation
        spin.params = params
示例#29
0
    def test_bruker_read_r1(self):
        """Test the reading of a DC R1 file."""

        # Read the sequence data.
        self.interpreter.sequence.read(file="seq", dir=status.install_path + sep+'test_suite'+sep+'shared_data'+sep+'bruker_files', res_num_col=2, res_name_col=1)

        # The ID string.
        ri_id = 'NOE_600'

        # Read the DC file.
        self.interpreter.bruker.read(ri_id=ri_id, file="testT1.txt", dir=status.install_path + sep+'test_suite'+sep+'shared_data'+sep+'bruker_files')

        # Check the data pipe structures.
        self.assertEqual(cdp.ri_ids, [ri_id])
        self.assertEqual(cdp.spectrometer_frq[ri_id], 600.13*1e6)
        self.assertEqual(cdp.ri_type[ri_id], 'R1')

        # The R1 values and errors.
        r1 = [2.1931556000035091, 2.3314642761386288, 2.3482998309224121, 2.2490812503092488, 2.2794204801371301, 2.2197311905528241, 2.2402487572220018, 1.9682404717478763, 2.0880183244488153, 1.9977625059932875, 2.1644881093845711, 2.2725568309649504, 2.1992861117281328, 2.2794360675168961, 2.0871205875661878, 2.2847272835278019, 2.1080324468354217, 2.2433596554199569, 2.3491493730120321, 2.2750850881822982, 2.4672959916309321, 2.3956227181693608, 2.1334016021846032, 2.3625860867305351, 2.3848078202618042, 2.3269721670859096, 2.4206451987712803, 2.3722597434638315, 2.343270361847809, 2.1927612565399106, 2.2380977959212909, 2.2461360844008094, 1.9912266553564995, 2.2936831964769029, 2.25463891957703, 2.2244169803094609, 2.280408101833904, 2.172312143876578, 2.2795451851446598, 2.266191370796498, 2.1729305009908564, 2.1917183729559486, 2.201809006279559, 2.1141693745652739, 2.2445782213064343, 2.133488082335572, 2.0460023160746217, 2.1921507848995887, 2.2750902642062325, 2.3691236848402144, 2.2981479225891852, 2.377233708223089, 2.2256001887308958, 2.2846020109066898, 2.3422878999749375, 1.973756927886817, 2.1651301459730745, 2.3191578673951914, 2.1891945734244915, 2.1815674998800136, 2.2678668217887572, 2.2465094858863042, 2.248479465761279, 2.3154901661132645, 2.1756630333094011, 2.1637200405913881, 1.8566309574645847, 1.6125599066005301, 1.1626041402658644, 0.76306229106400647]

        r1_err = [0.014883089934780979, 0.016303964816225223, 0.020363318742260723, 0.016687709376937879, 0.015718752396670817, 0.014518431475680691, 0.021886132469627697, 0.031556287075440621, 0.013515188095333659, 0.012453357417944776, 0.017587242385253953, 0.019302908234606619, 0.01371059959156644, 0.018437979357718477, 0.011698687778157989, 0.014869218069149722, 0.015737214115414941, 0.01390943018668532, 0.011941067694394526, 0.018293553488398374, 0.02261268912683069, 0.018087051681058786, 0.011598407444726788, 0.020469296587543661, 0.016620045900872408, 0.018909060457610323, 0.016739624643405365, 0.014806679126327058, 0.014476089754057037, 0.013123976098001535, 0.014050407715829098, 0.011838554421252851, 0.010844835351527457, 0.012711044971238742, 0.014752794876103476, 0.018227294017845289, 0.021723973501089892, 0.023441165299977383, 0.020591141498844744, 0.021778249169927173, 0.048387937817301517, 0.014867254858784009, 0.015546891671168217, 0.0142895492367403, 0.019750595476352866, 0.018562225014765673, 0.01329331372822814, 0.017647341591456655, 0.022969665803225174, 0.017861428710653073, 0.013099301992997067, 0.016245795194826523, 0.01547652953130973, 0.012508928370486994, 0.018321615170728861, 0.012861357034233434, 0.0098069239594803376, 0.019462269334464877, 0.015102761537490045, 0.015366805452534153, 0.020263438728953861, 0.020365125023511663, 0.015793641211181965, 0.020435935240713243, 0.014399976749920211, 0.012424600763085578, 0.0098441373116733167, 0.011085457618140082, 0.013079658707916478, 0.0029578895055556633]

        # Loop over the spins.
        i = 0
        for spin in spin_loop():
            # Check the R1 value and error.
            self.assertAlmostEqual(spin.ri_data[ri_id], r1[i], 5)
            self.assertAlmostEqual(spin.ri_data_err[ri_id], r1_err[i], 5)

            # Increment the data index.
            i += 1
示例#30
0
    def test_bruker_read_noe(self):
        """Test the reading of a DC NOE file."""

        # Read the sequence data.
        self.interpreter.sequence.read(file="seq", dir=status.install_path + sep+'test_suite'+sep+'shared_data'+sep+'bruker_files', res_num_col=2, res_name_col=1)

        # The ID string.
        ri_id = 'NOE_600'

        # Read the DC file.
        self.interpreter.bruker.read(ri_id=ri_id, file="testNOE.txt", dir=status.install_path + sep+'test_suite'+sep+'shared_data'+sep+'bruker_files')

        # Check the data pipe structures.
        self.assertEqual(cdp.ri_ids, [ri_id])
        self.assertEqual(cdp.spectrometer_frq[ri_id], 600.13*1e6)
        self.assertEqual(cdp.ri_type[ri_id], 'NOE')

        # The NOE values and errors.
        noe = [0.70140000000000002, 0.72260000000000002, 0.78410000000000002, 0.71389999999999998, 0.72219999999999995, 0.73450000000000004, 0.65800000000000003, 0.61319999999999997, 0.64359999999999995, 0.55810000000000004, 0.64349999999999996, 0.72719999999999996, 0.76690000000000003, 0.78159999999999996, 0.78320000000000001, 0.71179999999999999, 0.73529999999999995, 0.7339, 0.76639999999999997, 0.79600000000000004, 0.76980000000000004, 0.76090000000000002, 0.77000000000000002, 0.76839999999999997, 0.746, 0.75119999999999998, 0.7258, 0.76139999999999997, 0.75970000000000004, 0.76270000000000004, 0.71899999999999997, 0.7752, 0.78710000000000002, 0.75270000000000004, 0.75860000000000005, 0.73709999999999998, 0.76649999999999996, 0.78059999999999996, 0.77710000000000001, 0.74419999999999997, 0.71909999999999996, 0.73429999999999995, 0.69320000000000004, 0.60419999999999996, 0.71460000000000001, 0.73599999999999999, 0.78359999999999996, 0.79749999999999999, 0.75949999999999995, 0.76659999999999995, 0.77559999999999996, 0.73729999999999996, 0.73080000000000001, 0.78420000000000001, 0.70409999999999995, 0.6069, 0.79710000000000003, 0.74829999999999997, 0.72860000000000003, 0.73939999999999995, 0.751, 0.73150000000000004, 0.7238, 0.72529999999999994, 0.7218, 0.62980000000000003, 0.3004, 0.15970000000000001, -0.41570000000000001, -1.3540000000000001]

        noe_err = [0.0071371999999999998, 0.0071482999999999998, 0.0090542000000000001, 0.0073617999999999999, 0.0071636, 0.0067083000000000004, 0.0067882000000000003, 0.0076052000000000003, 0.0046737000000000003, 0.0047003000000000001, 0.0061779000000000001, 0.0087358000000000002, 0.0064637999999999996, 0.0084919999999999995, 0.0067708000000000004, 0.0064495999999999998, 0.0079068000000000003, 0.0059157999999999997, 0.0053657000000000002, 0.0088774000000000006, 0.0096562999999999996, 0.0078910000000000004, 0.0066074000000000003, 0.0091068, 0.0079459000000000005, 0.0088655999999999995, 0.0071831000000000004, 0.0069040999999999998, 0.0070117000000000001, 0.0065712000000000001, 0.0063590000000000001, 0.0054622999999999998, 0.0061237000000000002, 0.0058399999999999997, 0.0072487000000000003, 0.0082611999999999998, 0.010810999999999999, 0.010808999999999999, 0.010059999999999999, 0.0091409999999999998, 0.012137999999999999, 0.0063179999999999998, 0.0080087000000000005, 0.0067654999999999998, 0.0090647000000000002, 0.0085708999999999994, 0.0071379, 0.0088193999999999998, 0.010037000000000001, 0.0074373, 0.0059819000000000001, 0.0065192999999999996, 0.006594, 0.0057096999999999998, 0.0078305000000000007, 0.0062278999999999998, 0.0053839999999999999, 0.0085550000000000001, 0.0064421000000000001, 0.0066708000000000002, 0.0089885, 0.0095670000000000009, 0.0073683999999999998, 0.0092160000000000002, 0.0079343999999999994, 0.0059852999999999998, 0.0039353000000000001, 0.0040734999999999999, 0.0060822000000000003, 0.0067099000000000004]

        # Loop over the spins.
        i = 0
        for spin in spin_loop():
            # Check the R1 value and error.
            self.assertAlmostEqual(spin.ri_data[ri_id], noe[i])
            self.assertAlmostEqual(spin.ri_data_err[ri_id], noe_err[i])

            # Increment the data index.
            i += 1
示例#31
0
文件: api.py 项目: pombredanne/relax
    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))
示例#32
0
    def check_curve_fitting_manual(self):
        """Check the results of the curve-fitting."""

        # Data.
        relax_times = [0.0176, 0.0176, 0.0352, 0.0704, 0.0704, 0.1056, 0.1584, 0.1584, 0.1936, 0.1936]
        chi2 = [2.916952651567855, 5.4916923952919632, 16.21182245065274, 4.3591263759462926, 9.8925377583244316, 6.0238341559877782]
        rx = [8.0814894819820662, 8.6478971039559642, 9.5710638183013845, 10.716551838066295, 11.143793935455122, 12.82875370075309]
        i0 = [1996050.9679875025, 2068490.9458927638, 1611556.5194095275, 1362887.2331948928, 1877670.5623875158, 897044.17382064369]

        # Some checks.
        self.assertEqual(cdp.curve_type, 'exp')
        self.assertEqual(cdp.int_method, ds.int_type)
        self.assertEqual(len(cdp.relax_times), 10)
        cdp_relax_times = sorted(cdp.relax_times.values())
        for i in range(10):
            self.assertEqual(cdp_relax_times[i], relax_times[i])

        # Check the errors.
        for key in cdp.sigma_I:
            self.assertAlmostEqual(cdp.sigma_I[key], 10578.039482421433, 6)
            self.assertAlmostEqual(cdp.var_I[key], 111894919.29166669)

        # Spin data check.
        i = 0
        for spin in spin_loop(skip_desel=True):
            self.assertAlmostEqual(spin.chi2, chi2[i])
            self.assertAlmostEqual(spin.rx, rx[i])
            self.assertAlmostEqual(spin.i0/1e6, i0[i]/1e6)

            # Increment the spin index.
            i = i + 1
示例#33
0
def __deselect_spins():
    """Deselect spins with no or too little data, that are overfitting, etc."""

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

    # Is structural data required?
    need_vect = False
    if hasattr(cdp, 'diff_tensor') and (cdp.diff_tensor.type == 'spheroid' or
                                        cdp.diff_tensor.type == 'ellipsoid'):
        need_vect = True

    # Loop over the sequence.
    for spin in spin_loop():
        # Relaxation data and errors must exist!
        if (not hasattr(spin, 'ri_data')
                or spin.ri_data == None) or (not hasattr(spin, 'ri_data_err')
                                             or spin.ri_data_err == None):
            spin.select = False

        # Require 3 or more relaxation data points.
        elif len(spin.ri_data) < 3:
            spin.select = False

        # Require at least as many data points as params to prevent over-fitting.
        elif hasattr(spin, 'params') and spin.params and len(
                spin.params) > len(spin.ri_data):
            spin.select = False
示例#34
0
文件: uf.py 项目: pombredanne/relax
def delete():
    """Delete all the model-free data."""

    # Test if the current pipe exists.
    check_pipe()

    # Test if the pipe type is set to 'mf'.
    function_type = pipes.get_type()
    if function_type != "mf":
        raise RelaxFuncSetupError(specific_analyses.setup.get_string(function_type))

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

    # Get all data structure names.
    names = api_model_free.data_names(scope="spin")

    # Loop over the spins.
    for spin in spin_loop():
        # Loop through the data structure names.
        for name in names:
            # Skip the data structure if it does not exist.
            if not hasattr(spin, name):
                continue

            # Delete the data.
            delattr(spin, name)
示例#35
0
文件: spectrum.py 项目: tlinnet/relax
def baseplane_rmsd(error=0.0, spectrum_id=None, spin_id=None):
    """Set the peak intensity errors, as defined as the baseplane RMSD.

    @param error:           The peak intensity error value defined as the RMSD of the base plane
                            noise.
    @type error:            float
    @keyword spectrum_id:   The spectrum id.
    @type spectrum_id:      str
    @param spin_id:         The spin identification string.
    @type spin_id:          str
    """

    # Data checks.
    check_pipe()
    check_mol_res_spin_data()
    check_spectrum_id(spectrum_id)

    # The scaling by NC_proc.
    if hasattr(cdp, 'ncproc') and spectrum_id in cdp.ncproc:
        scale = 1.0 / 2**cdp.ncproc[spectrum_id]
    else:
        scale = 1.0

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

        # Initialise or update the baseplane_rmsd data structure as necessary.
        if not hasattr(spin, 'baseplane_rmsd'):
            spin.baseplane_rmsd = {}

        # Set the error.
        spin.baseplane_rmsd[spectrum_id] = float(error) * scale
示例#36
0
文件: uf.py 项目: pombredanne/relax
def model_setup(model=None, equation=None, params=None, spin_id=None):
    """Function for updating various data structures depending on the model selected.

    @param model:       The name of the model.
    @type model:        str
    @param equation:    The equation type to use.  The 3 allowed types are:  'mf_orig' for the original model-free equations with parameters {s2, te}; 'mf_ext' for the extended model-free equations with parameters {s2f, tf, s2, ts}; and 'mf_ext2' for the extended model-free equations with parameters {s2f, tf, s2s, ts}.
    @type equation:     str
    @param params:      A list of the parameters to include in the model.  The allowed parameter names includes those for the equation type as well as chemical exchange 'rex', the bond length 'r', and the chemical shift anisotropy 'csa'.
    @type params:       list of str
    @param spin_id:     The spin identification string.
    @type spin_id:      str
    """

    # Test that no diffusion tensor exists if local tm is a parameter in the model.
    if params:
        for param in params:
            if param == "local_tm" and hasattr(pipes.get_pipe(), "diff_tensor"):
                raise RelaxTensorError("diffusion")

    # Loop over the sequence.
    for spin, spin_id in spin_loop(spin_id, return_id=True):
        # Initialise the data structures (if needed).
        api_model_free.data_init(spin_id)

        # Model-free model, equation, and parameter types.
        spin.model = model
        spin.equation = equation
        spin.params = params
示例#37
0
文件: spectrum.py 项目: tlinnet/relax
def __errors_volume_no_repl(subset=None):
    """Calculate the errors for peak volumes when no spectra are replicated."""

    # Loop over the spins and set the error to the RMSD of the base plane noise.
    for spin, spin_id in spin_loop(return_id=True):
        # Skip deselected spins.
        if not spin.select:
            continue

        # Skip spins missing intensity data.
        if not hasattr(spin, 'peak_intensity'):
            continue

        # Test if the RMSD has been set.
        if not hasattr(spin, 'baseplane_rmsd'):
            raise RelaxError(
                "The RMSD of the base plane noise for spin '%s' has not been set."
                % spin_id)

        # Test that the total number of points have been set.
        if not hasattr(spin, 'N'):
            raise RelaxError(
                "The total number of points used in the volume integration has not been specified for spin '%s'."
                % spin_id)

        # Set the error to the RMSD multiplied by the square root of the total number of points.
        for key in spin.peak_intensity:
            spin.peak_intensity_err[key] = spin.baseplane_rmsd[key] * sqrt(
                spin.N)
示例#38
0
    def error_analysis(self):
        """Perform an error analysis of the peak intensities for each field strength separately."""

        # Printout.
        section(file=sys.stdout, text="Error analysis", prespace=2)

        # Check if intensity errors have already been calculated by the user.
        precalc = True
        for spin in spin_loop(skip_desel=True):
            # No structure.
            if not hasattr(spin, 'peak_intensity_err'):
                precalc = False
                break

            # Determine if a spectrum ID is missing from the list.
            for id in cdp.spectrum_ids:
                if id not in spin.peak_intensity_err:
                    precalc = False
                    break

        # Skip.
        if precalc:
            print("Skipping the error analysis as it has already been performed.")
            return

        # Perform the error analysis.
        self.interpreter.spectrum.error_analysis_per_field()
示例#39
0
文件: uf.py 项目: tlinnet/relax
def delete():
    """Delete all the model-free data."""

    # Test if the current pipe exists.
    check_pipe()

    # Test if the pipe type is set to 'mf'.
    function_type = pipes.get_type()
    if function_type != 'mf':
        raise RelaxFuncSetupError(
            specific_analyses.setup.get_string(function_type))

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

    # Get all data structure names.
    names = api_model_free.data_names(scope='spin')

    # Loop over the spins.
    for spin in spin_loop():
        # Loop through the data structure names.
        for name in names:
            # Skip the data structure if it does not exist.
            if not hasattr(spin, name):
                continue

            # Delete the data.
            delattr(spin, name)
示例#40
0
    def test_read_xeasy(self):
        """Test the reading of chemical shifts from a XEasy peak list."""

        # Create the sequence data, and name the spins.
        for res_num in [21, 96, 104, 110]:
            self.interpreter.spin.create(res_num=res_num, spin_name='N')
            self.interpreter.spin.create(res_num=res_num, spin_name='HN')
        self.interpreter.spin.create(res_num=79, spin_name='NE1')
        self.interpreter.spin.create(res_num=79, spin_name='HE1')

        # Load the peak list.
        path = status.install_path + sep + 'test_suite' + sep + 'shared_data' + sep + 'peak_lists'
        self.interpreter.chemical_shift.read(file='xeasy_r1_20ms.text',
                                             dir=path)

        # Test the data.
        cs = [
            134.221, 10.014, 118.450, 8.364, 127.582, 9.211, 129.041, 9.882,
            132.592, 10.481
        ]
        i = 0
        for spin in spin_loop():
            # No data.
            if i > 10:
                self.assert_(not hasattr(spin, 'chemical_shift'))

            # Check the shift.
            self.assertEqual(spin.chemical_shift, cs[i])

            # Increment the index.
            i += 1
示例#41
0
    def test_load_multi_col_data(self):
        """Test the loading of PCS data from a file with different columns for each spin type."""

        # Create a data pipe for all the data.
        self.interpreter.pipe.create('CaM N-dom', 'N-state')

        # Create some spins.
        self.interpreter.spin.create(spin_name='N',
                                     spin_num=1,
                                     res_name='Gly',
                                     res_num=3)
        self.interpreter.spin.create(spin_name='H',
                                     spin_num=2,
                                     res_name='Gly',
                                     res_num=3)
        self.interpreter.spin.create(spin_name='N',
                                     spin_num=3,
                                     res_name='Gly',
                                     res_num=4)
        self.interpreter.spin.create(spin_name='H',
                                     spin_num=4,
                                     res_name='Gly',
                                     res_num=4)
        self.interpreter.sequence.display()

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

        # PCSs.
        self.interpreter.pcs.read(align_id='dy',
                                  file='pcs_dy_200911.txt',
                                  dir=dir,
                                  res_num_col=1,
                                  data_col=2,
                                  error_col=4,
                                  spin_id='@N')
        self.interpreter.pcs.read(align_id='dy',
                                  file='pcs_dy_200911.txt',
                                  dir=dir,
                                  res_num_col=1,
                                  data_col=3,
                                  error_col=4,
                                  spin_id='@H')

        # The data.
        pcs_data = {
            ':3@N': 0.917,
            ':3@H': 0.843,
            ':4@N': 1.131,
            ':4@H': 1.279,
        }

        # Check the PCS data.
        print("\n")
        for spin, spin_id in spin_loop(return_id=True):
            print("Checking the PCS data of spin '%s'." % spin_id)
            self.assert_(hasattr(spin, 'pcs'))
            self.assertEqual(spin.pcs['dy'], pcs_data[spin_id])
            self.assertEqual(spin.pcs_err['dy'], 0.1)
示例#42
0
def write(file, dir=None, sep=None, mol_name_flag=True, res_num_flag=True, res_name_flag=True, spin_num_flag=True, spin_name_flag=True, force=False):
    """Write the molecule, residue, and/or sequence data.

    This calls the lib.io.write_spin_data() function to do most of the work.


    @param file:                The name of the file to write the data to.
    @type file:                 str
    @keyword dir:               The directory to contain the file (defaults to the current directory if None).
    @type dir:                  str or None
    @keyword sep:               The column seperator which, if None, defaults to whitespace.
    @type sep:                  str or None
    @keyword mol_name_flag:     A flag which if True will cause the molecule name column to be written.
    @type mol_name_flag:        bool
    @keyword res_num_flag:      A flag which if True will cause the residue number column to be written.
    @type res_num_flag:         bool
    @keyword res_name_flag:     A flag which if True will cause the residue name column to be written.
    @type res_name_flag:        bool
    @keyword spin_name_flag:    A flag which if True will cause the spin name column to be written.
    @type spin_name_flag:       bool
    @keyword spin_num_flag:     A flag which if True will cause the spin number column to be written.
    @keyword force:             A flag which if True will cause an existing file to be overwritten.
    @type force:                bin
    """

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

    # Init the data.
    mol_names = []
    res_nums = []
    res_names = []
    spin_nums = []
    spin_names = []

    # Spin loop.
    for spin, mol_name, res_num, res_name in spin_loop(full_info=True):
        mol_names.append(mol_name)
        res_nums.append(res_num)
        res_names.append(res_name)
        spin_nums.append(spin.num)
        spin_names.append(spin.name)

    # Remove unwanted data.
    if not mol_name_flag:
        mol_names = None
    if not res_num_flag:
        res_nums = None
    if not res_name_flag:
        res_names = None
    if not spin_num_flag:
        spin_nums = None
    if not spin_name_flag:
        spin_names = None

    # Write the data.
    write_spin_data(file=file, dir=dir, sep=sep, mol_names=mol_names, res_nums=res_nums, res_names=res_names, spin_nums=spin_nums, spin_names=spin_names, force=force)
示例#43
0
    def _set_param_values_spin(self,
                               param=None,
                               value=None,
                               index=None,
                               spin_id=None,
                               error=False,
                               force=True):
        """Set the spin specific parameter values.

        @keyword param:     The parameter name list.
        @type param:        list of str
        @keyword value:     The parameter value list.
        @type value:        list
        @keyword index:     The index for parameters which are of the list-type.  This is unused.
        @type index:        None or int
        @keyword spin_id:   The spin identification string, only used for spin specific parameters.
        @type spin_id:      None or str
        @keyword error:     A flag which if True will allow the parameter errors to be set instead of the values.
        @type error:        bool
        @keyword force:     A flag which if True will cause current values to be overwritten.  If False, a RelaxError will raised if the parameter value is already set.
        @type force:        bool
        """

        # Checks.
        lib.arg_check.is_str_list(param, 'parameter name')
        lib.arg_check.is_list(value, 'parameter value')

        # Loop over the parameters.
        for i in range(len(param)):
            # Is the parameter is valid?
            if not self._PARAMS.contains(param[i]):
                raise RelaxError(
                    "The parameter '%s' is not valid for this data pipe type."
                    % param[i])

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

                # The object name.
                obj_name = param[i]
                if error:
                    obj_name += '_err'

                # Set the parameter.
                param_type = self._PARAMS.type(param[i])
                if param_type == dict:
                    obj = getattr(spin, obj_name)
                    for key in obj:
                        obj[key] = value[i]
                elif param_type == list:
                    obj = getattr(spin, obj_name)
                    for j in range(len(obj)):
                        obj[j] = value[i]
                else:
                    setattr(spin, obj_name, value[i])
示例#44
0
def write(file, dir=None, sep=None, mol_name_flag=True, res_num_flag=True, res_name_flag=True, spin_num_flag=True, spin_name_flag=True, force=False):
    """Write the molecule, residue, and/or sequence data.

    This calls the lib.io.write_spin_data() function to do most of the work.


    @param file:                The name of the file to write the data to.
    @type file:                 str
    @keyword dir:               The directory to contain the file (defaults to the current directory if None).
    @type dir:                  str or None
    @keyword sep:               The column seperator which, if None, defaults to whitespace.
    @type sep:                  str or None
    @keyword mol_name_flag:     A flag which if True will cause the molecule name column to be written.
    @type mol_name_flag:        bool
    @keyword res_num_flag:      A flag which if True will cause the residue number column to be written.
    @type res_num_flag:         bool
    @keyword res_name_flag:     A flag which if True will cause the residue name column to be written.
    @type res_name_flag:        bool
    @keyword spin_name_flag:    A flag which if True will cause the spin name column to be written.
    @type spin_name_flag:       bool
    @keyword spin_num_flag:     A flag which if True will cause the spin number column to be written.
    @keyword force:             A flag which if True will cause an existing file to be overwritten.
    @type force:                bin
    """

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

    # Init the data.
    mol_names = []
    res_nums = []
    res_names = []
    spin_nums = []
    spin_names = []

    # Spin loop.
    for spin, mol_name, res_num, res_name in spin_loop(full_info=True):
        mol_names.append(mol_name)
        res_nums.append(res_num)
        res_names.append(res_name)
        spin_nums.append(spin.num)
        spin_names.append(spin.name)

    # Remove unwanted data.
    if not mol_name_flag:
        mol_names = None
    if not res_num_flag:
        res_nums = None
    if not res_name_flag:
        res_names = None
    if not spin_num_flag:
        spin_nums = None
    if not spin_name_flag:
        spin_names = None

    # Write the data.
    write_spin_data(file=file, dir=dir, sep=sep, mol_names=mol_names, res_nums=res_nums, res_names=res_names, spin_nums=spin_nums, spin_names=spin_names, force=force)
示例#45
0
    def _fix_params(self, spin_line, col, verbosity=1):
        """Fix certain parameters depending on the model type.

        @param spin_line:   The line of data for a single spin.
        @type spin_line:    list of str
        @param col:         The column indices.
        @type col:          dict of int
        @keyword verbosity: A variable specifying the amount of information to print.  The higher
                            the value, the greater the verbosity.
        @type verbosity:    int
        """

        # Extract the model type if it exists, otherwise return.
        if spin_line[col['param_set']] != 'None':
            model_type = spin_line[col['param_set']]
        else:
            return

        # Local tm and model-free only model types.
        if model_type == 'local_tm' or model_type == 'mf':
            diff_fixed = True
            mf_fixed = False

        # Diffusion tensor model type.
        elif model_type == 'diff':
            diff_fixed = False
            mf_fixed = True

        # 'all' model type.
        elif model_type == 'all':
            diff_fixed = False
            mf_fixed = False

        # No model type.
        elif model_type == 'None':
            model_type = None
            diff_fixed = None
            mf_fixed = None

        # Print out.
        if verbosity >= 2:
            print("\nFixing parameters based on the model type.")
            print("Model type: " + model_type)
            print("Diffusion tensor fixed: " + repr(diff_fixed))
            print("Model-free parameters fixed: " + repr(mf_fixed))

        # Set the diffusion tensor fixed flag.
        if model_type != 'local_tm' and diff_fixed != None:
            cdp.diff_tensor.set_fixed(diff_fixed)

        # Set the spin specific fixed flags.
        for spin, id in spin_loop(return_id=True):
            if not spin.select:
                continue

            if mf_fixed != None:
                spin.fixed = mf_fixed
示例#46
0
def fix_params(spin_line, col, verbosity=1):
    """Fix certain parameters depending on the model type.

    @param spin_line:   The line of data for a single spin.
    @type spin_line:    list of str
    @param col:         The column indices.
    @type col:          dict of int
    @keyword verbosity: A variable specifying the amount of information to print.  The higher
                        the value, the greater the verbosity.
    @type verbosity:    int
    """

    # Extract the model type if it exists, otherwise return.
    if spin_line[col['param_set']] != 'None':
        model_type = spin_line[col['param_set']]
    else:
        return

    # Local tm and model-free only model types.
    if model_type == 'local_tm' or model_type == 'mf':
        diff_fixed = True
        mf_fixed = False

    # Diffusion tensor model type.
    elif model_type == 'diff':
        diff_fixed = False
        mf_fixed = True

    # 'all' model type.
    elif model_type == 'all':
        diff_fixed = False
        mf_fixed = False

    # No model type.
    elif model_type == 'None':
        model_type = None
        diff_fixed = None
        mf_fixed = None

    # Print out.
    if verbosity >= 2:
        print("\nFixing parameters based on the model type.")
        print("Model type: " + model_type)
        print("Diffusion tensor fixed: " + repr(diff_fixed))
        print("Model-free parameters fixed: " + repr(mf_fixed))

    # Set the diffusion tensor fixed flag.
    if model_type != 'local_tm' and diff_fixed != None:
        cdp.diff_tensor.set_fixed(diff_fixed)

    # Set the spin specific fixed flags.
    for spin, id in spin_loop(return_id=True):
        if not spin.select:
            continue

        if mf_fixed != None:
            spin.fixed = mf_fixed
示例#47
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])
示例#48
0
def cpmgfit_input(dir=None, binary='cpmgfit', spin_id=None, force=False):
    """Create the CPMGFit input files.

    @keyword dir:               The optional directory to place the files into.  If None, then the files will be placed into a directory named after the dispersion model.
    @type dir:                  str or None
    @keyword binary:            The name of the CPMGFit binary file.  This can include the path to the binary.
    @type binary:               str
    @keyword spin_id:           The spin ID string to restrict the file creation to.
    @type spin_id:              str
    @keyword force:             A flag which if True will cause all pre-existing files to be overwritten.
    @type force:                bool
    """

    # Test if the current pipe exists.
    check_pipe()

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

    # Test if the experiment type has been set.
    if not hasattr(cdp, 'exp_type'):
        raise RelaxError("The relaxation dispersion experiment type has not been specified.")

    # Test if the model has been set.
    if not hasattr(cdp, 'model_type'):
        raise RelaxError("The relaxation dispersion model has not been specified.")

    # Directory creation.
    if dir != None:
        mkdir_nofail(dir, verbosity=0)

    # The 'run.sh' script.
    batch = open_write_file('batch_run.sh', dir, force)
    batch.write("#! /bin/sh\n\n")

    # Generate the input files for each spin.
    for spin, spin_id in spin_loop(return_id=True, skip_desel=True):
        # Translate the model.
        function = translate_model(spin.model)

        # Create the input file.
        file_in = create_spin_input(function=function, spin=spin, spin_id=spin_id, dir=dir)

        # The output file name.
        file_out = spin_file_name(spin_id=spin_id, output=True)

        # Add the file to the batch script.
        batch.write("%s -grid -xmgr -f %s | tee %s\n" % (binary, file_in, file_out))

    # Close the batch script, then make it executable.
    batch.close()
    if dir:
        chmod(dir + sep + 'batch_run.sh', S_IRWXU|S_IRGRP|S_IROTH)
    else:
        chmod('batch_run.sh', S_IRWXU|S_IRGRP|S_IROTH)
示例#49
0
def cpmgfit_input(dir=None, binary='cpmgfit', spin_id=None, force=False):
    """Create the CPMGFit input files.

    @keyword dir:               The optional directory to place the files into.  If None, then the files will be placed into a directory named after the dispersion model.
    @type dir:                  str or None
    @keyword binary:            The name of the CPMGFit binary file.  This can include the path to the binary.
    @type binary:               str
    @keyword spin_id:           The spin ID string to restrict the file creation to.
    @type spin_id:              str
    @keyword force:             A flag which if True will cause all pre-existing files to be overwritten.
    @type force:                bool
    """

    # Test if the current pipe exists.
    check_pipe()

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

    # Test if the experiment type has been set.
    if not hasattr(cdp, 'exp_type'):
        raise RelaxError("The relaxation dispersion experiment type has not been specified.")

    # Test if the model has been set.
    if not hasattr(cdp, 'model_type'):
        raise RelaxError("The relaxation dispersion model has not been specified.")

    # Directory creation.
    if dir != None:
        mkdir_nofail(dir, verbosity=0)

    # The 'run.sh' script.
    batch = open_write_file('batch_run.sh', dir, force)
    batch.write("#! /bin/sh\n\n")

    # Generate the input files for each spin.
    for spin, spin_id in spin_loop(return_id=True, skip_desel=True):
        # Translate the model.
        function = translate_model(spin.model)

        # Create the input file.
        file_in = create_spin_input(function=function, spin=spin, spin_id=spin_id, dir=dir)

        # The output file name.
        file_out = spin_file_name(spin_id=spin_id, output=True)

        # Add the file to the batch script.
        batch.write("%s -grid -xmgr -f %s | tee %s\n" % (binary, file_in, file_out))

    # Close the batch script, then make it executable.
    batch.close()
    if dir:
        chmod(dir + sep + 'batch_run.sh', S_IRWXU|S_IRGRP|S_IROTH)
    else:
        chmod('batch_run.sh', S_IRWXU|S_IRGRP|S_IROTH)
示例#50
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])
示例#51
0
    def test_bug_20152_read_dc_file(self):
        """Test the reading of a DC file, catching U{bug #20152<https://gna.org/bugs/?20152>}."""

        # Simulate the new analysis wizard.
        analysis = self.new_analysis_wizard(analysis_type='mf', analysis_name='Model-free test')

        # Change the results directory.
        analysis.field_results_dir.SetValue(str_to_gui(ds.tmpdir))

        # Launch the spin viewer window.
        self.app.gui.show_tree()

        # Spin loading wizard:  Initialisation.
        self.app.gui.spin_viewer.load_spins_wizard()

        # Spin loading wizard:  The PDB file.
        page = self.app.gui.spin_viewer.wizard.get_page(0)
        page.selection = 'new pdb'
        self.app.gui.spin_viewer.wizard._go_next()
        page = self.app.gui.spin_viewer.wizard.get_page(self.app.gui.spin_viewer.wizard._current_page)
        page.uf_args['file'].SetValue(str_to_gui(status.install_path + sep + 'test_suite' + sep + 'shared_data' + sep + 'structures' + sep + '1UBQ_H_trunc.pdb'))
        self.app.gui.spin_viewer.wizard._go_next()
        interpreter.flush()    # Required because of the asynchronous uf call.

        # Spin loading wizard:  The spin loading.
        self.app.gui.spin_viewer.wizard._go_next()
        interpreter.flush()    # Required because of the asynchronous uf call.

        # Close the spin viewer window.
        self.app.gui.spin_viewer.handler_close()

        # Flush the interpreter in preparation for the synchronous user functions of the peak list wizard.
        interpreter.flush()

        # The data path.
        data_path = status.install_path + sep + 'test_suite' + sep + 'shared_data' + sep + 'model_free' + sep + 'sphere' + sep

        # Set up the Bruker DC wizard.
        analysis.relax_data.wizard_bruker(None)

        # The spectrum.
        page = analysis.relax_data.wizard.get_page(analysis.relax_data.page_indices['read'])
        page.uf_args['ri_id'].SetValue(str_to_gui('r1_700'))
        page.uf_args['file'].SetValue(str_to_gui(status.install_path + sep + 'test_suite' + sep + 'shared_data' + sep + 'bruker_files' + sep + 'T1_demo_1UBQ_H_trunc.txt'))

        # Cause the failure.
        analysis.relax_data.wizard._go_next(None)

        # Check that no data was loaded.
        self.assert_(not hasattr(cdp, 'ri_ids'))
        self.assert_(not hasattr(cdp, 'spectrometer_frq'))
        self.assert_(not hasattr(cdp, 'ri_type'))
        for spin in spin_loop():
            self.assert_(not hasattr(spin, 'ri_data'))
            self.assert_(not hasattr(spin, 'ri_data_err'))
示例#52
0
    def calculate(self, spin_id=None, verbosity=1, sim_index=None):
        """Calculate the NOE and its error.

        The error for each peak is calculated using the formula::
                          ___________________________________________
                       \/ {sd(sat)*I(unsat)}^2 + {sd(unsat)*I(sat)}^2
            sd(NOE) = -----------------------------------------------
                                          I(unsat)^2

        @keyword spin_id:   The spin identification string.
        @type spin_id:      None or str
        @keyword verbosity: The amount of information to print.  The higher the value, the greater the verbosity.
        @type verbosity:    int
        @keyword sim_index: The MC simulation index (unused).
        @type sim_index:    None
        """

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

        # The spectrum types have not been set.
        if not hasattr(cdp, 'spectrum_type'):
            raise RelaxError("The spectrum types have not been set.")

        # Test if the 2 spectra types 'ref' and 'sat' exist.
        if not 'ref' in cdp.spectrum_type.values() or not 'sat' in cdp.spectrum_type.values():
            raise RelaxError("The reference and saturated NOE spectra have not been loaded.")

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

            # Average intensities (if required).
            sat = 0.0
            sat_err = 0.0
            ref = 0.0
            ref_err = 0.0
            for id in cdp.spectrum_ids:
                # Sat spectra.
                if cdp.spectrum_type[id] == 'sat':
                    sat = sat + spin.intensities[id]
                    sat_err = sat_err + spin.intensity_err[id]

                # Ref spectra.
                if cdp.spectrum_type[id] == 'ref':
                    ref = ref + spin.intensities[id]
                    ref_err = ref_err + spin.intensity_err[id]

            # Calculate the NOE.
            spin.noe = sat / ref

            # Calculate the error.
            spin.noe_err = sqrt((sat_err * ref)**2 + (ref_err * sat)**2) / ref**2
示例#53
0
def cluster(cluster_id=None, spin_id=None):
    """Define spin clustering.

    @keyword cluster_id:    The cluster ID string.
    @type cluster_id:       str
    @keyword spin_id:       The spin ID string for the spin or group of spins to add to the cluster.
    @type spin_id:          str
    """

    # Initialise.
    if not hasattr(cdp, 'clustering'):
        # Create the dictionary.
        cdp.clustering = {}
        cdp.clustering['free spins'] = []

        # Add all spin IDs to the cluster.
        for spin, id in spin_loop(return_id=True):
            cdp.clustering['free spins'].append(id)

    # Add the key.
    if cluster_id not in cdp.clustering:
        cdp.clustering[cluster_id] = []

    # Loop over the spins to add to the cluster.
    for spin, id in spin_loop(selection=spin_id, return_id=True):
        # First remove the ID from all clusters.
        for key in cdp.clustering:
            if id in cdp.clustering[key]:
                cdp.clustering[key].pop(cdp.clustering[key].index(id))

        # Then add the ID to the cluster.
        cdp.clustering[cluster_id].append(id)

    # Clean up - delete any empty clusters (except the free spins).
    clean = []
    for key in cdp.clustering:
        if key == 'free spins':
            continue
        if cdp.clustering[key] == []:
            clean.append(key)
    for key in clean:
        cdp.clustering.pop(key)
示例#54
0
文件: uf.py 项目: tlinnet/relax
def remove_tm(spin_id=None):
    """Remove local tm from the set of model-free parameters for the given spins.

    @param spin_id: The spin identification string.
    @type spin_id:  str or None
    """

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

    # Test if the pipe type is 'mf'.
    function_type = pipes.get_type()
    if function_type != 'mf':
        raise RelaxFuncSetupError(specific_analyses.get_string(function_type))

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

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

        # Test if a local tm parameter exists.
        if not hasattr(spin, 'params') or not 'local_tm' in spin.params:
            continue

        # Remove tm.
        spin.params.remove('local_tm')

        # Model name.
        if match('^tm', spin.model):
            spin.model = spin.model[1:]

        # Delete the local tm variable.
        del spin.local_tm

        # Set all the minimisation stats to None.
        spin.chi2 = None
        spin.iter = None
        spin.f_count = None
        spin.g_count = None
        spin.h_count = None
        spin.warning = None

    # Set the global minimisation stats to None.
    cdp.chi2 = None
    cdp.iter = None
    cdp.f_count = None
    cdp.g_count = None
    cdp.h_count = None
    cdp.warning = None
示例#55
0
def sel_spin(spin_id=None, boolean='OR', change_all=False):
    """Select specific spins.

    @keyword spin_id:               The spin identification string.
    @type spin_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 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 spins if the change_all flag is set.
    if change_all:
        # Loop over all spins.
        for spin in spin_loop():
            spin.select = False

    # Loop over the specified spins.
    for spin in spin_loop(spin_id):
        # Select just the specified residues.
        if change_all:
            spin.select = True

        # Boolean selections.
        else:
            spin.select = boolean_select(current=spin.select, boolean=boolean)
示例#56
0
def display(sep=None, mol_name_flag=True, res_num_flag=True, res_name_flag=True, spin_num_flag=True, spin_name_flag=True):
    """Display the current spin selections.

    @keyword sep:               The column seperator which, if None, defaults to whitespace.
    @type sep:                  str or None
    @keyword mol_name_flag:     A flag which if True will cause the molecule name column to be written.
    @type mol_name_flag:        bool
    @keyword res_num_flag:      A flag which if True will cause the residue number column to be written.
    @type res_num_flag:         bool
    @keyword res_name_flag:     A flag which if True will cause the residue name column to be written.
    @type res_name_flag:        bool
    @keyword spin_name_flag:    A flag which if True will cause the spin name column to be written.
    @type spin_name_flag:       bool
    @keyword spin_num_flag:     A flag which if True will cause the spin number column to be written.
    @type spin_num_flag:        bool
    """

    # Test if the sequence data is loaded.
    check_mol_res_spin_data()

    # Init the data.
    mol_names = []
    res_nums = []
    res_names = []
    spin_nums = []
    spin_names = []
    selections = []

    # Spin loop.
    for spin, mol_name, res_num, res_name in spin_loop(full_info=True, skip_desel=False):
        mol_names.append(mol_name)
        res_nums.append(res_num)
        res_names.append(res_name)
        spin_nums.append(spin.num)
        spin_names.append(spin.name)
        selections.append(spin.select)

    # Remove unwanted data.
    if not mol_name_flag:
        mol_names = None
    if not res_num_flag:
        res_nums = None
    if not res_name_flag:
        res_names = None
    if not spin_num_flag:
        spin_nums = None
    if not spin_name_flag:
        spin_names = None

    # Write the data.
    write_spin_data(file=sys.stdout, sep=sep, mol_names=mol_names, res_nums=res_nums, res_names=res_names, spin_nums=spin_nums, spin_names=spin_names, data=selections, data_name="selection")
示例#57
0
    def test_pcs_copy(self):
        """Test the operation of the pcs.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='pcs.txt',
                                       dir=dir,
                                       spin_name_col=1)
        self.interpreter.sequence.display()

        # Load the PCSs.
        self.interpreter.pcs.read(align_id='tb',
                                  file='pcs.txt',
                                  dir=dir,
                                  spin_name_col=1,
                                  data_col=2)
        self.interpreter.sequence.display()

        # The PCSs.
        pcs = [
            0.004, 0.008, 0.021, 0.029, 0.016, 0.010, 0.008, 0.003, 0.006,
            0.003, 0.007, 0.005, 0.001, 0.070, None, 0.025, 0.098, 0.054,
            0.075, 0.065, None, 0.070, 0.015, 0.098, 0.060, 0.120
        ]

        # 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 PCS data.
        self.interpreter.pcs.delete()

        # Copy the PCSs.
        self.interpreter.pcs.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, 'pcs_ids'))
        self.assert_('tb' in cdp.pcs_ids)
        self.assertEqual(count_spins(), 26)
        self.assertEqual(len(cdp.interatomic), 0)
        i = 0
        for spin in spin_loop():
            self.assertEqual(pcs[i], spin.pcs['tb'])
            i += 1
示例#58
0
def assemble_param_names(model_type, spin_id=None):
    """Function for assembling a list of all the model parameter names.

    @param model_type:  The model-free model type.  This must be one of 'mf', 'local_tm',
                        'diff', or 'all'.
    @type model_type:   str
    @param spin_id:     The spin identification string.
    @type spin_id:      str
    @return:            A list containing all the parameters of the model-free model.
    @rtype:             list of str
    """

    # Initialise.
    param_names = []

    # Diffusion tensor parameters.
    if model_type == 'diff' or model_type == 'all':
        # Spherical diffusion.
        if cdp.diff_tensor.type == 'sphere':
            param_names.append('tm')

        # Spheroidal diffusion.
        elif cdp.diff_tensor.type == 'spheroid':
            param_names.append('tm')
            param_names.append('Da')
            param_names.append('theta')
            param_names.append('phi')

        # Ellipsoidal diffusion.
        elif cdp.diff_tensor.type == 'ellipsoid':
            param_names.append('tm')
            param_names.append('Da')
            param_names.append('Dr')
            param_names.append('alpha')
            param_names.append('beta')
            param_names.append('gamma')

    # Model-free parameters (spin specific parameters).
    if model_type != 'diff':
        # Loop over the spins.
        for spin in spin_loop(spin_id):
            # Skip deselected spins.
            if not spin.select:
                continue

            # Add the spin specific model-free parameters.
            param_names = param_names + spin.params

    # Return the parameter names.
    return param_names
示例#59
0
    def test_delete(self):
        """Test the relax_data.delete user function, replicating U{bug #19785<https://web.archive.org/web/https://gna.org/bugs/?19785>}."""

        # Execute the script.
        self.interpreter.run(script_file=status.install_path + sep +
                             'test_suite' + sep + 'system_tests' + sep +
                             'scripts' + sep +
                             'bug_19785_relax_data_delete.py')

        # Switch to the first pipe.
        self.interpreter.pipe.switch('delete 1')

        # Checks.
        self.assertEqual(cdp.ri_ids,
                         ['R1_900', 'NOE_900', 'R1_500', 'R2_500', 'NOE_500'])
        self.assert_(not 'R2_900' in cdp.spectrometer_frq)
        self.assert_(not 'R2_900' in cdp.ri_type)
        for spin in spin_loop():
            # Protons.
            if spin.name in ['H', 'HE1']:
                self.assert_(not hasattr(spin, 'ri_data'))

            # Nitrogens.
            else:
                self.assert_(not 'R2_900' in spin.ri_data)
                self.assert_(not 'R2_900' in spin.ri_data_err)

        # Switch to the second pipe.
        self.interpreter.pipe.switch('delete 2')

        # Checks.
        self.assert_(not hasattr(cdp, 'ri_ids'))
        self.assert_(not hasattr(cdp, 'spectrometer_frq'))
        self.assert_(not hasattr(cdp, 'ri_type'))
        for spin in spin_loop():
            self.assert_(not hasattr(spin, 'ri_data'))
            self.assert_(not hasattr(spin, 'ri_data_err'))