예제 #1
0
파일: rotate.py 프로젝트: tlinnet/relax
def to_ieee_754(R):
    """Convert and return the rotation matrix as the full precision IEEE 754 byte array."""

    array = []

    for i in range(3):
        array.append([])
        for j in range(3):
            array[i].append(floatAsByteArray(R[i, j]))

    return array
예제 #2
0
def to_ieee_754(R):
    """Convert and return the rotation matrix as the full precision IEEE 754 byte array."""

    array = []

    for i in range(3):
        array.append([])
        for j in range(3):
            array[i].append(floatAsByteArray(R[i, j]))

    return array
예제 #3
0
파일: xml.py 프로젝트: ilsacripante/relax
def object_to_xml(doc, elem, value=None):
    """Convert the given value into an XML form.

    @param doc:             The XML document object.
    @type doc:              xml.dom.minidom.Document instance
    @param elem:            The element to add the Python objects to.
    @type elem:             XML element object
    @keyword value:         The Python object to convert.
    @type value:            anything
    """

    # Add the text value to the sub element.
    val_elem = doc.createElement('value')
    elem.appendChild(val_elem)
    val_elem.appendChild(doc.createTextNode(repr(value)))

    # The object type.
    if value is None:
        py_type = 'None'
    elif isinstance(value, bool):
        py_type = 'bool'
    elif isinstance(value, str) or isinstance(value, unicode):
        py_type = 'str'
    elif isinstance(value, float):
        py_type = 'float'
    elif isinstance(value, int):
        py_type = 'int'
    elif isinstance(value, list):
        py_type = 'list'
    elif isinstance(value, dict):
        py_type = 'dict'
    elif isinstance(value, ndarray):
        py_type = repr(value.dtype)
    else:
        raise RelaxError("Unknown type for the value %s."  % repr(value))

    # Store as an attribute.
    elem.setAttribute('type', py_type)

    # Store floats as IEEE-754 byte arrays (for full precision storage).
    if lib.check_types.is_float(value):
        val_elem = doc.createElement('ieee_754_byte_array')
        elem.appendChild(val_elem)
        val_elem.appendChild(doc.createTextNode(repr(floatAsByteArray(value))))

    # Store lists with floats as IEEE-754 byte arrays.
    elif (isinstance(value, list) or isinstance(value, ndarray)) and len(value) and lib.check_types.is_float(value[0]):
        # The converted list.
        ieee_obj = []
        conv = False
        for i in range(len(value)):
            # A float.
            if lib.check_types.is_float(value[i]):
                ieee_obj.append(floatAsByteArray(value[i]))
                conv = True

            # All other data.
            else:
                ieee_obj.append(value)

        # Store as XML.
        if conv:
            # The element.
            val_elem = doc.createElement('ieee_754_byte_array')
            elem.appendChild(val_elem)

            # Add the text.
            val_elem.appendChild(doc.createTextNode(repr(ieee_obj)))

    # Store dictionaries with floats as IEEE-754 byte arrays.
    elif py_type == 'dict':
        # The converted dict.
        ieee_obj = {}
        conv = False
        for key in value:
            if lib.check_types.is_float(value[key]):
                ieee_obj[key] = floatAsByteArray(value[key])
                conv = True

        # Store as XML.
        if conv:
            # The element.
            val_elem = doc.createElement('ieee_754_byte_array')
            elem.appendChild(val_elem)

            # Add the text.
            val_elem.appendChild(doc.createTextNode(repr(ieee_obj)))

    # Store matrices of floats as IEEE-754 byte arrays.
    elif lib.arg_check.is_float_matrix(value, none_elements=True, raise_error=False):
        # The converted list.
        ieee_obj = []
        for i in range(len(value)):
            # Handle None elements.
            if value[i] is None:
                ieee_obj.append(None)
                continue

            # A normal float list or numpy array.
            ieee_obj.append([])
            for j in range(len(value[i])):
                ieee_obj[-1].append(floatAsByteArray(value[i][j]))

        # The element.
        val_elem = doc.createElement('ieee_754_byte_array')
        elem.appendChild(val_elem)

        # Add the text.
        val_elem.appendChild(doc.createTextNode(repr(ieee_obj)))
예제 #4
0
def object_to_xml(doc, elem, value=None):
    """Convert the given value into an XML form.

    @param doc:             The XML document object.
    @type doc:              xml.dom.minidom.Document instance
    @param elem:            The element to add the Python objects to.
    @type elem:             XML element object
    @keyword value:         The Python object to convert.
    @type value:            anything
    """

    # Add the text value to the sub element.
    val_elem = doc.createElement('value')
    elem.appendChild(val_elem)
    val_elem.appendChild(doc.createTextNode(repr(value)))

    # The object type.
    if value == None:
        py_type = 'None'
    elif isinstance(value, bool):
        py_type = 'bool'
    elif isinstance(value, str):
        py_type = 'str'
    elif isinstance(value, float):
        py_type = 'float'
    elif isinstance(value, int):
        py_type = 'int'
    elif isinstance(value, list):
        py_type = 'list'
    elif isinstance(value, dict):
        py_type = 'dict'
    elif isinstance(value, ndarray):
        py_type = repr(value.dtype)
    else:
        raise RelaxError("Unknown type for the value '%s'."  % value)

    # Store as an attribute.
    elem.setAttribute('type', py_type)

    # Store floats as IEEE-754 byte arrays (for full precision storage).
    if lib.check_types.is_float(value):
        val_elem = doc.createElement('ieee_754_byte_array')
        elem.appendChild(val_elem)
        val_elem.appendChild(doc.createTextNode(repr(floatAsByteArray(value))))

    # Store lists with floats as IEEE-754 byte arrays.
    elif (isinstance(value, list) or isinstance(value, ndarray)) and len(value) and lib.check_types.is_float(value[0]):
        # The converted list.
        ieee_obj = []
        conv = False
        for i in range(len(value)):
            # A float.
            if lib.check_types.is_float(value[i]):
                ieee_obj.append(floatAsByteArray(value[i]))
                conv = True

            # All other data.
            else:
                ieee_obj.append(value)

        # Store as XML.
        if conv:
            # The element.
            val_elem = doc.createElement('ieee_754_byte_array')
            elem.appendChild(val_elem)

            # Add the text.
            val_elem.appendChild(doc.createTextNode(repr(ieee_obj)))

    # Store dictionaries with floats as IEEE-754 byte arrays.
    elif py_type == 'dict':
        # The converted dict.
        ieee_obj = {}
        conv = False
        for key in list(value.keys()):
            if lib.check_types.is_float(value[key]):
                ieee_obj[key] = floatAsByteArray(value[key])
                conv = True

        # Store as XML.
        if conv:
            # The element.
            val_elem = doc.createElement('ieee_754_byte_array')
            elem.appendChild(val_elem)

            # Add the text.
            val_elem.appendChild(doc.createTextNode(repr(ieee_obj)))

    # Store matrices of floats as IEEE-754 byte arrays.
    elif lib.arg_check.is_float_matrix(value, raise_error=False):
        # The converted list.
        ieee_obj = []
        for i in range(len(value)):
            ieee_obj.append([])
            for j in range(len(value[i])):
                ieee_obj[-1].append(floatAsByteArray(value[i][j]))

        # The element.
        val_elem = doc.createElement('ieee_754_byte_array')
        elem.appendChild(val_elem)

        # Add the text.
        val_elem.appendChild(doc.createTextNode(repr(ieee_obj)))
예제 #5
0
    def convergence(self):
        """Test for the convergence of the global model."""

        # Print out.
        print("\n\n\n")
        print("#####################")
        print("# Convergence tests #")
        print("#####################\n")

        # Maximum number of iterations reached.
        if self.max_iter and self.round > self.max_iter:
            print("Maximum number of global iterations reached.  Terminating the protocol before convergence has been reached.")
            return True

        # Store the data of the current data pipe.
        self.conv_data.chi2.append(cdp.chi2)

        # Create a string representation of the model-free models of the current data pipe.
        curr_models = ''
        for spin in spin_loop():
            if hasattr(spin, 'model'):
                if not spin.model == 'None':
                    curr_models = curr_models + spin.model
        self.conv_data.models.append(curr_models)

        # Store the diffusion tensor parameters.
        self.conv_data.diff_vals.append([])
        for param in self.conv_data.diff_params:
            # Get the parameter values.
            self.conv_data.diff_vals[-1].append(getattr(cdp.diff_tensor, param))

        # Store the model-free parameters.
        self.conv_data.mf_vals.append([])
        self.conv_data.mf_params.append([])
        self.conv_data.spin_ids.append([])
        for spin, spin_id in spin_loop(return_id=True):
            # Skip spin systems with no 'params' object.
            if not hasattr(spin, 'params'):
                continue

            # Add the spin ID, parameters, and empty value list.
            self.conv_data.spin_ids[-1].append(spin_id)
            self.conv_data.mf_params[-1].append([])
            self.conv_data.mf_vals[-1].append([])

            # Loop over the parameters.
            for j in range(len(spin.params)):
                # Get the parameters and values.
                self.conv_data.mf_params[-1][-1].append(spin.params[j])
                self.conv_data.mf_vals[-1][-1].append(getattr(spin, spin.params[j].lower()))

        # No need for tests.
        if self.round == 1:
            print("First round of optimisation, skipping the convergence tests.\n\n\n")
            return False

        # Loop over the iterations.
        converged = False
        for i in range(self.start_round, self.round - 1):
            # Print out.
            print("\n\n\n# Comparing the current iteration to iteration %i.\n" % (i+1))

            # Index.
            index = i - self.start_round

            # Chi-squared test.
            print("Chi-squared test:")
            print("    chi2 (iter %i):  %s" % (i+1, self.conv_data.chi2[index]))
            print("        (as an IEEE-754 byte array:  %s)" % floatAsByteArray(self.conv_data.chi2[index]))
            print("    chi2 (iter %i):  %s" % (self.round, self.conv_data.chi2[-1]))
            print("        (as an IEEE-754 byte array:  %s)" % floatAsByteArray(self.conv_data.chi2[-1]))
            print("    chi2 (difference):  %s" % (self.conv_data.chi2[index] - self.conv_data.chi2[-1]))
            if self.conv_data.chi2[index] == self.conv_data.chi2[-1]:
                print("    The chi-squared value has converged.\n")
            else:
                print("    The chi-squared value has not converged.\n")
                continue

            # Identical model-free model test.
            print("Identical model-free models test:")
            if self.conv_data.models[index] == self.conv_data.models[-1]:
                print("    The model-free models have converged.\n")
            else:
                print("    The model-free models have not converged.\n")
                continue

            # Identical diffusion tensor parameter value test.
            print("Identical diffusion tensor parameter test:")
            params_converged = True
            for k in range(len(self.conv_data.diff_params)):
                # Test if not identical.
                if self.conv_data.diff_vals[index][k] != self.conv_data.diff_vals[-1][k]:
                    print("    Parameter:   %s" % param)
                    print("    Value (iter %i):  %s" % (i+1, self.conv_data.diff_vals[index][k]))
                    print("        (as an IEEE-754 byte array:  %s)" % floatAsByteArray(self.conv_data.diff_vals[index][k]))
                    print("    Value (iter %i):  %s" % (self.round, self.conv_data.diff_vals[-1][k]))
                    print("        (as an IEEE-754 byte array:  %s)" % floatAsByteArray(self.conv_data.diff_vals[-1][k]))
                    print("    The diffusion parameters have not converged.\n")
                    params_converged = False
                    break
            if not params_converged:
                continue
            print("    The diffusion tensor parameters have converged.\n")

            # Identical model-free parameter value test.
            print("\nIdentical model-free parameter test:")
            if len(self.conv_data.spin_ids[index]) != len(self.conv_data.spin_ids[-1]):
                print("    Different number of spins.")
                continue
            for j in range(len(self.conv_data.spin_ids[-1])):
                # Loop over the parameters.
                for k in range(len(self.conv_data.mf_params[-1][j])):
                    # Test if not identical.
                    if self.conv_data.mf_vals[index][j][k] != self.conv_data.mf_vals[-1][j][k]:
                        print("    Spin ID:     %s" % self.conv_data.spin_ids[-1][j])
                        print("    Parameter:   %s" % self.conv_data.mf_params[-1][j][k])
                        print("    Value (iter %i): %s" % (i+1, self.conv_data.mf_vals[index][j][k]))
                        print("        (as an IEEE-754 byte array:  %s)" % floatAsByteArray(self.conv_data.mf_vals[index][j][k]))
                        print("    Value (iter %i): %s" % (self.round, self.conv_data.mf_vals[-1][j][k]))
                        print("        (as an IEEE-754 byte array:  %s)" % floatAsByteArray(self.conv_data.mf_vals[index][j][k]))
                        print("    The model-free parameters have not converged.\n")
                        params_converged = False
                        break
            if not params_converged:
                continue
            print("    The model-free parameters have converged.\n")

            # Convergence.
            converged = True
            break


        # Final printout.
        ##################

        print("\nConvergence:")
        if converged:
            # Update the status.
            status.auto_analysis[self.pipe_bundle].convergence = True

            # Print out.
            print("    [ Yes ]")

            # Return the termination condition.
            return True
        else:
            # Print out.
            print("    [ No ]")

            # Return False to not terminate.
            return False
예제 #6
0
파일: rotate.py 프로젝트: tlinnet/relax
PIVOT = array([ 37.254, 0.5, 16.7465])
R_PIVOT = zeros((3, 3), float64)

TORSION_ANGLE = 100 / 3.0
COM_C = array([ 26.83678091, -12.37906417,  28.34154128])
R_TORSION = zeros((3, 3), float64)
VECT_TORSION = COM_C - PIVOT
VECT_TORSION = VECT_TORSION / norm(VECT_TORSION)


# Generate a random pivot rotation.
R_random_axis(R_PIVOT, PIVOT_ANGLE)

# Print out.
print("\nThe pivot rotation angle is: %20.40f" % PIVOT_ANGLE)
print("The pivot rotation angle is: %s" % floatAsByteArray(PIVOT_ANGLE))
print("\nThe pivot rotation matrix is:\n%s" % R_PIVOT)
print("Or:")
float_array = to_ieee_754(R_PIVOT)
for i in range(3):
    print(float_array[i])

# Generate the torsion angle rotation.
axis_angle_to_R(VECT_TORSION, TORSION_ANGLE, R_TORSION)

# Print out.
print("\nThe torsion rotation matrix is:\n%s" % R_TORSION)
print("Or:")
float_array = to_ieee_754(R_TORSION)
for i in range(3):
    print(float_array[i])
예제 #7
0
PIVOT = array([ 37.254, 0.5, 16.7465])
R_PIVOT = zeros((3, 3), float64)

TORSION_ANGLE = 100 / 3.0
COM_C = array([ 26.83678091, -12.37906417,  28.34154128])
R_TORSION = zeros((3, 3), float64)
VECT_TORSION = COM_C - PIVOT
VECT_TORSION = VECT_TORSION / norm(VECT_TORSION)


# Generate a random pivot rotation.
R_random_axis(R_PIVOT, PIVOT_ANGLE)

# Print out.
print("\nThe pivot rotation angle is: %20.40f" % PIVOT_ANGLE)
print("The pivot rotation angle is: %s" % floatAsByteArray(PIVOT_ANGLE))
print("\nThe pivot rotation matrix is:\n%s" % R_PIVOT)
print("Or:")
float_array = to_ieee_754(R_PIVOT)
for i in range(3):
    print(float_array[i])

# Generate the torsion angle rotation.
axis_angle_to_R(VECT_TORSION, TORSION_ANGLE, R_TORSION)

# Print out.
print("\nThe torsion rotation matrix is:\n%s" % R_TORSION)
print("Or:")
float_array = to_ieee_754(R_TORSION)
for i in range(3):
    print(float_array[i])