Exemplo n.º 1
0
def create_script(file, model_type, algor):
    """Create the Dasha script file.

    @param file:        The opened file descriptor.
    @type file:         file object
    @param model_type:  The model-free model type.
    @type model_type:   str
    @param algor:       The optimisation algorithm to use.  This can be the Levenberg-Marquardt algorithm 'LM' or the Newton-Raphson algorithm 'NR'.
    @type algor:        str
    """

    # Delete all data.
    file.write("# Delete all data.\n")
    file.write("del 1 10000\n")

    # Nucleus type.
    file.write("\n# Nucleus type.\n")
    nucleus = None
    for spin in spin_loop():
        # Skip protons.
        if spin.isotope == '1H':
            continue

        # Can only handle one spin type.
        if nucleus and spin.isotope != nucleus:
            raise RelaxError("The nuclei '%s' and '%s' do not match, relax can only handle one nucleus type in Dasha." % (nucleus, spin.isotope))

        # Set the nucleus.
        if not nucleus:
            nucleus = spin.isotope

    # Convert the name and write it.
    if nucleus == '15N':
        nucleus = 'N15'
    elif nucleus == '13C':
        nucleus = 'C13'
    else:
        raise RelaxError("Cannot handle the nucleus type '%s' within Dasha." % nucleus)
    file.write("set nucl %s\n" % nucleus)

    # Number of frequencies.
    file.write("\n# Number of frequencies.\n")
    file.write("set n_freq %s\n" % cdp.spectrometer_frq_count)

    # Frequency values.
    file.write("\n# Frequency values.\n")
    count = 1
    for frq in loop_frequencies():
        file.write("set H1_freq %s %s\n" % (frq / 1e6, count))
        count += 1

    # Set the diffusion tensor.
    file.write("\n# Set the diffusion tensor.\n")
    if model_type != 'local_tm':
        # Sphere.
        if cdp.diff_tensor.type == 'sphere':
            file.write("set tr %s\n" % (cdp.diff_tensor.tm / 1e-9))

        # Spheroid.
        elif cdp.diff_tensor.type == 'spheroid':
            file.write('set tr %s\n' % (cdp.diff_tensor.tm / 1e-9))

        # Ellipsoid.
        elif cdp.diff_tensor.type == 'ellipsoid':
            # Get the eigenvales.
            Dx, Dy, Dz = diffusion_tensor.return_eigenvalues()

            # Geometric parameters.
            file.write("set tr %s\n" % (cdp.diff_tensor.tm / 1e-9))
            file.write("set D1/D3 %s\n" % (Dx / Dz))
            file.write("set D2/D3 %s\n" % (Dy / Dz))

            # Orientational parameters.
            file.write("set alfa %s\n" % (cdp.diff_tensor.alpha / (2.0 * pi) * 360.0))
            file.write("set betta %s\n" % (cdp.diff_tensor.beta / (2.0 * pi) * 360.0))
            file.write("set gamma %s\n" % (cdp.diff_tensor.gamma / (2.0 * pi) * 360.0))

    # Reading the relaxation data.
    file.write("\n# Reading the relaxation data.\n")
    file.write("echo Reading the relaxation data.\n")
    noe_index = 1
    r1_index = 1
    r2_index = 1
    for ri_id in cdp.ri_ids:
        # NOE.
        if cdp.ri_type[ri_id] == 'NOE':
            # Data set number.
            number = noe_index

            # Data type.
            data_type = 'noe'

            # Increment the data set index.
            noe_index = noe_index + 1

        # R1.
        elif cdp.ri_type[ri_id] == 'R1':
            # Data set number.
            number = r1_index

            # Data type.
            data_type = '1/T1'

            # Increment the data set index.
            r1_index = r1_index + 1

        # R2.
        elif cdp.ri_type[ri_id] == 'R2':
            # Data set number.
            number = r2_index

            # Data type.
            data_type = '1/T2'

            # Increment the data set index.
            r2_index = r2_index + 1

        # Set the data type.
        if number == 1:
            file.write("\nread < %s\n" % data_type)
        else:
            file.write("\nread < %s %s\n" % (data_type, number))

        # The relaxation data.
        for residue in residue_loop():
            # Alias the spin.
            spin = residue.spin[0]

            # Skip deselected spins.
            if not spin.select:
                continue

            # Skip and deselect spins for which relaxation data is missing.
            if len(spin.ri_data) != len(cdp.ri_ids) or spin.ri_data[ri_id] == None:
                spin.select = False
                continue

            # Data and errors.
            file.write("%s %s %s\n" % (residue.num, spin.ri_data[ri_id], spin.ri_data_err[ri_id]))

        # Terminate the reading.
        file.write("exit\n")

    # Individual residue optimisation.
    if model_type == 'mf':
        # Loop over the residues.
        for residue in residue_loop():
            # Alias the spin.
            spin = residue.spin[0]

            # Skip deselected spins.
            if not spin.select:
                continue

            # Get the interatomic data containers.
            interatoms = return_interatom_list(spin._spin_ids[0])
            if len(interatoms) == 0:
                raise RelaxNoInteratomError
            elif len(interatoms) > 1:
                raise RelaxError("Only one interatomic data container, hence dipole-dipole interaction, is supported per spin.")

            # Comment.
            file.write("\n\n\n# Residue %s\n\n" % residue.num)

            # Echo.
            file.write("echo Optimisation of residue %s\n" % residue.num)

            # Select the spin.
            file.write("\n# Select the residue.\n")
            file.write("set cres %s\n" % residue.num)

            # The angle alpha of the XH vector in the spheroid diffusion frame.
            if cdp.diff_tensor.type == 'spheroid':
                file.write("set teta %s\n" % spin.alpha)

            # The angles theta and phi of the XH vector in the ellipsoid diffusion frame.
            elif cdp.diff_tensor.type == 'ellipsoid':
                file.write("\n# Setting the spherical angles of the XH vector in the ellipsoid diffusion frame.\n")
                file.write("set teta %s\n" % spin.theta)
                file.write("set fi %s\n" % spin.phi)

            # The 'jmode'.
            if 'ts' in spin.params:
                jmode = 3
            elif 'te' in spin.params:
                jmode = 2
            elif 's2' in spin.params:
                jmode = 1

            # Chemical exchange.
            if 'rex' in spin.params:
                exch = True
            else:
                exch = False

            # Anisotropic diffusion.
            if cdp.diff_tensor.type == 'sphere':
                anis = False
            else:
                anis = True

            # Axial symmetry.
            if cdp.diff_tensor.type == 'spheroid':
                sym = True
            else:
                sym = False

            # Set the jmode.
            file.write("\n# Set the jmode.\n")
            file.write("set def jmode %s" % jmode)
            if exch:
                file.write(" exch")
            if anis:
                file.write(" anis")
            if sym:
                file.write(" sym")
            file.write("\n")

            # Parameter default values.
            file.write("\n# Parameter default values.\n")
            file.write("reset jmode %s\n" % residue.num)

            # Bond length.
            file.write("\n# Bond length.\n")
            file.write("set r_hx %s\n" % (interatoms[0].r / 1e-10))

            # CSA value.
            file.write("\n# CSA value.\n")
            file.write("set csa %s\n" % (spin.csa / 1e-6))

            # Fix the tf parameter if it isn't in the model.
            if not 'tf' in spin.params and jmode == 3:
                file.write("\n# Fix the tf parameter.\n")
                file.write("fix tf 0\n")

        # Optimisation of all residues.
        file.write("\n\n\n# Optimisation of all residues.\n")
        if algor == 'LM':
            file.write("lmin %s %s" % (first_residue_num(), last_residue_num()))
        elif algor == 'NR':
            file.write("min %s %s" % (first_residue_num(), last_residue_num()))

        # Show the results.
        file.write("\n# Show the results.\n")
        file.write("echo\n")
        file.write("show all\n")

        # Write the results.
        file.write("\n# Write the results.\n")
        file.write("write s2.out S\n")
        file.write("write s2f.out Sf\n")
        file.write("write s2s.out Ss\n")
        file.write("write te.out te\n")
        file.write("write tf.out tf\n")
        file.write("write ts.out ts\n")
        file.write("write rex.out rex\n")
        file.write("write chi2.out F\n")

    else:
        raise RelaxError("Optimisation of the parameter set '%s' currently not supported." % model_type)
Exemplo n.º 2
0
def bmrb_write(star):
    """Generate the relaxation data saveframes for the NMR-STAR dictionary object.

    @param star:    The NMR-STAR dictionary object.
    @type star:     NMR_STAR instance
    """

    # Get the current data pipe.
    cdp = pipes.get_pipe()

    # Initialise the spin specific data lists.
    mol_name_list = []
    res_num_list = []
    res_name_list = []
    atom_name_list = []
    isotope_list = []
    element_list = []
    attached_atom_name_list = []
    attached_isotope_list = []
    attached_element_list = []
    ri_data_list = []
    ri_data_err_list = []
    for i in range(len(cdp.ri_ids)):
        ri_data_list.append([])
        ri_data_err_list.append([])

    # Relax data labels.
    labels = cdp.ri_ids
    exp_label = []
    spectro_ids = []
    spectro_labels = []

    # Store the spin specific data in lists for later use.
    for spin, mol_name, res_num, res_name, spin_id in spin_loop(full_info=True, return_id=True):
        # Skip spins with no relaxation data.
        if not hasattr(spin, 'ri_data'):
            continue

        # Check the data for None (not allowed in BMRB!).
        if res_num == None:
            raise RelaxError("For the BMRB, the residue of spin '%s' must be numbered." % spin_id)
        if res_name == None:
            raise RelaxError("For the BMRB, the residue of spin '%s' must be named." % spin_id)
        if spin.name == None:
            raise RelaxError("For the BMRB, the spin '%s' must be named." % spin_id)
        if spin.isotope == None:
            raise RelaxError("For the BMRB, the spin isotope type of '%s' must be specified." % spin_id)

        # The molecule/residue/spin info.
        mol_name_list.append(mol_name)
        res_num_list.append(str(res_num))
        res_name_list.append(str(res_name))
        atom_name_list.append(str(spin.name))

        # Interatomic info.
        interatoms = return_interatom_list(spin_id)
        if len(interatoms) == 0:
            raise RelaxError("No interatomic interactions are defined for the spin '%s'." % spin_id)
        if len(interatoms) > 1:
            raise RelaxError("The BMRB only handles a signal interatomic interaction for the spin '%s'." % spin_id)

        # Get the attached spin.
        spin_attached = return_spin(interatoms[0].spin_id1)
        if id(spin_attached) == id(spin):
            spin_attached = return_spin(interatoms[0].spin_id2)

        # The attached atom info.
        if hasattr(spin_attached, 'name'):
            attached_atom_name_list.append(str(spin_attached.name))
        else:
            attached_atom_name_list.append(None)
        if hasattr(spin_attached, 'isotope'):
            attached_element_list.append(element_from_isotope(spin_attached.isotope))
            attached_isotope_list.append(str(number_from_isotope(spin_attached.isotope)))
        else:
            attached_element_list.append(None)
            attached_isotope_list.append(None)

        # The relaxation data.
        used_index = -ones(len(cdp.ri_ids))
        for i in range(len(cdp.ri_ids)):
            # Data exists.
            if cdp.ri_ids[i] in list(spin.ri_data.keys()):
                ri_data_list[i].append(str(spin.ri_data[cdp.ri_ids[i]]))
                ri_data_err_list[i].append(str(spin.ri_data_err[cdp.ri_ids[i]]))
            else:
                ri_data_list[i].append(None)
                ri_data_err_list[i].append(None)

        # Other info.
        isotope_list.append(int(spin.isotope.strip(string.ascii_letters)))
        element_list.append(spin.element)

    # Convert the molecule names into the entity IDs.
    entity_ids = zeros(len(mol_name_list), int32)
    mol_names = get_molecule_names()
    for i in range(len(mol_name_list)):
        for j in range(len(mol_names)):
            if mol_name_list[i] == mol_names[j]:
                entity_ids[i] = j+1

    # Check the temperature control methods.
    if not hasattr(cdp, 'exp_info') or not hasattr(cdp.exp_info, 'temp_calibration'):
        raise RelaxError("The temperature calibration methods have not been specified.")
    if not hasattr(cdp, 'exp_info') or not hasattr(cdp.exp_info, 'temp_control'):
        raise RelaxError("The temperature control methods have not been specified.")

    # Check the peak intensity type.
    if not hasattr(cdp, 'exp_info') or not hasattr(cdp.exp_info, 'peak_intensity_type'):
        raise RelaxError("The peak intensity types measured for the relaxation data have not been specified.")

    # Loop over the relaxation data.
    for i in range(len(cdp.ri_ids)):
        # Alias.
        ri_id = cdp.ri_ids[i]
        ri_type = cdp.ri_type[ri_id]

        # Convert to MHz.
        frq = cdp.spectrometer_frq[ri_id] * 1e-6

        # Get the temperature control methods.
        temp_calib = cdp.exp_info.temp_calibration[ri_id]
        temp_control = cdp.exp_info.temp_control[ri_id]

        # Get the peak intensity type.
        peak_intensity_type = cdp.exp_info.peak_intensity_type[ri_id]

        # Check.
        if not temp_calib:
            raise RelaxError("The temperature calibration method for the '%s' relaxation data ID string has not been specified." % ri_id)
        if not temp_control:
            raise RelaxError("The temperature control method for the '%s' relaxation data ID string has not been specified." % ri_id)

        # Add the relaxation data.
        star.relaxation.add(data_type=ri_type, frq=frq, entity_ids=entity_ids, res_nums=res_num_list, res_names=res_name_list, atom_names=atom_name_list, atom_types=element_list, isotope=isotope_list, entity_ids_2=entity_ids, res_nums_2=res_num_list, res_names_2=res_name_list, atom_names_2=attached_atom_name_list, atom_types_2=attached_element_list, isotope_2=attached_isotope_list, data=ri_data_list[i], errors=ri_data_err_list[i], temp_calibration=temp_calib, temp_control=temp_control, peak_intensity_type=peak_intensity_type)

        # The experimental label.
        if ri_type == 'NOE':
            exp_name = 'steady-state NOE'
        else:
            exp_name = ri_type
        exp_label.append("%s MHz %s" % (frq, exp_name))

        # Spectrometer info.
        frq_num = 1
        for frq in loop_frequencies():
            if frq == cdp.spectrometer_frq[ri_id]:
                break
            frq_num += 1
        spectro_ids.append(frq_num)
        spectro_labels.append("$spectrometer_%s" % spectro_ids[-1])

    # Add the spectrometer info.
    num = 1
    for frq in loop_frequencies():
        star.nmr_spectrometer.add(name="$spectrometer_%s" % num, manufacturer=None, model=None, frq=int(frq/1e6))
        num += 1

    # Add the experiment saveframe.
    star.experiment.add(name=exp_label, spectrometer_ids=spectro_ids, spectrometer_labels=spectro_labels)
Exemplo n.º 3
0
def bmrb_write(star):
    """Generate the relaxation data saveframes for the NMR-STAR dictionary object.

    @param star:    The NMR-STAR dictionary object.
    @type star:     NMR_STAR instance
    """

    # Get the current data pipe.
    cdp = pipes.get_pipe()

    # Initialise the spin specific data lists.
    mol_name_list = []
    res_num_list = []
    res_name_list = []
    atom_name_list = []
    isotope_list = []
    element_list = []
    attached_atom_name_list = []
    attached_isotope_list = []
    attached_element_list = []
    ri_data_list = []
    ri_data_err_list = []
    for i in range(len(cdp.ri_ids)):
        ri_data_list.append([])
        ri_data_err_list.append([])

    # Relax data labels.
    labels = cdp.ri_ids
    exp_label = []
    spectro_ids = []
    spectro_labels = []

    # Store the spin specific data in lists for later use.
    for spin, mol_name, res_num, res_name, spin_id in spin_loop(
            full_info=True, return_id=True):
        # Skip spins with no relaxation data.
        if not hasattr(spin, 'ri_data'):
            continue

        # Check the data for None (not allowed in BMRB!).
        if res_num == None:
            raise RelaxError(
                "For the BMRB, the residue of spin '%s' must be numbered." %
                spin_id)
        if res_name == None:
            raise RelaxError(
                "For the BMRB, the residue of spin '%s' must be named." %
                spin_id)
        if spin.name == None:
            raise RelaxError("For the BMRB, the spin '%s' must be named." %
                             spin_id)
        if spin.isotope == None:
            raise RelaxError(
                "For the BMRB, the spin isotope type of '%s' must be specified."
                % spin_id)

        # The molecule/residue/spin info.
        mol_name_list.append(mol_name)
        res_num_list.append(str(res_num))
        res_name_list.append(str(res_name))
        atom_name_list.append(str(spin.name))

        # Interatomic info.
        interatoms = return_interatom_list(spin_hash=spin._hash)
        if len(interatoms) == 0:
            raise RelaxError(
                "No interatomic interactions are defined for the spin '%s'." %
                spin_id)
        if len(interatoms) > 1:
            raise RelaxError(
                "The BMRB only handles a signal interatomic interaction for the spin '%s'."
                % spin_id)

        # Get the attached spin.
        spin_attached = return_spin(spin_hash=interatoms[0]._spin_hash1)
        if id(spin_attached) == id(spin):
            spin_attached = return_spin(spin_hash=interatoms[0]._spin_hash2)

        # The attached atom info.
        if hasattr(spin_attached, 'name'):
            attached_atom_name_list.append(str(spin_attached.name))
        else:
            attached_atom_name_list.append(None)
        if hasattr(spin_attached, 'isotope'):
            attached_element_list.append(
                element_from_isotope(spin_attached.isotope))
            attached_isotope_list.append(
                str(number_from_isotope(spin_attached.isotope)))
        else:
            attached_element_list.append(None)
            attached_isotope_list.append(None)

        # The relaxation data.
        used_index = -ones(len(cdp.ri_ids))
        for i in range(len(cdp.ri_ids)):
            # Data exists.
            if cdp.ri_ids[i] in spin.ri_data:
                ri_data_list[i].append(str(spin.ri_data[cdp.ri_ids[i]]))
                ri_data_err_list[i].append(str(
                    spin.ri_data_err[cdp.ri_ids[i]]))
            else:
                ri_data_list[i].append(None)
                ri_data_err_list[i].append(None)

        # Other info.
        isotope_list.append(int(spin.isotope.strip(string.ascii_letters)))
        element_list.append(spin.element)

    # Convert the molecule names into the entity IDs.
    entity_ids = zeros(len(mol_name_list), int32)
    mol_names = get_molecule_names()
    for i in range(len(mol_name_list)):
        for j in range(len(mol_names)):
            if mol_name_list[i] == mol_names[j]:
                entity_ids[i] = j + 1

    # Check the temperature control methods.
    if not hasattr(cdp, 'exp_info') or not hasattr(cdp.exp_info,
                                                   'temp_calibration'):
        raise RelaxError(
            "The temperature calibration methods have not been specified.")
    if not hasattr(cdp, 'exp_info') or not hasattr(cdp.exp_info,
                                                   'temp_control'):
        raise RelaxError(
            "The temperature control methods have not been specified.")

    # Check the peak intensity type.
    if not hasattr(cdp, 'exp_info') or not hasattr(cdp.exp_info,
                                                   'peak_intensity_type'):
        raise RelaxError(
            "The peak intensity types measured for the relaxation data have not been specified."
        )

    # Loop over the relaxation data.
    for i in range(len(cdp.ri_ids)):
        # Alias.
        ri_id = cdp.ri_ids[i]
        ri_type = cdp.ri_type[ri_id]

        # Convert to MHz.
        frq = cdp.spectrometer_frq[ri_id] * 1e-6

        # Get the temperature control methods.
        temp_calib = cdp.exp_info.temp_calibration[ri_id]
        temp_control = cdp.exp_info.temp_control[ri_id]

        # Get the peak intensity type.
        peak_intensity_type = cdp.exp_info.peak_intensity_type[ri_id]

        # Check.
        if not temp_calib:
            raise RelaxError(
                "The temperature calibration method for the '%s' relaxation data ID string has not been specified."
                % ri_id)
        if not temp_control:
            raise RelaxError(
                "The temperature control method for the '%s' relaxation data ID string has not been specified."
                % ri_id)

        # Add the relaxation data.
        star.relaxation.add(data_type=ri_type,
                            frq=frq,
                            entity_ids=entity_ids,
                            res_nums=res_num_list,
                            res_names=res_name_list,
                            atom_names=atom_name_list,
                            atom_types=element_list,
                            isotope=isotope_list,
                            entity_ids_2=entity_ids,
                            res_nums_2=res_num_list,
                            res_names_2=res_name_list,
                            atom_names_2=attached_atom_name_list,
                            atom_types_2=attached_element_list,
                            isotope_2=attached_isotope_list,
                            data=ri_data_list[i],
                            errors=ri_data_err_list[i],
                            temp_calibration=temp_calib,
                            temp_control=temp_control,
                            peak_intensity_type=peak_intensity_type)

        # The experimental label.
        if ri_type == 'NOE':
            exp_name = 'steady-state NOE'
        else:
            exp_name = ri_type
        exp_label.append("%s MHz %s" % (frq, exp_name))

        # Spectrometer info.
        frq_num = 1
        for frq in loop_frequencies():
            if frq == cdp.spectrometer_frq[ri_id]:
                break
            frq_num += 1
        spectro_ids.append(frq_num)
        spectro_labels.append("$spectrometer_%s" % spectro_ids[-1])

    # Add the spectrometer info.
    num = 1
    for frq in loop_frequencies():
        star.nmr_spectrometer.add(name="$spectrometer_%s" % num,
                                  manufacturer=None,
                                  model=None,
                                  frq=int(frq / 1e6))
        num += 1

    # Add the experiment saveframe.
    star.experiment.add(name=exp_label,
                        spectrometer_ids=spectro_ids,
                        spectrometer_labels=spectro_labels)
Exemplo n.º 4
0
def create_script(file, model_type, algor):
    """Create the Dasha script file.

    @param file:        The opened file descriptor.
    @type file:         file object
    @param model_type:  The model-free model type.
    @type model_type:   str
    @param algor:       The optimisation algorithm to use.  This can be the Levenberg-Marquardt algorithm 'LM' or the Newton-Raphson algorithm 'NR'.
    @type algor:        str
    """

    # Delete all data.
    file.write("# Delete all data.\n")
    file.write("del 1 10000\n")

    # Nucleus type.
    file.write("\n# Nucleus type.\n")
    nucleus = None
    for spin in spin_loop():
        # Skip protons.
        if spin.isotope == '1H':
            continue

        # Can only handle one spin type.
        if nucleus and spin.isotope != nucleus:
            raise RelaxError(
                "The nuclei '%s' and '%s' do not match, relax can only handle one nucleus type in Dasha."
                % (nucleus, spin.isotope))

        # Set the nucleus.
        if not nucleus:
            nucleus = spin.isotope

    # Convert the name and write it.
    if nucleus == '15N':
        nucleus = 'N15'
    elif nucleus == '13C':
        nucleus = 'C13'
    else:
        raise RelaxError("Cannot handle the nucleus type '%s' within Dasha." %
                         nucleus)
    file.write("set nucl %s\n" % nucleus)

    # Number of frequencies.
    file.write("\n# Number of frequencies.\n")
    file.write("set n_freq %s\n" % cdp.spectrometer_frq_count)

    # Frequency values.
    file.write("\n# Frequency values.\n")
    count = 1
    for frq in loop_frequencies():
        file.write("set H1_freq %s %s\n" % (frq / 1e6, count))
        count += 1

    # Set the diffusion tensor.
    file.write("\n# Set the diffusion tensor.\n")
    if model_type != 'local_tm':
        # Sphere.
        if cdp.diff_tensor.type == 'sphere':
            file.write("set tr %s\n" % (cdp.diff_tensor.tm / 1e-9))

        # Spheroid.
        elif cdp.diff_tensor.type == 'spheroid':
            file.write('set tr %s\n' % (cdp.diff_tensor.tm / 1e-9))

        # Ellipsoid.
        elif cdp.diff_tensor.type == 'ellipsoid':
            # Get the eigenvales.
            Dx, Dy, Dz = diffusion_tensor.return_eigenvalues()

            # Geometric parameters.
            file.write("set tr %s\n" % (cdp.diff_tensor.tm / 1e-9))
            file.write("set D1/D3 %s\n" % (Dx / Dz))
            file.write("set D2/D3 %s\n" % (Dy / Dz))

            # Orientational parameters.
            file.write("set alfa %s\n" % (cdp.diff_tensor.alpha /
                                          (2.0 * pi) * 360.0))
            file.write("set betta %s\n" % (cdp.diff_tensor.beta /
                                           (2.0 * pi) * 360.0))
            file.write("set gamma %s\n" % (cdp.diff_tensor.gamma /
                                           (2.0 * pi) * 360.0))

    # Reading the relaxation data.
    file.write("\n# Reading the relaxation data.\n")
    file.write("echo Reading the relaxation data.\n")
    noe_index = 1
    r1_index = 1
    r2_index = 1
    for ri_id in cdp.ri_ids:
        # NOE.
        if cdp.ri_type[ri_id] == 'NOE':
            # Data set number.
            number = noe_index

            # Data type.
            data_type = 'noe'

            # Increment the data set index.
            noe_index = noe_index + 1

        # R1.
        elif cdp.ri_type[ri_id] == 'R1':
            # Data set number.
            number = r1_index

            # Data type.
            data_type = '1/T1'

            # Increment the data set index.
            r1_index = r1_index + 1

        # R2.
        elif cdp.ri_type[ri_id] == 'R2':
            # Data set number.
            number = r2_index

            # Data type.
            data_type = '1/T2'

            # Increment the data set index.
            r2_index = r2_index + 1

        # Set the data type.
        if number == 1:
            file.write("\nread < %s\n" % data_type)
        else:
            file.write("\nread < %s %s\n" % (data_type, number))

        # The relaxation data.
        for residue in residue_loop():
            # Alias the spin.
            spin = residue.spin[0]

            # Skip deselected spins.
            if not spin.select:
                continue

            # Skip and deselect spins for which relaxation data is missing.
            if len(spin.ri_data) != len(
                    cdp.ri_ids) or spin.ri_data[ri_id] == None:
                spin.select = False
                continue

            # Data and errors.
            file.write(
                "%s %s %s\n" %
                (residue.num, spin.ri_data[ri_id], spin.ri_data_err[ri_id]))

        # Terminate the reading.
        file.write("exit\n")

    # Individual residue optimisation.
    if model_type == 'mf':
        # Loop over the residues.
        for residue in residue_loop():
            # Alias the spin.
            spin = residue.spin[0]

            # Skip deselected spins.
            if not spin.select:
                continue

            # Get the interatomic data containers.
            interatoms = return_interatom_list(spin_hash=spin._hash)
            if len(interatoms) == 0:
                raise RelaxNoInteratomError
            elif len(interatoms) > 1:
                raise RelaxError(
                    "Only one interatomic data container, hence dipole-dipole interaction, is supported per spin."
                )

            # Comment.
            file.write("\n\n\n# Residue %s\n\n" % residue.num)

            # Echo.
            file.write("echo Optimisation of residue %s\n" % residue.num)

            # Select the spin.
            file.write("\n# Select the residue.\n")
            file.write("set cres %s\n" % residue.num)

            # The angle alpha of the XH vector in the spheroid diffusion frame.
            if cdp.diff_tensor.type == 'spheroid':
                file.write("set teta %s\n" % spin.alpha)

            # The angles theta and phi of the XH vector in the ellipsoid diffusion frame.
            elif cdp.diff_tensor.type == 'ellipsoid':
                file.write(
                    "\n# Setting the spherical angles of the XH vector in the ellipsoid diffusion frame.\n"
                )
                file.write("set teta %s\n" % spin.theta)
                file.write("set fi %s\n" % spin.phi)

            # The 'jmode'.
            if 'ts' in spin.params:
                jmode = 3
            elif 'te' in spin.params:
                jmode = 2
            elif 's2' in spin.params:
                jmode = 1

            # Chemical exchange.
            if 'rex' in spin.params:
                exch = True
            else:
                exch = False

            # Anisotropic diffusion.
            if cdp.diff_tensor.type == 'sphere':
                anis = False
            else:
                anis = True

            # Axial symmetry.
            if cdp.diff_tensor.type == 'spheroid':
                sym = True
            else:
                sym = False

            # Set the jmode.
            file.write("\n# Set the jmode.\n")
            file.write("set def jmode %s" % jmode)
            if exch:
                file.write(" exch")
            if anis:
                file.write(" anis")
            if sym:
                file.write(" sym")
            file.write("\n")

            # Parameter default values.
            file.write("\n# Parameter default values.\n")
            file.write("reset jmode %s\n" % residue.num)

            # Bond length.
            file.write("\n# Bond length.\n")
            file.write("set r_hx %s\n" % (interatoms[0].r / 1e-10))

            # CSA value.
            file.write("\n# CSA value.\n")
            file.write("set csa %s\n" % (spin.csa / 1e-6))

            # Fix the tf parameter if it isn't in the model.
            if not 'tf' in spin.params and jmode == 3:
                file.write("\n# Fix the tf parameter.\n")
                file.write("fix tf 0\n")

        # Optimisation of all residues.
        file.write("\n\n\n# Optimisation of all residues.\n")
        if algor == 'LM':
            file.write("lmin %s %s" %
                       (first_residue_num(), last_residue_num()))
        elif algor == 'NR':
            file.write("min %s %s" % (first_residue_num(), last_residue_num()))

        # Show the results.
        file.write("\n# Show the results.\n")
        file.write("echo\n")
        file.write("show all\n")

        # Write the results.
        file.write("\n# Write the results.\n")
        file.write("write s2.out S\n")
        file.write("write s2f.out Sf\n")
        file.write("write s2s.out Ss\n")
        file.write("write te.out te\n")
        file.write("write tf.out tf\n")
        file.write("write ts.out ts\n")
        file.write("write rex.out rex\n")
        file.write("write chi2.out F\n")

    else:
        raise RelaxError(
            "Optimisation of the parameter set '%s' currently not supported." %
            model_type)