Example #1
0
    def minimise(self, min_algor=None, min_options=None, func_tol=None, grad_tol=None, max_iterations=None, constraints=False, scaling_matrix=None, verbosity=0, sim_index=None, lower=None, upper=None, inc=None):
        """Minimisation function.

        @param min_algor:           The minimisation algorithm to use.
        @type min_algor:            str
        @param min_options:         An array of options to be used by the minimisation algorithm.
        @type min_options:          array of str
        @param func_tol:            The function tolerance which, when reached, terminates optimisation. Setting this to None turns of the check.
        @type func_tol:             None or float
        @param grad_tol:            The gradient tolerance which, when reached, terminates optimisation. Setting this to None turns of the check.
        @type grad_tol:             None or float
        @param max_iterations:      The maximum number of iterations for the algorithm.
        @type max_iterations:       int
        @param constraints:         If True, constraints are used during optimisation.
        @type constraints:          bool
        @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 verbosity:           A flag specifying the amount of information to print.  The higher the value, the greater the verbosity.
        @type verbosity:            int
        @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
        @keyword lower:             The per-model 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:                list of lists of numbers
        @keyword upper:             The per-model 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:                list of lists of numbers
        @keyword inc:               The per-model 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:                  list of lists of int
        """

        # Set up the target function for direct calculation.
        model, param_vector, data_types = target_fn_setup(sim_index=sim_index, scaling_matrix=scaling_matrix[0], verbosity=verbosity)

        # Nothing to do!
        if not len(param_vector):
            warn(RelaxWarning("The model has no parameters, minimisation cannot be performed."))
            return

        # Right, constraints cannot be used for the 'fixed' model.
        if constraints and cdp.model == 'fixed':
            if verbosity:
                warn(RelaxWarning("Turning constraints off.  These cannot be used for the 'fixed' model."))
            constraints = False

            # Pop out the Method of Multipliers algorithm.
            if min_algor == 'Method of Multipliers':
                min_algor = min_options[0]
                min_options = min_options[1:]

        # And constraints absolutely must be used for the 'population' model.
        if not constraints and cdp.model == 'population':
            warn(RelaxWarning("Turning constraints on.  These absolutely must be used for the 'population' model."))
            constraints = True

            # Add the Method of Multipliers algorithm.
            min_options = (min_algor,) + min_options
            min_algor = 'Method of Multipliers'

        # Disallow Newton optimisation and other Hessian optimisers for the paramagnetic centre position optimisation (the PCS Hessian is not yet implemented).
        if hasattr(cdp, 'paramag_centre_fixed') and not cdp.paramag_centre_fixed:
            if min_algor in ['newton']:
                raise RelaxError("For the paramagnetic centre position, as the Hessians are not yet implemented Newton optimisation cannot be performed.")

        # Linear constraints.
        A, b = None, None
        if constraints:
            A, b = linear_constraints(data_types=data_types, scaling_matrix=scaling_matrix[0])

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

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

        # Minimisation.
        else:
            results = generic_minimise(func=model.func, dfunc=model.dfunc, d2func=model.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=1, print_flag=verbosity)

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

        # Catch infinite chi-squared values.
        if isInf(func):
            raise RelaxInfError('chi-squared')

        # Catch chi-squared values of NaN.
        if isNaN(func):
            raise RelaxNaNError('chi-squared')

        # Make a last function call to update the back-calculated RDC and PCS structures to the optimal values.
        chi2 = model.func(param_vector)

        # Scaling.
        if scaling_matrix[0] is not None:
            param_vector = dot(scaling_matrix[0], param_vector)

        # Disassemble the parameter vector.
        disassemble_param_vector(param_vector=param_vector, data_types=data_types, sim_index=sim_index)

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

            # Iterations.
            cdp.iter_sim[sim_index] = iter_count

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

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

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

            # Warning.
            cdp.warning_sim[sim_index] = warning

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

            # Iterations.
            cdp.iter = iter_count

            # Function evaluations.
            cdp.f_count = f_count

            # Gradient evaluations.
            cdp.g_count = g_count

            # Hessian evaluations.
            cdp.h_count = h_count

            # Warning.
            cdp.warning = warning

        # Statistical analysis.
        if 'rdc' in data_types or 'pcs' in data_types:
            # Get the final back calculated data (for the Q factor and
            minimise_bc_data(model, sim_index=sim_index)

            # Calculate the RDC Q factors.
            if 'rdc' in data_types:
                rdc.q_factors(sim_index=sim_index, verbosity=verbosity)

            # Calculate the PCS Q factors.
            if 'pcs' in data_types:
                pcs.q_factors(sim_index=sim_index, verbosity=verbosity)
Example #2
0
File: api.py Project: tlinnet/relax
    def minimise(self,
                 min_algor=None,
                 min_options=None,
                 func_tol=None,
                 grad_tol=None,
                 max_iterations=None,
                 constraints=False,
                 scaling_matrix=None,
                 verbosity=0,
                 sim_index=None,
                 lower=None,
                 upper=None,
                 inc=None):
        """Minimisation function.

        @param min_algor:           The minimisation algorithm to use.
        @type min_algor:            str
        @param min_options:         An array of options to be used by the minimisation algorithm.
        @type min_options:          array of str
        @param func_tol:            The function tolerance which, when reached, terminates optimisation. Setting this to None turns of the check.
        @type func_tol:             None or float
        @param grad_tol:            The gradient tolerance which, when reached, terminates optimisation. Setting this to None turns of the check.
        @type grad_tol:             None or float
        @param max_iterations:      The maximum number of iterations for the algorithm.
        @type max_iterations:       int
        @param constraints:         If True, constraints are used during optimisation.
        @type constraints:          bool
        @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 verbosity:           A flag specifying the amount of information to print.  The higher the value, the greater the verbosity.
        @type verbosity:            int
        @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
        @keyword lower:             The per-model 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:                list of lists of numbers
        @keyword upper:             The per-model 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:                list of lists of numbers
        @keyword inc:               The per-model 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:                  list of lists of int
        """

        # Set up the target function for direct calculation.
        model, param_vector, data_types = target_fn_setup(
            sim_index=sim_index,
            scaling_matrix=scaling_matrix[0],
            verbosity=verbosity)

        # Nothing to do!
        if not len(param_vector):
            warn(
                RelaxWarning(
                    "The model has no parameters, minimisation cannot be performed."
                ))
            return

        # Right, constraints cannot be used for the 'fixed' model.
        if constraints and cdp.model == 'fixed':
            if verbosity:
                warn(
                    RelaxWarning(
                        "Turning constraints off.  These cannot be used for the 'fixed' model."
                    ))
            constraints = False

            # Pop out the Method of Multipliers algorithm.
            if min_algor == 'Method of Multipliers':
                min_algor = min_options[0]
                min_options = min_options[1:]

        # And constraints absolutely must be used for the 'population' model.
        if not constraints and cdp.model == 'population':
            warn(
                RelaxWarning(
                    "Turning constraints on.  These absolutely must be used for the 'population' model."
                ))
            constraints = True

            # Add the Method of Multipliers algorithm.
            min_options = (min_algor, ) + min_options
            min_algor = 'Method of Multipliers'

        # Disallow Newton optimisation and other Hessian optimisers for the paramagnetic centre position optimisation (the PCS Hessian is not yet implemented).
        if hasattr(cdp,
                   'paramag_centre_fixed') and not cdp.paramag_centre_fixed:
            if min_algor in ['newton']:
                raise RelaxError(
                    "For the paramagnetic centre position, as the Hessians are not yet implemented Newton optimisation cannot be performed."
                )

        # Linear constraints.
        A, b = None, None
        if constraints:
            A, b = linear_constraints(data_types=data_types,
                                      scaling_matrix=scaling_matrix[0])

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

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

        # Minimisation.
        else:
            results = generic_minimise(func=model.func,
                                       dfunc=model.dfunc,
                                       d2func=model.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=1,
                                       print_flag=verbosity)

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

        # Catch infinite chi-squared values.
        if isInf(func):
            raise RelaxInfError('chi-squared')

        # Catch chi-squared values of NaN.
        if isNaN(func):
            raise RelaxNaNError('chi-squared')

        # Make a last function call to update the back-calculated RDC and PCS structures to the optimal values.
        chi2 = model.func(param_vector)

        # Scaling.
        if scaling_matrix[0] is not None:
            param_vector = dot(scaling_matrix[0], param_vector)

        # Disassemble the parameter vector.
        disassemble_param_vector(param_vector=param_vector,
                                 data_types=data_types,
                                 sim_index=sim_index)

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

            # Iterations.
            cdp.iter_sim[sim_index] = iter_count

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

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

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

            # Warning.
            cdp.warning_sim[sim_index] = warning

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

            # Iterations.
            cdp.iter = iter_count

            # Function evaluations.
            cdp.f_count = f_count

            # Gradient evaluations.
            cdp.g_count = g_count

            # Hessian evaluations.
            cdp.h_count = h_count

            # Warning.
            cdp.warning = warning

        # Statistical analysis.
        if 'rdc' in data_types or 'pcs' in data_types:
            # Get the final back calculated data (for the Q factor and
            minimise_bc_data(model, sim_index=sim_index)

            # Calculate the RDC Q factors.
            if 'rdc' in data_types:
                rdc.q_factors(sim_index=sim_index, verbosity=verbosity)

            # Calculate the PCS Q factors.
            if 'pcs' in data_types:
                pcs.q_factors(sim_index=sim_index, verbosity=verbosity)
Example #3
0
    def calculate(self, spin_id=None, scaling_matrix=None, verbosity=1, sim_index=None):
        """Calculation function.

        Currently this function simply calculates the NOESY flat-bottom quadratic energy potential,
        if NOE restraints are available.

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

        # Set up the target function for direct calculation.
        if scaling_matrix != None:
            scaling_matrix = scaling_matrix[0]
        model, param_vector, data_types = target_fn_setup(scaling_matrix=scaling_matrix, verbosity=verbosity)

        # Calculate the chi-squared value.
        if model:
            # Make a function call.
            chi2 = model.func(param_vector)

            # Store the global chi-squared value.
            cdp.chi2 = chi2

            # Store the back-calculated data.
            minimise_bc_data(model, sim_index=sim_index)

            # Calculate the RDC Q factors.
            if 'rdc' in data_types:
                rdc.q_factors(sim_index=sim_index, verbosity=verbosity)

            # Calculate the PCS Q factors.
            if 'pcs' in data_types:
                pcs.q_factors(sim_index=sim_index, verbosity=verbosity)

        # NOE potential.
        if hasattr(cdp, 'noe_restraints'):
            # Init some numpy arrays.
            num_restraints = len(cdp.noe_restraints)
            dist = zeros(num_restraints, float64)
            pot = zeros(num_restraints, float64)
            lower = zeros(num_restraints, float64)
            upper = zeros(num_restraints, float64)

            # Loop over the NOEs.
            for i in range(num_restraints):
                # Create arrays of the NOEs.
                lower[i] = cdp.noe_restraints[i][2]
                upper[i] = cdp.noe_restraints[i][3]

                # Calculate the average distances, using -6 power averaging.
                dist[i] = calc_ave_dist(cdp.noe_restraints[i][0], cdp.noe_restraints[i][1], exp=-6)

            # Calculate the quadratic potential.
            quad_pot(dist, pot, lower, upper)

            # Store the distance and potential information.
            cdp.ave_dist = []
            cdp.quad_pot = []
            for i in range(num_restraints):
                cdp.ave_dist.append([cdp.noe_restraints[i][0], cdp.noe_restraints[i][1], dist[i]])
                cdp.quad_pot.append([cdp.noe_restraints[i][0], cdp.noe_restraints[i][1], pot[i]])
Example #4
0
File: api.py Project: tlinnet/relax
    def calculate(self,
                  spin_id=None,
                  scaling_matrix=None,
                  verbosity=1,
                  sim_index=None):
        """Calculation function.

        Currently this function simply calculates the NOESY flat-bottom quadratic energy potential,
        if NOE restraints are available.

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

        # Set up the target function for direct calculation.
        if scaling_matrix != None:
            scaling_matrix = scaling_matrix[0]
        model, param_vector, data_types = target_fn_setup(
            scaling_matrix=scaling_matrix, verbosity=verbosity)

        # Calculate the chi-squared value.
        if model:
            # Make a function call.
            chi2 = model.func(param_vector)

            # Store the global chi-squared value.
            cdp.chi2 = chi2

            # Store the back-calculated data.
            minimise_bc_data(model, sim_index=sim_index)

            # Calculate the RDC Q factors.
            if 'rdc' in data_types:
                rdc.q_factors(sim_index=sim_index, verbosity=verbosity)

            # Calculate the PCS Q factors.
            if 'pcs' in data_types:
                pcs.q_factors(sim_index=sim_index, verbosity=verbosity)

        # NOE potential.
        if hasattr(cdp, 'noe_restraints'):
            # Init some numpy arrays.
            num_restraints = len(cdp.noe_restraints)
            dist = zeros(num_restraints, float64)
            pot = zeros(num_restraints, float64)
            lower = zeros(num_restraints, float64)
            upper = zeros(num_restraints, float64)

            # Loop over the NOEs.
            for i in range(num_restraints):
                # Create arrays of the NOEs.
                lower[i] = cdp.noe_restraints[i][2]
                upper[i] = cdp.noe_restraints[i][3]

                # Calculate the average distances, using -6 power averaging.
                dist[i] = calc_ave_dist(cdp.noe_restraints[i][0],
                                        cdp.noe_restraints[i][1],
                                        exp=-6)

            # Calculate the quadratic potential.
            quad_pot(dist, pot, lower, upper)

            # Store the distance and potential information.
            cdp.ave_dist = []
            cdp.quad_pot = []
            for i in range(num_restraints):
                cdp.ave_dist.append([
                    cdp.noe_restraints[i][0], cdp.noe_restraints[i][1], dist[i]
                ])
                cdp.quad_pot.append([
                    cdp.noe_restraints[i][0], cdp.noe_restraints[i][1], pot[i]
                ])