Example #1
0
    def _sf_csa_read(self, star):
        """Place the CSA data from the saveframe records into the spin container.

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

        # Get the entities.
        for data in star.chem_shift_anisotropy.loop():
            # The number of spins.
            N = bmrb.num_spins(data)

            # No data in the saveframe.
            if N == 0:
                continue

            # The molecule names.
            mol_names = bmrb.molecule_names(data, N)

            # Loop over the spins.
            for i in range(len(data['data_ids'])):
                # Generate a spin ID.
                spin_id = mol_res_spin.generate_spin_id_unique(mol_name=mol_names[i], res_num=data['res_nums'][i], spin_name=data['atom_names'][i])

                # Obtain the spin.
                spin = mol_res_spin.return_spin(spin_id)

                # The CSA value (converted from ppm).
                setattr(spin, 'csa', data['csa'][i] * 1e-6)
Example #2
0
def sf_csa_read(star):
    """Place the CSA data from the saveframe records into the spin container.

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

    # Get the entities.
    for data in star.chem_shift_anisotropy.loop():
        # The number of spins.
        N = bmrb.num_spins(data)

        # No data in the saveframe.
        if N == 0:
            continue

        # The molecule names.
        mol_names = bmrb.molecule_names(data, N)

        # Loop over the spins.
        for i in range(len(data['data_ids'])):
            # Generate a spin ID.
            spin_id = mol_res_spin.generate_spin_id_unique(
                mol_name=mol_names[i],
                res_num=data['res_nums'][i],
                spin_name=data['atom_names'][i])

            # Obtain the spin.
            spin = mol_res_spin.return_spin(spin_id=spin_id)

            # The CSA value (converted from ppm).
            setattr(spin, 'csa', data['csa'][i] * 1e-6)
Example #3
0
def read_spins(file=None, dir=None, dim=1, spin_id_col=None, mol_name_col=None, res_num_col=None, res_name_col=None, spin_num_col=None, spin_name_col=None, sep=None, spin_id=None, verbose=True):
    """Read the peak intensity data.

    @keyword file:          The name of the file containing the peak intensities.
    @type file:             str
    @keyword dir:           The directory where the file is located.
    @type dir:              str
    @keyword dim:           The dimension of the peak list to associate the data with.
    @type dim:              int
    @keyword spin_id_col:   The column containing the spin ID strings (used by the generic intensity file format).  If supplied, the mol_name_col, res_name_col, res_num_col, spin_name_col, and spin_num_col arguments must be none.
    @type spin_id_col:      int or None
    @keyword mol_name_col:  The column containing the molecule name information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type mol_name_col:     int or None
    @keyword res_name_col:  The column containing the residue name information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type res_name_col:     int or None
    @keyword res_num_col:   The column containing the residue number information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type res_num_col:      int or None
    @keyword spin_name_col: The column containing the spin name information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type spin_name_col:    int or None
    @keyword spin_num_col:  The column containing the spin number information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type spin_num_col:     int or None
    @keyword sep:           The column separator which, if None, defaults to whitespace.
    @type sep:              str or None
    @keyword spin_id:       The spin ID string used to restrict data loading to a subset of all spins.  If 'auto' is provided for a NMRPipe seriesTab formatted file, the ID's are auto generated in form of Z_Ai.
    @type spin_id:          None or str
    @keyword verbose:       A flag which if True will cause all relaxation data loaded to be printed out.
    @type verbose:          bool
    """

    # Data checks.
    check_pipe()

    # Check the file name.
    if file == None:
        raise RelaxError("The file name must be supplied.")

    # Read the peak list data.
    peak_list = read_peak_list(file=file, dir=dir, spin_id_col=spin_id_col, mol_name_col=mol_name_col, res_num_col=res_num_col, res_name_col=res_name_col, spin_num_col=spin_num_col, spin_name_col=spin_name_col, sep=sep, spin_id=spin_id)

    # Loop over the peak_list.
    created_spins = []
    for assign in peak_list:
        mol_name = assign.mol_names[dim-1]
        res_num = assign.res_nums[dim-1]
        res_name = assign.res_names[dim-1]
        spin_num = assign.spin_nums[dim-1]
        spin_name = assign.spin_names[dim-1]

        # Generate the spin_id.
        spin_id = generate_spin_id_unique(mol_name=mol_name, res_num=res_num, res_name=res_name, spin_name=spin_name)

        # Check if the spin already exist.
        if return_spin(spin_id=spin_id) == None:
            # Create the spin if not exist.
            create_spin(spin_num=spin_num, spin_name=spin_name, res_num=res_num, res_name=res_name, mol_name=mol_name)

    # Test that data exists.
    check_mol_res_spin_data()
Example #4
0
def generate_sequence(spin_line, col, verbosity=1):
    """Generate the sequence.

    @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
    """

    # The spin info (for relax 1.2).
    if 'num' in col:
        mol_name = None
        res_num = int(spin_line[col['num']])
        res_name = spin_line[col['name']]
        spin_num = None
        spin_name = None
        if col['nucleus'] < len(spin_line) and search(
                'N', spin_line[col['nucleus']]):
            spin_name = 'N'
        if col['nucleus'] < len(spin_line) and search(
                'C', spin_line[col['nucleus']]):
            spin_name = 'C'

    # The spin info.
    else:
        mol_name = spin_line[col['mol_name']]
        res_num = int(spin_line[col['res_num']])
        res_name = spin_line[col['res_name']]
        spin_num = int(spin_line[col['spin_num']])
        spin_name = spin_line[col['spin_name']]

    # Generate the sequence.
    pipe_control.sequence.generate(mol_name,
                                   res_num,
                                   res_name,
                                   spin_num,
                                   spin_name,
                                   verbose=False)

    # Get the spin identification string.
    spin_id = generate_spin_id_unique(mol_name=mol_name,
                                      res_num=res_num,
                                      res_name=res_name,
                                      spin_num=spin_num,
                                      spin_name=spin_name)

    # Set the selection status.
    select = bool(int(spin_line[col['select']]))
    if select:
        pipe_control.selection.sel_spin(spin_id)
    else:
        pipe_control.selection.desel_spin(spin_id)
Example #5
0
def generate_sequence(spin_line, col, verbosity=1):
    """Generate the sequence.

    @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
    """

    # The spin info (for relax 1.2).
    if "num" in col:
        mol_name = None
        res_num = int(spin_line[col["num"]])
        res_name = spin_line[col["name"]]
        spin_num = None
        spin_name = None
        if col["nucleus"] < len(spin_line) and search("N", spin_line[col["nucleus"]]):
            spin_name = "N"
        if col["nucleus"] < len(spin_line) and search("C", spin_line[col["nucleus"]]):
            spin_name = "C"

    # The spin info.
    else:
        mol_name = spin_line[col["mol_name"]]
        res_num = int(spin_line[col["res_num"]])
        res_name = spin_line[col["res_name"]]
        spin_num = int(spin_line[col["spin_num"]])
        spin_name = spin_line[col["spin_name"]]

    # Generate the sequence.
    pipe_control.sequence.generate(mol_name, res_num, res_name, spin_num, spin_name, verbose=False)

    # Get the spin identification string.
    spin_id = generate_spin_id_unique(
        mol_name=mol_name, res_num=res_num, res_name=res_name, spin_num=spin_num, spin_name=spin_name
    )

    # Set the selection status.
    select = bool(int(spin_line[col["select"]]))
    if select:
        pipe_control.selection.sel_spin(spin_id)
    else:
        pipe_control.selection.desel_spin(spin_id)
Example #6
0
def desel_read(file=None, dir=None, file_data=None, spin_id_col=None, mol_name_col=None, res_num_col=None, res_name_col=None, spin_num_col=None, spin_name_col=None, sep=None, spin_id=None, boolean='AND', change_all=False):
    """Deselect the spins contained in the given file.

    @keyword file:                  The name of the file to open.
    @type file:                     str
    @keyword dir:                   The directory containing the file (defaults to the current
                                    directory if None).
    @type dir:                      str or None
    @keyword file_data:             An alternative opening a file, if the data already exists in the
                                    correct format.  The format is a list of lists where the first
                                    index corresponds to the row and the second the column.
    @type file_data:                list of lists
    @keyword spin_id_col:           The column containing the spin ID strings.  If supplied, the
                                    mol_name_col, res_name_col, res_num_col, spin_name_col, and
                                    spin_num_col arguments must be none.
    @type spin_id_col:              int or None
    @keyword mol_name_col:          The column containing the molecule name information.  If
                                    supplied, spin_id_col must be None.
    @type mol_name_col:             int or None
    @keyword res_name_col:          The column containing the residue name information.  If
                                    supplied, spin_id_col must be None.
    @type res_name_col:             int or None
    @keyword res_num_col:           The column containing the residue number information.  If
                                    supplied, spin_id_col must be None.
    @type res_num_col:              int or None
    @keyword spin_name_col:         The column containing the spin name information.  If supplied,
                                    spin_id_col must be None.
    @type spin_name_col:            int or None
    @keyword spin_num_col:          The column containing the spin number information.  If supplied,
                                    spin_id_col must be None.
    @type spin_num_col:             int or None
    @keyword sep:                   The column separator which, if None, defaults to whitespace.
    @type sep:                      str or None
    @keyword spin_id:               The spin ID string used to restrict data loading to a subset of
                                    all spins.
    @type spin_id:                  None or str
    @param boolean:                 The boolean operator used to deselect 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 selected.  Only the boolean operator 'AND' 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 select all spins if the change_all flag is set.
    if change_all:
        for spin in spin_loop():
            spin.select = True

    # Then deselect the spins in the file.
    ids = []
    for mol_name, res_num, res_name, spin_num, spin_name in read_spin_data(file=file, dir=dir, file_data=file_data, spin_id_col=spin_id_col, mol_name_col=mol_name_col, res_num_col=res_num_col, res_name_col=res_name_col, spin_num_col=spin_num_col, spin_name_col=spin_name_col, sep=sep, spin_id=spin_id):
        # Get the corresponding spin container.
        id = generate_spin_id_unique(mol_name=mol_name, res_num=res_num, res_name=res_name, spin_num=spin_num, spin_name=spin_name)
        spin = return_spin(spin_id=id)

        # No spin.
        if spin == None:
            warn(RelaxNoSpinWarning(id))
            continue

        # Deselect the spin.
        if change_all:
            spin.select = False

        # Boolean selections.
        else:
            spin.select = boolean_deselect(current=spin.select, boolean=boolean)

        # Store the spin ID for printouts.
        if not spin.select:
            ids.append(id)

    # Printout.
    if not len(ids):
        print("No spins deselected.")
    else:
        print("The following spins were deselected:")
        for id in ids:
            print(id)
Example #7
0
def read_1_2_results(file_data, verbosity=1):
    """Read the relax 1.2 model-free results file.

    @param file_data:   The processed results file data.
    @type file_data:    list of lists of str
    @keyword verbosity: A variable specifying the amount of information to print.  The higher
                        the value, the greater the verbosity.
    @type verbosity:    int
    """

    # Extract and remove the header.
    header = file_data[0]
    file_data = file_data[1:]

    # Sort the column numbers.
    col = read_1_2_col_numbers(header)

    # Test the file.
    if len(col) < 2:
        raise RelaxInvalidDataError

    # Initialise some data structures and flags.
    sim_num = None
    sims = []
    all_select_sim = []
    diff_data_set = False
    diff_error_set = False
    diff_sim_set = None
    model_type = None
    pdb = False
    pdb_model = None
    pdb_heteronuc = None
    pdb_proton = None
    ri_labels = None

    # Generate the sequence.
    if verbosity:
        print("\nGenerating the sequence.")
    for file_line in file_data:
        # The data set.
        data_set = file_line[col['data_set']]

        # Stop creating the sequence once the data_set is no longer 'value'.
        if data_set != 'value':
            break

        # Sequence.
        generate_sequence(file_line, col, verbosity)

    # Count the number of simulations.
    for file_line in file_data:
        # The data set.
        data_set = file_line[col['data_set']]

        # Simulation number.
        if data_set != 'value' and data_set != 'error':
            # Extract the number from the data_set string.
            sim_num = data_set.split('_')
            try:
                sim_num = int(sim_num[1])
            except:
                raise RelaxError("The simulation number '%s' is invalid." %
                                 sim_num)
    if sim_num != None:
        cdp.sim_number = sim_num + 1

    # Loop over the lines of the file data.
    for file_line in file_data:
        # The data set.
        data_set = file_line[col['data_set']]

        # The spin info (for relax 1.2).
        if 'num' in col:
            mol_name = None
            res_num = int(file_line[col['num']])
            res_name = file_line[col['name']]
            spin_num = None
            spin_name = None
            if col['nucleus'] < len(file_line) and search(
                    'N', file_line[col['nucleus']]):
                spin_name = 'N'
            if col['nucleus'] < len(file_line) and search(
                    'C', file_line[col['nucleus']]):
                spin_name = 'C'

        # The spin info.
        else:
            mol_name = file_line[col['mol_name']]
            res_num = int(file_line[col['res_num']])
            res_name = file_line[col['res_name']]
            spin_num = int(file_line[col['spin_num']])
            spin_name = file_line[col['spin_name']]

        # Create the spin ID.
        spin_id = generate_spin_id_unique(mol_name=mol_name,
                                          res_num=res_num,
                                          res_name=res_name,
                                          spin_num=spin_num,
                                          spin_name=spin_name)

        # Get the spin container.
        spin = return_spin(spin_id=spin_id)

        # Create a new spin container for the proton, then set up a dipole interaction between the two spins.
        if data_set == 'value' and spin_name:
            h_spin = create_spin(mol_name=mol_name,
                                 res_num=res_num,
                                 res_name=res_name,
                                 spin_name='H')[0]
            h_spin.select = False
            h_spin.element = 'H'
            h_spin.isotope = '1H'
            spin_id2 = generate_spin_id_unique(mol_name=mol_name,
                                               res_num=res_num,
                                               res_name=res_name,
                                               spin_name='H')
            define_dipole_pair(spin_id1=spin_id,
                               spin_id2=spin_id2,
                               spin1=spin,
                               spin2=h_spin,
                               verbose=False)

        # Backwards compatibility for the reading of the results file from versions 1.2.0 to 1.2.9.
        if len(file_line) == 4:
            continue

        # Set the nuclear isotope types and spin names (absent from the 1.2 results file).
        if data_set == 'value':
            if file_line[col['nucleus']] != 'None':
                if search('N', file_line[col['nucleus']]):
                    spin.isotope = '15N'
                    if spin.name == None:
                        spin.name = 'N'
                elif search('C', file_line[col['nucleus']]):
                    spin.isotope = '13C'
                    if spin.name == None:
                        spin.name = 'C'

        # Simulation number.
        if data_set != 'value' and data_set != 'error':
            # Extract the number from the data_set string.
            sim_num = data_set.split('_')
            try:
                sim_num = int(sim_num[1])
            except:
                raise RelaxError("The simulation number '%s' is invalid." %
                                 sim_num)

            # A new simulation number.
            if sim_num not in sims:
                # Update the sims array and append an empty array to the selected sims array.
                sims.append(sim_num)
                all_select_sim.append([])

            # Selected simulations.
            all_select_sim[-1].append(bool(file_line[col['select']]))

            # Initial printout for the simulation.
            if verbosity:
                if diff_sim_set == None:
                    print("\nLoading simulations.")
                if sim_num != diff_sim_set:
                    print(data_set)

        # Diffusion tensor data.
        if data_set == 'value' and not diff_data_set:
            read_1_2_set_diff_tensor(file_line,
                                     col,
                                     data_set,
                                     verbosity,
                                     sim_num=sim_num)
            diff_data_set = True

        # Diffusion tensor errors.
        elif data_set == 'error' and not diff_error_set:
            read_1_2_set_diff_tensor(file_line,
                                     col,
                                     data_set,
                                     verbosity,
                                     sim_num=sim_num)
            diff_error_set = True

        # Diffusion tensor simulation data.
        elif data_set != 'value' and data_set != 'error' and sim_num != diff_sim_set:
            # Set up the diffusion tensor.
            if not hasattr(cdp.diff_tensor,
                           '_sim_num') or cdp.diff_tensor._sim_num == None:
                cdp.diff_tensor.set_sim_num(cdp.sim_number)

            read_1_2_set_diff_tensor(file_line,
                                     col,
                                     data_set,
                                     verbosity,
                                     sim_num=sim_num)
            diff_sim_set = sim_num

        # Model type.
        if model_type == None:
            fix_params(file_line, col, verbosity)

        # PDB.
        if not pdb:
            if load_structure(file_line, col, verbosity):
                pdb = True

        # XH vector, heteronucleus, and proton.
        if data_set == 'value':
            set_xh_vect(file_line,
                        col,
                        spin,
                        spin_id1=spin_id,
                        spin_id2=spin_id2,
                        spin_hash1=spin._hash,
                        spin_hash2=h_spin._hash,
                        verbosity=verbosity)

        # Relaxation data.
        load_relax_data(file_line, col, data_set, spin, verbosity)

        # Model-free data.
        load_model_free_data(file_line, col, data_set, spin, spin_id,
                             verbosity)

    # Set up the simulations.
    if len(sims):
        # Convert the selected simulation array of arrays into a Numeric matrix, transpose it, then convert back to a Python list.
        all_select_sim = transpose(array(all_select_sim))
        all_select_sim = all_select_sim.tolist()

        # Set up the Monte Carlo simulations.
        pipe_control.error_analysis.monte_carlo_setup(
            number=len(sims), all_select_sim=all_select_sim)

        # Turn the simulation state to off!
        cdp.sim_state = False
Example #8
0
def vectors(spin_id1=None, spin_id2=None, model=None, verbosity=1, ave=True, unit=True):
    """Extract the bond vectors from the loaded structures and store them in the spin container.

    @keyword spin_id1:      The spin identifier string of the first spin of the pair.
    @type spin_id1:         str
    @keyword spin_id2:      The spin identifier string of the second spin of the pair.
    @type spin_id2:         str
    @keyword model:         The model to extract the vector from.  If None, all vectors will be extracted.
    @type model:            str
    @keyword verbosity:     The higher the value, the more information is printed to screen.
    @type verbosity:        int
    @keyword ave:           A flag which if True will cause the average of all vectors to be extracted.
    @type ave:              bool
    @keyword unit:          A flag which if True will cause the function to calculate the unit vectors.
    @type unit:             bool
    """

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

    # Test if the PDB file has been loaded.
    if not hasattr(cdp, 'structure'):
        raise RelaxNoPdbError

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

    # Print out.
    if verbosity:
        # Number of models.
        num_models = cdp.structure.num_models()

        # Multiple models loaded.
        if num_models > 1:
            if model:
                print("Extracting vectors for model '%s'." % model)
            else:
                print("Extracting vectors for all %s models." % num_models)
                if ave:
                    print("Averaging all vectors.")

        # Single model loaded.
        else:
            print("Extracting vectors from the single model.")

        # Unit vectors.
        if unit:
            print("Calculating the unit vectors.")

    # Loop over the spins.
    no_vectors = True
    for spin, mol_name, res_num, res_name in spin_loop(selection=spin_id, full_info=True):
        # Skip deselected spins.
        if not spin.select:
            continue

        # The spin identification string.  The residue name and spin num is not included to allow molecules with point mutations to be used as different models.
        id = generate_spin_id_unique(res_num=res_num, res_name=None, spin_name=spin.name, spin_num=spin.num)

        # Test that the spin number or name are set (one or both are essential for the identification of the atom).
        if spin.num == None and spin.name == None:
            warn(RelaxWarning("Either the spin number or name must be set for the spin " + repr(id) + " to identify the corresponding atom in the molecule."))
            continue

        # The bond vector already exists.
        if hasattr(spin, 'vector'):
            obj = getattr(spin, 'vector')
            if obj != None:
                warn(RelaxWarning("The bond vector for the spin " + repr(id) + " already exists."))
                continue

        # Get the bond info.
        bond_vectors, attached_name, warnings = cdp.structure.bond_vectors(attached_atom=attached, model_num=model, res_num=res_num, spin_name=spin.name, spin_num=spin.num, return_name=True, return_warnings=True)
        id2 = generate_spin_id_unique(res_num=res_num, res_name=None, spin_name=spin.name)

        # No attached atom.
        if not bond_vectors:
            # Warning messages.
            if warnings:
                warn(RelaxWarning(warnings + " (atom ID " + repr(id) + ")."))

            # Skip the spin.
            continue

        # Set the attached atom name.
        if not hasattr(spin, 'attached_atom'):
            spin.attached_atom = attached_name
        elif spin.attached_atom != attached_name:
            raise RelaxError("The " + repr(spin.attached_atom) + " atom already attached to the spin does not match the attached atom " + repr(attached_name) + ".")

        # Initialise the average vector.
        if ave:
            ave_vector = zeros(3, float64)

        # Loop over the individual vectors.
        for i in range(len(bond_vectors)):
            # Unit vector.
            if unit:
                # Normalisation factor.
                norm_factor = norm(bond_vectors[i])

                # Test for zero length.
                if norm_factor == 0.0:
                    warn(RelaxZeroVectorWarning(spin_id1=id, spin_id2=id2))

                # Calculate the normalised vector.
                else:
                    bond_vectors[i] = bond_vectors[i] / norm_factor

            # Sum the vectors.
            if ave:
                ave_vector = ave_vector + bond_vectors[i]

        # Average.
        if ave:
            vector = ave_vector / float(len(bond_vectors))
        else:
            vector = bond_vectors

        # Convert to a single vector if needed.
        if len(vector) == 1:
            vector = vector[0]

        # Set the vector.
        setattr(spin, 'vector', vector)

        # We have a vector!
        no_vectors = False

        # Print out of modified spins.
        if verbosity:
            # The number of vectors.
            num = len(bond_vectors)
            plural = 's'
            if num == 1:
                plural = ''

            if spin.name:
                print("Extracted %s %s-%s vector%s for the spin '%s'." % (num, spin.name, attached_name, plural, id))
            else:
                print("Extracted %s %s-%s vector%s for the spin '%s'." % (num, spin.num, attached_name, plural, id))

    # Right, catch the problem of missing vectors to prevent massive user confusion!
    if no_vectors:
        raise RelaxError("No vectors could be extracted.")
Example #9
0
def read(file=None, dir=None, spin_id_col=None, mol_name_col=None, res_num_col=None, res_name_col=None, spin_num_col=None, spin_name_col=None, sep=None, spin_id=None, verbose=True):
    """Read the peak intensity data.

    @keyword file:          The name of the file containing the peak intensities.
    @type file:             str
    @keyword dir:           The directory where the file is located.
    @type dir:              str
    @keyword spin_id_col:   The column containing the spin ID strings (used by the generic intensity file format).  If supplied, the mol_name_col, res_name_col, res_num_col, spin_name_col, and spin_num_col arguments must be none.
    @type spin_id_col:      int or None
    @keyword mol_name_col:  The column containing the molecule name information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type mol_name_col:     int or None
    @keyword res_name_col:  The column containing the residue name information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type res_name_col:     int or None
    @keyword res_num_col:   The column containing the residue number information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type res_num_col:      int or None
    @keyword spin_name_col: The column containing the spin name information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type spin_name_col:    int or None
    @keyword spin_num_col:  The column containing the spin number information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type spin_num_col:     int or None
    @keyword sep:           The column separator which, if None, defaults to whitespace.
    @type sep:              str or None
    @keyword spin_id:       The spin ID string used to restrict data loading to a subset of all spins.  If 'auto' is provided for a NMRPipe seriesTab formatted file, the ID's are auto generated in form of Z_Ai.
    @type spin_id:          None or str
    @keyword verbose:       A flag which if True will cause all chemical shift data loaded to be printed out.
    @type verbose:          bool
    """

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

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

    # Check the file name.
    if file == None:
        raise RelaxError("The file name must be supplied.")

    # Read the peak list data.
    peak_list = read_peak_list(file=file, dir=dir, spin_id_col=spin_id_col, mol_name_col=mol_name_col, res_num_col=res_num_col, res_name_col=res_name_col, spin_num_col=spin_num_col, spin_name_col=spin_name_col, sep=sep, spin_id=spin_id)

    # Loop over the assignments.
    data = []
    data_flag = False
    for assign in peak_list:
        # Loop over the dimensions of the peak list.
        for i in range(peak_list.dimensionality):
            # Generate the spin_id.
            spin_id = generate_spin_id_unique(res_num=assign.res_nums[i], spin_name=assign.spin_names[i])

            # Get the spin container.
            spin = return_spin(spin_id)
            if not spin:
                warn(RelaxNoSpinWarning(spin_id))
                continue

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

            # Store the shift.
            spin.chemical_shift = assign.shifts[i]

            # Switch the flag.
            data_flag = True

            # Append the data for printing out.
            data.append([spin_id, repr(spin.chemical_shift)])

    # No data.
    if not data_flag:
        raise RelaxError("No chemical shifts could be loaded from the peak list")

    # Print out.
    if verbose:
        print("\nThe following chemical shifts have been loaded into the relax data store:\n")
        write_data(out=sys.stdout, headings=["Spin_ID", "Chemical shift"], data=data)
Example #10
0
def pack_data(ri_id,
              ri_type,
              frq,
              values,
              errors,
              spin_ids=None,
              mol_names=None,
              res_nums=None,
              res_names=None,
              spin_nums=None,
              spin_names=None,
              spin_id=None,
              gen_seq=False,
              verbose=True):
    """Pack the relaxation data into the data pipe and spin containers.

    The values, errors, and spin_ids arguments must be lists of equal length or None.  Each element i corresponds to a unique spin.

    @param ri_id:           The relaxation data ID string.
    @type ri_id:            str
    @param ri_type:         The relaxation data type, ie 'R1', 'R2', or 'NOE'.
    @type ri_type:          str
    @param frq:             The spectrometer proton frequency in Hz.
    @type frq:              float
    @keyword values:        The relaxation data for each spin.
    @type values:           None or list of float or float array
    @keyword errors:        The relaxation data errors for each spin.
    @type errors:           None or list of float or float array
    @keyword spin_ids:      The list of spin ID strings.  If the other spin identifiers are given, i.e. mol_names, res_nums, res_names, spin_nums, and/or spin_names, then this argument is not necessary.
    @type spin_ids:         None or list of str
    @keyword mol_names:     The list of molecule names used for creating the spin IDs (if not given) or for generating the sequence data.
    @type mol_names:        None or list of str
    @keyword res_nums:      The list of residue numbers used for creating the spin IDs (if not given) or for generating the sequence data.
    @type res_nums:         None or list of str
    @keyword res_names:     The list of residue names used for creating the spin IDs (if not given) or for generating the sequence data.
    @type res_names:        None or list of str
    @keyword spin_nums:     The list of spin numbers used for creating the spin IDs (if not given) or for generating the sequence data.
    @type spin_nums:        None or list of str
    @keyword spin_names:    The list of spin names used for creating the spin IDs (if not given) or for generating the sequence data.
    @type spin_names:       None or list of str
    @keyword gen_seq:       A flag which if True will cause the molecule, residue, and spin sequence data to be generated.
    @type gen_seq:          bool
    @keyword verbose:       A flag which if True will cause all relaxation data loaded to be printed out.
    @type verbose:          bool
    """

    # The number of spins.
    N = len(values)

    # Test the data.
    if errors != None and len(errors) != N:
        raise RelaxError(
            "The length of the errors arg (%s) does not match that of the value arg (%s)."
            % (len(errors), N))
    if spin_ids and len(spin_ids) != N:
        raise RelaxError(
            "The length of the spin ID strings arg (%s) does not match that of the value arg (%s)."
            % (len(mol_names), N))
    if mol_names and len(mol_names) != N:
        raise RelaxError(
            "The length of the molecule names arg (%s) does not match that of the value arg (%s)."
            % (len(mol_names), N))
    if res_nums and len(res_nums) != N:
        raise RelaxError(
            "The length of the residue numbers arg (%s) does not match that of the value arg (%s)."
            % (len(res_nums), N))
    if res_names and len(res_names) != N:
        raise RelaxError(
            "The length of the residue names arg (%s) does not match that of the value arg (%s)."
            % (len(res_names), N))
    if spin_nums and len(spin_nums) != N:
        raise RelaxError(
            "The length of the spin numbers arg (%s) does not match that of the value arg (%s)."
            % (len(spin_nums), N))
    if spin_names and len(spin_names) != N:
        raise RelaxError(
            "The length of the spin names arg (%s) does not match that of the value arg (%s)."
            % (len(spin_names), N))

    # Generate some empty lists.
    if not mol_names:
        mol_names = [None] * N
    if not res_nums:
        res_nums = [None] * N
    if not res_names:
        res_names = [None] * N
    if not spin_nums:
        spin_nums = [None] * N
    if not spin_names:
        spin_names = [None] * N
    if errors == None:
        errors = [None] * N

    # Generate the spin IDs.
    if not spin_ids:
        spin_ids = []
        for i in range(N):
            spin_ids.append(
                generate_spin_id_unique(spin_num=spin_nums[i],
                                        spin_name=spin_names[i],
                                        res_num=res_nums[i],
                                        res_name=res_names[i],
                                        mol_name=mol_names[i]))

    # Initialise the global data for the current pipe if necessary.
    if not hasattr(cdp, 'ri_type'):
        cdp.ri_type = {}
    if not hasattr(cdp, 'ri_ids'):
        cdp.ri_ids = []

    # Set the spectrometer frequency.
    set_frequency(id=ri_id, frq=frq)

    # Update the global data.
    cdp.ri_ids.append(ri_id)
    cdp.ri_type[ri_id] = ri_type

    # The selection object.
    select_obj = None
    if spin_id:
        select_obj = Selection(spin_id)

    # Loop over the spin data.
    data = []
    for i in range(N):
        # A selection union.
        select_id = spin_ids[i]
        if spin_id != None:
            select_id = "%s&%s" % (select_id, spin_id)

        # Get the corresponding spin container.
        match_mol_names, match_res_nums, match_res_names, spins = return_spin_from_selection(
            selection=select_id, full_info=True, multi=True)

        # No spin.
        if len(spins) == 0:
            continue

        # Check that multiple spins are not present.
        if len(spins) > 1:
            # Generate the list of spin IDs.
            new_ids = []
            for j in range(len(spins)):
                new_ids.append(
                    generate_spin_id_unique(mol_name=match_mol_names[j],
                                            res_num=match_res_nums[j],
                                            res_name=match_res_names[j],
                                            spin_num=spins[j].num,
                                            spin_name=spins[j].name))

            # Raise the error.
            raise RelaxMultiSpinIDError(spin_ids[i], new_ids)

        # Check that at least one spin is present.
        if len(spins) == 0:
            raise RelaxNoSpinError(spin_ids[i])

        # Loop over the spins.
        for j in range(len(spins)):
            # No match to the selection.
            if select_obj and not select_obj.contains_spin(
                    spin_num=spins[j].num,
                    spin_name=spins[j].name,
                    res_num=res_nums[j],
                    res_name=res_names[j],
                    mol=mol_names[j]):
                continue

            # Initialise the spin data if necessary.
            if not hasattr(spins[j], 'ri_data') or spins[j].ri_data == None:
                spins[j].ri_data = {}
            if not hasattr(spins[j],
                           'ri_data_err') or spins[j].ri_data_err == None:
                spins[j].ri_data_err = {}

            # Update all data structures.
            spins[j].ri_data[ri_id] = values[i]
            spins[j].ri_data_err[ri_id] = errors[i]

            # Append the data for printing out.
            data.append([spin_ids[i], repr(values[i]), repr(errors[i])])

    # Print out.
    if verbose:
        print(
            "\nThe following %s MHz %s relaxation data with the ID '%s' has been loaded into the relax data store:\n"
            % (frq / 1e6, ri_type, ri_id))
        write_data(out=sys.stdout,
                   headings=["Spin_ID", "Value", "Error"],
                   data=data)
Example #11
0
    def _read_1_2_results(self, file_data, verbosity=1):
        """Read the relax 1.2 model-free results file.

        @param file_data:   The processed results file data.
        @type file_data:    list of lists of str
        @keyword verbosity: A variable specifying the amount of information to print.  The higher
                            the value, the greater the verbosity.
        @type verbosity:    int
        """

        # Extract and remove the header.
        header = file_data[0]
        file_data = file_data[1:]

        # Sort the column numbers.
        col = self._read_1_2_col_numbers(header)

        # Test the file.
        if len(col) < 2:
            raise RelaxInvalidDataError

        # Initialise some data structures and flags.
        sim_num = None
        sims = []
        all_select_sim = []
        diff_data_set = False
        diff_error_set = False
        diff_sim_set = None
        model_type = None
        pdb = False
        pdb_model = None
        pdb_heteronuc = None
        pdb_proton = None
        ri_labels = None

        # Generate the sequence.
        if verbosity:
            print("\nGenerating the sequence.")
        for file_line in file_data:
            # The data set.
            data_set = file_line[col['data_set']]

            # Stop creating the sequence once the data_set is no longer 'value'.
            if data_set != 'value':
                break

            # Sequence.
            self._generate_sequence(file_line, col, verbosity)

        # Count the number of simulations.
        for file_line in file_data:
            # The data set.
            data_set = file_line[col['data_set']]

            # Simulation number.
            if data_set != 'value' and data_set != 'error':
                # Extract the number from the data_set string.
                sim_num = data_set.split('_')
                try:
                    sim_num = int(sim_num[1])
                except:
                    raise RelaxError("The simulation number '%s' is invalid." % sim_num)
        if sim_num != None:
            cdp.sim_number = sim_num + 1

        # Loop over the lines of the file data.
        for file_line in file_data:
            # The data set.
            data_set = file_line[col['data_set']]

            # The spin info (for relax 1.2).
            if 'num' in col:
                mol_name = None
                res_num = int(file_line[col['num']])
                res_name = file_line[col['name']]
                spin_num = None
                spin_name = None
                if col['nucleus'] < len(file_line) and search('N', file_line[col['nucleus']]):
                    spin_name = 'N'
                if col['nucleus'] < len(file_line) and search('C', file_line[col['nucleus']]):
                    spin_name = 'C'

            # The spin info.
            else:
                mol_name = file_line[col['mol_name']]
                res_num = int(file_line[col['res_num']])
                res_name = file_line[col['res_name']]
                spin_num = int(file_line[col['spin_num']])
                spin_name = file_line[col['spin_name']]

            # Create the spin ID.
            spin_id = generate_spin_id_unique(mol_name=mol_name, res_num=res_num, res_name=res_name, spin_num=spin_num, spin_name=spin_name)

            # Get the spin container.
            spin = return_spin(spin_id)

            # Create a new spin container for the proton, then set up a dipole interaction between the two spins.
            if data_set == 'value' and spin_name:
                h_spin = create_spin(mol_name=mol_name, res_num=res_num, res_name=res_name, spin_name='H')
                h_spin.select = False
                h_spin.element = 'H'
                h_spin.isotope = '1H'
                spin_id2 = generate_spin_id_unique(mol_name=mol_name, res_num=res_num, res_name=res_name, spin_name='H')
                define(spin_id, spin_id2, verbose=False)

            # Backwards compatibility for the reading of the results file from versions 1.2.0 to 1.2.9.
            if len(file_line) == 4:
                continue

            # Set the nuclear isotope types and spin names (absent from the 1.2 results file).
            if data_set == 'value':
                if file_line[col['nucleus']] != 'None':
                    if search('N', file_line[col['nucleus']]):
                        spin.isotope = '15N'
                        if spin.name == None:
                            spin.name = 'N'
                    elif search('C', file_line[col['nucleus']]):
                        spin.isotope = '13C'
                        if spin.name == None:
                            spin.name = 'C'

            # Simulation number.
            if data_set != 'value' and data_set != 'error':
                # Extract the number from the data_set string.
                sim_num = data_set.split('_')
                try:
                    sim_num = int(sim_num[1])
                except:
                    raise RelaxError("The simulation number '%s' is invalid." % sim_num)

                # A new simulation number.
                if sim_num not in sims:
                    # Update the sims array and append an empty array to the selected sims array.
                    sims.append(sim_num)
                    all_select_sim.append([])

                # Selected simulations.
                all_select_sim[-1].append(bool(file_line[col['select']]))

                # Initial printout for the simulation.
                if verbosity:
                    if diff_sim_set == None:
                        print("\nLoading simulations.")
                    if sim_num != diff_sim_set:
                        print(data_set)

            # Diffusion tensor data.
            if data_set == 'value' and not diff_data_set:
                self._read_1_2_set_diff_tensor(file_line, col, data_set, verbosity, sim_num=sim_num)
                diff_data_set = True

            # Diffusion tensor errors.
            elif data_set == 'error' and not diff_error_set:
                self._read_1_2_set_diff_tensor(file_line, col, data_set, verbosity, sim_num=sim_num)
                diff_error_set = True

            # Diffusion tensor simulation data.
            elif data_set != 'value' and data_set != 'error' and sim_num != diff_sim_set:
                # Set up the diffusion tensor.
                if not hasattr(cdp.diff_tensor, '_sim_num') or cdp.diff_tensor._sim_num == None:
                    cdp.diff_tensor.set_sim_num(cdp.sim_number)

                self._read_1_2_set_diff_tensor(file_line, col, data_set, verbosity, sim_num=sim_num)
                diff_sim_set = sim_num

            # Model type.
            if model_type == None:
                self._fix_params(file_line, col, verbosity)

            # PDB.
            if not pdb:
                if self._load_structure(file_line, col, verbosity):
                    pdb = True

            # XH vector, heteronucleus, and proton.
            if data_set == 'value':
                self._set_xh_vect(file_line, col, spin, spin_id1=spin_id, spin_id2=spin_id2, verbosity=verbosity)

            # Relaxation data.
            self._load_relax_data(file_line, col, data_set, spin, verbosity)

            # Model-free data.
            self._load_model_free_data(file_line, col, data_set, spin, spin_id, verbosity)

        # Set up the simulations.
        if len(sims):
            # Convert the selected simulation array of arrays into a Numeric matrix, transpose it, then convert back to a Python list.
            all_select_sim = transpose(array(all_select_sim))
            all_select_sim = all_select_sim.tolist()

            # Set up the Monte Carlo simulations.
            pipe_control.monte_carlo.setup(number=len(sims), all_select_sim=all_select_sim)

            # Turn the simulation state to off!
            cdp.sim_state = False
Example #12
0
def read_spins(file=None,
               dir=None,
               dim=1,
               spin_id_col=None,
               mol_name_col=None,
               res_num_col=None,
               res_name_col=None,
               spin_num_col=None,
               spin_name_col=None,
               sep=None,
               spin_id=None,
               verbose=True):
    """Read the peak intensity data.

    @keyword file:          The name of the file containing the peak intensities.
    @type file:             str
    @keyword dir:           The directory where the file is located.
    @type dir:              str
    @keyword dim:           The dimension of the peak list to associate the data with.
    @type dim:              int
    @keyword spin_id_col:   The column containing the spin ID strings (used by the generic intensity file format).  If supplied, the mol_name_col, res_name_col, res_num_col, spin_name_col, and spin_num_col arguments must be none.
    @type spin_id_col:      int or None
    @keyword mol_name_col:  The column containing the molecule name information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type mol_name_col:     int or None
    @keyword res_name_col:  The column containing the residue name information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type res_name_col:     int or None
    @keyword res_num_col:   The column containing the residue number information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type res_num_col:      int or None
    @keyword spin_name_col: The column containing the spin name information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type spin_name_col:    int or None
    @keyword spin_num_col:  The column containing the spin number information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type spin_num_col:     int or None
    @keyword sep:           The column separator which, if None, defaults to whitespace.
    @type sep:              str or None
    @keyword spin_id:       The spin ID string used to restrict data loading to a subset of all spins.  If 'auto' is provided for a NMRPipe seriesTab formatted file, the ID's are auto generated in form of Z_Ai.
    @type spin_id:          None or str
    @keyword verbose:       A flag which if True will cause all relaxation data loaded to be printed out.
    @type verbose:          bool
    """

    # Data checks.
    check_pipe()

    # Check the file name.
    if file == None:
        raise RelaxError("The file name must be supplied.")

    # Read the peak list data.
    peak_list = read_peak_list(file=file,
                               dir=dir,
                               spin_id_col=spin_id_col,
                               mol_name_col=mol_name_col,
                               res_num_col=res_num_col,
                               res_name_col=res_name_col,
                               spin_num_col=spin_num_col,
                               spin_name_col=spin_name_col,
                               sep=sep,
                               spin_id=spin_id)

    # Loop over the peak_list.
    created_spins = []
    for assign in peak_list:
        mol_name = assign.mol_names[dim - 1]
        res_num = assign.res_nums[dim - 1]
        res_name = assign.res_names[dim - 1]
        spin_num = assign.spin_nums[dim - 1]
        spin_name = assign.spin_names[dim - 1]

        # Generate the spin_id.
        spin_id = generate_spin_id_unique(mol_name=mol_name,
                                          res_num=res_num,
                                          res_name=res_name,
                                          spin_name=spin_name)

        # Check if the spin already exist.
        if return_spin(spin_id=spin_id) == None:
            # Create the spin if not exist.
            create_spin(spin_num=spin_num,
                        spin_name=spin_name,
                        res_num=res_num,
                        res_name=res_name,
                        mol_name=mol_name)

    # Test that data exists.
    check_mol_res_spin_data()
Example #13
0
def bmrb_read(star, sample_conditions=None):
    """Read the relaxation data from the NMR-STAR dictionary object.

    @param star:                The NMR-STAR dictionary object.
    @type star:                 NMR_STAR instance
    @keyword sample_conditions: The sample condition label to read.  Only one sample condition can be read per data pipe.
    @type sample_conditions:    None or str
    """

    # Get the relaxation data.
    for data in star.relaxation.loop():
        # Store the keys.
        keys = list(data.keys())

        # Sample conditions do not match (remove the $ sign).
        if 'sample_cond_list_label' in keys and sample_conditions and data['sample_cond_list_label'].replace('$', '') != sample_conditions:
            continue

        # Create the labels.
        ri_type = data['data_type']
        frq = float(data['frq']) * 1e6

        # Round the label to the nearest factor of 10.
        frq_label = create_frq_label(float(data['frq']) * 1e6)

        # The ID string.
        ri_id = "%s_%s" % (ri_type, frq_label)

        # The number of spins.
        N = bmrb.num_spins(data)

        # No data in the saveframe.
        if N == 0:
            continue

        # The molecule names.
        mol_names = bmrb.molecule_names(data, N)

        # Generate the sequence if needed.
        bmrb.generate_sequence(N, spin_names=data['atom_names'], res_nums=data['res_nums'], res_names=data['res_names'], mol_names=mol_names, isotopes=data['isotope'], elements=data['atom_types'])

        # The attached protons.
        if 'atom_names_2' in data:
            # Generate the proton spins.
            bmrb.generate_sequence(N, spin_names=data['atom_names_2'], res_nums=data['res_nums'], res_names=data['res_names'], mol_names=mol_names, isotopes=data['isotope_2'], elements=data['atom_types_2'])

            # Define the dipolar interaction.
            for i in range(len(data['atom_names'])):
                # The spin IDs.
                spin_id1 = generate_spin_id_unique(spin_name=data['atom_names'][i], res_num=data['res_nums'][i], res_name=data['res_names'][i], mol_name=mol_names[i])
                spin_id2 = generate_spin_id_unique(spin_name=data['atom_names_2'][i], res_num=data['res_nums'][i], res_name=data['res_names'][i], mol_name=mol_names[i])

                # Check if the container exists.
                if return_interatom(spin_id1=spin_id1, spin_id2=spin_id2):
                    continue

                # Define.
                define(spin_id1=spin_id1, spin_id2=spin_id2, verbose=False)

        # The data and error.
        vals = data['data']
        errors = data['errors']
        if vals == None:
            vals = [None] * N
        if errors == None:
            errors = [None] * N

        # Data transformation.
        if vals != None and 'units' in keys:
            # Scaling.
            if data['units'] == 'ms':
                # Loop over the data.
                for i in range(N):
                    # The value.
                    if vals[i] != None:
                        vals[i] = vals[i] / 1000

                    # The error.
                    if errors[i] != None:
                        errors[i] = errors[i] / 1000

            # Invert.
            if data['units'] in ['s', 'ms']:
                # Loop over the data.
                for i in range(len(vals)):
                    # The value.
                    if vals[i] != None:
                        vals[i] = 1.0 / vals[i]

                    # The error.
                    if vals[i] != None and errors[i] != None:
                        errors[i] = errors[i] * vals[i]**2

        # Pack the data.
        pack_data(ri_id, ri_type, frq, vals, errors, mol_names=mol_names, res_nums=data['res_nums'], res_names=data['res_names'], spin_nums=None, spin_names=data['atom_names'], gen_seq=True, verbose=False)

        # Store the temperature calibration and control.
        if data['temp_calibration']:
            temp_calibration(ri_id=ri_id, method=data['temp_calibration'])
        if data['temp_control']:
            temp_control(ri_id=ri_id, method=data['temp_control'])

        # Peak intensity type.
        if data['peak_intensity_type']:
            peak_intensity_type(ri_id=ri_id, type=data['peak_intensity_type'])
Example #14
0
def pack_data(ri_id, ri_type, frq, values, errors, spin_ids=None, mol_names=None, res_nums=None, res_names=None, spin_nums=None, spin_names=None, spin_id=None, gen_seq=False, verbose=True):
    """Pack the relaxation data into the data pipe and spin containers.

    The values, errors, and spin_ids arguments must be lists of equal length or None.  Each element i corresponds to a unique spin.

    @param ri_id:           The relaxation data ID string.
    @type ri_id:            str
    @param ri_type:         The relaxation data type, ie 'R1', 'R2', or 'NOE'.
    @type ri_type:          str
    @param frq:             The spectrometer proton frequency in Hz.
    @type frq:              float
    @keyword values:        The relaxation data for each spin.
    @type values:           None or list of float or float array
    @keyword errors:        The relaxation data errors for each spin.
    @type errors:           None or list of float or float array
    @keyword spin_ids:      The list of spin ID strings.  If the other spin identifiers are given, i.e. mol_names, res_nums, res_names, spin_nums, and/or spin_names, then this argument is not necessary.
    @type spin_ids:         None or list of str
    @keyword mol_names:     The list of molecule names used for creating the spin IDs (if not given) or for generating the sequence data.
    @type mol_names:        None or list of str
    @keyword res_nums:      The list of residue numbers used for creating the spin IDs (if not given) or for generating the sequence data.
    @type res_nums:         None or list of str
    @keyword res_names:     The list of residue names used for creating the spin IDs (if not given) or for generating the sequence data.
    @type res_names:        None or list of str
    @keyword spin_nums:     The list of spin numbers used for creating the spin IDs (if not given) or for generating the sequence data.
    @type spin_nums:        None or list of str
    @keyword spin_names:    The list of spin names used for creating the spin IDs (if not given) or for generating the sequence data.
    @type spin_names:       None or list of str
    @keyword gen_seq:       A flag which if True will cause the molecule, residue, and spin sequence data to be generated.
    @type gen_seq:          bool
    @keyword verbose:       A flag which if True will cause all relaxation data loaded to be printed out.
    @type verbose:          bool
    """

    # The number of spins.
    N = len(values)

    # Test the data.
    if errors != None and len(errors) != N:
        raise RelaxError("The length of the errors arg (%s) does not match that of the value arg (%s)." % (len(errors), N))
    if spin_ids and len(spin_ids) != N:
        raise RelaxError("The length of the spin ID strings arg (%s) does not match that of the value arg (%s)." % (len(mol_names), N))
    if mol_names and len(mol_names) != N:
        raise RelaxError("The length of the molecule names arg (%s) does not match that of the value arg (%s)." % (len(mol_names), N))
    if res_nums and len(res_nums) != N:
        raise RelaxError("The length of the residue numbers arg (%s) does not match that of the value arg (%s)." % (len(res_nums), N))
    if res_names and len(res_names) != N:
        raise RelaxError("The length of the residue names arg (%s) does not match that of the value arg (%s)." % (len(res_names), N))
    if spin_nums and len(spin_nums) != N:
        raise RelaxError("The length of the spin numbers arg (%s) does not match that of the value arg (%s)." % (len(spin_nums), N))
    if spin_names and len(spin_names) != N:
        raise RelaxError("The length of the spin names arg (%s) does not match that of the value arg (%s)." % (len(spin_names), N))

    # Generate some empty lists.
    if not mol_names:
        mol_names = [None] * N
    if not res_nums:
        res_nums = [None] * N
    if not res_names:
        res_names = [None] * N
    if not spin_nums:
        spin_nums = [None] * N
    if not spin_names:
        spin_names = [None] * N
    if errors == None:
        errors = [None] * N

    # Generate the spin IDs.
    if not spin_ids:
        spin_ids = []
        for i in range(N):
            spin_ids.append(generate_spin_id_unique(spin_num=spin_nums[i], spin_name=spin_names[i], res_num=res_nums[i], res_name=res_names[i], mol_name=mol_names[i]))

    # Initialise the global data for the current pipe if necessary.
    if not hasattr(cdp, 'ri_type'):
        cdp.ri_type = {}
    if not hasattr(cdp, 'ri_ids'):
        cdp.ri_ids = []

    # Set the spectrometer frequency.
    set_frequency(id=ri_id, frq=frq)

    # Update the global data.
    cdp.ri_ids.append(ri_id)
    cdp.ri_type[ri_id] = ri_type

    # The selection object.
    select_obj = None
    if spin_id:
        select_obj = Selection(spin_id)

    # Loop over the spin data.
    data = []
    for i in range(N):
        # Get the corresponding spin container.
        match_mol_names, match_res_nums, match_res_names, spins = return_spin_from_selection(spin_ids[i], full_info=True, multi=True)
        if spins in [None, []]:
            raise RelaxNoSpinError(spin_ids[i])

        # Remove non-matching spins.
        if select_obj:
            new_spins = []
            new_mol_names = []
            new_res_nums = []
            new_res_names = []
            new_ids = []
            for j in range(len(spins)):
                if select_obj.contains_spin(spin_num=spins[j].num, spin_name=spins[j].name, res_num=match_res_nums[j], res_name=match_res_names[j], mol=match_mol_names[j]):
                    new_spins.append(spins[j])
                    new_mol_names.append(match_mol_names[j])
                    new_res_nums.append(match_res_nums[j])
                    new_res_names.append(match_res_names[j])
                    new_ids.append(generate_spin_id_unique(mol_name=mol_names[i], res_num=res_nums[i], res_name=res_names[i], spin_num=spins[j].num, spin_name=spins[j].name))
            new_id = new_ids[0]

        # Aliases for normal operation.
        else:
            new_spins = spins
            new_mol_names = match_mol_names
            new_res_nums = match_res_nums
            new_res_names = match_res_names
            new_id = spin_ids[i]
            new_ids = None

        # Check that only a singe spin is present.
        if len(new_spins) > 1:
            if new_ids:
                raise RelaxMultiSpinIDError(spin_ids[i], new_ids)
            else:
                raise RelaxMultiSpinIDError(spin_ids[i], new_ids)
        if len(new_spins) == 0:
            raise RelaxNoSpinError(spin_ids[i])

        # Loop over the spins.
        for j in range(len(new_spins)):
            # No match to the selection.
            if select_obj and not select_obj.contains_spin(spin_num=new_spins[j].num, spin_name=new_spins[j].name, res_num=new_res_nums[j], res_name=new_res_names[j], mol=new_mol_names[j]):
                continue

            # Initialise the spin data if necessary.
            if not hasattr(new_spins[j], 'ri_data') or new_spins[j].ri_data == None:
                new_spins[j].ri_data = {}
            if not hasattr(new_spins[j], 'ri_data_err') or new_spins[j].ri_data_err == None:
                new_spins[j].ri_data_err = {}

            # Update all data structures.
            new_spins[j].ri_data[ri_id] = values[i]
            new_spins[j].ri_data_err[ri_id] = errors[i]

            # Append the data for printing out.
            data.append([new_id, repr(values[i]), repr(errors[i])])

    # Print out.
    if verbose:
        print("\nThe following %s MHz %s relaxation data with the ID '%s' has been loaded into the relax data store:\n" % (frq/1e6, ri_type, ri_id))
        write_data(out=sys.stdout, headings=["Spin_ID", "Value", "Error"], data=data)
Example #15
0
    def minimise(self, min_algor=None, min_options=None, func_tol=None, grad_tol=None, max_iterations=None, constraints=False, scaling=True, verbosity=0, sim_index=None, lower=None, upper=None, inc=None):
        """Relaxation curve fitting minimisation method.

        @keyword min_algor:         The minimisation algorithm to use.
        @type min_algor:            str
        @keyword min_options:       An array of options to be used by the minimisation algorithm.
        @type min_options:          array of str
        @keyword func_tol:          The function tolerance which, when reached, terminates optimisation.  Setting this to None turns of the check.
        @type func_tol:             None or float
        @keyword grad_tol:          The gradient tolerance which, when reached, terminates optimisation.  Setting this to None turns of the check.
        @type grad_tol:             None or float
        @keyword max_iterations:    The maximum number of iterations for the algorithm.
        @type max_iterations:       int
        @keyword constraints:       If True, constraints are used during optimisation.
        @type constraints:          bool
        @keyword scaling:           If True, diagonal scaling is enabled during optimisation to allow the problem to be better conditioned.
        @type scaling:              bool
        @keyword verbosity:         The amount of information to print.  The higher the value, the greater the verbosity.
        @type verbosity:            int
        @keyword sim_index:         The index of the simulation to optimise.  This should be None if normal optimisation is desired.
        @type sim_index:            None or int
        @keyword lower:             The lower bounds of the grid search which must be equal to the number of parameters in the model.  This optional argument is only used when doing a grid search.
        @type lower:                array of numbers
        @keyword upper:             The upper bounds of the grid search which must be equal to the number of parameters in the model.  This optional argument is only used when doing a grid search.
        @type upper:                array of numbers
        @keyword inc:               The increments for each dimension of the space for the grid search.  The number of elements in the array must equal to the number of parameters in the model.  This argument is only used when doing a grid search.
        @type inc:                  array of int
        """

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

        # Loop over the sequence.
        for spin, mol_name, res_num, res_name in spin_loop(full_info=True):
            # Skip deselected spins.
            if not spin.select:
                continue

            # Skip spins which have no data.
            if not hasattr(spin, 'intensities'):
                continue

            # Create the initial parameter vector.
            param_vector = self._assemble_param_vector(spin=spin)

            # Diagonal scaling.
            scaling_matrix = self._assemble_scaling_matrix(spin=spin, scaling=scaling)
            if len(scaling_matrix):
                param_vector = dot(inv(scaling_matrix), param_vector)

            # Get the grid search minimisation options.
            if match('^[Gg]rid', min_algor):
                inc, lower_new, upper_new = self._grid_search_setup(spin=spin, param_vector=param_vector, lower=lower, upper=upper, inc=inc, scaling_matrix=scaling_matrix)

            # Linear constraints.
            if constraints:
                A, b = self._linear_constraints(spin=spin, scaling_matrix=scaling_matrix)
            else:
                A, b = None, None

            # Print out.
            if verbosity >= 1:
                # Get the spin id string.
                spin_id = generate_spin_id_unique(mol_name=mol_name, res_num=res_num, res_name=res_name, spin_num=spin.num, spin_name=spin.name)

                # Individual spin printout.
                if verbosity >= 2:
                    print("\n\n")

                string = "Fitting to spin " + repr(spin_id)
                print("\n\n" + string)
                print(len(string) * '~')


            # Initialise the function to minimise.
            ######################################

            # The keys.
            keys = list(spin.intensities.keys())

            # The peak intensities and times.
            values = []
            errors = []
            times = []
            for key in keys:
                # The values.
                if sim_index == None:
                    values.append(spin.intensities[key])
                else:
                    values.append(spin.sim_intensities[sim_index][key])

                # The errors.
                errors.append(spin.intensity_err[key])

                # The relaxation times.
                times.append(cdp.relax_times[key])

            # The scaling matrix in a diagonalised list form.
            scaling_list = []
            for i in range(len(scaling_matrix)):
                scaling_list.append(scaling_matrix[i, i])

            setup(num_params=len(spin.params), num_times=len(values), values=values, sd=errors, relax_times=times, scaling_matrix=scaling_list)


            # Setup the minimisation algorithm when constraints are present.
            ################################################################

            if constraints and not match('^[Gg]rid', min_algor):
                algor = min_options[0]
            else:
                algor = min_algor


            # Levenberg-Marquardt minimisation.
            ###################################

            if match('[Ll][Mm]$', algor) or match('[Ll]evenburg-[Mm]arquardt$', algor):
                # Reconstruct the error data structure.
                lm_error = zeros(len(spin.relax_times), float64)
                index = 0
                for k in range(len(spin.relax_times)):
                    lm_error[index:index+len(relax_error[k])] = relax_error[k]
                    index = index + len(relax_error[k])

                min_options = min_options + (self.relax_fit.lm_dri, lm_error)


            # Minimisation.
            ###############

            # Grid search.
            if search('^[Gg]rid', min_algor):
                results = grid(func=self._func, args=(), num_incs=inc, lower=lower_new, upper=upper_new, A=A, b=b, verbosity=verbosity)

                # Unpack the results.
                param_vector, chi2, iter_count, warning = results
                f_count = iter_count
                g_count = 0.0
                h_count = 0.0

            # Minimisation.
            else:
                results = generic_minimise(func=self._func, dfunc=self._dfunc, d2func=self._d2func, args=(), x0=param_vector, min_algor=min_algor, min_options=min_options, func_tol=func_tol, grad_tol=grad_tol, maxiter=max_iterations, A=A, b=b, full_output=True, print_flag=verbosity)

                # Unpack the results.
                if results == None:
                    return
                param_vector, chi2, iter_count, f_count, g_count, h_count, warning = results

            # Scaling.
            if scaling:
                param_vector = dot(scaling_matrix, param_vector)

            # Disassemble the parameter vector.
            self._disassemble_param_vector(param_vector=param_vector, spin=spin, sim_index=sim_index)

            # Monte Carlo minimisation statistics.
            if sim_index != None:
                # Chi-squared statistic.
                spin.chi2_sim[sim_index] = chi2

                # Iterations.
                spin.iter_sim[sim_index] = iter_count

                # Function evaluations.
                spin.f_count_sim[sim_index] = f_count

                # Gradient evaluations.
                spin.g_count_sim[sim_index] = g_count

                # Hessian evaluations.
                spin.h_count_sim[sim_index] = h_count

                # Warning.
                spin.warning_sim[sim_index] = warning


            # Normal statistics.
            else:
                # Chi-squared statistic.
                spin.chi2 = chi2

                # Iterations.
                spin.iter = iter_count

                # Function evaluations.
                spin.f_count = f_count

                # Gradient evaluations.
                spin.g_count = g_count

                # Hessian evaluations.
                spin.h_count = h_count

                # Warning.
                spin.warning = warning
Example #16
0
def read(param=None, scaling=1.0, file=None, dir=None, file_data=None, spin_id_col=None, mol_name_col=None, res_num_col=None, res_name_col=None, spin_num_col=None, spin_name_col=None, data_col=None, error_col=None, sep=None, spin_id=None):
    """Read spin specific data values from a file.

    @keyword param:         The name of the parameter to read.
    @type param:            str
    @keyword scaling:       A scaling factor by which all read values are multiplied by.
    @type scaling:          float
    @keyword file:          The name of the file to open.
    @type file:             str
    @keyword dir:           The directory containing the file (defaults to the current directory if None).
    @type dir:              str or None
    @keyword file_data:     An alternative to opening a file, if the data already exists in the correct format.  The format is a list of lists where the first index corresponds to the row and the second the column.
    @type file_data:        list of lists
    @keyword spin_id_col:   The column containing the spin ID strings.  If supplied, the mol_name_col, res_name_col, res_num_col, spin_name_col, and spin_num_col arguments must be none.
    @type spin_id_col:      int or None
    @keyword mol_name_col:  The column containing the molecule name information.  If supplied, spin_id_col must be None.
    @type mol_name_col:     int or None
    @keyword res_name_col:  The column containing the residue name information.  If supplied, spin_id_col must be None.
    @type res_name_col:     int or None
    @keyword res_num_col:   The column containing the residue number information.  If supplied, spin_id_col must be None.
    @type res_num_col:      int or None
    @keyword spin_name_col: The column containing the spin name information.  If supplied, spin_id_col must be None.
    @type spin_name_col:    int or None
    @keyword spin_num_col:  The column containing the spin number information.  If supplied, spin_id_col must be None.
    @type spin_num_col:     int or None
    @keyword data_col:      The column containing the RDC data in Hz.
    @type data_col:         int or None
    @keyword error_col:     The column containing the RDC errors.
    @type error_col:        int or None
    @keyword sep:           The column separator which, if None, defaults to whitespace.
    @type sep:              str or None
    @keyword spin_id:       The spin ID string.
    @type spin_id:          None or str
    """

    # Test if the current pipe exists.
    check_pipe()

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

        # Minimisation statistic flag.
        min_stat = False

        # Alias specific analysis API object method.
        api = return_api()
        return_value = api.return_value

        # Specific set function.                                                           
        set_fn = set

    # Test data corresponding to param already exists.
    for spin in spin_loop():
        # Skip deselected spins.
        if not spin.select:
            continue

        # Get the value and error.
        value, error = return_value(spin, param)

        # Data exists.
        if value != None or error != None:
            raise RelaxValueError(param)

    # Loop over the data.
    mol_names = []
    res_nums = []
    res_names = []
    spin_nums = []
    spin_names = []
    values = []
    errors = []
    for data in read_spin_data(file=file, dir=dir, file_data=file_data, spin_id_col=spin_id_col, mol_name_col=mol_name_col, res_num_col=res_num_col, res_name_col=res_name_col, spin_num_col=spin_num_col, spin_name_col=spin_name_col, data_col=data_col, error_col=error_col, sep=sep, spin_id=spin_id):
        # Unpack.
        if data_col and error_col:
            mol_name, res_num, res_name, spin_num, spin_name, value, error = data
        elif data_col:
            mol_name, res_num, res_name, spin_num, spin_name, value = data
            error = None
        else:
            mol_name, res_num, res_name, spin_num, spin_name, error = data
            value = None

        # Set the value.
        id = generate_spin_id_unique(mol_name=mol_name, res_num=res_num, res_name=res_name, spin_num=spin_num, spin_name=spin_name)
        set_fn(val=value, error=error, param=param, spin_id=id)

        # Append the data for printout.
        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)
        values.append(value)
        errors.append(error)

    # Print out.
    write_spin_data(file=sys.stdout, mol_names=mol_names, res_nums=res_nums, res_names=res_names, spin_nums=spin_nums, spin_names=spin_names, data=values, data_name=param, error=errors, error_name='%s_error'%param)

    # Reset the minimisation statistics.
    if api.set(param) == 'min':
        minimise.reset_min_stats()
Example #17
0
def define(spin_id1=None, spin_id2=None, pipe=None, direct_bond=False, spin_selection=False, verbose=True):
    """Set up the magnetic dipole-dipole interaction.

    @keyword spin_id1:          The spin identifier string of the first spin of the pair.
    @type spin_id1:             str
    @keyword spin_id2:          The spin identifier string of the second spin of the pair.
    @type spin_id2:             str
    @param pipe:                The data pipe to operate on.  Defaults to the current data pipe.
    @type pipe:                 str
    @keyword direct_bond:       A flag specifying if the two spins are directly bonded.
    @type direct_bond:          bool
    @keyword spin_selection:    Define the interatomic data container selection based on the spin selection.  If either spin is deselected, the interatomic container will also be deselected.  Otherwise the container will be selected.
    @type spin_selection:       bool
    @keyword verbose:           A flag which if True will result in printouts of the created interatomoic data containers.
    @type verbose:              bool
    """

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

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

    # Initialise the spin ID pairs list.
    ids = []
    spin_selections = []

    # Use the structural data to find connected atoms.
    if hasattr(dp, 'structure'):
        # The selection objects.
        selection1 = cdp.structure.selection(atom_id=spin_id1)
        selection2 = cdp.structure.selection(atom_id=spin_id2)

        # Loop over the atoms of the first spin selection.
        for mol_name1, res_num1, res_name1, atom_num1, atom_name1, mol_index1, atom_index1 in dp.structure.atom_loop(selection=selection1, model_num=1, mol_name_flag=True, res_num_flag=True, res_name_flag=True, atom_num_flag=True, atom_name_flag=True, mol_index_flag=True, index_flag=True):
            # Generate the first spin ID.
            id1 = generate_spin_id_unique(pipe_cont=dp, mol_name=mol_name1, res_num=res_num1, res_name=res_name1, spin_num=atom_num1, spin_name=atom_name1)

            # Do the spin exist?
            spin1 = return_spin(id1)
            if not spin1:
                continue

            # Loop over the atoms of the second spin selection.
            for mol_name2, res_num2, res_name2, atom_num2, atom_name2, mol_index2, atom_index2 in dp.structure.atom_loop(selection=selection2, model_num=1, mol_name_flag=True, res_num_flag=True, res_name_flag=True, atom_num_flag=True, atom_name_flag=True, mol_index_flag=True, index_flag=True):
                # Directly bonded atoms.
                if direct_bond:
                    # Different molecules.
                    if mol_name1 != mol_name2:
                        continue

                    # Skip non-bonded atom pairs.
                    if not dp.structure.are_bonded_index(mol_index1=mol_index1, atom_index1=atom_index1, mol_index2=mol_index2, atom_index2=atom_index2):
                        continue

                # Generate the second spin ID.
                id2 = generate_spin_id_unique(pipe_cont=dp, mol_name=mol_name2, res_num=res_num2, res_name=res_name2, spin_num=atom_num2, spin_name=atom_name2)

                # Do the spin exist?
                spin2 = return_spin(id2)
                if not spin2:
                    continue

                # Store the IDs for the printout.
                ids.append([id1, id2])
                spin_selections.append([spin1.select, spin2.select])

    # No structural data present or the spin IDs are not in the structural data, so use spin loops and some basic rules.
    if ids == []:
        for spin1, mol_name1, res_num1, res_name1, id1 in spin_loop(spin_id1, pipe=pipe, full_info=True, return_id=True):
            for spin2, mol_name2, res_num2, res_name2, id2 in spin_loop(spin_id2, pipe=pipe, full_info=True, return_id=True):
                # Directly bonded atoms.
                if direct_bond:
                    # Different molecules.
                    if mol_name1 != mol_name2:
                        continue

                    # No element info.
                    if not hasattr(spin1, 'element'):
                        raise RelaxError("The spin '%s' does not have the element type set." % id1)
                    if not hasattr(spin2, 'element'):
                        raise RelaxError("The spin '%s' does not have the element type set." % id2)

                    # Backbone NH and CH pairs.
                    pair = False
                    if (spin1.element == 'N' and spin2.element == 'H') or (spin2.element == 'N' and spin1.element == 'H'):
                        pair = True
                    elif (spin1.element == 'C' and spin2.element == 'H') or (spin2.element == 'C' and spin1.element == 'H'):
                        pair = True

                    # Same residue, so skip.
                    if pair and res_num1 != None and res_num1 != res_num2:
                        continue
                    elif pair and res_num1 == None and res_name1 != res_name2:
                        continue

                # Store the IDs for the printout.
                ids.append([id1, id2])
                spin_selections.append([spin1.select, spin2.select])

    # No matches, so fail!
    if not len(ids):
        # Find the problem.
        count1 = 0
        count2 = 0
        for spin in spin_loop(spin_id1):
            count1 += 1
        for spin in spin_loop(spin_id2):
            count2 += 1

        # Report the problem.
        if count1 == 0 and count2 == 0:
            raise RelaxError("Neither spin IDs '%s' and '%s' match any spins." % (spin_id1, spin_id2))
        elif count1 == 0:
            raise RelaxError("The spin ID '%s' matches no spins." % spin_id1)
        elif count2 == 0:
            raise RelaxError("The spin ID '%s' matches no spins." % spin_id2)
        else:
            raise RelaxError("Unknown error.")

    # Define the interaction.
    for i in range(len(ids)):
        # Unpack.
        id1, id2 = ids[i]
        # Get the interatomic data object, if it exists.
        interatom = return_interatom(id1, id2, pipe=pipe)

        # Create the container if needed.
        if interatom == None:
            interatom = create_interatom(spin_id1=id1, spin_id2=id2, pipe=pipe)

        # Check that this has not already been set up.
        if interatom.dipole_pair:
            raise RelaxError("The magnetic dipole-dipole interaction already exists between the spins '%s' and '%s'." % (id1, id2))

        # Set a flag indicating that a dipole-dipole interaction is present.
        interatom.dipole_pair = True

        # Set the selection.
        if spin_selection:
            interatom.select = False
            if spin_selections[i][0] and spin_selections[i][1]:
                interatom.select = True

    # Printout.
    if verbose:
        # Conversion.
        for i in range(len(ids)):
            ids[i][0] = repr(ids[i][0])
            ids[i][1] = repr(ids[i][1])

        # The printout.
        print("Interatomic interactions are now defined for the following spins:\n")
        write_data(out=sys.stdout, headings=["Spin_ID_1", "Spin_ID_2"], data=ids)
Example #18
0
def read(file=None, dir=None, spectrum_id=None, dim=1, int_col=None, int_method=None, spin_id_col=None, mol_name_col=None, res_num_col=None, res_name_col=None, spin_num_col=None, spin_name_col=None, sep=None, spin_id=None, ncproc=None, verbose=True):
    """Read the peak intensity data.

    @keyword file:          The name of the file(s) containing the peak intensities.
    @type file:             str or list of str
    @keyword dir:           The directory where the file is located.
    @type dir:              str
    @keyword spectrum_id:   The spectrum identification string.
    @type spectrum_id:      str or list of str
    @keyword dim:           The dimension of the peak list to associate the data with.
    @type dim:              int
    @keyword int_col:       The column containing the peak intensity data (used by the generic intensity file format).
    @type int_col:          int or list of int
    @keyword int_method:    The integration method, one of 'height', 'point sum' or 'other'.
    @type int_method:       str
    @keyword spin_id_col:   The column containing the spin ID strings (used by the generic intensity file format).  If supplied, the mol_name_col, res_name_col, res_num_col, spin_name_col, and spin_num_col arguments must be none.
    @type spin_id_col:      int or None
    @keyword mol_name_col:  The column containing the molecule name information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type mol_name_col:     int or None
    @keyword res_name_col:  The column containing the residue name information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type res_name_col:     int or None
    @keyword res_num_col:   The column containing the residue number information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type res_num_col:      int or None
    @keyword spin_name_col: The column containing the spin name information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type spin_name_col:    int or None
    @keyword spin_num_col:  The column containing the spin number information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type spin_num_col:     int or None
    @keyword sep:           The column separator which, if None, defaults to whitespace.
    @type sep:              str or None
    @keyword spin_id:       The spin ID string used to restrict data loading to a subset of all spins.  If 'auto' is provided for a NMRPipe seriesTab formatted file, the ID's are auto generated in form of Z_Ai.
    @type spin_id:          None or str
    @keyword ncproc:        The Bruker ncproc binary intensity scaling factor.
    @type ncproc:           int or None
    @keyword verbose:       A flag which if True will cause all relaxation data loaded to be printed out.
    @type verbose:          bool
    """

    # Data checks.
    check_pipe()
    check_mol_res_spin_data()

    # Check the file name.
    if file == None:
        raise RelaxError("The file name must be supplied.")

    # Test that the intensity measures are identical.
    if hasattr(cdp, 'int_method') and cdp.int_method != int_method:
        raise RelaxError("The '%s' measure of peak intensities does not match '%s' of the previously loaded spectra." % (int_method, cdp.int_method))

    # Multiple ID flags.
    flag_multi = False
    flag_multi_file = False
    flag_multi_col = False
    if isinstance(spectrum_id, list) or spectrum_id == 'auto':
        flag_multi = True
    if isinstance(file, list):
        flag_multi_file = True
    if isinstance(int_col, list) or spectrum_id == 'auto':
        flag_multi_col = True

    # List argument checks.
    if flag_multi:
        # Too many lists.
        if flag_multi_file and flag_multi_col:
            raise RelaxError("If a list of spectrum IDs is supplied, the file names and intensity column arguments cannot both be lists.")

        # Not enough lists.
        if not flag_multi_file and not flag_multi_col:
            raise RelaxError("If a list of spectrum IDs is supplied, either the file name or intensity column arguments must be a list of equal length.")

        # List lengths for multiple files.
        if flag_multi_file and len(spectrum_id) != len(file):
                raise RelaxError("The file list %s and spectrum ID list %s do not have the same number of elements." % (file, spectrum_id))

        # List lengths for multiple intensity columns.
        if flag_multi_col and spectrum_id != 'auto' and len(spectrum_id) != len(int_col):
            raise RelaxError("The spectrum ID list %s and intensity column list %s do not have the same number of elements." % (spectrum_id, int_col))

    # More list argument checks (when only one spectrum ID is supplied).
    else:
        # Multiple files.
        if flag_multi_file:
            raise RelaxError("If multiple files are supplied, then multiple spectrum IDs must also be supplied.")

        # Multiple intensity columns.
        if flag_multi_col:
            raise RelaxError("If multiple intensity columns are supplied, then multiple spectrum IDs must also be supplied.")

    # Intensity column checks.
    if spectrum_id != 'auto' and not flag_multi and flag_multi_col:
        raise RelaxError("If a list of intensity columns is supplied, the spectrum ID argument must also be a list of equal length.")

    # Check the intensity measure.
    if not int_method in ['height', 'point sum', 'other']:
        raise RelaxError("The intensity measure '%s' is not one of 'height', 'point sum', 'other'." % int_method)

    # Set the peak intensity measure.
    cdp.int_method = int_method

    # Convert the file argument to a list if necessary.
    if not isinstance(file, list):
        file = [file]

    # Loop over all files.
    for file_index in range(len(file)):
        # Read the peak list data.
        peak_list = read_peak_list(file=file[file_index], dir=dir, int_col=int_col, spin_id_col=spin_id_col, mol_name_col=mol_name_col, res_num_col=res_num_col, res_name_col=res_name_col, spin_num_col=spin_num_col, spin_name_col=spin_name_col, sep=sep, spin_id=spin_id)

        # Automatic spectrum IDs.
        if spectrum_id == 'auto':
            spectrum_id = peak_list[0].intensity_name

        # Loop over the assignments.
        data = []
        data_flag = False
        for assign in peak_list:
            # Generate the spin_id.
            spin_id = generate_spin_id_unique(res_num=assign.res_nums[dim-1], spin_name=assign.spin_names[dim-1])

            # Convert the intensity data to a list if needed.
            intensity = assign.intensity
            if not isinstance(intensity, list):
                intensity = [intensity]

            # Loop over the intensity data.
            for int_index in range(len(intensity)):
                # Sanity check.
                if intensity[int_index] == 0.0:
                    warn(RelaxWarning("A peak intensity of zero has been encountered for the spin '%s' - this could be fatal later on." % spin_id))

                # Get the spin container.
                spin = return_spin(spin_id)
                if not spin:
                    warn(RelaxNoSpinWarning(spin_id))
                    continue

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

                # Initialise.
                if not hasattr(spin, 'peak_intensity'):
                    spin.peak_intensity = {}

                # Intensity scaling.
                if ncproc != None:
                    intensity[int_index] = intensity[int_index] / float(2**ncproc)

                # Add the data.
                if flag_multi_file:
                    id = spectrum_id[file_index]
                elif flag_multi_col:
                    id = spectrum_id[int_index]
                else:
                    id = spectrum_id
                spin.peak_intensity[id] = intensity[int_index]

                # Switch the flag.
                data_flag = True

                # Append the data for printing out.
                data.append([spin_id, repr(intensity[int_index])])

        # Add the spectrum id (and ncproc) to the relax data store.
        spectrum_ids = spectrum_id
        if isinstance(spectrum_id, str):
            spectrum_ids = [spectrum_id]
        if ncproc != None and not hasattr(cdp, 'ncproc'):
            cdp.ncproc = {}
        for i in range(len(spectrum_ids)):
            add_spectrum_id(spectrum_ids[i])
            if ncproc != None:
                cdp.ncproc[spectrum_ids[i]] = ncproc

        # No data.
        if not data_flag:
            # Delete all the data.
            delete(spectrum_id)

            # Raise the error.
            raise RelaxError("No data could be loaded from the peak list")

        # Printout.
        if verbose:
            print("\nThe following intensities have been loaded into the relax data store:\n")
            write_data(out=sys.stdout, headings=["Spin_ID", "Intensity"], data=data)
        print('')
Example #19
0
def read(param=None, scaling=1.0, file=None, dir=None, file_data=None, spin_id_col=None, mol_name_col=None, res_num_col=None, res_name_col=None, spin_num_col=None, spin_name_col=None, data_col=None, error_col=None, sep=None, spin_id=None):
    """Read spin specific data values from a file.

    @keyword param:         The name of the parameter to read.
    @type param:            str
    @keyword scaling:       A scaling factor by which all read values are multiplied by.
    @type scaling:          float
    @keyword file:          The name of the file to open.
    @type file:             str
    @keyword dir:           The directory containing the file (defaults to the current directory if None).
    @type dir:              str or None
    @keyword file_data:     An alternative to opening a file, if the data already exists in the correct format.  The format is a list of lists where the first index corresponds to the row and the second the column.
    @type file_data:        list of lists
    @keyword spin_id_col:   The column containing the spin ID strings.  If supplied, the mol_name_col, res_name_col, res_num_col, spin_name_col, and spin_num_col arguments must be none.
    @type spin_id_col:      int or None
    @keyword mol_name_col:  The column containing the molecule name information.  If supplied, spin_id_col must be None.
    @type mol_name_col:     int or None
    @keyword res_name_col:  The column containing the residue name information.  If supplied, spin_id_col must be None.
    @type res_name_col:     int or None
    @keyword res_num_col:   The column containing the residue number information.  If supplied, spin_id_col must be None.
    @type res_num_col:      int or None
    @keyword spin_name_col: The column containing the spin name information.  If supplied, spin_id_col must be None.
    @type spin_name_col:    int or None
    @keyword spin_num_col:  The column containing the spin number information.  If supplied, spin_id_col must be None.
    @type spin_num_col:     int or None
    @keyword data_col:      The column containing the RDC data in Hz.
    @type data_col:         int or None
    @keyword error_col:     The column containing the RDC errors.
    @type error_col:        int or None
    @keyword sep:           The column separator which, if None, defaults to whitespace.
    @type sep:              str or None
    @keyword spin_id:       The spin ID string.
    @type spin_id:          None or str
    """

    # Test if the current pipe exists.
    check_pipe()

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

        # Minimisation statistic flag.
        min_stat = False

        # Alias specific analysis API object method.
        api = return_api()
        return_value = api.return_value

        # Specific set function.                                                           
        set_fn = set

    # Test data corresponding to param already exists.
    for spin in spin_loop():
        # Skip deselected spins.
        if not spin.select:
            continue

        # Get the value and error.
        value, error = return_value(spin, param)

        # Data exists.
        if value != None or error != None:
            raise RelaxValueError(param)

    # Loop over the data.
    mol_names = []
    res_nums = []
    res_names = []
    spin_nums = []
    spin_names = []
    values = []
    errors = []
    for data in read_spin_data(file=file, dir=dir, file_data=file_data, spin_id_col=spin_id_col, mol_name_col=mol_name_col, res_num_col=res_num_col, res_name_col=res_name_col, spin_num_col=spin_num_col, spin_name_col=spin_name_col, data_col=data_col, error_col=error_col, sep=sep, spin_id=spin_id):
        # Unpack.
        if data_col and error_col:
            mol_name, res_num, res_name, spin_num, spin_name, value, error = data
        elif data_col:
            mol_name, res_num, res_name, spin_num, spin_name, value = data
            error = None
        else:
            mol_name, res_num, res_name, spin_num, spin_name, error = data
            value = None

        # Set the value.
        id = generate_spin_id_unique(mol_name=mol_name, res_num=res_num, res_name=res_name, spin_num=spin_num, spin_name=spin_name)
        set_fn(val=value, error=error, param=param, spin_id=id)

        # Append the data for printout.
        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)
        values.append(value)
        errors.append(error)

    # Print out.
    write_spin_data(file=sys.stdout, mol_names=mol_names, res_nums=res_nums, res_names=res_names, spin_nums=spin_nums, spin_names=spin_names, data=values, data_name=param, error=errors, error_name='%s_error'%param)

    # Reset the minimisation statistics.
    if api.set(param) == 'min':
        minimise.reset_min_stats()
Example #20
0
def sf_model_free_read(star, sample_conditions=None):
    """Fill the spin containers with the model-free data from the saveframe records.

    @param star:                The NMR-STAR dictionary object.
    @type star:                 NMR_STAR instance
    @keyword sample_conditions: The sample condition label to read.  Only one sample condition can be read per data pipe.
    @type sample_conditions:    None or str
    """

    # The list of model-free parameters (both bmrblib names and relax names).
    mf_bmrb_key = [
        'bond_length', 'local_tm', 's2', 's2f', 's2s', 'te', 'tf', 'ts', 'rex',
        'chi2'
    ]
    mf_params = [
        'r', 'local_tm', 's2', 's2f', 's2s', 'te', 'tf', 'ts', 'rex', 'chi2'
    ]

    # Get the entities.
    for data in star.model_free.loop():
        # Sample conditions do not match (remove the $ sign).
        if 'sample_cond_list_label' in data and sample_conditions and data[
                'sample_cond_list_label'].replace('$',
                                                  '') != sample_conditions:
            continue

        # Global data.
        if 'global_chi2' in data:
            setattr(cdp, 'chi2', data['global_chi2'])

        # The number of spins.
        N = bmrb.num_spins(data)

        # No data in the saveframe.
        if N == 0:
            continue

        # The molecule names.
        mol_names = bmrb.molecule_names(data, N)

        # Missing atom names.
        if 'atom_names' not in data or data['atom_names'] == None:
            data['atom_names'] = [None] * N

        # Generate the sequence if needed.
        bmrb.generate_sequence(N,
                               spin_names=data['atom_names'],
                               res_nums=data['res_nums'],
                               res_names=data['res_names'],
                               mol_names=mol_names)

        # Correlation time scaling.
        table = {'s': 1.0, 'ns': 1e-9, 'ps': 1e-12}
        te_scale = 1.0
        if data['te_units']:
            te_scale = table[data['te_units']]

        # Fast correlation time scaling.
        if data['tf_units']:
            tf_scale = table[data['tf_units']]
        else:
            tf_scale = te_scale

        # Slow correlation time scaling.
        if data['ts_units']:
            ts_scale = table[data['ts_units']]
        else:
            ts_scale = te_scale

        # Rex scaling.
        rex_scale = 1.0
        if hasattr(cdp, 'spectrometer_frq') and len(cdp.spectrometer_frq):
            rex_scale = 1.0 / (2.0 * pi *
                               cdp.spectrometer_frq[cdp.ri_ids[0]])**2

        # Loop over the spins.
        for i in range(N):
            # Generate a spin ID.
            spin_id = mol_res_spin.generate_spin_id_unique(
                mol_name=mol_names[i],
                res_name=data['res_names'][i],
                res_num=data['res_nums'][i],
                spin_name=data['atom_names'][i])

            # Obtain the spin.
            spin = mol_res_spin.return_spin(spin_id=spin_id)

            # No spin?!?
            if spin == None:
                raise RelaxError("The spin '%s' does not exist." % spin_id)

            # Loop over and set the model-free parameters.
            for j in range(len(mf_params)):
                # The parameter.
                param = mf_params[j]

                # No parameter.
                if not mf_bmrb_key[j] in data:
                    continue

                # The parameter and its value.
                if data[mf_bmrb_key[j]] != None:
                    # The value.
                    value = data[mf_bmrb_key[j]][i]

                    # Parameter scaling.
                    if value != None:
                        if param == 'te':
                            value = value * te_scale
                        elif param == 'tf':
                            value = value * tf_scale
                        elif param == 'ts':
                            value = value * ts_scale
                        elif param == 'rex':
                            value = value * rex_scale

                # No parameter value.
                else:
                    value = None

                # Set the parameter.
                setattr(spin, param, value)

                # The error.
                mf_bmrb_key_err = mf_bmrb_key[j] + '_err'
                error = None
                if mf_bmrb_key_err in data and data[mf_bmrb_key_err] != None:
                    error = data[mf_bmrb_key_err][i]

                # Error scaling.
                if error != None:
                    if param == 'te':
                        error = error * te_scale
                    elif param == 'tf':
                        error = error * tf_scale
                    elif param == 'ts':
                        error = error * ts_scale
                    elif param == 'rex':
                        error = error * rex_scale

                # Set the error.
                mf_param_err = param + '_err'
                if mf_bmrb_key_err in data and data[mf_bmrb_key_err] != None:
                    setattr(spin, mf_param_err, error)

            # The model.
            if data['model_fit'] != None and data['model_fit'][i] != None:
                model = from_bmrb_model(data['model_fit'][i])
                setattr(spin, 'model', model)

                # The equation and parameters.
                equation, params = model_map(model)
                setattr(spin, 'equation', equation)
                setattr(spin, 'params', params)

            # Convert te values which should be ts!
            if hasattr(spin, 'model') and spin.model in [
                    'm5', 'm6', 'm7', 'm8'
            ] and hasattr(spin, 'te') and spin.te != None:
                # Change the parameter name of te to ts.
                spin.ts = spin.te
                if hasattr(spin, 'te_err'):
                    spin.ts_err = spin.te_err

                # Set the te and te_err values to None.
                spin.te = None
                spin.te_err = None

            # The element.
            if 'atom_types' in data and data['atom_types'] != None:
                setattr(spin, 'element', data['atom_types'][i])

            # Heteronucleus type.
            if 'atom_types' in data and data['atom_types'] != None and data[
                    'atom_types'][i] != None and 'isotope' in data and data[
                        'isotope'] != None:
                # The isotope number.
                iso_num = data['isotope'][i]

                # No isotope number.
                iso_table = {'C': 13, 'N': 15}
                if not data['isotope'][i]:
                    iso_num = iso_table[data['atom_types'][i]]

                # Set the type.
                setattr(spin, 'isotope', str(iso_num) + data['atom_types'][i])
Example #21
0
    def _sf_model_free_read(self, star, sample_conditions=None):
        """Fill the spin containers with the model-free data from the saveframe records.

        @param star:                The NMR-STAR dictionary object.
        @type star:                 NMR_STAR instance
        @keyword sample_conditions: The sample condition label to read.  Only one sample condition can be read per data pipe.
        @type sample_conditions:    None or str
        """

        # The list of model-free parameters (both bmrblib names and relax names).
        mf_bmrb_key = ['bond_length', 'local_tm', 's2', 's2f', 's2s', 'te', 'tf', 'ts', 'rex', 'chi2']
        mf_params =   ['r', 'local_tm', 's2', 's2f', 's2s', 'te', 'tf', 'ts', 'rex', 'chi2']

        # Get the entities.
        for data in star.model_free.loop():
            # Store the keys.
            keys = data.keys()

            # Sample conditions do not match (remove the $ sign).
            if 'sample_cond_list_label' in keys and sample_conditions and data['sample_cond_list_label'].replace('$', '') != sample_conditions:
                continue

            # Global data.
            if 'global_chi2' in keys:
                setattr(cdp, 'chi2', data['global_chi2'])

            # The number of spins.
            N = bmrb.num_spins(data)

            # No data in the saveframe.
            if N == 0:
                continue

            # The molecule names.
            mol_names = bmrb.molecule_names(data, N)

            # Missing atom names.
            if 'atom_names' not in keys or data['atom_names'] == None:
                data['atom_names'] = [None] * N

            # Generate the sequence if needed.
            bmrb.generate_sequence(N, spin_names=data['atom_names'], res_nums=data['res_nums'], res_names=data['res_names'], mol_names=mol_names)

            # Correlation time scaling.
            table = {'s':   1.0,
                     'ns':  1e-9,
                     'ps':  1e-12}
            te_scale = 1.0
            if data['te_units']:
                te_scale = table[data['te_units']]

            # Fast correlation time scaling.
            if data['tf_units']:
                tf_scale = table[data['tf_units']]
            else:
                tf_scale = te_scale

            # Slow correlation time scaling.
            if data['ts_units']:
                ts_scale = table[data['ts_units']]
            else:
                ts_scale = te_scale

            # Rex scaling.
            rex_scale = 1.0
            if hasattr(cdp, 'spectrometer_frq') and len(cdp.spectrometer_frq):
                rex_scale = 1.0 / (2.0*pi*cdp.spectrometer_frq[cdp.ri_ids[0]])**2

            # Loop over the spins.
            for i in range(N):
                # Generate a spin ID.
                spin_id = mol_res_spin.generate_spin_id_unique(mol_name=mol_names[i], res_name=data['res_names'][i], res_num=data['res_nums'][i], spin_name=data['atom_names'][i])

                # Obtain the spin.
                spin = mol_res_spin.return_spin(spin_id)

                # No spin?!?
                if spin == None:
                    raise RelaxError("The spin '%s' does not exist." % spin_id) 

                # Loop over and set the model-free parameters.
                for j in range(len(mf_params)):
                    # The parameter.
                    param = mf_params[j]

                    # No parameter.
                    if not mf_bmrb_key[j] in keys:
                        continue

                    # The parameter and its value.
                    if data[mf_bmrb_key[j]] != None:
                        # The value.
                        value = data[mf_bmrb_key[j]][i]

                        # Parameter scaling.
                        if value != None:
                            if param == 'te':
                                value = value * te_scale
                            elif param == 'tf':
                                value = value * tf_scale
                            elif param == 'ts':
                                value = value * ts_scale
                            elif param == 'rex':
                                value = value * rex_scale

                    # No parameter value.
                    else:
                        value = None

                    # Set the parameter.
                    setattr(spin, param, value)

                    # The error.
                    mf_bmrb_key_err = mf_bmrb_key[j] + '_err'
                    error = None
                    if mf_bmrb_key_err in keys and data[mf_bmrb_key_err] != None:
                        error = data[mf_bmrb_key_err][i]

                    # Error scaling.
                    if error != None:
                        if param == 'te':
                            error = error * te_scale
                        elif param == 'tf':
                            error = error * tf_scale
                        elif param == 'ts':
                            error = error * ts_scale
                        elif param == 'rex':
                            error = error * rex_scale

                    # Set the error.
                    mf_param_err = param + '_err'
                    if mf_bmrb_key_err in keys and data[mf_bmrb_key_err] != None:
                        setattr(spin, mf_param_err, error)

                # The model.
                if data['model_fit'] != None and data['model_fit'][i] != None:
                    model = self._from_bmrb_model(data['model_fit'][i])
                    setattr(spin, 'model', model)

                    # The equation and parameters.
                    equation, params = self._model_map(model)
                    setattr(spin, 'equation', equation)
                    setattr(spin, 'params', params)

                # Convert te values which should be ts!
                if hasattr(spin, 'model') and spin.model in ['m5', 'm6', 'm7', 'm8'] and hasattr(spin, 'te') and spin.te != None:
                    # Change the parameter name of te to ts.
                    spin.ts = spin.te
                    if hasattr(spin, 'te_err'):
                        spin.ts_err = spin.te_err

                    # Set the te and te_err values to None.
                    spin.te = None
                    spin.te_err = None

                # The element.
                if'atom_types' in keys and data['atom_types'] != None:
                    setattr(spin, 'element', data['atom_types'][i])

                # Heteronucleus type.
                if'atom_types' in keys and data['atom_types'] != None and data['atom_types'][i] != None and 'isotope' in keys and data['isotope'] != None:
                    # The isotope number.
                    iso_num = data['isotope'][i]

                    # No isotope number.
                    iso_table = {'C': 13, 'N': 15}
                    if not data['isotope'][i]:
                        iso_num = iso_table[data['atom_types'][i]]

                    # Set the type.
                    setattr(spin, 'isotope', str(iso_num) + data['atom_types'][i])
Example #22
0
def read(file=None,
         dir=None,
         spectrum_id=None,
         dim=1,
         int_col=None,
         int_method=None,
         spin_id_col=None,
         mol_name_col=None,
         res_num_col=None,
         res_name_col=None,
         spin_num_col=None,
         spin_name_col=None,
         sep=None,
         spin_id=None,
         ncproc=None,
         verbose=True):
    """Read the peak intensity data.

    @keyword file:          The name of the file(s) containing the peak intensities.
    @type file:             str or list of str
    @keyword dir:           The directory where the file is located.
    @type dir:              str
    @keyword spectrum_id:   The spectrum identification string.
    @type spectrum_id:      str or list of str
    @keyword dim:           The dimension of the peak list to associate the data with.
    @type dim:              int
    @keyword int_col:       The column containing the peak intensity data (used by the generic intensity file format).
    @type int_col:          int or list of int
    @keyword int_method:    The integration method, one of 'height', 'point sum' or 'other'.
    @type int_method:       str
    @keyword spin_id_col:   The column containing the spin ID strings (used by the generic intensity file format).  If supplied, the mol_name_col, res_name_col, res_num_col, spin_name_col, and spin_num_col arguments must be none.
    @type spin_id_col:      int or None
    @keyword mol_name_col:  The column containing the molecule name information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type mol_name_col:     int or None
    @keyword res_name_col:  The column containing the residue name information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type res_name_col:     int or None
    @keyword res_num_col:   The column containing the residue number information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type res_num_col:      int or None
    @keyword spin_name_col: The column containing the spin name information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type spin_name_col:    int or None
    @keyword spin_num_col:  The column containing the spin number information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type spin_num_col:     int or None
    @keyword sep:           The column separator which, if None, defaults to whitespace.
    @type sep:              str or None
    @keyword spin_id:       The spin ID string used to restrict data loading to a subset of all spins.  If 'auto' is provided for a NMRPipe seriesTab formatted file, the ID's are auto generated in form of Z_Ai.
    @type spin_id:          None or str
    @keyword ncproc:        The Bruker ncproc binary intensity scaling factor.
    @type ncproc:           int or None
    @keyword verbose:       A flag which if True will cause all relaxation data loaded to be printed out.
    @type verbose:          bool
    """

    # Data checks.
    check_pipe()
    check_mol_res_spin_data()

    # Check the file name.
    if file == None:
        raise RelaxError("The file name must be supplied.")

    # Test that the intensity measures are identical.
    if hasattr(cdp, 'int_method') and cdp.int_method != int_method:
        raise RelaxError(
            "The '%s' measure of peak intensities does not match '%s' of the previously loaded spectra."
            % (int_method, cdp.int_method))

    # Multiple ID flags.
    flag_multi = False
    flag_multi_file = False
    flag_multi_col = False
    if isinstance(spectrum_id, list) or spectrum_id == 'auto':
        flag_multi = True
    if isinstance(file, list):
        flag_multi_file = True
    if isinstance(int_col, list) or spectrum_id == 'auto':
        flag_multi_col = True

    # List argument checks.
    if flag_multi:
        # Too many lists.
        if flag_multi_file and flag_multi_col:
            raise RelaxError(
                "If a list of spectrum IDs is supplied, the file names and intensity column arguments cannot both be lists."
            )

        # Not enough lists.
        if not flag_multi_file and not flag_multi_col:
            raise RelaxError(
                "If a list of spectrum IDs is supplied, either the file name or intensity column arguments must be a list of equal length."
            )

        # List lengths for multiple files.
        if flag_multi_file and len(spectrum_id) != len(file):
            raise RelaxError(
                "The file list %s and spectrum ID list %s do not have the same number of elements."
                % (file, spectrum_id))

        # List lengths for multiple intensity columns.
        if flag_multi_col and spectrum_id != 'auto' and len(
                spectrum_id) != len(int_col):
            raise RelaxError(
                "The spectrum ID list %s and intensity column list %s do not have the same number of elements."
                % (spectrum_id, int_col))

    # More list argument checks (when only one spectrum ID is supplied).
    else:
        # Multiple files.
        if flag_multi_file:
            raise RelaxError(
                "If multiple files are supplied, then multiple spectrum IDs must also be supplied."
            )

        # Multiple intensity columns.
        if flag_multi_col:
            raise RelaxError(
                "If multiple intensity columns are supplied, then multiple spectrum IDs must also be supplied."
            )

    # Intensity column checks.
    if spectrum_id != 'auto' and not flag_multi and flag_multi_col:
        raise RelaxError(
            "If a list of intensity columns is supplied, the spectrum ID argument must also be a list of equal length."
        )

    # Check the intensity measure.
    if not int_method in ['height', 'point sum', 'other']:
        raise RelaxError(
            "The intensity measure '%s' is not one of 'height', 'point sum', 'other'."
            % int_method)

    # Set the peak intensity measure.
    cdp.int_method = int_method

    # Convert the file argument to a list if necessary.
    if not isinstance(file, list):
        file = [file]

    # Loop over all files.
    for file_index in range(len(file)):
        # Read the peak list data.
        peak_list = read_peak_list(file=file[file_index],
                                   dir=dir,
                                   int_col=int_col,
                                   spin_id_col=spin_id_col,
                                   mol_name_col=mol_name_col,
                                   res_num_col=res_num_col,
                                   res_name_col=res_name_col,
                                   spin_num_col=spin_num_col,
                                   spin_name_col=spin_name_col,
                                   sep=sep,
                                   spin_id=spin_id)

        # Automatic spectrum IDs.
        if spectrum_id == 'auto':
            spectrum_id = peak_list[0].intensity_name

        # Loop over the assignments.
        data = []
        data_flag = False
        for assign in peak_list:
            # Generate the spin_id.
            spin_id = generate_spin_id_unique(res_num=assign.res_nums[dim - 1],
                                              spin_name=assign.spin_names[dim -
                                                                          1])

            # Convert the intensity data to a list if needed.
            intensity = assign.intensity
            if not isinstance(intensity, list):
                intensity = [intensity]

            # Loop over the intensity data.
            for int_index in range(len(intensity)):
                # Sanity check.
                if intensity[int_index] == 0.0:
                    warn(
                        RelaxWarning(
                            "A peak intensity of zero has been encountered for the spin '%s' - this could be fatal later on."
                            % spin_id))

                # Get the spin container.
                spin = return_spin(spin_id=spin_id)
                if not spin:
                    warn(RelaxNoSpinWarning(spin_id))
                    continue

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

                # Initialise.
                if not hasattr(spin, 'peak_intensity'):
                    spin.peak_intensity = {}

                # Intensity scaling.
                if ncproc != None:
                    intensity[int_index] = intensity[int_index] / float(2**
                                                                        ncproc)

                # Add the data.
                if flag_multi_file:
                    id = spectrum_id[file_index]
                elif flag_multi_col:
                    id = spectrum_id[int_index]
                else:
                    id = spectrum_id
                spin.peak_intensity[id] = intensity[int_index]

                # Switch the flag.
                data_flag = True

                # Append the data for printing out.
                data.append([spin_id, repr(intensity[int_index])])

        # Add the spectrum id (and ncproc) to the relax data store.
        spectrum_ids = spectrum_id
        if isinstance(spectrum_id, str):
            spectrum_ids = [spectrum_id]
        if ncproc != None and not hasattr(cdp, 'ncproc'):
            cdp.ncproc = {}
        for i in range(len(spectrum_ids)):
            add_spectrum_id(spectrum_ids[i])
            if ncproc != None:
                cdp.ncproc[spectrum_ids[i]] = ncproc

        # No data.
        if not data_flag:
            # Delete all the data.
            delete(spectrum_id)

            # Raise the error.
            raise RelaxError("No data could be loaded from the peak list")

        # Printout.
        if verbose:
            print(
                "\nThe following intensities have been loaded into the relax data store:\n"
            )
            write_data(out=sys.stdout,
                       headings=["Spin_ID", "Intensity"],
                       data=data)
        print('')
Example #23
0
def read(align_id=None, file=None, dir=None, file_data=None, spin_id_col=None, mol_name_col=None, res_num_col=None, res_name_col=None, spin_num_col=None, spin_name_col=None, data_col=None, error_col=None, sep=None, spin_id=None):
    """Read the PCS data from file.

    @param align_id:        The alignment tensor ID string.
    @type align_id:         str
    @param file:            The name of the file to open.
    @type file:             str
    @param dir:             The directory containing the file (defaults to the current directory if None).
    @type dir:              str or None
    @param file_data:       An alternative opening a file, if the data already exists in the correct format.  The format is a list of lists where the first index corresponds to the row and the second the column.
    @type file_data:        list of lists
    @keyword spin_id_col:   The column containing the spin ID strings.  If supplied, the mol_name_col, res_name_col, res_num_col, spin_name_col, and spin_num_col arguments must be none.
    @type spin_id_col:      int or None
    @keyword mol_name_col:  The column containing the molecule name information.  If supplied, spin_id_col must be None.
    @type mol_name_col:     int or None
    @keyword res_name_col:  The column containing the residue name information.  If supplied, spin_id_col must be None.
    @type res_name_col:     int or None
    @keyword res_num_col:   The column containing the residue number information.  If supplied, spin_id_col must be None.
    @type res_num_col:      int or None
    @keyword spin_name_col: The column containing the spin name information.  If supplied, spin_id_col must be None.
    @type spin_name_col:    int or None
    @keyword spin_num_col:  The column containing the spin number information.  If supplied, spin_id_col must be None.
    @type spin_num_col:     int or None
    @keyword data_col:      The column containing the PCS data in Hz.
    @type data_col:         int or None
    @keyword error_col:     The column containing the PCS errors.
    @type error_col:        int or None
    @keyword sep:           The column separator which, if None, defaults to whitespace.
    @type sep:              str or None
    @keyword spin_id:       The spin ID string used to restrict data loading to a subset of all spins.
    @type spin_id:          None or str
    """

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

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

    # Either the data or error column must be supplied.
    if data_col == None and error_col == None:
        raise RelaxError("One of either the data or error column must be supplied.")


    # Spin specific data.
    #####################

    # Loop over the PCS data.
    mol_names = []
    res_nums = []
    res_names = []
    spin_nums = []
    spin_names = []
    values = []
    errors = []
    for data in read_spin_data(file=file, dir=dir, file_data=file_data, spin_id_col=spin_id_col, mol_name_col=mol_name_col, res_num_col=res_num_col, res_name_col=res_name_col, spin_num_col=spin_num_col, spin_name_col=spin_name_col, data_col=data_col, error_col=error_col, sep=sep, spin_id=spin_id):
        # Unpack.
        if data_col and error_col:
            mol_name, res_num, res_name, spin_num, spin_name, value, error = data
        elif data_col:
            mol_name, res_num, res_name, spin_num, spin_name, value = data
            error = None
        else:
            mol_name, res_num, res_name, spin_num, spin_name, error = data
            value = None

        # Test the error value (cannot be 0.0).
        if error == 0.0:
            raise RelaxError("An invalid error value of zero has been encountered.")

        # Get the corresponding spin container.
        id = generate_spin_id_unique(mol_name=mol_name, res_num=res_num, res_name=res_name, spin_num=spin_num, spin_name=spin_name)
        spin = return_spin(id)
        if spin == None and spin_id and spin_id[0] == '@':    # Allow spin IDs of atom names to be used to specify multi column data.
            spin = return_spin(id+spin_id)
        if spin == None:
            warn(RelaxNoSpinWarning(id))
            continue

        # Add the data.
        if data_col:
            # Initialise.
            if not hasattr(spin, 'pcs'):
                spin.pcs = {}

            # Append the value.
            spin.pcs[align_id] = value

        # Add the error.
        if error_col:
            # Initialise.
            if not hasattr(spin, 'pcs_err'):
                spin.pcs_err = {}

            # Append the error.
            spin.pcs_err[align_id] = error

        # Append the data for printout.
        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)
        values.append(value)
        errors.append(error)

    # Print out.
    write_spin_data(file=sys.stdout, mol_names=mol_names, res_nums=res_nums, res_names=res_names, spin_nums=spin_nums, spin_names=spin_names, data=values, data_name='PCSs', error=errors, error_name='PCS_error')


    # Global (non-spin specific) data.
    ##################################

    # No data, so return.
    if not len(values):
        return

    # Initialise.
    if not hasattr(cdp, 'align_ids'):
        cdp.align_ids = []
    if not hasattr(cdp, 'pcs_ids'):
        cdp.pcs_ids = []

    # Add the PCS id string.
    if align_id not in cdp.align_ids:
        cdp.align_ids.append(align_id)
    if align_id not in cdp.pcs_ids:
        cdp.pcs_ids.append(align_id)
Example #24
0
def define_dipole_pair(spin_id1=None, spin_id2=None, spin1=None, spin2=None, pipe=None, direct_bond=False, spin_selection=False, verbose=True):
    """Set up the magnetic dipole-dipole interaction.

    @keyword spin_id1:          The spin identifier string of the first spin of the pair.
    @type spin_id1:             str
    @keyword spin_id2:          The spin identifier string of the second spin of the pair.
    @type spin_id2:             str
    @keyword spin1:             An optional single spin container for the first atom.  This is for speeding up the interatomic data container creation, if the spin containers are already available in the calling function.
    @type spin1:                str
    @keyword spin2:             An optional single spin container for the second atom.  This is for speeding up the interatomic data container creation, if the spin containers are already available in the calling function.
    @type spin2:                str
    @param pipe:                The data pipe to operate on.  Defaults to the current data pipe.
    @type pipe:                 str
    @keyword direct_bond:       A flag specifying if the two spins are directly bonded.
    @type direct_bond:          bool
    @keyword spin_selection:    Define the interatomic data container selection based on the spin selection.  If either spin is deselected, the interatomic container will also be deselected.  Otherwise the container will be selected.
    @type spin_selection:       bool
    @keyword verbose:           A flag which if True will result in printouts of the created interatomoic data containers.
    @type verbose:              bool
    """

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

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

    # Initialise data structures for storing spin data.
    ids = []
    spins = []
    spin_selections = []

    # Pre-supplied spins.
    if spin1 and spin2:
        # Store the IDs for the printout.
        ids.append([spin_id1, spin_id2])

        # Store the spin data.
        spins.append([spin1, spin2])
        spin_selections.append([spin1.select, spin2.select])

    # Use the structural data to find connected atoms.
    elif hasattr(dp, 'structure'):
        # The selection objects.
        selection1 = cdp.structure.selection(atom_id=spin_id1)
        selection2 = cdp.structure.selection(atom_id=spin_id2)

        # Loop over the atoms of the first spin selection.
        for mol_name1, res_num1, res_name1, atom_num1, atom_name1, mol_index1, atom_index1 in dp.structure.atom_loop(selection=selection1, model_num=1, mol_name_flag=True, res_num_flag=True, res_name_flag=True, atom_num_flag=True, atom_name_flag=True, mol_index_flag=True, index_flag=True):
            # Generate the first spin ID.
            id1 = generate_spin_id_unique(pipe_cont=dp, mol_name=mol_name1, res_num=res_num1, res_name=res_name1, spin_num=atom_num1, spin_name=atom_name1)

            # Do the spin exist?
            spin1 = return_spin(spin_id=id1)
            if not spin1:
                continue

            # Loop over the atoms of the second spin selection.
            for mol_name2, res_num2, res_name2, atom_num2, atom_name2, mol_index2, atom_index2 in dp.structure.atom_loop(selection=selection2, model_num=1, mol_name_flag=True, res_num_flag=True, res_name_flag=True, atom_num_flag=True, atom_name_flag=True, mol_index_flag=True, index_flag=True):
                # Directly bonded atoms.
                if direct_bond:
                    # Different molecules.
                    if mol_name1 != mol_name2:
                        continue

                    # Skip non-bonded atom pairs.
                    if not dp.structure.are_bonded_index(mol_index1=mol_index1, atom_index1=atom_index1, mol_index2=mol_index2, atom_index2=atom_index2):
                        continue

                # Generate the second spin ID.
                id2 = generate_spin_id_unique(pipe_cont=dp, mol_name=mol_name2, res_num=res_num2, res_name=res_name2, spin_num=atom_num2, spin_name=atom_name2)

                # Do the spin exist?
                spin2 = return_spin(spin_id=id2)
                if not spin2:
                    continue

                # Store the IDs for the printout.
                ids.append([id1, id2])

                # Store the spin data.
                spins.append([spin1, spin2])
                spin_selections.append([spin1.select, spin2.select])

    # No structural data present or the spin IDs are not in the structural data, so use spin loops and some basic rules.
    if ids == []:
        for spin1, mol_name1, res_num1, res_name1, id1 in spin_loop(spin_id1, pipe=pipe, full_info=True, return_id=True):
            for spin2, mol_name2, res_num2, res_name2, id2 in spin_loop(spin_id2, pipe=pipe, full_info=True, return_id=True):
                # Directly bonded atoms.
                if direct_bond:
                    # Different molecules.
                    if mol_name1 != mol_name2:
                        continue

                    # No element info.
                    if not hasattr(spin1, 'element'):
                        raise RelaxError("The spin '%s' does not have the element type set." % id1)
                    if not hasattr(spin2, 'element'):
                        raise RelaxError("The spin '%s' does not have the element type set." % id2)

                    # Backbone NH and CH pairs.
                    pair = False
                    if (spin1.element == 'N' and spin2.element == 'H') or (spin2.element == 'N' and spin1.element == 'H'):
                        pair = True
                    elif (spin1.element == 'C' and spin2.element == 'H') or (spin2.element == 'C' and spin1.element == 'H'):
                        pair = True

                    # Same residue, so skip.
                    if pair and res_num1 != None and res_num1 != res_num2:
                        continue
                    elif pair and res_num1 == None and res_name1 != res_name2:
                        continue

                # Store the IDs for the printout.
                ids.append([id1, id2])

                # Store the spin data.
                spins.append([spin1, spin2])
                spin_selections.append([spin1.select, spin2.select])

    # No matches, so fail!
    if not len(ids):
        # Find the problem.
        count1 = 0
        count2 = 0
        for spin in spin_loop(spin_id1):
            count1 += 1
        for spin in spin_loop(spin_id2):
            count2 += 1

        # Report the problem.
        if count1 == 0 and count2 == 0:
            raise RelaxError("Neither spin IDs '%s' and '%s' match any spins." % (spin_id1, spin_id2))
        elif count1 == 0:
            raise RelaxError("The spin ID '%s' matches no spins." % spin_id1)
        elif count2 == 0:
            raise RelaxError("The spin ID '%s' matches no spins." % spin_id2)
        else:
            raise RelaxError("Unknown error.")

    # Define the interaction.
    for i in range(len(ids)):
        # Unpack.
        id1, id2 = ids[i]
        spin1, spin2 = spins[i]

        # Get the interatomic data object, if it exists.
        interatom = return_interatom(spin_hash1=spin1._hash, spin_hash2=spin2._hash, pipe=pipe)

        # Create the container if needed.
        if interatom == None:
            interatom = create_interatom(spin_id1=id1, spin_id2=id2, spin1=spins[i][0], spin2=spins[i][1], pipe=pipe)

        # Check that this has not already been set up.
        if interatom.dipole_pair:
            raise RelaxError("The magnetic dipole-dipole interaction already exists between the spins '%s' and '%s'." % (id1, id2))

        # Set a flag indicating that a dipole-dipole interaction is present.
        interatom.dipole_pair = True

        # Set the selection.
        if spin_selection:
            interatom.select = False
            if spin_selections[i][0] and spin_selections[i][1]:
                interatom.select = True

    # Printout.
    if verbose:
        # Conversion.
        for i in range(len(ids)):
            ids[i][0] = repr(ids[i][0])
            ids[i][1] = repr(ids[i][1])

        # The printout.
        print("Interatomic interactions are now defined for the following spins:\n")
        write_data(out=sys.stdout, headings=["Spin_ID_1", "Spin_ID_2"], data=ids)
Example #25
0
def get_pos(spin_id=None, str_id=None, ave_pos=False):
    """Load the spins from the structural object into the relax data store.

    @keyword spin_id:           The molecule, residue, and spin identifier string.
    @type spin_id:              str
    @keyword str_id:            The structure identifier.  This can be the file name, model number, or structure number.
    @type str_id:               int or str
    @keyword ave_pos:           A flag specifying if the average atom position or the atom position from all loaded structures is loaded into the SpinContainer.
    @type ave_pos:              bool
    """

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

    # Test if the structure exists.
    if not hasattr(cdp, 'structure') or not cdp.structure.num_models() or not cdp.structure.num_molecules():
        raise RelaxNoPdbError

    # Loop over all atoms of the spin_id selection.
    data = []
    for mol_name, res_num, res_name, atom_num, atom_name, element, pos in cdp.structure.atom_loop(atom_id=spin_id, str_id=str_id, mol_name_flag=True, res_num_flag=True, res_name_flag=True, atom_num_flag=True, atom_name_flag=True, element_flag=True, pos_flag=True, ave=ave_pos):
        # Remove the '+' regular expression character from the mol, res, and spin names!
        if mol_name and search('\+', mol_name):
            mol_name = mol_name.replace('+', '')
        if res_name and search('\+', res_name):
            res_name = res_name.replace('+', '')
        if atom_name and search('\+', atom_name):
            atom_name = atom_name.replace('+', '')

        # The spin identification string.
        id = generate_spin_id_unique(res_num=res_num, res_name=None, spin_num=atom_num, spin_name=atom_name)

        # Get the spin container.
        spin_cont = return_spin(id)

        # Skip the spin if it doesn't exist.
        if spin_cont == None:
            continue

        # Add the position vector to the spin container.
        spin_cont.pos = pos

        # Store the data for a printout at the end.
        data.append([id, repr(pos)])

    # No positions found.
    if not len(data):
        raise RelaxError("No positional information matching the spin ID '%s' could be found." % spin_id)

    # Update pseudo-atoms.
    for spin in spin_loop():
        if hasattr(spin, 'members'):
            # Get the spin positions.
            positions = []
            for atom in spin.members:
                # Get the spin container.
                subspin = return_spin(atom)

                # Test that the spin exists.
                if subspin == None:
                    raise RelaxNoSpinError(atom)

                # Test the position.
                if not hasattr(subspin, 'pos') or subspin.pos == None or not len(subspin.pos):
                    raise RelaxError("Positional information is not available for the atom '%s'." % atom)

                # Alias the position.
                pos = subspin.pos

                # Convert to a list of lists if not already.
                multi_model = True
                if type(pos[0]) in [float, float64]:
                    multi_model = False
                    pos = [pos]

                # Store the position.
                positions.append([])
                for i in range(len(pos)):
                    positions[-1].append(pos[i].tolist())

            # The averaging.
            if spin.averaging == 'linear':
                # Average pos.
                ave = linear_ave(positions)

                # Convert to the correct structure.
                if multi_model:
                    spin.pos = ave
                else:
                    spin.pos = ave[0]

    # Print out.
    write_data(out=sys.stdout, headings=["Spin_ID", "Position"], data=data)
Example #26
0
def bmrb_read(star, sample_conditions=None):
    """Read the relaxation data from the NMR-STAR dictionary object.

    @param star:                The NMR-STAR dictionary object.
    @type star:                 NMR_STAR instance
    @keyword sample_conditions: The sample condition label to read.  Only one sample condition can be read per data pipe.
    @type sample_conditions:    None or str
    """

    # Get the relaxation data.
    for data in star.relaxation.loop():
        # Sample conditions do not match (remove the $ sign).
        if 'sample_cond_list_label' in data and sample_conditions and data[
                'sample_cond_list_label'].replace('$',
                                                  '') != sample_conditions:
            continue

        # Create the labels.
        ri_type = data['data_type']
        frq = float(data['frq']) * 1e6

        # Round the label to the nearest factor of 10.
        frq_label = create_frq_label(float(data['frq']) * 1e6)

        # The ID string.
        ri_id = "%s_%s" % (ri_type, frq_label)

        # The number of spins.
        N = bmrb.num_spins(data)

        # No data in the saveframe.
        if N == 0:
            continue

        # The molecule names.
        mol_names = bmrb.molecule_names(data, N)

        # Generate the sequence if needed.
        bmrb.generate_sequence(N,
                               spin_names=data['atom_names'],
                               res_nums=data['res_nums'],
                               res_names=data['res_names'],
                               mol_names=mol_names,
                               isotopes=data['isotope'],
                               elements=data['atom_types'])

        # The attached protons.
        if 'atom_names_2' in data:
            # Generate the proton spins.
            bmrb.generate_sequence(N,
                                   spin_names=data['atom_names_2'],
                                   res_nums=data['res_nums'],
                                   res_names=data['res_names'],
                                   mol_names=mol_names,
                                   isotopes=data['isotope_2'],
                                   elements=data['atom_types_2'])

            # Define the dipolar interaction.
            for i in range(len(data['atom_names'])):
                # The spin IDs.
                spin_id1 = generate_spin_id_unique(
                    spin_name=data['atom_names'][i],
                    res_num=data['res_nums'][i],
                    res_name=data['res_names'][i],
                    mol_name=mol_names[i])
                spin_id2 = generate_spin_id_unique(
                    spin_name=data['atom_names_2'][i],
                    res_num=data['res_nums'][i],
                    res_name=data['res_names'][i],
                    mol_name=mol_names[i])

                # Check if the container exists.
                spin1 = return_spin(spin_id=spin_id1)
                spin2 = return_spin(spin_id=spin_id2)
                if return_interatom(spin_hash1=spin1._hash,
                                    spin_hash2=spin2._hash):
                    continue

                # Define.
                define_dipole_pair(spin_id1=spin_id1,
                                   spin_id2=spin_id2,
                                   spin1=spin1,
                                   spin2=spin2,
                                   verbose=False)

        # The data and error.
        vals = data['data']
        errors = data['errors']
        if vals == None:
            vals = [None] * N
        if errors == None:
            errors = [None] * N

        # Data transformation.
        if vals != None and 'units' in data:
            # Scaling.
            if data['units'] == 'ms':
                # Loop over the data.
                for i in range(N):
                    # The value.
                    if vals[i] != None:
                        vals[i] = vals[i] / 1000

                    # The error.
                    if errors[i] != None:
                        errors[i] = errors[i] / 1000

            # Invert.
            if data['units'] in ['s', 'ms']:
                # Loop over the data.
                for i in range(len(vals)):
                    # The value.
                    if vals[i] != None:
                        vals[i] = 1.0 / vals[i]

                    # The error.
                    if vals[i] != None and errors[i] != None:
                        errors[i] = errors[i] * vals[i]**2

        # Pack the data.
        pack_data(ri_id,
                  ri_type,
                  frq,
                  vals,
                  errors,
                  mol_names=mol_names,
                  res_nums=data['res_nums'],
                  res_names=data['res_names'],
                  spin_nums=None,
                  spin_names=data['atom_names'],
                  gen_seq=True,
                  verbose=False)

        # Store the temperature calibration and control.
        if data['temp_calibration']:
            temp_calibration(ri_id=ri_id, method=data['temp_calibration'])
        if data['temp_control']:
            temp_control(ri_id=ri_id, method=data['temp_control'])

        # Peak intensity type.
        if data['peak_intensity_type']:
            peak_intensity_type(ri_id=ri_id, type=data['peak_intensity_type'])
Example #27
0
def load_spins(spin_id=None, str_id=None, mol_name_target=None, ave_pos=False):
    """Load the spins from the structural object into the relax data store.

    @keyword spin_id:           The molecule, residue, and spin identifier string.
    @type spin_id:              str
    @keyword str_id:            The structure identifier.  This can be the file name, model number, or structure number.
    @type str_id:               int or str
    @keyword mol_name:          The name of target molecule container, overriding the name of the loaded structures
    @type mol_name:             str or None
    @keyword ave_pos:           A flag specifying if the average atom position or the atom position from all loaded structures is loaded into the SpinContainer.
    @type ave_pos:              bool
    """

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

    # Test if the structure exists.
    if not hasattr(cdp, 'structure') or not cdp.structure.num_models() or not cdp.structure.num_molecules():
        raise RelaxNoPdbError

    # Print out.
    print("Adding the following spins to the relax data store.\n")

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

    # Loop over all atoms of the spin_id selection.
    for mol_name, res_num, res_name, atom_num, atom_name, element, pos in cdp.structure.atom_loop(atom_id=spin_id, str_id=str_id, mol_name_flag=True, res_num_flag=True, res_name_flag=True, atom_num_flag=True, atom_name_flag=True, element_flag=True, pos_flag=True, ave=ave_pos):
        # Override the molecule name.
        if mol_name_target:
            mol_name = mol_name_target

        # Remove the '+' regular expression character from the mol, res, and spin names!
        if mol_name and search('\+', mol_name):
            mol_name = mol_name.replace('+', '')
        if res_name and search('\+', res_name):
            res_name = res_name.replace('+', '')
        if atom_name and search('\+', atom_name):
            atom_name = atom_name.replace('+', '')

        # Generate a spin ID for the current atom.
        id = generate_spin_id_unique(mol_name=mol_name, res_num=res_num, res_name=res_name, spin_num=atom_num, spin_name=atom_name)

        # Create the spin.
        try:
            spin_cont = create_spin(mol_name=mol_name, res_num=res_num, res_name=res_name, spin_num=atom_num, spin_name=atom_name)

        # Otherwise, get the spin container.
        except RelaxError:
            spin_cont = return_spin(id)

        # Append all the spin ID info for printing later.
        if mol_name_target:
            mol_names.append(mol_name_target)
        else:
            mol_names.append(mol_name)
        res_nums.append(res_num)
        res_names.append(res_name)
        spin_nums.append(atom_num)
        spin_names.append(atom_name)

        # Position vector.
        spin_cont.pos = pos

        # Add the element.
        spin_cont.element = element

    # Catch no data.
    if len(mol_names) == 0:
        warn(RelaxWarning("No spins matching the '%s' ID string could be found." % spin_id))
        return

    # Print out.
    write_spin_data(file=sys.stdout, mol_names=mol_names, res_nums=res_nums, res_names=res_names, spin_nums=spin_nums, spin_names=spin_names)
Example #28
0
def desel_read(file=None, dir=None, file_data=None, spin_id_col=None, mol_name_col=None, res_num_col=None, res_name_col=None, spin_num_col=None, spin_name_col=None, sep=None, spin_id=None, boolean='AND', change_all=False):
    """Deselect the spins contained in the given file.

    @keyword file:                  The name of the file to open.
    @type file:                     str
    @keyword dir:                   The directory containing the file (defaults to the current
                                    directory if None).
    @type dir:                      str or None
    @keyword file_data:             An alternative opening a file, if the data already exists in the
                                    correct format.  The format is a list of lists where the first
                                    index corresponds to the row and the second the column.
    @type file_data:                list of lists
    @keyword spin_id_col:           The column containing the spin ID strings.  If supplied, the
                                    mol_name_col, res_name_col, res_num_col, spin_name_col, and
                                    spin_num_col arguments must be none.
    @type spin_id_col:              int or None
    @keyword mol_name_col:          The column containing the molecule name information.  If
                                    supplied, spin_id_col must be None.
    @type mol_name_col:             int or None
    @keyword res_name_col:          The column containing the residue name information.  If
                                    supplied, spin_id_col must be None.
    @type res_name_col:             int or None
    @keyword res_num_col:           The column containing the residue number information.  If
                                    supplied, spin_id_col must be None.
    @type res_num_col:              int or None
    @keyword spin_name_col:         The column containing the spin name information.  If supplied,
                                    spin_id_col must be None.
    @type spin_name_col:            int or None
    @keyword spin_num_col:          The column containing the spin number information.  If supplied,
                                    spin_id_col must be None.
    @type spin_num_col:             int or None
    @keyword sep:                   The column separator which, if None, defaults to whitespace.
    @type sep:                      str or None
    @keyword spin_id:               The spin ID string used to restrict data loading to a subset of
                                    all spins.
    @type spin_id:                  None or str
    @param boolean:                 The boolean operator used to deselect 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 selected.  Only the boolean operator 'AND' is
                                    compatible with this flag set to True (all others will be
                                    ignored).
    @type change_all:               bool
    @raises RelaxNoSequenceError:   If no molecule/residue/spins sequence data exists.
    @raises RelaxError:             If the boolean operator is unknown.
    """

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

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

    # First select all spins if the change_all flag is set.
    if change_all:
        for spin in spin_loop():
            spin.select = True

    # Then deselect the spins in the file.
    ids = []
    for mol_name, res_num, res_name, spin_num, spin_name in read_spin_data(file=file, dir=dir, file_data=file_data, spin_id_col=spin_id_col, mol_name_col=mol_name_col, res_num_col=res_num_col, res_name_col=res_name_col, spin_num_col=spin_num_col, spin_name_col=spin_name_col, sep=sep, spin_id=spin_id):
        # Get the corresponding spin container.
        id = generate_spin_id_unique(mol_name=mol_name, res_num=res_num, res_name=res_name, spin_num=spin_num, spin_name=spin_name)
        spin = return_spin(id)

        # No spin.
        if spin == None:
            warn(RelaxNoSpinWarning(id))
            continue

        # Deselect the spin.
        if change_all:
            spin.select = False

        # Boolean selections.
        else:
            spin.select = boolean_deselect(current=spin.select, boolean=boolean)

        # Store the spin ID for printouts.
        if not spin.select:
            ids.append(id)

    # Printout.
    if not len(ids):
        print("No spins deselected.")
    else:
        print("The following spins were deselected:")
        for id in ids:
            print(id)
Example #29
0
def read(file=None, dir=None, spin_id_col=None, mol_name_col=None, res_num_col=None, res_name_col=None, spin_num_col=None, spin_name_col=None, sep=None, spin_id=None, verbose=True):
    """Read the peak intensity data.

    @keyword file:          The name of the file containing the peak intensities.
    @type file:             str
    @keyword dir:           The directory where the file is located.
    @type dir:              str
    @keyword spin_id_col:   The column containing the spin ID strings (used by the generic intensity file format).  If supplied, the mol_name_col, res_name_col, res_num_col, spin_name_col, and spin_num_col arguments must be none.
    @type spin_id_col:      int or None
    @keyword mol_name_col:  The column containing the molecule name information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type mol_name_col:     int or None
    @keyword res_name_col:  The column containing the residue name information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type res_name_col:     int or None
    @keyword res_num_col:   The column containing the residue number information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type res_num_col:      int or None
    @keyword spin_name_col: The column containing the spin name information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type spin_name_col:    int or None
    @keyword spin_num_col:  The column containing the spin number information (used by the generic intensity file format).  If supplied, spin_id_col must be None.
    @type spin_num_col:     int or None
    @keyword sep:           The column separator which, if None, defaults to whitespace.
    @type sep:              str or None
    @keyword spin_id:       The spin ID string used to restrict data loading to a subset of all spins.  If 'auto' is provided for a NMRPipe seriesTab formatted file, the ID's are auto generated in form of Z_Ai.
    @type spin_id:          None or str
    @keyword verbose:       A flag which if True will cause all chemical shift data loaded to be printed out.
    @type verbose:          bool
    """

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

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

    # Check the file name.
    if file == None:
        raise RelaxError("The file name must be supplied.")

    # Read the peak list data.
    peak_list = read_peak_list(file=file, dir=dir, spin_id_col=spin_id_col, mol_name_col=mol_name_col, res_num_col=res_num_col, res_name_col=res_name_col, spin_num_col=spin_num_col, spin_name_col=spin_name_col, sep=sep, spin_id=spin_id)

    # Loop over the assignments.
    data = []
    data_flag = False
    for assign in peak_list:
        # Loop over the dimensions of the peak list.
        for i in range(peak_list.dimensionality):
            # Generate the spin_id.
            spin_id = generate_spin_id_unique(res_num=assign.res_nums[i], spin_name=assign.spin_names[i])

            # Get the spin container.
            spin = return_spin(spin_id=spin_id)
            if not spin:
                warn(RelaxNoSpinWarning(spin_id))
                continue

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

            # Store the shift.
            spin.chemical_shift = assign.shifts[i]

            # Switch the flag.
            data_flag = True

            # Append the data for printing out.
            data.append([spin_id, repr(spin.chemical_shift)])

    # No data.
    if not data_flag:
        raise RelaxError("No chemical shifts could be loaded from the peak list")

    # Print out.
    if verbose:
        print("\nThe following chemical shifts have been loaded into the relax data store:\n")
        write_data(out=sys.stdout, headings=["Spin_ID", "Chemical shift"], data=data)