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

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

				alpha_normal.c

Purpose:
	Refine the normal vector which is required to define the membrane
	for  alpha helix bundle  protein.  The normal vector  is declined
	from its original direction and a set of alternative positions is
	scanned.  For each trial,  calculate  the average  hydrophobicity
	associated with the cell which is nearest to the reference point.
	The  sliding  window  width  should  be  similar to  the membrane
	thickness  (slightly larger, in fact). The best  normal vector is
	the one  which gives  the highest  average hydrophobicity  at the
	reference point.

Input:
	(1) Pointer to  VectorS structure,  with  the normal vector.  The
	    components of this vector will be updated.
	(2) Pointer to MolComplexS structure,  with the chosen structure.
	(3) The tilt step,  used to decline  the normal  vector  from its
	    original direction.

Output:
	(1) On success, the normal vector will be refined.
	(2) Return value.

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

Notes:
	(1) Indentation is exceptionally four spaces.

	(2) On failure,  remember  to free  the allocated storage  before
	    returning to the caller.

	(3) If the  tilt_step is set equal to 0.05, the maximal deviation
	    of  the normal vector  from  its original  direction  will be
	    about 31 degree in each direction, about each of two axis.

	(4) On success,  this function will normalize  the normal vector.

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

#include <stdio.h>

#include <stdlib.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		AbsoluteValue_ (VectorS *);
double		ScalarProduct_ (VectorS *, VectorS *);
void		VectorProduct_ (VectorS *, VectorS *, VectorS *);
int		ExtractCA_ (VectorS *, AtomS *, size_t, size_t);

/*======refine the normal vector (helix bundle version):=====================*/

int AlphaNormalVector_ (VectorS *normal_vectorSP,
			MolComplexS *mol_complexSP, double tilt_step)
{
int			residuesN, residueI;
size_t			double_size, int_size;
int			cellsN = 10000;
static double		*hydrophobicityP;
static int		*projectionsNP;
static int		*cells_usedNP;
VectorS			center_vectorS;
int			centralI;
double			cell_width = 1.0, half_cell_width;
double			reciprocal_cell_width;
int			half_window_width;
double			abs_value, reciprocal_abs_value;
VectorS			unit_vector1S, unit_vector2S, unit_vector3S;
VectorS			aux_vectorS;
double			best_average;
int			best_i, best_j;
int			i, j, k;
double			d1, d2;
ResidueS		*curr_residueSP;
int			first_atomI, last_atomI;
int			n;
VectorS			CA_vectorS;
AtomS			*first_atomSP;
double			hydrophobicity;
VectorS			radius_vectorS;
double			reciprocal_denominator;
double			projection;
int			cellI;
int			used_cellsN;
double			average;
int			windowI, combinedI;

/* Copy the number of residues: */
residuesN = mol_complexSP->residuesN;

/* Double and int size: */
double_size = sizeof (double);
int_size = sizeof (int);

/* Allocate the memory for the array of hydrophobicity values: */
hydrophobicityP = (double *) calloc (cellsN, double_size);
if (!hydrophobicityP)
    {
    return -1;
    }

/* Allocate the memory required to store the number of projections per cell: */
projectionsNP = (int *) calloc (cellsN, int_size);
if (!projectionsNP)
    {
    free (hydrophobicityP);
    return -2;
    }

/* Allocate the memory for the total number of used cells: */
cells_usedNP = (int *) calloc (cellsN, int_size);
if (!cells_usedNP)
    {
    free (hydrophobicityP);
    free (projectionsNP);
    return -3;
    }

/* Copy the vector which defines the membrane center: */
center_vectorS.x = mol_complexSP->membraneS.center_x;
center_vectorS.y = mol_complexSP->membraneS.center_y;
center_vectorS.z = mol_complexSP->membraneS.center_z;

/* Prepare  the central  index,  half of the */
/* cell width and the reciprocal cell width: */
centralI = cellsN / 2;
if (cell_width == 0.0)
    {
    free (hydrophobicityP);
    free (projectionsNP);
    free (cells_usedNP);
    return -4;
    }
half_cell_width = 0.5 * cell_width;
reciprocal_cell_width = 1.0 / cell_width;

/* Prepare the half of the window width.  The window is used for */
/* the averaging of  total hydrophobicities.  The width  of this */
/* window should be slightly larger than the membrane thickness. */
/* The minimal half-width is 1 and  the minimal full width is 3. */
half_window_width = (int) (mol_complexSP->membraneS.thickness / cell_width);
half_window_width /= 2;
half_window_width += 1;

/* Prepare the first unit vector. This vector */
/* will be collinear  with the normal vector: */
abs_value = AbsoluteValue_ (normal_vectorSP);
if (abs_value == 0.0)
    {
    free (hydrophobicityP);
    free (projectionsNP);
    free (cells_usedNP);
    return -5;
    }
reciprocal_abs_value = 1.0 / abs_value;
unit_vector1S.x = reciprocal_abs_value * normal_vectorSP->x;
unit_vector1S.y = reciprocal_abs_value * normal_vectorSP->y;
unit_vector1S.z = reciprocal_abs_value * normal_vectorSP->z;

/* Now prepare the second unit vector. It will */
/* be perpendicular to  the first unit vector. */

/* Prepare  one  auxiliary  vector  which  is  not */
/* collinear with the first unit vector.  For each */
/* unit vector, the absolute value of at least one */
/* component is larger than or equal to  0.577350. */
if (fabs (unit_vector1S.x) >= 0.5)
    {
    aux_vectorS.x = 0.0;
    aux_vectorS.y = unit_vector1S.y + 4.0;
    aux_vectorS.z = unit_vector1S.z + 4.0;
    }
else if (fabs (unit_vector1S.y) >= 0.5)
    {
    aux_vectorS.x = unit_vector1S.x + 4.0;
    aux_vectorS.y = 0.0;
    aux_vectorS.z = unit_vector1S.z + 4.0;
    }
else
    {
    aux_vectorS.x = unit_vector1S.x + 4.0;
    aux_vectorS.y = unit_vector1S.y + 4.0;
    aux_vectorS.z = 0.0;
    }

/* Check  the scalar product between  the auxialiary */
/* vector and the first unit vector (I am paranoic): */
if (ScalarProduct_ (&aux_vectorS, &unit_vector1S) == 0.0)
    {
    free (hydrophobicityP);
    free (projectionsNP);
    free (cells_usedNP);
    return -6;
    }

/* Now prepare the second unit vector. It will */
/* be perpendicular to  the first unit vector: */
VectorProduct_ (&unit_vector2S, &unit_vector1S, &aux_vectorS);

/* Check and normalize the second unit vector: */
abs_value = AbsoluteValue_ (&unit_vector2S);
if (abs_value == 0.0)
    {
    free (hydrophobicityP);
    free (projectionsNP);
    free (cells_usedNP);
    return -7;
    }
reciprocal_abs_value = 1.0 / abs_value;
unit_vector2S.x *= reciprocal_abs_value;
unit_vector2S.y *= reciprocal_abs_value;
unit_vector2S.z *= reciprocal_abs_value;

/* Prepare the third unit vector: */
VectorProduct_ (&unit_vector3S, &unit_vector1S, &unit_vector2S);

/*--------------------------------------------------*/
/*                                                  */
/* Prepare 25 x 25 = 625 vectors. For each of these */
/* vectors,  a number of operations should be done: */
/*                                                  */
/*---------------------------------------------------------------------*/
/*                                                                     */
/* (1) Project all residues to  the axis  defined by  the given vector */
/*     and by the reference point (this point is the membrane center). */
/*                                                                     */
/* (2) Divide  the axis  into  a number  of cells  and for  each  cell */
/*     calculate  the total hydrophobicity  for residues which project */
/*     to this cell.                                                   */
/*                                                                     */
/* (3) Average  the  total  hydrophobicities  for  all  cells  in  the */
/*     neighborhood of the central cell.  Take the window which covers */ 
/*     the entire thickness of  the membrane.  The central cell should */
/*     be in the middle of this window, of course.                     */
/*                                                                     */
/* (4) Take  the vector  for which  the average  total  hydrophobicity */
/*     assigned to  the central cell has the highest value.  Copy this */
/*     vector to the normal vector.                                    */
/*                                                                     */
/*---------------------------------------------------------------------*/

best_average = -999999.0;
best_i = 999;
best_j = 999;

/* Check 25 x 25 vectors: */
for (i = -12; i <= 12; i++)
    {
    d1 = i * tilt_step;
    for (j = -12; j <= 12; j++)
	{
	/* Prepare the auxiliary vector: */
	d2 = j * tilt_step;
	aux_vectorS.x = unit_vector1S.x +
			unit_vector2S.x * d1 +
			unit_vector3S.x * d2;
	aux_vectorS.y = unit_vector1S.y +
			unit_vector2S.y * d1 +
			unit_vector3S.y * d2;
	aux_vectorS.z = unit_vector1S.z +
			unit_vector2S.z * d1 +
			unit_vector3S.z * d2;

	/* Normalize the auxiliary vector: */
	abs_value = AbsoluteValue_ (&aux_vectorS);
	if (abs_value == 0.0)
	    {
	    free (hydrophobicityP);
	    free (projectionsNP);
	    free (cells_usedNP);
	    return -8;
	    }
	reciprocal_denominator = 1.0 / abs_value;
	aux_vectorS.x *= reciprocal_denominator;
	aux_vectorS.y *= reciprocal_denominator;
	aux_vectorS.z *= reciprocal_denominator;

	/* Reset three arrays which are used in residueI loop: */
	for (k = 0; k < cellsN; k++)
	    {
	    *(hydrophobicityP + k) = 0.0;
	    *(projectionsNP   + k) = 0;
	    *(cells_usedNP    + k) = 0;
	    }

	/* Now project  the hydrophobicities of  all residues to */
	/* the reference axis  defined  by the current  membrane */
	/* center and by the normal vector.  The axis is divided */
	/* into cells. The width of a single cell is cell_width. */

	/* Scan all residues and project CA atoms to the reference axis: */
	for (residueI = 0; residueI < residuesN; residueI++)
	    {
	    /* Pointer to the current residue: */
	    curr_residueSP = mol_complexSP->residueSP + residueI;

	    /* Copy the indices of the first and of the last atom: */
	    first_atomI = curr_residueSP->residue_startI;
	    last_atomI  = curr_residueSP->residue_endI;

	    /* Extract the position of CA atom. */
	    n = ExtractCA_ (&CA_vectorS, mol_complexSP->atomSP,
			    first_atomI, last_atomI);
	    if (n != 1) continue;

	    /* Copy the hydrophobicity associated with this residue: */
	    first_atomSP = (mol_complexSP->atomSP + first_atomI);
	    hydrophobicity = first_atomSP->raw_atomS.hydrophobicity;

	    /* Prepare the vector from the membrane center to the CA atom: */
	    radius_vectorS.x = CA_vectorS.x - center_vectorS.x;
	    radius_vectorS.y = CA_vectorS.y - center_vectorS.y;
	    radius_vectorS.z = CA_vectorS.z - center_vectorS.z;

	    /* Project the radius vector: */
	    projection = ScalarProduct_ (&radius_vectorS, &aux_vectorS);

	    /* Prepare and check the cell index: */
	    cellI = centralI +
		    reciprocal_cell_width * (projection - half_cell_width);
	    if (cellI < 0) continue;
	    if (cellI >= cellsN) continue;

	    /* Update the total hydrophobicity stored */
	    /* to the cell with the given cell index. */

	    /* Update the total hydrophobicity stored */
	    /* to the cell with the given cell index. */

	    /* Update the number of CA atoms projected to the given cell: */
	    (*(projectionsNP + cellI))++;

	    /* Update the total hydrophobicity: */
	    *(hydrophobicityP + cellI) += hydrophobicity;
	    }

	/* Average the total hydrophobicities  over cells. */
	/* The cell which is associated  with the membrane */
	/* center should be in  the middle  of the window. */

	/* Reset the number of cells in a window and the average value: */
	used_cellsN = 0;
	average = 0.0;

	/* Scan the window: */
        for (windowI = -half_window_width;
	     windowI <= half_window_width; windowI++)
	    {
	    /* Prepare the combined index: */
	    combinedI = centralI + windowI;

	    /* Skip empty cells: */
	    if (*(projectionsNP + combinedI) == 0) continue;

	    /* Update the number of used cells and */
	    /* the sum of  total hydrophobicities: */
	    used_cellsN++;
	    average += *(hydrophobicityP + combinedI);
	    }

	/* Calculate the average value: */
	if (used_cellsN != 0) average /= (double) used_cellsN;
	else average = -999999.0;

	/* Check is it the best overall average: */
	if (average > best_average)
	    {
	    best_average = average;
	    best_i = i;
	    best_j = j;
	    }
	}
    }

/* If the best average value was not found (rather strange */
/* outcome,  but I am paranoic),  return  negative  value: */
if ((best_i == 999) || (best_j == 999))
    {
    free (hydrophobicityP);
    free (projectionsNP);
    free (cells_usedNP);
    return -9;
    }

/* If this point is reached, the best average */
/* value was found. Update the normal vector: */
d1 = best_i * tilt_step;
d2 = best_j * tilt_step;
normal_vectorSP->x = unit_vector1S.x +
		     unit_vector2S.x * d1 +
		     unit_vector3S.x * d2;
normal_vectorSP->y = unit_vector1S.y +
		     unit_vector2S.y * d1 +
		     unit_vector3S.y * d2;
normal_vectorSP->z = unit_vector1S.z +
		     unit_vector2S.z * d1 +
		     unit_vector3S.z * d2;

/* Make sure that the absolute value of the normal vector is equal to one: */
abs_value = AbsoluteValue_ (normal_vectorSP);
if (abs_value == 0.0)
    {
    free (hydrophobicityP);
    free (projectionsNP);
    free (cells_usedNP);
    return -10;
    }
reciprocal_denominator = 1.0 / abs_value;
normal_vectorSP->x *= reciprocal_denominator;
normal_vectorSP->y *= reciprocal_denominator;
normal_vectorSP->z *= reciprocal_denominator;

/* Free storage: */
free (hydrophobicityP);
free (projectionsNP);
free (cells_usedNP);

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

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


