/* Copyright (C) 2001-2003 Damir Zucic */

/*=============================================================================

				alpha_membrane.c

Purpose:
	Find the position and orientation of the membrane with respect to
	the macromolecular structure. The structure in question should be
	some membrane protein of alpha helix bundle type. Otherwise, this
	function will fail to work properly.

Input:
	(1) Pointer to MolComplexS structure,  with the chosen structure.
	(2) Pointer to RuntimeS structure.
	(3) Pointer to ConfigS structure (stereo angle required).
	(4) Pointer to GUIS structure.

Output:
	(1) The membrane position and orientation  will be calculated for
	    the first time or updated.
	(2) Return value.

Return value:
	(1) Positive on success.
	(2) Negative on failure.

Notes:
	(1) A short description of some tricks used in this function:
	    -------------------------------------------------------------
	    In the  first step,  the approximate membrane  orientation is
	    determined.  The current  sliding  window  width  is used  to
	    calculate the average hydrophobicity for the entire sequence,
	    chain by chain. The residue with the highest average hydroph.
	    is identified and treated as the central residue of  the most
	    hydrophobic structural motif.  The four residues which are at
	    the beginning of  the most hydrophobic window are identified,
	    as well as the four residues at the end of this window. These
	    eight atoms are used to define  the first vector which should
	    be  approximately  perpendicular  to the membrane.  After the
	    first step, the second most hydrophobic segment is found. The
	    second vector is calculated in  the same manner  as the first
	    vector.  The procedure is repeated to find  all segments with
	    the average hydrophobicity above the specified threshold. All
	    extracted vectors are normalized and combined (added) into a
	    single vector. This vector is treated as the normal vector of
	    the membrane. In addition to the normal vector, the geometric
	    center of the whole structure is used as the reference point.
	    -------------------------------------------------------------
	    In the second step,  all residues are  projected to  the axis
	    defined by the reference point and by the normal vector.  The
	    axis is  divided into  a number  of cells  ("boxes")  and the
	    projected residues are grouped into these cells, depending on
	    the distance of the projection from the reference point.  For
	    each cell,  the total projected hydrophobicity is calculated.
	    After  the total hydrophobicity value  is calculated  for all
	    individual cells,  the set of cells  is scanned  to calculate
	    the average hydrophobicity for the specified number of cells.
	    The sliding window width multiplied by  the width of a single
	    cell (in angstroms) should be similar to the thickness of the
	    phospholipid bilayer. At the end of the second step, the cell
	    with  the highest  average  hydrophobicity  is found  and the
	    reference point is moved to the position of this cell.
	    -------------------------------------------------------------
	    The third step is  the refinement of  the normal vector.  The
	    normal vector is declined from its original direction to scan
	    a set of alternative positions.  For each trial,  the average
	    hydrophobicity  associated with the cell  which is nearest to
	    the reference point is calculated.  Again, the sliding window
	    width should be similar  to the membrane thickness.  The best
	    normal vector  is  the one  which  gives  the highest average
	    hydrophobicity at the reference point. This operation is done
	    twice.
	    -------------------------------------------------------------
	    In the fourth step the position of the membrane center is
	    refined once more.
	    -------------------------------------------------------------

	(2) The components of  the normal vector  are used  to initialize
	    the corresponding members of two  PlaneS structures which are
	    used to define the membrane.

	(3) An interesting article  (from Stephen White Laboratory) about
	    the structure of lipid bilayers may be found at:

	    http://blanco.biomol.uci.edu/Bilayer_Struc_frames.html

========includes:============================================================*/

#include <stdio.h>

#include <string.h>
#include <math.h>

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>
#include <X11/Xatom.h>

#include "defines.h"
#include "typedefs.h"

/*======function prototypes:=================================================*/

double		Hydrophobicity_ (char *, int, int);
int		ExtractCA_ (VectorS *, AtomS *, size_t, size_t);
int		ExtractVector_ (VectorS *, MolComplexS *, RuntimeS *, double);
double		AbsoluteValue_ (VectorS *);
double		ScalarProduct_ (VectorS *, VectorS *);
int		AlphaMembraneCenter_ (MolComplexS *, VectorS *);
int		AlphaNormalVector_ (VectorS *, MolComplexS *, double);

/*======find membrane position (helix bundle version):=======================*/

int AlphaMembrane_ (MolComplexS *mol_complexSP,
		    RuntimeS *runtimeSP, ConfigS *configSP, GUIS *guiSP)
{
int		max_length;
int		residuesN, residueI, start_residueI, end_residueI;
ResidueS	*residueSP;
AtomS		*first_atomSP;
char		*residue_nameP, *destP;
int		scaleI;
size_t		offset;
char		residue_nameA[RESNAMESIZE];
double		hydrophobicity, average_hyphob;
int		window_width, half_window_width, windowI, combinedI;
int		used_residuesN;
double		mean_value, standard_deviation, threshold;
double		difference, total;
double		max_average_hyphob, min_average_hyphob;
int		central_residueI, window_startI, window_endI;
int		vectors_extractedN;
VectorS		vector1S, vector2S, vector3S, vector4S;
VectorS		vector5S, vector6S, vector7S, vector8S;
VectorS		normal_vectorS;
int		n;
double		scalar_product;
double		abs_value, reciprocal_denominator;
double		tilt_step;
double		sin_angle, cos_angle;

/*------check the number of residues:----------------------------------------*/

/* The minimal number of residues is equal to the sliding window width: */
if ((int) mol_complexSP->residuesN < runtimeSP->sliding_window_width)
	{
	return -1;
	}

/*------copy the sequence:---------------------------------------------------*/

/* The maximal residue name length: */
max_length = RESNAMESIZE - 1;

/* Copy the number of residues: */
residuesN = mol_complexSP->residuesN;
if (residuesN == 0) return -2;

/* Scan the macromolecular complex, residue by residue: */
for (residueI = 0; residueI < residuesN; residueI++)
	{
	/* Pointer to the current residue: */
	residueSP = mol_complexSP->residueSP + residueI;

	/* Pointer to the first atom: */
	first_atomSP = mol_complexSP->atomSP + residueSP->residue_startI;

	/* Pointer to the residue name associated with this atom: */
	residue_nameP = first_atomSP->raw_atomS.pure_residue_nameA;

	/* Prepare and check the position  in the general purpose */
	/* sequence buffer where the residue name will be copied: */
	offset = max_length * residueI;
	if (offset > runtimeSP->sequence_buffer_size - 10 * max_length)
		{
		return -3;
		}

	/* Copy the residue name: */
	destP = runtimeSP->sequenceP + offset;
	strncpy (destP, residue_nameP, max_length);
	}

/* Store the number of residues to RuntimeS: */
runtimeSP->residuesN = residuesN;

/*------assign the hydrophobicity values:------------------------------------*/

/* Hydrophobicity scale index: */
scaleI = runtimeSP->hydrophobicity_scaleI;

/* Scan the general purpose sequence: */
for (residueI = 0; residueI < (int) runtimeSP->residuesN; residueI++)
	{
	/* Pointer to the current residue name: */
	residue_nameP = runtimeSP->sequenceP + residueI * max_length;

	/* Copy the residue name: */
	strncpy (residue_nameA, residue_nameP, max_length);
	residue_nameA[max_length] = '\0';

	/* The corresponding hydrophobicity: */
	hydrophobicity = Hydrophobicity_ (residue_nameA, scaleI, 0);

	/* Store the hydrophobicity value: */
	*(runtimeSP->hydrophobicityP + residueI) = hydrophobicity;
	}

/*------calculate the average hydrophobicity:--------------------------------*/

/* The sliding window width should be at least seven: */
window_width = runtimeSP->sliding_window_width;
if (window_width < 7) return -4;
half_window_width = window_width / 2;

/* Scan the sequence: */
for (residueI = 0; residueI < residuesN; residueI++)
	{
	/* Reset the number of residues used for averaging: */
	used_residuesN = 0;

	/* Reset the average hydrophobicity: */
	average_hyphob = 0.0;

	/* Scan the sliding window: */
	for (windowI = 0; windowI < window_width; windowI++)
		{
		/* Prepare and check the combined index: */
		combinedI = residueI - half_window_width + windowI;
		if (combinedI < 0) continue;
		if (combinedI >= residuesN) continue;

		/* The hydrophobicity of the residue defined by combinedI: */
		hydrophobicity =
			(double) *(runtimeSP->hydrophobicityP + combinedI);

		/* Add hydrophobicity to the total: */
		average_hyphob += hydrophobicity;

		/* Increase the number of residues used for averaging: */
		used_residuesN++;
		}

	/* Check how many residues were used: */
	if (used_residuesN == window_width)
		{
		average_hyphob /= (double) window_width;
		}
	else average_hyphob = 0.0;

	/* Store the average hydrophobicity: */
	*(runtimeSP->average_hydrophobicityP + residueI) = average_hyphob;
	}

/*------calculate the mean value and the standard deviation:-----------------*/

/* Initialize the counter and the overall */
/* mean value of  average hydrophobicity: */
used_residuesN = 0;
mean_value = 0.0;

/* Scan the sequence skipping the residues for which the */
/* average hydrophobicity  was not calculated  properly: */
for (residueI = 0; residueI < residuesN; residueI++)
	{
	/* Skip the residues which are too close to */
	/* the start or to the end of the sequence: */
	start_residueI = residueI - half_window_width;
	if (start_residueI < 0) continue;
	end_residueI = residueI - half_window_width + window_width - 1;
	if (end_residueI >= residuesN) continue;

	/* Add the average hydrophobicity to the mean_value: */
	mean_value += *(runtimeSP->average_hydrophobicityP + residueI);

	/* Increment the counter: */
	used_residuesN++;
	}

/* Check was there at least one residue: */
if (used_residuesN == 0) return -5;

/* Calculate the overall mean value of the average hydrophobicity: */
mean_value /= (double) used_residuesN;

/* Initialize the variable which is used */
/* to calculate  the standard deviation: */
total = 0.0;

/* Now scan the sequence again, to calculate squared */
/* differences required for  the standard deviation: */
for (residueI = 0; residueI < residuesN; residueI++)
	{
	/* Skip the residues which are too close to */
	/* the start or to the end of the sequence: */ 
	start_residueI = residueI - half_window_width;
	if (start_residueI < 0) continue;
	end_residueI = residueI - half_window_width + window_width - 1;
	if (end_residueI >= residuesN) continue;

	/* Calculate the difference between the average */
	/* hydrophobicity and  the overall  mean value: */
	difference = *(runtimeSP->average_hydrophobicityP + residueI) -
		     mean_value;

	/* Add the square of this difference to the total: */
	total += difference * difference;
	}

/* Calculate the standard deviation: */
standard_deviation = sqrt (total / (double) used_residuesN);

/* Prepare  the threshold value,  required */
/* to identify the transmembrane segments. */
threshold = mean_value + 1.5 * standard_deviation;

/*------the first estimate of the normal vector:-----------------------------*/

/* Initialize the maximal and minimal average hydrophobicity: */
max_average_hyphob = -999999.0;
min_average_hyphob =  999999.0;

/* Initialize the index  of the residue  which is */
/* in the middle of the most hydrophobic segment. */
central_residueI = -1;

/* Find the sequence position with the highest average hydrophobicity. */
/* Find also the values of maximal and minimal average hydrophobicity. */
for (residueI = 0; residueI < residuesN; residueI++)
	{
	average_hyphob = *(runtimeSP->average_hydrophobicityP + residueI);
	if (average_hyphob > max_average_hyphob)
		{
		max_average_hyphob = average_hyphob;
		central_residueI = residueI;
		}
	else if (average_hyphob < min_average_hyphob)
		{
		min_average_hyphob = average_hyphob;
		}
	}

/* This should never happen but I am paranoic: */
if (central_residueI == -1) return -6;

/* Check the maximal average hydrophobicity: */
if (max_average_hyphob < threshold) return -7;

/* Now use  the index of  the central residue  to define  the entire */
/* sliding window which contains the maximal average hydrophobicity: */
window_startI = central_residueI - half_window_width;
window_endI   = window_startI + window_width;

/* Check both indices; if the central residue is too close to */
/* the first  or to  the last residue,  something went wrong: */
if ((window_startI < 0) || (window_startI >= residuesN)) return -8;

/* Use  the first  four residues  from  the  sliding  window  to */
/* define  the first point  in space and the last  four residues */
/* to define  the second point  in space.  Use these  two points */
/* to prepare  the initial normal vector.  This vector should be */
/* approximately perpendicular to the membrane.  The coordinates */
/* of CA atoms are used (some structures contain only CA atoms). */

/* Prepare eight vectors: */
vectors_extractedN = 0;
residueSP = mol_complexSP->residueSP + window_startI;
vectors_extractedN += ExtractCA_ (&vector1S, mol_complexSP->atomSP,
				  residueSP->residue_startI,
				  residueSP->residue_endI);
residueSP = mol_complexSP->residueSP + window_startI + 1;
vectors_extractedN += ExtractCA_ (&vector2S, mol_complexSP->atomSP,
				  residueSP->residue_startI,
				  residueSP->residue_endI);
residueSP = mol_complexSP->residueSP + window_startI + 2;
vectors_extractedN += ExtractCA_ (&vector3S, mol_complexSP->atomSP,
				  residueSP->residue_startI,
				  residueSP->residue_endI);
residueSP = mol_complexSP->residueSP + window_startI + 3;
vectors_extractedN += ExtractCA_ (&vector4S, mol_complexSP->atomSP,
                                  residueSP->residue_startI,
                                  residueSP->residue_endI);
residueSP = mol_complexSP->residueSP + window_endI;
vectors_extractedN += ExtractCA_ (&vector5S, mol_complexSP->atomSP,
				  residueSP->residue_startI,
				  residueSP->residue_endI);
residueSP = mol_complexSP->residueSP + window_endI - 1;
vectors_extractedN += ExtractCA_ (&vector6S, mol_complexSP->atomSP,
				  residueSP->residue_startI,
				  residueSP->residue_endI);
residueSP = mol_complexSP->residueSP + window_endI - 2;
vectors_extractedN += ExtractCA_ (&vector7S, mol_complexSP->atomSP,
				  residueSP->residue_startI,
				  residueSP->residue_endI);
residueSP = mol_complexSP->residueSP + window_endI - 3;
vectors_extractedN += ExtractCA_ (&vector8S, mol_complexSP->atomSP,
				  residueSP->residue_startI,
				  residueSP->residue_endI);
if (vectors_extractedN != 8) return -9;

/* The first (crude) estimate of the normal vector: */
normal_vectorS.x = vector5S.x + vector6S.x + vector7S.x + vector8S.x
		 - vector1S.x - vector2S.x - vector3S.x - vector4S.x;
normal_vectorS.y = vector5S.y + vector6S.y + vector7S.y + vector8S.y
                 - vector1S.y - vector2S.y - vector3S.y - vector4S.y;
normal_vectorS.z = vector5S.z + vector6S.z + vector7S.z + vector8S.z
                 - vector1S.z - vector2S.z - vector3S.z - vector4S.z;

/* Remove the highest peak. Replace the average hydrophobicities */
/* in the whole interval by the minimal  average hydrophobicity. */
for (residueI = window_startI; residueI <= window_endI; residueI++)
	{
	*(runtimeSP->average_hydrophobicityP + residueI) = min_average_hyphob;
	}

/*------update the normal vector by adding more vectors:---------------------*/

/* Extract all peaks above the specified threshold: */
while (1)
	{
	/* Try to extract one vector: */
	n = ExtractVector_ (&vector1S, mol_complexSP, runtimeSP, threshold);
	if (n < 0) break;

	/* Now check  the scalar product  between the */
	/* current normal vector and this new vector. */
	/* If it is  negative,  flip  the new vector. */
	scalar_product = ScalarProduct_ (&normal_vectorS, &vector1S);
	if (scalar_product < 0.0)
		{
		vector1S.x = -vector1S.x;
		vector1S.y = -vector1S.y;
		vector1S.z = -vector1S.z;
		}

	/* Update the normal vector by adding the new vector: */
	normal_vectorS.x += vector1S.x;
	normal_vectorS.y += vector1S.y;
	normal_vectorS.z += vector1S.z;
	}

/*------normalize the normal vector:-----------------------------------------*/

/* Make sure that the absolute value of the normal vector is equal to one: */
abs_value = AbsoluteValue_ (&normal_vectorS);
if (abs_value == 0.0) return -10;
reciprocal_denominator = 1.0 / abs_value;
normal_vectorS.x *= reciprocal_denominator;
normal_vectorS.y *= reciprocal_denominator;
normal_vectorS.z *= reciprocal_denominator;

/*------the first estimate of the membrane center:---------------------------*/

/* Take the geometric center as the initial membrane center: */
mol_complexSP->membraneS.center_x = mol_complexSP->geometric_center_vectorS.x;
mol_complexSP->membraneS.center_y = mol_complexSP->geometric_center_vectorS.y;
mol_complexSP->membraneS.center_z = mol_complexSP->geometric_center_vectorS.z;

/* Find a better estimate of the membrane center: */
AlphaMembraneCenter_ (mol_complexSP, &normal_vectorS);

/*------refine the normal vector twice, using different steps:---------------*/

/* Refine the normal vector which defines the membrane. */

/* The first passage - use a large tilt step: */
tilt_step = 0.05;
AlphaNormalVector_ (&normal_vectorS, mol_complexSP, tilt_step);

/* The second passage - use a small tilt step: */
tilt_step = 0.01;
AlphaNormalVector_ (&normal_vectorS, mol_complexSP, tilt_step);

/*------refine the membrane center once more:--------------------------------*/

AlphaMembraneCenter_ (mol_complexSP, &normal_vectorS);

/*------store the normal vector:---------------------------------------------*/

/* Store (copy) the components of the normal vector. */

/* The normal vector of the first plane points to the same direction: */
mol_complexSP->membraneS.plane1S.normal_x[0] =  normal_vectorS.x;
mol_complexSP->membraneS.plane1S.normal_y    =  normal_vectorS.y;
mol_complexSP->membraneS.plane1S.normal_z[0] =  normal_vectorS.z;

/* The normal vector of the second plane points to the opposite direction: */
mol_complexSP->membraneS.plane2S.normal_x[0] = -normal_vectorS.x;
mol_complexSP->membraneS.plane2S.normal_y    = -normal_vectorS.y;
mol_complexSP->membraneS.plane2S.normal_z[0] = -normal_vectorS.z;

/* Prepare the stereo data for these two normal vectors. */

/* Prepare the sine and cosine of the stereo angle: */
sin_angle = sin (configSP->stereo_angle);
cos_angle = cos (configSP->stereo_angle);

/* Calculate the stereo data: */
mol_complexSP->membraneS.plane1S.normal_x[1] =
		 mol_complexSP->membraneS.plane1S.normal_x[0] * cos_angle +
		 mol_complexSP->membraneS.plane1S.normal_z[0] * sin_angle;
mol_complexSP->membraneS.plane1S.normal_z[1] =
		-mol_complexSP->membraneS.plane1S.normal_x[0] * sin_angle +
		 mol_complexSP->membraneS.plane1S.normal_z[0] * cos_angle;
mol_complexSP->membraneS.plane2S.normal_x[1] =
		 mol_complexSP->membraneS.plane2S.normal_x[0] * cos_angle +
		 mol_complexSP->membraneS.plane2S.normal_z[0] * sin_angle;
mol_complexSP->membraneS.plane2S.normal_z[1] =
		-mol_complexSP->membraneS.plane2S.normal_x[0] * sin_angle +
		 mol_complexSP->membraneS.plane2S.normal_z[0] * cos_angle;

/*---------------------------------------------------------------------------*/

/* Return positive value on success: */
return 1;
}

/*===========================================================================*/


