Ejemplo n.º 1
0
Archivo: api.py Proyecto: tlinnet/relax
    def get_param_names(self, model_info=None):
        """Return a vector of parameter names.

        @keyword model_info:    The model information from model_loop().  This is unused.
        @type model_info:       None
        @return:                The vector of parameter names.
        @rtype:                 list of str
        """

        # Init.
        param_names = []

        # A RDC or PCS data type requires the alignment tensors to be at the start of the parameter vector (unless the tensors are fixed).
        if opt_uses_align_data():
            for i in range(len(cdp.align_tensors)):
                # Skip non-optimised tensors.
                if not opt_uses_tensor(cdp.align_tensors[i]):
                    continue

                # Add the parameters.
                param_names += ['Axx', 'Ayy', 'Axy', 'Axz', 'Ayz']

        # Populations.
        if cdp.model in ['2-domain', 'population']:
            for i in range(cdp.N - 1):
                param_names.append('probs')

        # The Euler angles.
        if cdp.model == '2-domain':
            for i in range(cdp.N):
                param_names.append('alpha')
                param_names.append('beta')
                param_names.append('gamma')

        # The paramagnetic centre.
        if hasattr(cdp,
                   'paramag_centre_fixed') and not cdp.paramag_centre_fixed:
            for i in range(3):
                param_names.append('paramagnetic_centre')

        # Return the list.
        return param_names
Ejemplo n.º 2
0
    def get_param_names(self, model_info=None):
        """Return a vector of parameter names.

        @keyword model_info:    The model information from model_loop().  This is unused.
        @type model_info:       None
        @return:                The vector of parameter names.
        @rtype:                 list of str
        """

        # Init.
        param_names = []

        # A RDC or PCS data type requires the alignment tensors to be at the start of the parameter vector (unless the tensors are fixed).
        if opt_uses_align_data():
            for i in range(len(cdp.align_tensors)):
                # Skip non-optimised tensors.
                if not opt_uses_tensor(cdp.align_tensors[i]):
                    continue

                # Add the parameters.
                param_names += ['Axx', 'Ayy', 'Axy', 'Axz', 'Ayz']

        # Populations.
        if cdp.model in ['2-domain', 'population']:
            for i in range(cdp.N - 1):
                param_names.append('probs')

        # The Euler angles.
        if cdp.model == '2-domain':
            for i in range(cdp.N):
                param_names.append('alpha')
                param_names.append('beta')
                param_names.append('gamma')

        # The paramagnetic centre.
        if hasattr(cdp, 'paramag_centre_fixed') and not cdp.paramag_centre_fixed:
            for i in range(3):
                param_names.append('paramagnetic_centre')

        # Return the list.
        return param_names
Ejemplo n.º 3
0
def minimise_setup_fixed_tensors():
    """Set up the data structures for the fixed alignment tensors.

    @return:            The assembled data structures for the fixed alignment tensors.
    @rtype:             numpy rank-1 array.
    """

    # Initialise.
    n = align_tensor.num_tensors(skip_fixed=False) - align_tensor.num_tensors(
        skip_fixed=True)
    tensors = zeros(n * 5, float64)

    # Nothing to do.
    if n == 0:
        return None

    # Loop over the tensors.
    index = 0
    for i in range(len(cdp.align_tensors)):
        # Skip non-optimised data.
        if not opt_uses_align_data(cdp.align_tensors[i].name):
            continue

        # No parameters have been set.
        if not hasattr(cdp.align_tensors[i], 'Axx'):
            continue

        # The real tensors.
        tensors[5 * index + 0] = cdp.align_tensors[i].Axx
        tensors[5 * index + 1] = cdp.align_tensors[i].Ayy
        tensors[5 * index + 2] = cdp.align_tensors[i].Axy
        tensors[5 * index + 3] = cdp.align_tensors[i].Axz
        tensors[5 * index + 4] = cdp.align_tensors[i].Ayz

        # Increment the index.
        index += 1

    # Return the data structure.
    return tensors
Ejemplo n.º 4
0
def minimise_setup_fixed_tensors():
    """Set up the data structures for the fixed alignment tensors.

    @return:            The assembled data structures for the fixed alignment tensors.
    @rtype:             numpy rank-1 array.
    """

    # Initialise.
    n = align_tensor.num_tensors(skip_fixed=False) - align_tensor.num_tensors(skip_fixed=True)
    tensors = zeros(n*5, float64)

    # Nothing to do.
    if n == 0:
        return None

    # Loop over the tensors.
    index = 0
    for i in range(len(cdp.align_tensors)):
        # Skip non-optimised data.
        if not opt_uses_align_data(cdp.align_tensors[i].name):
            continue

        # No parameters have been set.
        if not hasattr(cdp.align_tensors[i], 'Axx'):
            continue

        # The real tensors.
        tensors[5*index + 0] = cdp.align_tensors[i].Axx
        tensors[5*index + 1] = cdp.align_tensors[i].Ayy
        tensors[5*index + 2] = cdp.align_tensors[i].Axy
        tensors[5*index + 3] = cdp.align_tensors[i].Axz
        tensors[5*index + 4] = cdp.align_tensors[i].Ayz

        # Increment the index.
        index += 1

    # Return the data structure.
    return tensors
Ejemplo n.º 5
0
def target_fn_setup(sim_index=None, scaling_matrix=None, verbosity=0):
    """Initialise the target function for optimisation or direct calculation.

    @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 scaling_matrix:    The diagonal and square scaling matrix.
    @type scaling_matrix:       numpy rank-2, float64 array or None
    @keyword verbosity:         A flag specifying the amount of information to print.  The higher the value, the greater the verbosity.
    @type verbosity:            int
    """

    # Test if the N-state model has been set up.
    if not hasattr(cdp, 'model'):
        raise RelaxNoModelError('N-state')

    # '2-domain' model setup tests.
    if cdp.model == '2-domain':
        # The number of states.
        if not hasattr(cdp, 'N'):
            raise RelaxError("The number of states has not been set.")

        # The reference domain.
        if not hasattr(cdp, 'ref_domain'):
            raise RelaxError("The reference domain has not been set.")

    # Update the model parameters if necessary.
    update_model()

    # Create the initial parameter vector.
    param_vector = assemble_param_vector(sim_index=sim_index)

    # Replace all NaNs with 0.0.
    fix_invalid(param_vector, copy=False, fill_value=0.0)

    # Determine if alignment tensors or RDCs are to be used.
    data_types = base_data_types()

    # The probabilities.
    probs = None
    if hasattr(cdp, 'probs') and len(cdp.probs) and cdp.probs[0] != None:
        probs = cdp.probs

    # Diagonal scaling.
    if len(param_vector) and scaling_matrix is not None:
        param_vector = dot(inv(scaling_matrix), param_vector)

    # Get the data structures for optimisation using the tensors as base data sets.
    full_tensors, red_tensor_elem, red_tensor_err, full_in_ref_frame = None, None, None, None
    if 'tensor' in data_types:
        full_tensors, red_tensor_elem, red_tensor_err, full_in_ref_frame = minimise_setup_tensors(sim_index=sim_index)

    # Get the data structures for optimisation using PCSs as base data sets.
    pcs, pcs_err, pcs_weight, temp, frq, pcs_pseudo_flags = None, None, None, None, None, None
    if 'pcs' in data_types:
        pcs, pcs_err, pcs_weight, temp, frq, pcs_pseudo_flags = return_pcs_data(sim_index=sim_index, verbosity=verbosity)

    # Get the data structures for optimisation using RDCs as base data sets.
    rdcs, rdc_err, rdc_weight, rdc_vector, rdc_dj, absolute_rdc, T_flags, j_couplings, rdc_pseudo_flags = None, None, None, None, None, None, None, None, None
    if 'rdc' in data_types:
        # The data.
        rdcs, rdc_err, rdc_weight, rdc_vector, rdc_dj, absolute_rdc, T_flags, j_couplings, rdc_pseudo_flags = return_rdc_data(sim_index=sim_index, verbosity=verbosity)

    # Get the fixed tensors.
    fixed_tensors = None
    if 'rdc' in data_types or 'pcs' in data_types:
        full_tensors = minimise_setup_fixed_tensors()

        # The flag list.
        fixed_tensors = []
        for i in range(len(cdp.align_tensors)):
            # Skip non-optimised data.
            if not opt_uses_align_data(cdp.align_tensors[i].name):
                continue

            if cdp.align_tensors[i].fixed:
                fixed_tensors.append(True)
            else:
                fixed_tensors.append(False)

    # Get the atomic_positions.
    atomic_pos, paramag_centre, centre_fixed = None, None, True
    if 'pcs' in data_types or 'pre' in data_types:
        atomic_pos, paramag_centre = minimise_setup_atomic_pos(sim_index=sim_index)

        # Optimisation of the centre.
        if hasattr(cdp, 'paramag_centre_fixed'):
            centre_fixed = cdp.paramag_centre_fixed

    # Set up the class instance containing the target function.
    model = N_state_opt(model=cdp.model, N=cdp.N, init_params=param_vector, probs=probs, full_tensors=full_tensors, red_data=red_tensor_elem, red_errors=red_tensor_err, full_in_ref_frame=full_in_ref_frame, fixed_tensors=fixed_tensors, pcs=pcs, rdcs=rdcs, pcs_errors=pcs_err, rdc_errors=rdc_err, T_flags=T_flags, j_couplings=j_couplings, rdc_pseudo_flags=rdc_pseudo_flags, pcs_pseudo_flags=pcs_pseudo_flags, pcs_weights=pcs_weight, rdc_weights=rdc_weight, rdc_vect=rdc_vector, temp=temp, frq=frq, dip_const=rdc_dj, absolute_rdc=absolute_rdc, atomic_pos=atomic_pos, paramag_centre=paramag_centre, scaling_matrix=scaling_matrix, centre_fixed=centre_fixed)

    # Return the data.
    return model, param_vector, data_types
Ejemplo n.º 6
0
def target_fn_setup(sim_index=None, scaling_matrix=None, verbosity=0):
    """Initialise the target function for optimisation or direct calculation.

    @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 scaling_matrix:    The diagonal and square scaling matrix.
    @type scaling_matrix:       numpy rank-2, float64 array or None
    @keyword verbosity:         A flag specifying the amount of information to print.  The higher the value, the greater the verbosity.
    @type verbosity:            int
    """

    # Test if the N-state model has been set up.
    if not hasattr(cdp, 'model'):
        raise RelaxNoModelError('N-state')

    # '2-domain' model setup tests.
    if cdp.model == '2-domain':
        # The number of states.
        if not hasattr(cdp, 'N'):
            raise RelaxError("The number of states has not been set.")

        # The reference domain.
        if not hasattr(cdp, 'ref_domain'):
            raise RelaxError("The reference domain has not been set.")

    # Update the model parameters if necessary.
    update_model()

    # Create the initial parameter vector.
    param_vector = assemble_param_vector(sim_index=sim_index)

    # Replace all NaNs with 0.0.
    fix_invalid(param_vector, copy=False, fill_value=0.0)

    # Determine if alignment tensors or RDCs are to be used.
    data_types = base_data_types()

    # The probabilities.
    probs = None
    if hasattr(cdp, 'probs') and len(cdp.probs) and cdp.probs[0] != None:
        probs = cdp.probs

    # Diagonal scaling.
    if len(param_vector) and scaling_matrix is not None:
        param_vector = dot(inv(scaling_matrix), param_vector)

    # Get the data structures for optimisation using the tensors as base data sets.
    full_tensors, red_tensor_elem, red_tensor_err, full_in_ref_frame = None, None, None, None
    if 'tensor' in data_types:
        full_tensors, red_tensor_elem, red_tensor_err, full_in_ref_frame = minimise_setup_tensors(
            sim_index=sim_index)

    # Get the data structures for optimisation using PCSs as base data sets.
    pcs, pcs_err, pcs_weight, temp, frq, pcs_pseudo_flags = None, None, None, None, None, None
    if 'pcs' in data_types:
        pcs, pcs_err, pcs_weight, temp, frq, pcs_pseudo_flags = return_pcs_data(
            sim_index=sim_index, verbosity=verbosity)

    # Get the data structures for optimisation using RDCs as base data sets.
    rdcs, rdc_err, rdc_weight, rdc_vector, rdc_dj, absolute_rdc, T_flags, j_couplings, rdc_pseudo_flags = None, None, None, None, None, None, None, None, None
    if 'rdc' in data_types:
        # The data.
        rdcs, rdc_err, rdc_weight, rdc_vector, rdc_dj, absolute_rdc, T_flags, j_couplings, rdc_pseudo_flags = return_rdc_data(
            sim_index=sim_index, verbosity=verbosity)

    # Get the fixed tensors.
    fixed_tensors = None
    if 'rdc' in data_types or 'pcs' in data_types:
        full_tensors = minimise_setup_fixed_tensors()

        # The flag list.
        fixed_tensors = []
        for i in range(len(cdp.align_tensors)):
            # Skip non-optimised data.
            if not opt_uses_align_data(cdp.align_tensors[i].name):
                continue

            if cdp.align_tensors[i].fixed:
                fixed_tensors.append(True)
            else:
                fixed_tensors.append(False)

    # Get the atomic_positions.
    atomic_pos, paramag_centre, centre_fixed = None, None, True
    if 'pcs' in data_types or 'pre' in data_types:
        atomic_pos, paramag_centre = minimise_setup_atomic_pos(
            sim_index=sim_index)

        # Optimisation of the centre.
        if hasattr(cdp, 'paramag_centre_fixed'):
            centre_fixed = cdp.paramag_centre_fixed

    # Set up the class instance containing the target function.
    model = N_state_opt(model=cdp.model,
                        N=cdp.N,
                        init_params=param_vector,
                        probs=probs,
                        full_tensors=full_tensors,
                        red_data=red_tensor_elem,
                        red_errors=red_tensor_err,
                        full_in_ref_frame=full_in_ref_frame,
                        fixed_tensors=fixed_tensors,
                        pcs=pcs,
                        rdcs=rdcs,
                        pcs_errors=pcs_err,
                        rdc_errors=rdc_err,
                        T_flags=T_flags,
                        j_couplings=j_couplings,
                        rdc_pseudo_flags=rdc_pseudo_flags,
                        pcs_pseudo_flags=pcs_pseudo_flags,
                        pcs_weights=pcs_weight,
                        rdc_weights=rdc_weight,
                        rdc_vect=rdc_vector,
                        temp=temp,
                        frq=frq,
                        dip_const=rdc_dj,
                        absolute_rdc=absolute_rdc,
                        atomic_pos=atomic_pos,
                        paramag_centre=paramag_centre,
                        scaling_matrix=scaling_matrix,
                        centre_fixed=centre_fixed)

    # Return the data.
    return model, param_vector, data_types
Ejemplo n.º 7
0
def return_rdc_data(sim_index=None):
    """Set up the data structures for optimisation using RDCs as base data sets.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            # Defaults of None.
            value = None
            error = None

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

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

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

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

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

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

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

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

    # Return the data structures.
    return rdc, rdc_err, rdc_weight, unit_vect, rdc_const, absolute, T_flags, j_couplings, pseudo_flags
Ejemplo n.º 8
0
def assemble_param_vector(sim_index=None):
    """Assemble all the parameters of the model into a single array.

    @param sim_index:       The index of the simulation to optimise.  This should be None if normal optimisation is desired.
    @type sim_index:        None or int
    @return:                The parameter vector used for optimisation.
    @rtype:                 numpy array
    """

    # Test if the model is selected.
    if not hasattr(cdp, 'model') or not isinstance(cdp.model, str):
        raise RelaxNoModelError

    # Determine the data type.
    data_types = base_data_types()

    # Initialise the parameter vector.
    param_vector = []

    # A RDC or PCS data type requires the alignment tensors to be at the start of the parameter vector (unless the tensors are fixed).
    if opt_uses_align_data():
        for i in range(len(cdp.align_tensors)):
            # Skip non-optimised tensors.
            if not opt_uses_tensor(cdp.align_tensors[i]):
                continue

            # No values set.
            if not hasattr(cdp.align_tensors[i], 'A_5D'):
                param_vector += [None, None, None, None, None]

            # Otherwise add the parameters.
            else:
                param_vector += list(cdp.align_tensors[i].A_5D)

    # Monte Carlo simulation data structures.
    if sim_index != None:
        # Populations.
        if cdp.model in ['2-domain', 'population']:
            probs = cdp.probs_sim[sim_index]

        # Euler angles.
        if cdp.model == '2-domain':
            alpha = cdp.alpha_sim[sim_index]
            beta = cdp.beta_sim[sim_index]
            gamma = cdp.gamma_sim[sim_index]

    # Normal data structures.
    else:
        # Populations.
        if cdp.model in ['2-domain', 'population']:
            probs = cdp.probs

        # Euler angles.
        if cdp.model == '2-domain':
            alpha = cdp.alpha
            beta = cdp.beta
            gamma = cdp.gamma

    # The probabilities (exclude that of state N).
    if cdp.model in ['2-domain', 'population']:
        param_vector = param_vector + probs[0:-1]

    # The Euler angles.
    if cdp.model == '2-domain':
        for i in range(cdp.N):
            param_vector.append(alpha[i])
            param_vector.append(beta[i])
            param_vector.append(gamma[i])

    # The paramagnetic centre.
    if hasattr(cdp, 'paramag_centre_fixed') and not cdp.paramag_centre_fixed:
        if not hasattr(cdp, 'paramagnetic_centre'):
            for i in range(3):
                param_vector.append(None)
        elif sim_index != None:
            if cdp.paramagnetic_centre_sim[sim_index] is None:
                for i in range(3):
                    param_vector.append(None)
            else:
                for i in range(3):
                    param_vector.append(
                        cdp.paramagnetic_centre_sim[sim_index][i])
        else:
            for i in range(3):
                param_vector.append(cdp.paramagnetic_centre[i])

    # Return a numpy arrary.
    return array(param_vector, float64)
Ejemplo n.º 9
0
def return_pcs_data(sim_index=None, verbosity=0):
    """Set up the data structures for optimisation using PCSs as base data sets.

    @keyword sim_index: The index of the simulation to optimise.  This should be None if normal optimisation is desired.
    @type sim_index:    None or int
    @keyword verbosity: A flag specifying the amount of information to print.  The higher the value, the greater the verbosity.
    @type verbosity:    int
    @return:            The assembled data structures for using PCSs as the base data for optimisation.  These include:
                            - the PCS values.
                            - the unit vectors connecting the paramagnetic centre (the electron spin) to the spin.
                            - the PCS weight.
                            - the experimental temperatures.
                            - the spectrometer frequencies.
                            - pseudo_flags, the list of flags indicating if the interatomic data contains a pseudo-atom (as 1's and 0's).
    @rtype:             tuple of (numpy rank-2 float64 array, numpy rank-2 float64 array, numpy rank-2 float64 array, list of float, list of float, numpy rank-1 int32 array)
    """

    # Initial printout.
    if verbosity:
        print("\nPCS data counts:")

    # Data setup tests.
    if not hasattr(cdp, 'paramagnetic_centre') and (hasattr(cdp, 'paramag_centre_fixed') and cdp.paramag_centre_fixed):
        raise RelaxError("The paramagnetic centre has not yet been specified.")
    if not hasattr(cdp, 'temperature'):
        raise RelaxError("The experimental temperatures have not been set.")
    if not hasattr(cdp, 'spectrometer_frq'):
        raise RelaxError("The spectrometer frequencies of the experiments have not been set.")

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

    # Initialise.
    pcs = []
    pcs_err = []
    pcs_weight = []
    temp = []
    frq = []
    pseudo_flags = []

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

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

        # Append empty arrays to the PCS structures.
        pcs.append([])
        pcs_err.append([])
        pcs_weight.append([])

        # Get the temperature for the PCS constant.
        if align_id in cdp.temperature:
            temp.append(cdp.temperature[align_id])

        # The temperature must be given!
        else:
            raise RelaxError("The experimental temperature for the alignment ID '%s' has not been set." % align_id)

        # Get the spectrometer frequency in Tesla units for the PCS constant.
        if align_id in cdp.spectrometer_frq:
            frq.append(cdp.spectrometer_frq[align_id] * 2.0 * pi / periodic_table.gyromagnetic_ratio('1H'))

        # The frequency must be given!
        else:
            raise RelaxError("The spectrometer frequency for the alignment ID '%s' has not been set." % align_id)

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

            # Skip spins without PCS data.
            if not hasattr(spin, 'pcs'):
                continue

            # Append the PCSs to the list.
            if align_id in spin.pcs:
                if sim_index != None:
                    pcs[-1].append(spin.pcs_sim[align_id][sim_index])
                else:
                    pcs[-1].append(spin.pcs[align_id])

                # Increment the PCS count.
                if pcs[-1][-1] != None:
                    j += 1

            # No data.
            else:
                pcs[-1].append(None)

            # Append the PCS errors.
            if hasattr(spin, 'pcs_err') and align_id in spin.pcs_err:
                pcs_err[-1].append(spin.pcs_err[align_id])
            else:
                pcs_err[-1].append(None)

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

        # ID and PCS count printout.
        if verbosity:
            print("    Alignment ID '%s':  %i" % (align_id, j))

    # Pseudo-atom.
    for spin in spin_loop():
        if is_pseudoatom(spin):
            pseudo_flags.append(1)
        else:
            pseudo_flags.append(0)

    # Convert to numpy objects.
    pcs = array(pcs, float64)
    pcs_err = array(pcs_err, float64)
    pcs_weight = array(pcs_weight, float64)
    pseudo_flags = array(pseudo_flags, int32)

    # Convert the PCS from ppm to no units.
    pcs = pcs * 1e-6
    pcs_err = pcs_err * 1e-6

    # Return the data structures.
    return pcs, pcs_err, pcs_weight, temp, frq, pseudo_flags
Ejemplo n.º 10
0
def assemble_param_vector(sim_index=None):
    """Assemble all the parameters of the model into a single array.

    @param sim_index:       The index of the simulation to optimise.  This should be None if normal optimisation is desired.
    @type sim_index:        None or int
    @return:                The parameter vector used for optimisation.
    @rtype:                 numpy array
    """

    # Test if the model is selected.
    if not hasattr(cdp, 'model') or not isinstance(cdp.model, str):
        raise RelaxNoModelError

    # Determine the data type.
    data_types = base_data_types()

    # Initialise the parameter vector.
    param_vector = []

    # A RDC or PCS data type requires the alignment tensors to be at the start of the parameter vector (unless the tensors are fixed).
    if opt_uses_align_data():
        for i in range(len(cdp.align_tensors)):
            # Skip non-optimised tensors.
            if not opt_uses_tensor(cdp.align_tensors[i]):
                continue

            # Add the parameters.
            param_vector = param_vector + list(cdp.align_tensors[i].A_5D)

    # Monte Carlo simulation data structures.
    if sim_index != None:
        # Populations.
        if cdp.model in ['2-domain', 'population']:
            probs = cdp.probs_sim[sim_index]

        # Euler angles.
        if cdp.model == '2-domain':
            alpha = cdp.alpha_sim[sim_index]
            beta = cdp.beta_sim[sim_index]
            gamma = cdp.gamma_sim[sim_index]

    # Normal data structures.
    else:
        # Populations.
        if cdp.model in ['2-domain', 'population']:
            probs = cdp.probs

        # Euler angles.
        if cdp.model == '2-domain':
            alpha = cdp.alpha
            beta = cdp.beta
            gamma = cdp.gamma

    # The probabilities (exclude that of state N).
    if cdp.model in ['2-domain', 'population']:
        param_vector = param_vector + probs[0:-1]

    # The Euler angles.
    if cdp.model == '2-domain':
        for i in range(cdp.N):
            param_vector.append(alpha[i])
            param_vector.append(beta[i])
            param_vector.append(gamma[i])

    # The paramagnetic centre.
    if hasattr(cdp, 'paramag_centre_fixed') and not cdp.paramag_centre_fixed:
        if not hasattr(cdp, 'paramagnetic_centre'):
            for i in range(3):
                param_vector.append(0.0)
        elif sim_index != None:
            if cdp.paramagnetic_centre_sim[sim_index] == None:
                for i in range(3):
                    param_vector.append(0.0)
            else:
                for i in range(3):
                    param_vector.append(cdp.paramagnetic_centre_sim[sim_index][i])
        else:
            for i in range(3):
                param_vector.append(cdp.paramagnetic_centre[i])

    # Convert all None values to zero (to avoid conversion to NaN).
    for i in range(len(param_vector)):
        if param_vector[i] == None:
            param_vector[i] = 0.0

    # Return a numpy arrary.
    return array(param_vector, float64)