Example #1
0
def param_num():
    """Determine the number of parameters in the model.

    @return:    The number of model parameters.
    @rtype:     int
    """

    # Determine the data type.
    data_types = base_data_types()

    # Init.
    num = 0

    # Alignment tensor params.
    if ('rdc' in data_types
            or 'pcs' in data_types) and not align_tensor.all_tensors_fixed():
        # Loop over the alignments.
        for i in range(len(cdp.align_tensors)):
            # Skip non-optimised tensors.
            if not opt_uses_tensor(cdp.align_tensors[i]):
                continue

            # Add 5 tensor parameters.
            num += 5

    # Populations.
    if cdp.model in ['2-domain', 'population']:
        num = num + (cdp.N - 1)

    # Euler angles.
    if cdp.model == '2-domain':
        num = num + 3 * cdp.N

    # The paramagnetic centre.
    if hasattr(cdp, 'paramag_centre_fixed') and not cdp.paramag_centre_fixed:
        num = num + 3

    # Return the param number.
    return num
Example #2
0
def param_num():
    """Determine the number of parameters in the model.

    @return:    The number of model parameters.
    @rtype:     int
    """

    # Determine the data type.
    data_types = base_data_types()

    # Init.
    num = 0

    # Alignment tensor params.
    if ('rdc' in data_types or 'pcs' in data_types) and not align_tensor.all_tensors_fixed():
        # Loop over the alignments.
        for i in range(len(cdp.align_tensors)):
            # Skip non-optimised tensors.
            if not opt_uses_tensor(cdp.align_tensors[i]):
                continue

            # Add 5 tensor parameters.
            num += 5

    # Populations.
    if cdp.model in ['2-domain', 'population']:
        num = num + (cdp.N - 1)

    # Euler angles.
    if cdp.model == '2-domain':
        num = num + 3*cdp.N

    # The paramagnetic centre.
    if hasattr(cdp, 'paramag_centre_fixed') and not cdp.paramag_centre_fixed:
        num = num + 3

     # Return the param number.
    return num
Example #3
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
Example #4
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
Example #5
0
def update_model():
    """Update the model parameters as necessary."""

    # Initialise the list of model parameters.
    if not hasattr(cdp, 'params'):
        cdp.params = []

    # Determine the number of states (loaded as structural models), if not already set.
    if not hasattr(cdp, 'N'):
        # Set the number.
        if hasattr(cdp, 'structure'):
            cdp.N = cdp.structure.num_models()

        # Otherwise return as the rest cannot be updated without N.
        else:
            return

    # Set up the parameter arrays.
    if not cdp.params:
        # Add the probability or population weight parameters.
        if cdp.model in ['2-domain', 'population']:
            for i in range(cdp.N - 1):
                cdp.params.append('p' + repr(i))

        # Add the Euler angle parameters.
        if cdp.model == '2-domain':
            for i in range(cdp.N):
                cdp.params.append('alpha' + repr(i))
                cdp.params.append('beta' + repr(i))
                cdp.params.append('gamma' + repr(i))

    # Initialise the probability and Euler angle arrays.
    if cdp.model in ['2-domain', 'population']:
        if not hasattr(cdp, 'probs'):
            cdp.probs = [None] * cdp.N
    if cdp.model == '2-domain':
        if not hasattr(cdp, 'alpha'):
            cdp.alpha = [None] * cdp.N
        if not hasattr(cdp, 'beta'):
            cdp.beta = [None] * cdp.N
        if not hasattr(cdp, 'gamma'):
            cdp.gamma = [None] * cdp.N

    # Determine the data type.
    data_types = base_data_types()

    # Set up tensors for each alignment.
    if hasattr(cdp, 'align_ids'):
        for id in cdp.align_ids:
            # No tensors initialised.
            if not hasattr(cdp, 'align_tensors'):
                align_tensor.init(tensor=id, align_id=id)

            # Find if the tensor corresponding to the id exists.
            exists = False
            for tensor in cdp.align_tensors:
                if id == tensor.align_id:
                    exists = True

            # Initialise the tensor.
            if not exists:
                align_tensor.init(tensor=id, align_id=id)
Example #6
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)
Example #7
0
def update_model():
    """Update the model parameters as necessary."""

    # Initialise the list of model parameters.
    if not hasattr(cdp, 'params'):
        cdp.params = []

    # Determine the number of states (loaded as structural models), if not already set.
    if not hasattr(cdp, 'N'):
        # Set the number.
        if hasattr(cdp, 'structure'):
            cdp.N = cdp.structure.num_models()

        # Otherwise return as the rest cannot be updated without N.
        else:
            return

    # Set up the parameter arrays.
    if not cdp.params:
        # Add the probability or population weight parameters.
        if cdp.model in ['2-domain', 'population']:
            for i in range(cdp.N-1):
                cdp.params.append('p' + repr(i))

        # Add the Euler angle parameters.
        if cdp.model == '2-domain':
            for i in range(cdp.N):
                cdp.params.append('alpha' + repr(i))
                cdp.params.append('beta' + repr(i))
                cdp.params.append('gamma' + repr(i))

    # Initialise the probability and Euler angle arrays.
    if cdp.model in ['2-domain', 'population']:
        if not hasattr(cdp, 'probs'):
            cdp.probs = [None] * cdp.N
    if cdp.model == '2-domain':
        if not hasattr(cdp, 'alpha'):
            cdp.alpha = [None] * cdp.N
        if not hasattr(cdp, 'beta'):
            cdp.beta = [None] * cdp.N
        if not hasattr(cdp, 'gamma'):
            cdp.gamma = [None] * cdp.N

    # Determine the data type.
    data_types = base_data_types()

    # Set up tensors for each alignment.
    if hasattr(cdp, 'align_ids'):
        for id in cdp.align_ids:
            # No tensors initialised.
            if not hasattr(cdp, 'align_tensors'):
                align_tensor.init(tensor=id, align_id=id, params=[0.0, 0.0, 0.0, 0.0, 0.0])

            # Find if the tensor corresponding to the id exists.
            exists = False
            for tensor in cdp.align_tensors:
                if id == tensor.align_id:
                    exists = True

            # Initialise the tensor.
            if not exists:
                align_tensor.init(tensor=id, align_id=id, params=[0.0, 0.0, 0.0, 0.0, 0.0])
Example #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

            # 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)
Example #9
0
    def grid_search(self, lower=None, upper=None, inc=None, scaling_matrix=None, constraints=False, verbosity=0, sim_index=None):
        """The grid search function.

        @param lower:           The lower bounds of the grid search which must be equal to the number of parameters in the model.
        @type lower:            list of lists of floats
        @param upper:           The upper bounds of the grid search which must be equal to the number of parameters in the model.
        @type upper:            list of lists of floats
        @param 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.
        @type inc:              list of lists of int
        @keyword scaling_matrix:    The per-model list of diagonal and square scaling matrices.
        @type scaling_matrix:       list of numpy rank-2, float64 array or list of None
        @param constraints:     If True, constraints are applied during the grid search (elinating parts of the grid).  If False, no constraints are used.
        @type constraints:      bool
        @param 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')

        # The number of parameters.
        n = param_num()

        # Determine the data type.
        data_types = base_data_types()

        # The number of tensors to optimise.
        tensor_num = align_tensor.num_tensors(skip_fixed=True)

        # Custom sub-grid search for when only tensors are optimised (as each tensor is independent, the number of points collapses from inc**(5*N) to N*inc**5).
        if cdp.model == 'fixed' and tensor_num > 1 and ('rdc' in data_types or 'pcs' in data_types) and not align_tensor.all_tensors_fixed() and hasattr(cdp, 'paramag_centre_fixed') and cdp.paramag_centre_fixed:
            # Print out.
            print("Optimising each alignment tensor separately.")

            # Store the alignment tensor fixed flags.
            fixed_flags = []
            for i in range(len(cdp.align_ids)):
                # Get the tensor object.
                tensor = align_tensor.return_tensor(index=i, skip_fixed=False)

                # Store the flag.
                fixed_flags.append(tensor.fixed)

                # Fix the tensor.
                tensor.set('fixed', True)

            # Loop over each sub-grid.
            for i in range(len(cdp.align_ids)):
                # Skip the tensor if originally fixed.
                if fixed_flags[i]:
                    continue

                # Get the tensor object.
                tensor = align_tensor.return_tensor(index=i, skip_fixed=False)

                # Unfix the current tensor.
                tensor.set('fixed', False)

                # Grid search parameter subsets.
                lower_sub = lower[0][i*5:i*5+5]
                upper_sub = upper[0][i*5:i*5+5]
                inc_sub = inc[0][i*5:i*5+5]

                # Minimisation of the sub-grid.
                self.minimise(min_algor='grid', lower=[lower_sub], upper=[upper_sub], inc=[inc_sub], scaling_matrix=[None], constraints=constraints, verbosity=verbosity, sim_index=sim_index)

                # Fix the tensor again.
                tensor.set('fixed', True)

            # Reset the state of the tensors.
            for i in range(len(cdp.align_ids)):
                # Get the tensor object.
                tensor = align_tensor.return_tensor(index=i, skip_fixed=False)

                # Fix the tensor.
                tensor.set('fixed', fixed_flags[i])

        # All other minimisation.
        else:
            self.minimise(min_algor='grid', lower=lower, upper=upper, inc=inc, scaling_matrix=scaling_matrix, constraints=constraints, verbosity=verbosity, sim_index=sim_index)
Example #10
0
File: api.py Project: tlinnet/relax
    def grid_search(self,
                    lower=None,
                    upper=None,
                    inc=None,
                    scaling_matrix=None,
                    constraints=False,
                    verbosity=0,
                    sim_index=None):
        """The grid search function.

        @param lower:           The lower bounds of the grid search which must be equal to the number of parameters in the model.
        @type lower:            list of lists of floats
        @param upper:           The upper bounds of the grid search which must be equal to the number of parameters in the model.
        @type upper:            list of lists of floats
        @param 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.
        @type inc:              list of lists of int
        @keyword scaling_matrix:    The per-model list of diagonal and square scaling matrices.
        @type scaling_matrix:       list of numpy rank-2, float64 array or list of None
        @param constraints:     If True, constraints are applied during the grid search (elinating parts of the grid).  If False, no constraints are used.
        @type constraints:      bool
        @param 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')

        # The number of parameters.
        n = param_num()

        # Determine the data type.
        data_types = base_data_types()

        # The number of tensors to optimise.
        tensor_num = align_tensor.num_tensors(skip_fixed=True)

        # Custom sub-grid search for when only tensors are optimised (as each tensor is independent, the number of points collapses from inc**(5*N) to N*inc**5).
        if cdp.model == 'fixed' and tensor_num > 1 and (
                'rdc' in data_types or 'pcs' in data_types
        ) and not align_tensor.all_tensors_fixed() and hasattr(
                cdp, 'paramag_centre_fixed') and cdp.paramag_centre_fixed:
            # Print out.
            print("Optimising each alignment tensor separately.")

            # Store the alignment tensor fixed flags.
            fixed_flags = []
            for i in range(len(cdp.align_ids)):
                # Get the tensor object.
                tensor = align_tensor.return_tensor(index=i, skip_fixed=False)

                # Store the flag.
                fixed_flags.append(tensor.fixed)

                # Fix the tensor.
                tensor.set('fixed', True)

            # Loop over each sub-grid.
            for i in range(len(cdp.align_ids)):
                # Skip the tensor if originally fixed.
                if fixed_flags[i]:
                    continue

                # Get the tensor object.
                tensor = align_tensor.return_tensor(index=i, skip_fixed=False)

                # Unfix the current tensor.
                tensor.set('fixed', False)

                # Grid search parameter subsets.
                lower_sub = lower[0][i * 5:i * 5 + 5]
                upper_sub = upper[0][i * 5:i * 5 + 5]
                inc_sub = inc[0][i * 5:i * 5 + 5]

                # Minimisation of the sub-grid.
                self.minimise(min_algor='grid',
                              lower=[lower_sub],
                              upper=[upper_sub],
                              inc=[inc_sub],
                              scaling_matrix=[None],
                              constraints=constraints,
                              verbosity=verbosity,
                              sim_index=sim_index)

                # Fix the tensor again.
                tensor.set('fixed', True)

            # Reset the state of the tensors.
            for i in range(len(cdp.align_ids)):
                # Get the tensor object.
                tensor = align_tensor.return_tensor(index=i, skip_fixed=False)

                # Fix the tensor.
                tensor.set('fixed', fixed_flags[i])

        # All other minimisation.
        else:
            self.minimise(min_algor='grid',
                          lower=lower,
                          upper=upper,
                          inc=inc,
                          scaling_matrix=scaling_matrix,
                          constraints=constraints,
                          verbosity=verbosity,
                          sim_index=sim_index)