Exemplo n.º 1
0
int main()
{
	srand(time(NULL));
	//fillArr(a, n);
	inverse_matrix();
	return 0;
}
		static testing::AssertionResult animated_transform_interpolate_near(
		        const char *animated_transform_expr,
		        const char *transform_expr,
		        const char * /*time_expr*/,
		        const char *abs_error_expr,
		        const AnimatedTransform &animated_transform,
		        const Transform &transform,
		        real_t time,
		        real_t abs_error)
		{
			auto transform_at_time = animated_transform.interpolate(time);
			auto m1 = transform_at_time.matrix();
			auto m1_inv = transform_at_time.inverse_matrix();
			auto m2 = transform.matrix();
			auto m2_inv = transform.inverse_matrix();

			for (unsigned int i = 0; i < 4; i++)
			{
				for (unsigned int j = 0; j < 4; j++)
					if (std::abs(m1(i, j) - m2(i, j)) > abs_error ||
					    std::abs(m1_inv(i, j) - m2_inv(i, j)) > abs_error)
						return testing::AssertionFailure()
						       << animated_transform_expr << " has elements that differ more "
						       << "than " << abs_error_expr << " from " << transform_expr
						       << " at time " << time << ".";
			}

			return testing::AssertionSuccess();
		}
Exemplo n.º 3
0
void inverse_interface(){
	int size;

	printf("Insert how many line/columns your matrix have: ");
	scanf("%d", &size);
 
	bool check_matrix = verify(0, size, size, 0, 0);
	if(check_matrix == true){
		double (**matrix) = createNewMatrix(size, size);
		if(determinant(matrix, size) != 0.0){
			double (**result) = inverse_matrix(matrix, size);
			printf("The inverse matrix is:\n");
			print_matrix(size, size, result);
		}else{
			printf("Your matrix do not have an inverse\n");
		}
	}else{
		printf("There is an error with your input data.\nCheck them please.\n");
	}
}
/* Aplica transformações geométrica à localização do vértice corrente e ao vetor normal associado a ele.
 *
 *   Argumentos de entrada:
 *     'vertex_oc'        : Localização do vértice representada no sistema de coordenadas do objeto (object coordinates, OC).
 *     'normal_oc'        : Vetor normal à superfície representada no sistema de coordenadas do objeto (OC).
 *     'modelview_matrix' : Matriz 4x4 composta pelas transformações de modelo e visualização (view_matrix * model_matrix).
 *     'projection_matrix': Matriz 4x4 de projeção.
 *
 *   Argumentos de saída:
 *     'vertex_ec'        : Localização do vértice representada no sistema de coordenadas da câmera (eye coordinates, EC).
 *     'vertex_cc'        : Localização do vértice representada no sistema coordenadas de recorte (clip coordinates, CC).
 *     'unit_normal_ec'   : Vetor normal à superfície representado no sistema de coordenadas da câmera (EC). Assume-se que
 *                          a norma deste vetor é igual a 1.0f.
 */
void vertex_transformation(const location_struct &vertex_oc, const direction_struct &normal_oc, const matrix_struct &modelview_matrix, const matrix_struct &projection_matrix, location_struct &vertex_ec, location_struct &vertex_cc, direction_struct &unit_normal_ec) {
     //Calcular 'vertex_ec'.
     //Calcular 'vertex_cc'.
     //Calcular 'unit_normal_ec'.

	vertex_ec[0] = vertex_oc[0] * modelview_matrix(0,0) + vertex_oc[1] * modelview_matrix(0,1) + 
		vertex_oc[2] * modelview_matrix(0,2) + vertex_oc[3] * modelview_matrix(0,3);
	vertex_ec[1] = vertex_oc[0] * modelview_matrix(1,0) + vertex_oc[1] * modelview_matrix(1,1) + 
		vertex_oc[2] * modelview_matrix(1,2) + vertex_oc[3] * modelview_matrix(1,3);
	vertex_ec[2] = vertex_oc[0] * modelview_matrix(2,0) + vertex_oc[1] * modelview_matrix(2,1) + 
		vertex_oc[2] * modelview_matrix(2,2) + vertex_oc[3] * modelview_matrix(2,3);
	vertex_ec[3] = vertex_oc[0] * modelview_matrix(3,0) + vertex_oc[1] * modelview_matrix(3,1) + 
		vertex_oc[2] * modelview_matrix(3,2) + vertex_oc[3] * modelview_matrix(3,3);

	vertex_cc[0] = vertex_ec[0] * projection_matrix(0,0) + vertex_ec[1] * projection_matrix(0,1) + 
		vertex_ec[2] * projection_matrix(0,2) + vertex_ec[3] * projection_matrix(0,3);
	vertex_cc[1] = vertex_ec[0] * projection_matrix(1,0) + vertex_ec[1] * projection_matrix(1,1) + 
		vertex_ec[2] * projection_matrix(1,2) + vertex_ec[3] * projection_matrix(1,3);
	vertex_cc[2] = vertex_ec[0] * projection_matrix(2,0) + vertex_ec[1] * projection_matrix(2,1) + 
		vertex_ec[2] * projection_matrix(2,2) + vertex_ec[3] * projection_matrix(2,3);
	vertex_cc[3] = vertex_ec[0] * projection_matrix(3,0) + vertex_ec[1] * projection_matrix(3,1) + 
		vertex_ec[2] * projection_matrix(3,2) + vertex_ec[3] * projection_matrix(3,3);

	matrix_struct transposta = matrix_struct();
	matrix_struct inverse = matrix_struct();

	inverse_matrix(modelview_matrix, inverse);

	transpose_matrix(inverse, transposta);

	unit_normal_ec[0] = normal_oc[0] * transposta(0,0) +  normal_oc[1] *  transposta(0,1) + 
		normal_oc[2] *  transposta(0,2);
	unit_normal_ec[1] = normal_oc[0] * transposta(1,0) +  normal_oc[1] *  transposta(1,1) + 
		normal_oc[2] *  transposta(1,2);
	unit_normal_ec[2] = normal_oc[0] * transposta(2,0) +  normal_oc[1] *  transposta(2,1) + 
		normal_oc[2] *  transposta(2,2);

	normalize(unit_normal_ec);
}
Exemplo n.º 5
0
void pie_Draw3DShape(iIMDShape *shape, int frame, int team, PIELIGHT colour, int pieFlag, int pieFlagData)
{
	PIELIGHT teamcolour;

	ASSERT_OR_RETURN(, shape, "Attempting to draw null sprite");

	teamcolour = pal_GetTeamColour(team);

	pieCount++;

	ASSERT(frame >= 0, "Negative frame %d", frame);
	ASSERT(team >= 0, "Negative team %d", team);

	if (drawing_interface || !shadows)
	{
		pie_Draw3DShape2(shape, frame, colour, teamcolour, pieFlag, pieFlagData);
	}
	else
	{
		if (pieFlag & (pie_ADDITIVE | pie_TRANSLUCENT | pie_PREMULTIPLIED) && !(pieFlag & pie_FORCE_IMMEDIATE))
		{
			TranslucentShape tshape;
			glGetFloatv(GL_MODELVIEW_MATRIX, tshape.matrix);
			tshape.shape = shape;
			tshape.frame = frame;
			tshape.colour = colour;
			tshape.flag = pieFlag;
			tshape.flag_data = pieFlagData;
			tshapes.push_back(tshape);
		}
		else
		{
			if(pieFlag & pie_SHADOW || pieFlag & pie_STATIC_SHADOW)
			{
				float distance;

				// draw a shadow
				ShadowcastingShape scshape;
				glGetFloatv(GL_MODELVIEW_MATRIX, scshape.matrix);
				distance = scshape.matrix[12] * scshape.matrix[12];
				distance += scshape.matrix[13] * scshape.matrix[13];
				distance += scshape.matrix[14] * scshape.matrix[14];

				// if object is too far in the fog don't generate a shadow.
				if (distance < SHADOW_END_DISTANCE)
				{
					float invmat[9], pos_light0[4];

					inverse_matrix( scshape.matrix, invmat );

					// Calculate the light position relative to the object
					glGetLightfv(GL_LIGHT0, GL_POSITION, pos_light0);
					scshape.light.x = invmat[0] * pos_light0[0] + invmat[3] * pos_light0[1] + invmat[6] * pos_light0[2];
					scshape.light.y = invmat[1] * pos_light0[0] + invmat[4] * pos_light0[1] + invmat[7] * pos_light0[2];
					scshape.light.z = invmat[2] * pos_light0[0] + invmat[5] * pos_light0[1] + invmat[8] * pos_light0[2];

					scshape.shape = shape;
					scshape.flag = pieFlag;
					scshape.flag_data = pieFlagData;

					scshapes.push_back(scshape);
				}
			}

			pie_Draw3DShape2(shape, frame, colour, teamcolour, pieFlag, pieFlagData);
		}
	}
}
Exemplo n.º 6
0
void pie_Draw3DShape(iIMDShape *shape, int frame, int team, PIELIGHT colour, PIELIGHT specular, int pieFlag, int pieFlagData)
{
	PIELIGHT teamcolour;

	ASSERT_OR_RETURN(, shape, "Attempting to draw null sprite");

	teamcolour = pal_GetTeamColour(team);

	pieCount++;

	if (frame == 0)
	{
		frame = team;
	}

	if (drawing_interface || !shadows)
	{
		pie_Draw3DShape2(shape, frame, colour, teamcolour, specular, pieFlag, pieFlagData);
	}
	else
	{
		if (pieFlag & (pie_ADDITIVE | pie_TRANSLUCENT))
		{
			if (tshapes_size <= nb_tshapes)
			{
				if (tshapes_size == 0)
				{
					tshapes_size = 64;
					tshapes = (transluscent_shape_t*)malloc(tshapes_size*sizeof(transluscent_shape_t));
					memset( tshapes, 0, tshapes_size*sizeof(transluscent_shape_t) );
				}
				else
				{
					const unsigned int old_size = tshapes_size;
					tshapes_size <<= 1;
					tshapes = (transluscent_shape_t*)realloc(tshapes, tshapes_size*sizeof(transluscent_shape_t));
					memset( &tshapes[old_size], 0, (tshapes_size-old_size)*sizeof(transluscent_shape_t) );
				}
			}
			glGetFloatv(GL_MODELVIEW_MATRIX, tshapes[nb_tshapes].matrix);
			tshapes[nb_tshapes].shape = shape;
			tshapes[nb_tshapes].frame = frame;
			tshapes[nb_tshapes].colour = colour;
			tshapes[nb_tshapes].specular = specular;
			tshapes[nb_tshapes].flag = pieFlag;
			tshapes[nb_tshapes].flag_data = pieFlagData;
			nb_tshapes++;
		}
		else
		{
			if(pieFlag & pie_SHADOW || pieFlag & pie_STATIC_SHADOW)
			{
				float distance;

				// draw a shadow
				if (scshapes_size <= nb_scshapes)
				{
					if (scshapes_size == 0)
					{
						scshapes_size = 64;
						scshapes = (shadowcasting_shape_t*)malloc(scshapes_size*sizeof(shadowcasting_shape_t));
						memset( scshapes, 0, scshapes_size*sizeof(shadowcasting_shape_t) );
					}
					else
					{
						const unsigned int old_size = scshapes_size;
						scshapes_size <<= 1;
						scshapes = (shadowcasting_shape_t*)realloc(scshapes, scshapes_size*sizeof(shadowcasting_shape_t));
						memset( &scshapes[old_size], 0, (scshapes_size-old_size)*sizeof(shadowcasting_shape_t) );
					}
				}

				glGetFloatv(GL_MODELVIEW_MATRIX, scshapes[nb_scshapes].matrix);
				distance = scshapes[nb_scshapes].matrix[12] * scshapes[nb_scshapes].matrix[12];
				distance += scshapes[nb_scshapes].matrix[13] * scshapes[nb_scshapes].matrix[13];
				distance += scshapes[nb_scshapes].matrix[14] * scshapes[nb_scshapes].matrix[14];

				// if object is too far in the fog don't generate a shadow.
				if (distance < SHADOW_END_DISTANCE)
				{
					float invmat[9], pos_light0[4];

					inverse_matrix( scshapes[nb_scshapes].matrix, invmat );

					// Calculate the light position relative to the object
					glGetLightfv(GL_LIGHT0, GL_POSITION, pos_light0);
					scshapes[nb_scshapes].light.x = invmat[0] * pos_light0[0] + invmat[3] * pos_light0[1] + invmat[6] * pos_light0[2];
					scshapes[nb_scshapes].light.y = invmat[1] * pos_light0[0] + invmat[4] * pos_light0[1] + invmat[7] * pos_light0[2];
					scshapes[nb_scshapes].light.z = invmat[2] * pos_light0[0] + invmat[5] * pos_light0[1] + invmat[8] * pos_light0[2];

					scshapes[nb_scshapes].shape = shape;
					scshapes[nb_scshapes].flag = pieFlag;
					scshapes[nb_scshapes].flag_data = pieFlagData;

					nb_scshapes++;
				}
			}

			pie_Draw3DShape2(shape, frame, colour, teamcolour, specular, pieFlag, pieFlagData);
		}
	}
}
Exemplo n.º 7
0
int main()
{
	inverse_matrix();
	return 0;
}
Exemplo n.º 8
0
static int computeMatrixLMSOpt(TAsoc *cp_ass, int cnt, Tsc *estimacion) {

int i;
float LMETRICA2;
float X1[MAXLASERPOINTS], Y1[MAXLASERPOINTS];
float X2[MAXLASERPOINTS],Y2[MAXLASERPOINTS];
float X2Y2[MAXLASERPOINTS],X1X2[MAXLASERPOINTS];
float X1Y2[MAXLASERPOINTS], Y1X2[MAXLASERPOINTS];
float Y1Y2[MAXLASERPOINTS];
float K[MAXLASERPOINTS], DS[MAXLASERPOINTS];
float DsD[MAXLASERPOINTS], X2DsD[MAXLASERPOINTS], Y2DsD[MAXLASERPOINTS];
float Bs[MAXLASERPOINTS], BsD[MAXLASERPOINTS];
float A1, A2, A3, B1, B2, B3, C1, C2, C3, D1, D2, D3;
MATRIX matA,invMatA;
VECTOR vecB,vecSol;

A1=0;A2=0;A3=0;B1=0;B2=0;B3=0;
C1=0;C2=0;C3=0;D1=0;D2=0;D3=0;


LMETRICA2=params.LMET*params.LMET;

for (i=0; i<cnt; i++){
	X1[i]=cp_ass[i].nx*cp_ass[i].nx;
	Y1[i]=cp_ass[i].ny*cp_ass[i].ny;
	X2[i]=cp_ass[i].rx*cp_ass[i].rx;
	Y2[i]=cp_ass[i].ry*cp_ass[i].ry;
	X2Y2[i]=cp_ass[i].rx*cp_ass[i].ry;

	X1X2[i]=cp_ass[i].nx*cp_ass[i].rx;
	X1Y2[i]=cp_ass[i].nx*cp_ass[i].ry;
	Y1X2[i]=cp_ass[i].ny*cp_ass[i].rx;
	Y1Y2[i]=cp_ass[i].ny*cp_ass[i].ry;

	K[i]=X2[i]+Y2[i] + LMETRICA2;
	DS[i]=Y1Y2[i] + X1X2[i];
	DsD[i]=DS[i]/K[i];
	X2DsD[i]=cp_ass[i].rx*DsD[i];
	Y2DsD[i]=cp_ass[i].ry*DsD[i];

	Bs[i]=X1Y2[i]-Y1X2[i];
	BsD[i]=Bs[i]/K[i];

	A1=A1 + (1-Y2[i]/K[i]);
	B1=B1 + X2Y2[i]/K[i];
	C1=C1 + (-cp_ass[i].ny + Y2DsD[i]);
	D1=D1 + (cp_ass[i].nx - cp_ass[i].rx -cp_ass[i].ry*BsD[i]);

	A2=B1;
	B2=B2 + (1-X2[i]/K[i]);
	C2=C2 + (cp_ass[i].nx-X2DsD[i]);
	D2=D2 + (cp_ass[i].ny -cp_ass[i].ry +cp_ass[i].rx*BsD[i]);

	A3=C1;
	B3=C2;
	C3=C3 + (X1[i] + Y1[i] - DS[i]*DS[i]/K[i]);
	D3=D3 + (Bs[i]*(-1+DsD[i]));
}


initialize_matrix(&matA,3,3);
MDATA(matA,0,0)=A1;	MDATA(matA,0,1)=B1;	MDATA(matA,0,2)=C1;
MDATA(matA,1,0)=A2;	MDATA(matA,1,1)=B2;	MDATA(matA,1,2)=C2;
MDATA(matA,2,0)=A3;	MDATA(matA,2,1)=B3;	MDATA(matA,2,2)=C3;

if (inverse_matrix (&matA, &invMatA)==-1)
	return -1;

#ifdef INTMATSM_DEB
print_matrix("inverted matrix", &invMatA);
#endif

initialize_vector(&vecB,3);
VDATA(vecB,0)=D1; VDATA(vecB,1)=D2; VDATA(vecB,2)=D3;
multiply_matrix_vector (&invMatA, &vecB, &vecSol);

estimacion->x=-VDATA(vecSol,0);
estimacion->y=-VDATA(vecSol,1);
estimacion->tita=-VDATA(vecSol,2);

return 1;
}
Exemplo n.º 9
0
/*!\rst
  Test that SPDMatrixInverse and CholeskyFactorLMatrixVectorSolve are  working correctly
  against some especially bad named matrices and some random inputs.
  Outline:

  1. Construct matrices, ``A``
  2. Select a solution, ``x``, randomly.
  3. Construct RHS by doing ``A*x``.
  4. Solve ``Ax = b`` using backsolve and direct-inverse; check the size of ``\|b - Ax\|``.

  \return
    number of test cases where the solver error is too large
\endrst*/
OL_WARN_UNUSED_RESULT int TestSPDLinearSolvers() {
  int total_errors = 0;

  // simple/small case where numerical factors are not present.
  // taken from: http://en.wikipedia.org/wiki/Cholesky_decomposition#Example
  {
    constexpr int size = 3;
    std::vector<double> matrix =
        {  4.0,   12.0, -16.0,
          12.0,   37.0, -43.0,
         -16.0,  -43.0,  98.0};

    const std::vector<double> cholesky_factor_L_truth =
        { 2.0, 6.0, -8.0,
          0.0, 1.0, 5.0,
          0.0, 0.0, 3.0};
    std::vector<double> rhs = {-20.0, -43.0, 192.0};
    std::vector<double> solution_truth = {1.0, 2.0, 3.0};

    int local_errors = 0;
    // check factorization is correct; only check lower-triangle
    if (ComputeCholeskyFactorL(size, matrix.data()) != 0) {
      ++total_errors;
    }
    for (int i = 0; i < size; ++i) {
      for (int j = 0; j < size; ++j) {
        if (j >= i) {
          if (!CheckDoubleWithinRelative(matrix[i*size + j], cholesky_factor_L_truth[i*size + j], 0.0)) {
            ++local_errors;
          }
        }
      }
    }

    // check the solve is correct
    CholeskyFactorLMatrixVectorSolve(matrix.data(), size, rhs.data());
    for (int i = 0; i < size; ++i) {
      if (!CheckDoubleWithinRelative(rhs[i], solution_truth[i], 0.0)) {
        ++local_errors;
      }
    }

    total_errors += local_errors;
  }

  const int num_tests = 10;
  const int num_test_sizes = 3;
  const int sizes[num_test_sizes] = {5, 11, 20};

  // following tolerances are based on numerical experiments and/or computations
  // of the matrix condition numbers (in MATLAB)
  const double tolerance_backsolve_max_list[3][num_test_sizes] =
      { {10*std::numeric_limits<double>::epsilon(), 100*std::numeric_limits<double>::epsilon(), 100*std::numeric_limits<double>::epsilon()},       // prolate
        {100*std::numeric_limits<double>::epsilon(), 1.0e4*std::numeric_limits<double>::epsilon(), 1.0e6*std::numeric_limits<double>::epsilon()},  // moler
        {50*std::numeric_limits<double>::epsilon(), 1.0e3*std::numeric_limits<double>::epsilon(), 5.0e4*std::numeric_limits<double>::epsilon()}    // random
      };
  const double tolerance_inverse_max_list[3][num_test_sizes] =
      { {1.0e-13, 1.0e-9, 1.0e-2},  // prolate
        {5.0e-13, 2.0e-8, 1.0e1},   // moler
        {7.0e-10, 7.0e-6, 1.0e2}    // random
      };

  UniformRandomGenerator uniform_generator(34187);
  // In each iteration, we form some an ill-conditioned SPD matrix.  We are using
  // prolate, moler, and random matrices.
  // Then we compute L * L^T = A.
  // We want to test solutions of A * x = b using two methods:
  //   1) Inverse: using L, we form A^-1 explicitly (ILL-CONDITIONED!)
  //   2) Backsolve: we never form A^-1, but instead backsolve L and L^T against b.
  // The resulting residual norms, ||b - A*x||_2 are computed; we check that
  // backsolve is accurate and inverse is affected strongly by conditioning.
  for (int j = 0; j < num_tests; ++j) {
    for (int i = 0; i < num_test_sizes; ++i) {
      std::vector<double> matrix(sizes[i]*sizes[i]);
      std::vector<double> inverse_matrix(sizes[i]*sizes[i]);
      std::vector<double> cholesky_factor(sizes[i]*sizes[i]);
      std::vector<double> rhs(sizes[i]);
      std::vector<double> solution(2*sizes[i]);

      double tolerance_backsolve_max;
      double tolerance_inverse_max;
      switch (j) {
        case 0: {
          BuildProlateMatrix(kProlateDefaultParameter, sizes[i], matrix.data());
          tolerance_backsolve_max = tolerance_backsolve_max_list[0][i];
          tolerance_inverse_max = tolerance_inverse_max_list[0][i];
          break;
        }
        case 1: {
          BuildMolerMatrix(-1.66666666666, sizes[i], matrix.data());
          tolerance_backsolve_max = tolerance_backsolve_max_list[1][i];
          tolerance_inverse_max = tolerance_inverse_max_list[1][i];
          break;
        }
        default: {
          if (j <= 1 || j > num_tests) {
            OL_THROW_EXCEPTION(BoundsException<int>, "Invalid switch option.", j, 2, num_tests);
          } else {
            BuildRandomSPDMatrix(sizes[i], &uniform_generator, matrix.data());
            tolerance_backsolve_max = tolerance_backsolve_max_list[2][i];
            tolerance_inverse_max = tolerance_inverse_max_list[2][i];
            break;
          }
        }
      }
      // cholesky-factor A, form A^-1
      std::copy(matrix.begin(), matrix.end(), cholesky_factor.begin());
      if (ComputeCholeskyFactorL(sizes[i], cholesky_factor.data()) != 0) {
        ++total_errors;
      }
      SPDMatrixInverse(cholesky_factor.data(), sizes[i], inverse_matrix.data());

      // set b = A*random_vector.  This way we know the solution explicitly.
      // this also allows us to ignore ||A|| in our computations when we
      // normalize the RHS.
      BuildRandomVector(sizes[i], 0.0, 1.0, &uniform_generator, solution.data());
      SymmetricMatrixVectorMultiply(matrix.data(), solution.data(), sizes[i], rhs.data());

      // re-scale the RHS so that its norm can be ignored in later computations
      double rhs_norm = VectorNorm(rhs.data(), sizes[i]);
      VectorScale(sizes[i], 1.0/rhs_norm, rhs.data());
      std::copy(rhs.begin(), rhs.end(), solution.begin());

      // Solve L * L^T * x1 = b (backsolve) and compute x2 = A^-1 * b
      CholeskyFactorLMatrixVectorSolve(cholesky_factor.data(), sizes[i], solution.data());
      SymmetricMatrixVectorMultiply(inverse_matrix.data(), rhs.data(), sizes[i], solution.data() + sizes[i]);

      double norm_residual_via_backsolve = ResidualNorm(matrix.data(), solution.data(), rhs.data(), sizes[i]);
      double norm_residual_via_inverse = ResidualNorm(matrix.data(), solution.data() + sizes[i], rhs.data(), sizes[i]);

      if (norm_residual_via_backsolve > tolerance_backsolve_max) {
        ++total_errors;
        OL_ERROR_PRINTF("experiment %d, size[%d] = %d, norm_backsolve = %.18E > %.18E = tol\n", j, i, sizes[i],
               norm_residual_via_backsolve, tolerance_backsolve_max);
      }

      if (norm_residual_via_inverse > tolerance_inverse_max) {
        ++total_errors;
        OL_ERROR_PRINTF("experiment %d, size[%d] = %d, norm_inverse = %.18E > %.18E = tol\n", j, i, sizes[i],
               norm_residual_via_inverse, tolerance_inverse_max);
      }
    }
  }

  return total_errors;
}
Exemplo n.º 10
0
/************************ end self doc ***********************************/ 
  void main (int argc, char **argv)
{
   /* declaration of variables */
   FILE *fp, *gp;                /* file pointers */
   char *orientation = " ";      /* orientation of recordings */
   char *recFile = " ";          /* receiver location file */  
   char *postFile = " ";         /* posteriori file */
   char *modelFile = " ";        /* elastic model file */
   char *corrDataFile = " ";     /* data covariance file */
   char *corrModelFile[3];       /* model covariance file */
   char *frechetFile = " ";      /* frechet derivative file */
   int verbose;                  /* verbose flag */
   int noFrechet;                /* if 1 don't store Frechet derivatives */
   int i, j, k, iU, iParam, offset, iR, shift;
                                 /* counters */
   int wL;                       /* taper length */
   int nParam;                   /* number of parameters altogether */
   int numberParImp;             /* number of distinct parameters in */
                                 /* impedance inversion */
   float dZ;                     /* layer thickness within target zone */
   float F1, F2, F3;             /* source components */
   float depth;                  /* current depth used in defining limits */
                                 /* for Frechet derivatives */
   float fR;                     /* reference frequency */
   float percU;                  /* amount of slowness windowing */
   float percW;                  /* amount of frequency windowing */
   float limZ[2];                /* target interval (Km) */
   float tMod;                   /* maximum modeling time */
   float phi;                    /* azimuth angle */
   float *buffer1, *buffer2;     /* auxiliary buffers */
   float **CmPost;               /* posteriori model covariance */
   float **CmPostInv;            /* posteriori model covariance - inverse */

   /* allocing for orientation */
   orientation = malloc(1);
   
   /* complex Zero */
   zeroC = cmplx(0, 0);

   /* getting input parameters */
   initargs(argc, argv);
   requestdoc(0);

   /* seismic data and model parameters */
   if (!getparstring("model", &modelFile)) modelFile = "model";
   if (!getparstring("postfile", &postFile)) postFile = "posteriori";
   if (!getparstring("corrData", &corrDataFile)) corrDataFile = "corrdata";
   
   if (!getparint("impedance", &IMPEDANCE)) IMPEDANCE = 0;
   if (!getparstring("frechetfile", &frechetFile)) noFrechet = 0;
   else noFrechet = 1;
   if (!getparint("prior", &PRIOR)) PRIOR = 1;
   if (IMPEDANCE)
   {
     if (!getparint("p", &ipFrechet)) vpFrechet = 1;
     if (!getparint("s", &isFrechet)) vsFrechet = 1;
     if (!getparint("r", &rhoFrechet)) rhoFrechet = 1;
   }
   else
   {
     if (!getparint("p", &vpFrechet)) vpFrechet = 1;
     if (!getparint("s", &vsFrechet)) vsFrechet = 1;
     if (!getparint("rho", &rhoFrechet)) rhoFrechet = 1;
   }
   
   /* a couple of things to use later in chain rule */
   if (!IMPEDANCE)
   {
      ipFrechet = 0;      isFrechet = 0;
   }
   else
   {
      if (ipFrechet && !isFrechet)
      {
	 vpFrechet = 1;	  vsFrechet = 0;
      }
      if (!ipFrechet && isFrechet)
      {
	 vpFrechet = 0;	  vsFrechet = 1;
      }
      if (!ipFrechet && !isFrechet)
      {
	 vpFrechet = 0;	  vsFrechet = 0;
      }
      if (ipFrechet && isFrechet)
      {
	 vpFrechet = 1;	  vsFrechet = 1;
      }
      if (rhoFrechet)
      {
	 vpFrechet = 1;	  vsFrechet = 1;   rhoFrechet = 1;
      }
   }
      
   if (!ipFrechet && ! isFrechet && !rhoFrechet && !vpFrechet && !vsFrechet)
      err("No inverse unknowns to work with!\n");

   numberPar = vpFrechet + vsFrechet + rhoFrechet;
   numberParImp = ipFrechet + isFrechet + rhoFrechet;

   if (PRIOR)
   {
      if (vpFrechet || ipFrechet)
      {
	 if (!getparstring("corrP", &corrModelFile[0])) 
	    corrModelFile[0] = "covP";
      }
      if (vsFrechet || isFrechet) 
      {
	 if (!getparstring("corrS", &corrModelFile[1])) 
	    corrModelFile[1] = "covS";
      }
      
      if (rhoFrechet) 
      {
	 if (!getparstring("corrR", &corrModelFile[2])) 
	    corrModelFile[2] = "covR";
      }
   }
   
   if (!getparstring("orientation", &orientation)) orientation[0] = 'Z';
   if (orientation[0] == 'z' || orientation[0] == 'Z')
   {
      VERTICAL = 1; RADIAL = 0;
   }
   else
   {
      VERTICAL = 0; RADIAL = 1;
   }
   
   if (!getparfloat("dz", &dZ)) dZ = .5;
   if (!getparfloat("targetbeg", &limZ[0])) limZ[0] = 0.5; 
   if (!getparfloat("targetend", &limZ[1])) limZ[1] = 1.0;

   /* geometry */
   if (!getparfloat("r1", &r1)) r1 = 0.25;
   if (!getparint("nr", &nR)) nR = 48;
   if (!getparfloat("dr", &dR)) dR = .025;
   if (!getparfloat("zs", &zs)) zs = .001;
   if (!getparfloat("F1", &F1)) F1 = 0;
   if (!getparfloat("F2", &F2)) F2 = 0;
   if (!getparfloat("F3", &F3)) F3 = 1;

   /* modeling */
   if (!getparstring("receiverfile", &recFile)) recFile = " ";
   if (!getparfloat("u1", &u1)) u1 = 0.0;
   if (!getparfloat("u2", &u2)) u2 = 1.;
   if (!getparint("directwave", &directWave)) directWave = 1;
   if (!getparfloat("tau", &tau)) err("Specify tau!\n");
   if (!getparint("nu", &nU)) nU = 1000;
   if (!getparfloat("f1", &f1)) f1 = 2;
   if (!getparfloat("f2", &f2)) f2 = 50;
   if (!getparfloat("dt", &dt)) dt = 0.004;
   if (!getparfloat("tmod", &tMod)) tMod = 8;
   if (!getparfloat("t1", &t1)) t1 = 0;
   if (!getparfloat("t2", &t2)) t2 = tMod;
   if (!getparint("hanning", &hanningFlag)) hanningFlag = 1;
   if (!getparfloat("wu", &percU)) percU = 10; percU /= 100;
   if (!getparfloat("ww", &percW)) percW = 25; percW /= 100;

   /* dialogue */
   if (!getparint("verbose", &verbose)) verbose = 0;

   /* checking number of receivers */
   fp = fopen(recFile, "r");
   if (fp != NULL)
   {
      nR = 0;
      while (fscanf(fp, "%f\n", &auxm1) != EOF) nR++;
   }
   fclose(fp);

   /* some hard-coded parameters */
   fR = 1; wR = 2 * PI * fR;         /* reference frequency */
   
   /* how many layers */
   fp = fopen(modelFile,"r");
   if (fp == NULL)
      err("No model file!\n");
   
   nL = 0;
   depth = 0;
   while (fscanf(fp, "%f %f %f %f %f %f\n", 
		 &aux, &aux, &aux, &aux, &aux, &aux) != EOF)
      nL++;
   nL--;

   /* considering the unknown layers */
   limRange = NINT((limZ[1] - limZ[0]) / dZ);

   if (verbose)
   {
      fprintf(stderr,"Number of layers: %d\n", nL + 1);
      fprintf(stderr,"Number of layers in target zone: %d\n", limRange);
   }


   if (IMPEDANCE)
   {
      nParam = numberParImp * limRange;
   }
   else
   {
      nParam = numberPar * limRange;
   }

   /* basic time-frequency stuff */
   nSamples = NINT(tMod / dt) + 1;
   nSamples = npfar(nSamples);

   /* length of time misfit */
   nDM = NINT((t2 - t1) / dt) + 1;

   /* maximum time for modeling */
   tMod = dt * (nSamples - 1);
   dF = 1. / (tMod);

   /* adjusting f1 and f2 */
   aux = dF;
   while (aux < f1)
      aux += dF;
   f1 = aux;
   while (aux < f2)
      aux += dF;
   f2 = aux;
   
   nF = NINT((f2 - f1) / dF); 
   if (nF%2 == 0) 
   {
      f2 += dF;
      nF++;
   }

   /* memory allocation */
   alpha = alloc1float(nL + 1);
   beta = alloc1float(nL + 1);
   rho = alloc1float(nL + 1);
   qP = alloc1float(nL + 1);
   qS = alloc1float(nL + 1);
   thick = alloc1float(nL + 1);
   recArray = alloc1float(nR);

   PSlowness = alloc2complex(2, nL + 1);
   SSlowness = alloc2complex(2, nL + 1);
   S2Velocity = alloc2complex(2, nL + 1);

   CD = alloc1float(nDM * (nDM + 1) / 2);
   if (PRIOR)
   {
      if(vpFrechet || ipFrechet)
	 CMP = alloc1float(limRange * (limRange + 1) / 2);
      if(vsFrechet || isFrechet)
	 CMS = alloc1float(limRange * (limRange + 1) / 2);
      if(rhoFrechet)
	 CMrho = alloc1float(limRange * (limRange + 1) / 2);
   }
   
   /* FRECHET derivative operator F */
   F = alloc2float(nR * nDM, numberPar * limRange);

   if (IMPEDANCE)
      CmPostInv = 
	 alloc2float(numberParImp * limRange, numberParImp * limRange);
   else
      CmPostInv = alloc2float(numberPar * limRange, numberPar * limRange);

   v1 = alloc2complex(2, numberPar * limRange + 1);
   v2 = alloc2complex(2, numberPar * limRange + 1);
   DmB = alloc3complex(4, numberPar * (limRange + 2), nL);
   derFactor = alloc2complex(2, nL + 1);
   aux11 = alloc2complex(nR, numberPar * limRange);
   aux12 = alloc2complex(nR, numberPar * limRange);
   aux21 = alloc2complex(nR, numberPar * limRange);
   aux22 = alloc2complex(nR, numberPar * limRange);
   aux11Old = alloc2complex(nR, numberPar * limRange);
   aux12Old = alloc2complex(nR, numberPar * limRange);
   aux21Old = alloc2complex(nR, numberPar * limRange);
   aux22Old = alloc2complex(nR, numberPar * limRange);

   /* reading receiver configuration */
   fp = fopen(recFile, "r");
   if (fp == NULL)
   {
      /* standard end-on */
      if (verbose) fprintf(stderr, "No receiver file available\n");
      for (i = 0; i < nR; i++)
      {
         recArray[i] = r1 + i * dR;
      }
   }
   else   
   {
      if (verbose) fprintf(stderr, "Reading receiver file %s\n", recFile);
      for (i = 0; i < nR; i++)
      {
         fscanf(fp, "%f\n", &recArray[i]);
      }
   }
   fclose(fp);
   
   /* reading the model file */
   fp = fopen(modelFile,"r");
   if (verbose)      
     fprintf(stderr,"  Thickness     rho     vP     qP    vS     qS\n");
   for (k = 0; k < nL + 1; k++)
   {
      fscanf(fp, "%f %f %f %f %f %f\n", &thick[k], &rho[k], &alpha[k], 
	     &qP[k], &beta[k], &qS[k]);
      if (verbose)
	fprintf(stderr,"   %7.4f      %4.3f   %3.2f  %5.1f  %3.2f  %5.1f\n",
		thick[k], rho[k], alpha[k], qP[k], beta[k], qS[k]);
   }
   fclose(fp);

   /* setting lim[0] and lim[1] */
   for (depth = thick[0], i = 1; i <= nL; depth += thick[i], i++)
   {
      if (NINT(depth / dZ) <= NINT(limZ[0] / dZ)) lim[0] = i;
      if (NINT(depth / dZ) < NINT(limZ[1] / dZ)) lim[1] = i;
   }
   lim[1]++;

   /* some modeling parameters */
   /* slowness increment */
   dU = (u2 - u1) / (float) nU;

   /* computing the window length for the slowness domain */
   epslon1 = (u2 - u1) * percU;
   wL = NINT(epslon1 / dU);
   wL = 2 * wL + 1;
   u2 += epslon1;
   nU = NINT((u2 - u1) / dU);    /* new nU to preserve last slowness */
                                 /* w/o being windowed */
   taper = alloc1float(nU);

   /* building window for slowness integration */
   for (i = (wL - 1) / 2, iU = 0; iU < nU; iU++)
   {
      taper[iU] = 1;
      if (iU >= nU - (wL - 1) / 2)
      {
         i++;
	 taper[iU] =
	    .42 - .5 * cos(2 * PI * (float) i / ((float) (wL - 1))) +
            .08 * cos(4 * PI * (float) i / ((float) (wL - 1)));
      }
   }

   /* filtering in frequency domain */
   filter(percW);
   
   /* building frequency filtering */
   /* I will assume that the receivers are in line (at z = 0) so phi = 0 */
   phi = 0;
   epslon1 = F3;
   epslon2 = F1 * cos(phi) + F2 * sin(phi);

   /* correction for the 1st layer */
   thick[0] -= zs;

   /* imaginary part of frequency for damping wrap-around */
   tau = log(tau) / tMod;
   if (tau > TAUMAX)
      tau = TAUMAX;

   /* normalization for the complex slowness */
   if (f1 > 7.5)
      wRef = f1 * 2 * PI;
   else
      wRef = 7.5 * 2 * PI;

   /* reading data and model covariance matrixes */
   inputCovar(corrDataFile, corrModelFile);
   
   /* starting inverse procedure */
   /* FRECHET derivative matrix  */
      gradient();
   
   if (!noFrechet)
   {
      fp = fopen(frechetFile, "w");
      for (i = 0; i < numberPar * limRange; i++)
      {
	 fwrite(&F[i][0], sizeof(float), nR * nDM, fp);
      }
      fclose(fp);
   }

   /* building a-posteriori model covariance matrix */
   /* prior information is used */
   buffer1 = alloc1float(nDM);
   buffer2 = alloc1float(nDM * nR);

   if (verbose) fprintf(stderr, "Building posteriori covariance...\n");

   for (iParam = 0; iParam < nParam; iParam++)
   {
      for (i = 0; i < nDM; i++)
      {
	 for (offset = i, k = 0; k < nDM; k++)
	 {
	    buffer1[k] = CD[offset];
	    offset += MAX(SGN0(i - k) * (nDM - 1 - k), 1);
	 }

	 /* doing the product CD F */
  	 for (iR = 0; iR < nR; iR++)
	 {
	    buffer2[iR * nDM + i] = 0;
	    for (k = 0; k < nDM; k++)  
	    {
	       buffer2[iR * nDM + i] += buffer1[k] * 
		                        F[iParam][iR * nDM + k];
	    }
 	 }
      }
      
      for (j = 0; j < nParam; j++)
      {
	 CmPostInv[j][iParam] = 0;
	 for (k = 0; k < nDM * nR; k++)
	 {
	    CmPostInv[j][iParam] += buffer2[k] * F[j][k];
	 }
      }
   }

   if (verbose) 
     fprintf(stderr, "Posteriori covariance built. Including prior...\n");

   free1float(buffer1);
   buffer1 = alloc1float(nParam);
   /* including prior covariance matrix */
   if (PRIOR)
   {
       shift = 0;
      if (IMPEDANCE)
      {
	 if (ipFrechet)
	 {
	    for (iParam = 0; iParam < limRange; iParam++)
	    {
	       for (offset = iParam, k = 0; k < limRange; k++)
	       {
		  buffer1[k] = CMP[offset];
		  offset += MAX(SGN0(iParam - k) * (limRange - 1 - k), 1);
	       }
	       
	       for (k = 0; k < limRange; k++) 
	       {
		  CmPostInv[iParam][k] += buffer1[k];
	       }
	    }
            shift += limRange;
	 }
      }
      else
      {
	 if (vpFrechet)
	 {
	    for (iParam = 0; iParam < limRange; iParam++)
	    {
	       for (offset = iParam, k = 0; k < limRange; k++)
	       {
		  buffer1[k] = CMP[offset];
		  offset += MAX(SGN0(iParam - k) * (limRange - 1 - k), 1);
	       }
	       
	       for (k = 0; k < limRange; k++) 
	       {
		  CmPostInv[iParam][k] += buffer1[k];
	       }
	    }
            shift += limRange;
	 }
      }

      if (IMPEDANCE)
      {
	 if (isFrechet)
	 {
	    for (iParam = 0; iParam < limRange; iParam++)
	    {
	       for (offset = iParam, k = 0; k < limRange; k++)
	       {
		  buffer1[k] = CMS[offset];
		  offset += MAX(SGN0(iParam - k) * (limRange - 1 - k), 1);
	       }
	       
	       for (k = 0; k < limRange; k++)
	       {
		  CmPostInv[iParam + shift][k + shift] += buffer1[k];
	       }
	    }
            shift += limRange;
	 }
      }
      else
      {
	 if (vsFrechet)
	 {
	    for (iParam = 0; iParam < limRange; iParam++)
	    {
	       for (offset = iParam, k = 0; k < limRange; k++)
	       {
		  buffer1[k] = CMS[offset];
		  offset += MAX(SGN0(iParam - k) * (limRange - 1 - k), 1);
	       }
	       
	       for (k = 0; k < limRange; k++)
	       {
		  CmPostInv[iParam + shift][k + shift] += buffer1[k];
	       }
	    }
            shift += limRange;
	 }
      }

      if (rhoFrechet)
      {
	 for (iParam = 0; iParam < limRange; iParam++)
	 {
	    for (offset = iParam, k = 0; k < limRange; k++)
	    {
	       buffer1[k] = CMrho[offset];
	       offset += MAX(SGN0(iParam - k) * (limRange - 1 - k), 1);
	    }
	    
	    for (k = 0; k < limRange; k++) 
	    {
	       CmPostInv[iParam + shift][k + shift] += buffer1[k];
	    }
	 }
      }
   }

   if (verbose) fprintf(stderr, "Prior included. Inverting matrix...\n");

   /* freeing memory */
   free1float(buffer1);
   free1float(buffer2);
   free1float(alpha);
   free1float(beta);
   free1float(rho);
   free1float(qP);
   free1float(qS);
   free1float(thick);
   free2complex(PSlowness);
   free2complex(SSlowness);
   free2complex(S2Velocity);
   free1float(CD);
   free1float(CMP);
   free1float(CMS);
   free1float(CMrho);
   free2float(F);
   free2complex(v1);
   free2complex(v2);
   free3complex(DmB);
   free2complex(derFactor); 
   free2complex(aux11);
   free2complex(aux12);
   free2complex(aux21);
   free2complex(aux22); 
   free2complex(aux11Old);
   free2complex(aux12Old);
   free2complex(aux21Old);
   free2complex(aux22Old); 

   /* inverting the matrix */
   CmPost = alloc2float(nParam, nParam);
   for (i = 0; i < nParam; i++) for (j = 0; j < nParam; j++)
      CmPostInv[i][j] = CmPost[i][j];
   inverse_matrix(nParam, CmPostInv);

   if (verbose) fprintf(stderr, "Done with inverse matrix routine.\n");
   
   buffer1 = alloc1float(nParam);
   gp = fopen(postFile, "w");
   for (i = 0; i < nParam; i++)
   {
      fwrite(CmPostInv[i], sizeof(float), nParam, gp);
   }
   fclose(fp);
}
Exemplo n.º 11
0
ENTRYPOINT void
draw_stream (ModeInfo *mi)
{
  stream_configuration *es = &ess[MI_SCREEN(mi)];
  Display *dpy = MI_DISPLAY(mi);
  Window window = MI_WINDOW(mi);
  streamtime current_time;
  float cur_time;
  int i;
  float alpha = 1.0;
  Vector vx;
  Vector vy;
  GLfloat m[4*4];

  if (!es->glx_context)
    return;

  gettime (&current_time);

  cur_time = (float)(GETSECS(current_time) * 1000 + GETMSECS(current_time) - es->start_time) / 1000.0;
  cur_time *= global_speed;

  glXMakeCurrent (MI_DISPLAY(mi), MI_WINDOW(mi), *es->glx_context);

  glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  glMatrixMode (GL_PROJECTION);
  glLoadIdentity ();
  glFrustum (-.6f, .6f, -.45f, .45f, 1, 1000);

  glMatrixMode (GL_MODELVIEW);
  glLoadIdentity ();

  glEnable (GL_LIGHTING);
  glEnable (GL_TEXTURE_2D);
  glEnable (GL_BLEND);
  glBlendFunc (GL_SRC_ALPHA, GL_ONE);
  glDisable (GL_CULL_FACE);
  glDisable (GL_DEPTH_TEST);
  glDepthMask (0);

  glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD);

  glTranslatef (0, 0, -300);
  glRotatef (cur_time * 30, 1, 0, 0);
  glRotatef (30 * sin(cur_time / 3) + 10, 0, 0, 1);

  {
    double x, y, z;
    get_position (es->rot, &x, &y, &z, !es->button_down_p);
    glTranslatef((x - 0.5) * 8,
                 (y - 0.5) * 8,
                 (z - 0.5) * 15);

    gltrackball_rotate (es->trackball);

    get_rotation (es->rot, &x, &y, &z, !es->button_down_p);
    glRotatef (x * 360, 1.0, 0.0, 0.0);
    glRotatef (y * 360, 0.0, 1.0, 0.0);
    glRotatef (z * 360, 0.0, 0.0, 1.0);
  }

  if (cur_time > change_time1)
  {
    if (cur_time > change_time2)
    {
      glRotatef (90, 0, 1, 0);

      if (cur_time > change_time3)
        es->start_time = GETSECS(current_time) * 1000 + GETMSECS(current_time) - 5000;
    }
    else
    {
      glRotatef (180, 0, 1, 0);
    }
  }

  glEnable ( GL_FOG);
  glFogf (GL_FOG_START, 200);
  glFogf (GL_FOG_END, 500);
  glFogf (GL_FOG_MODE, GL_LINEAR);

  glGetFloatv (GL_MODELVIEW_MATRIX, m);

  inverse_matrix (m);

  vx.x = m[0] * 10;
  vx.y = m[1] * 10;
  vx.z = m[2] * 10;

  vy.x = m[4] * 10;
  vy.y = m[5] * 10;
  vy.z = m[6] * 10;

  mi->polygon_count = 0;

  for (i = 0; i != es->num_streams; i++)
  {
    mi->polygon_count += es->streams[i].num_flares;
    render_flare_stream (&es->streams[i], cur_time, &vx, &vy, alpha);
  }

  glDisable (GL_TEXTURE_2D);
  glDisable (GL_LIGHTING);
  glDisable (GL_FOG);
  glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

  if (mi->fps_p) do_fps (mi);
  glFinish();

  glXSwapBuffers (dpy, window);
}
Exemplo n.º 12
0
int main(int argc,char *argv[])
{
	char *listfile,*inputfile;
	char choose= ' ';
	string operate=" ";
	double temperature=300;
	string output=" ";
	string segment="all";
	int segment_b=0;
	int segment_e=0;
//  读取当前的时间
	time_t t = time( 0 ); 
    char TIME[64]; 
    strftime( TIME, sizeof(TIME), "%Y/%m/%d %X ",localtime(&t) ); 
    
//

	switch(argc)
	{
	case 1:
		cout<<"Usage:CurAnalysis -f listfile.txt -i inputfile.txt"<<endl;
		
		exit(0);
	case 2:
		if(string(argv[1])=="-a")
		{
			Printversion();
			exit(0);
		}
		if(string(argv[1])=="-h")
		{
			Printhelp();
			exit(0);
		}
	case 5:
		if(string(argv[1])=="-f"&&string(argv[3])=="-i")
		{
			listfile=argv[2];
			inputfile=argv[4];
		}
		break;

	default:
		cout<<"Usage:CurAnalysis -f listfile.txt -i inputfile.txt"<<endl;
		exit(0);

	}

	ReadInput(inputfile,operate,choose,output,temperature,segment,segment_b,segment_e);
/*
average部分已经完成,经测试可以使用,主要的问题是读文件的异常
比如说文件残缺,文件丢失等的情况的处理的过程没有完成。
*/
	if(operate=="average")
	{
		if(choose=='E'||choose=='F'||choose=='G'||choose=='H')
		{
			double ***totaldata;
			struct	Filelist *fl;
			struct Paramater *spt;
			int N=0;
			ofstream outfile(output.c_str(),ios::app);
			fl=Readlist(listfile);
			switch(choose)
			{
			case 'E':
				spt=E_part(fl->file);
				break;
			case 'F':
				spt=F_part(fl->file);
				break;
			case 'G':
				spt=G_part(fl->file);
				break;
			case 'H':
				spt=H_part(fl->file);
				break;
			}
			int filesize=Getfilelen(fl);	
			int size=GetParamaterlen(spt);
			if(segment!="all")
			{
				size=segment_e - segment_b+1;
			}
			if(segment=="all")
			{
				segment_b=1;
				segment_e=size;
			}
			totaldata=f3tensor(0,5,0,size-1,0,filesize-1);
outfile<<"******************************************************************"<<endl;
//output the input file!
	ifstream infile(inputfile);
	string s;
    getline(infile,s);
   while(!infile.fail())
	{
		outfile<<"#"<<s<<endl;
		getline(infile,s);
	}
    outfile<<TIME<<endl;  //输出当前时间
	infile.close();

//
			while(fl!=NULL)
			{
				struct Paramater *sp; 
				switch(choose)
				{
					case 'E':
						sp=E_part(fl->file);
					break;
					case 'F':
						sp=F_part(fl->file);
					break;
					case 'G':
						sp=G_part(fl->file);
					break;
					case 'H':
						sp=H_part(fl->file);
					break;
				}
		//		int size=GetParamaterlen(sp);
				double **data;
				data=dmatrix(0,5,0,size-1);
				struct Namelist *name;
				name=(struct Namelist *)malloc(sizeof(struct Namelist));
				Paramater2double(sp,data,name,segment_b,segment_e);

				for(int i=0;i<6;i++)
				{
					for(int j=0;j<size;j++)
					{
						totaldata[i][j][N]=data[i][j];
					}
				}
				free_dmatrix(data,0,5,0,size-1);
				cout<<"Read file "<<fl->file<<" finished!"<<endl;//输出提示
				fl=fl->next;
				N++;
			}

			double **aveg;
			aveg=dmatrix(0,5,0,size-1);
			for(int i=0;i<6;i++)
			{
				for(int j=0;j<size;j++)
				{
					aveg[i][j]=0;
				}
			}

			outfile<<endl;
			outfile<<"******************************************************************"<<endl;
			outfile<<"\t"<<"rise"<<"\t"<<"roll"<<"\t"<<"shift"<<"\t"<<"slide"<<"\t"<<"tilt"<<"\t"<<"twist"<<endl;
			outfile<<endl;

			for(int i=0;i<size;i++)
			{
				outfile<<i+segment_b<<"\t";
				for(int j=0;j<6;j++)
				{
					for(int k=0;k<filesize;k++)
					{
						aveg[j][i]+=totaldata[j][i][k];
					}
					aveg[j][i]=aveg[j][i]/filesize;
					outfile<<fixed<<showpoint;
					
	 				outfile<<setprecision(2)<<aveg[j][i]<<"\t";
				}
				outfile<<endl;
			}
			outfile<<endl;
			outfile<<"******************************************************************"<<endl;
		   cout<<"finished the calculation of average !"<<endl;
		   cout<<"the output write in the file "<<output<<" !"<<endl;
			outfile.close();
			free_f3tensor(totaldata,0,5,0,size-1,0,filesize-1);
		}

		//average for J

		if(choose=='J')
		{
			double ***totaldata;
			struct	Filelist *fl;
			struct Backbone *spt;
			int N=0;
			fl=Readlist(listfile);
			spt=J_part(fl->file);
			int filesize=Getfilelen(fl);	
			int size=GetBackbonelen(spt);
			if(segment!="all")
			{
				size=segment_e - segment_b+1;
			}
			if(segment=="all")
			{
				segment_b=1;
				segment_e=size;
			}
			totaldata=f3tensor(0,13,0,size-1,0,filesize-1);
			ofstream outfile(output.c_str(),ios::app);

			outfile<<"******************************************************************"<<endl;
		//output the input file!
			ifstream infile(inputfile);
			string s;
			getline(infile,s);
			 while(!infile.fail())
			{
				outfile<<"#"<<s<<endl;
				getline(infile,s);
			}
			 outfile<<TIME<<endl; //输出当前时间
			infile.close();
//

			while(fl!=NULL)
			{
				struct Backbone *sp;
				sp=J_part(fl->file);
		//		int size=GetBackbonelen(sp);
				double **data;
				data=dmatrix(0,13,0,size-1);
				struct Namelist *name;
				name=(struct Namelist *)malloc(sizeof(struct Namelist));
				Backbone2double(sp,data,name,segment_b,segment_e);

				for(int i=0;i<14;i++)
				{
					for(int j=0;j<size;j++)
					{
						totaldata[i][j][N]=data[i][j];
					}
				}
				free_dmatrix(data,0,13,0,size-1);
				cout<<"Read file "<<fl->file<<" finished!"<<endl;//输出提示
				fl=fl->next;
				N++;
			}

			double **aveg;
			aveg=dmatrix(0,13,0,size-1);
			for(int i=0;i<14;i++)
			{
				for(int j=0;j<size;j++)
				{
					aveg[i][j]=0;
				}
			}

			outfile<<endl;
			outfile<<"******************************************************************"<<endl;
			outfile<<"\t"<<"alpha"<<"\t"<<"ampli"<<"\t"<<"beta"<<"\t"<<"c1"<<"\t"<<"c1c2"<<"\t"<<"c2"<<"\t"<<"c2c3"<<"\t"<<"c3"<<"\t"<<"chi"<<"\t"<<"delta"<<"\t"<<"epsil"<<"\t"<<"gamma"<<"\t"<<"phase"<<"\t"<<"zeta"<<endl;
			outfile<<endl;

			for(int i=0;i<size;i++)
			{
				outfile<<i+segment_b<<"\t";
				for(int j=0;j<14;j++)
				{
					for(int k=0;k<filesize;k++)
					{
						aveg[j][i]+=totaldata[j][i][k];
					}
					aveg[j][i]=aveg[j][i]/filesize;
					outfile<<fixed<<showpoint;
					outfile<<setprecision(2)<<aveg[j][i]<<"\t";
				}
				outfile<<endl;
			}
			outfile<<endl;
			outfile<<"******************************************************************"<<endl;
		   cout<<"finished the calculation of average !"<<endl;
		   cout<<"the output write in the file "<<output<<" !"<<endl;
			outfile.close();
			free_f3tensor(totaldata,0,13,0,size-1,0,filesize-1);
		}

	}

	
//计算某一数据的分布


	if(operate=="distribution")
	{
		//part 1: get the data
		if(choose=='E'||choose=='F'||choose=='G'||choose=='H')
		{
			double ***totaldata;
			struct	Filelist *fl;
			struct Paramater *spt;
			int N=0;
			ofstream outfile(output.c_str(),ios::app);
			fl=Readlist(listfile);
			switch(choose)
			{
			case 'E':
				spt=E_part(fl->file);
				break;
			case 'F':
				spt=F_part(fl->file);
				break;
			case 'G':
				spt=G_part(fl->file);
				break;
			case 'H':
				spt=H_part(fl->file);
				break;
			}
			int filesize=Getfilelen(fl);	
			int size=GetParamaterlen(spt);
			if(segment!="all")
			{
				size=segment_e - segment_b+1;
			}
			if(segment=="all")
			{
				segment_b=1;
				segment_e=size;
			}
			totaldata=f3tensor(0,5,0,size-1,0,filesize-1);
			outfile<<"******************************************************************"<<endl;

			//output the input file!
			ifstream infile(inputfile);
			string s;
			 getline(infile,s);
			while(!infile.fail())
			{
				outfile<<"#"<<s<<endl;
				getline(infile,s);
			}
		    outfile<<TIME<<endl;  //输出当前时间
			infile.close();

//
			while(fl!=NULL)
			{
				struct Paramater *sp; 
				switch(choose)
				{
					case 'E':
						sp=E_part(fl->file);
					break;
					case 'F':
						sp=F_part(fl->file);
					break;
					case 'G':
						sp=G_part(fl->file);
					break;
					case 'H':
						sp=H_part(fl->file);
					break;
				}
		//		int size=GetParamaterlen(sp);
				double **data;
				data=dmatrix(0,5,0,size-1);
				struct Namelist *name;
				name=(struct Namelist *)malloc(sizeof(struct Namelist));
				Paramater2double(sp,data,name,segment_b,segment_e);

				for(int i=0;i<6;i++)
				{
					for(int j=0;j<size;j++)
					{
						totaldata[i][j][N]=data[i][j];
					}
				}
				free_dmatrix(data,0,5,0,size-1);
				cout<<"Read file "<<fl->file<<" finished!"<<endl;//输出提示
				fl=fl->next;
				N++;
			}
// finished the input data
			//calculate the distribution!
			double *vect;
			vect=dvector(0, size*filesize-1) ;  
			for(int i=0;i<6;i++)
			{
				outfile<<"******************************************************************"<<endl;
				switch(i)
				{
					case 0:
						outfile<<"the distribution of RISE"<<endl;
						break;
					case 1:
						outfile<<"the distribution of ROLL"<<endl;
						break;
					case 2:
						outfile<<"the distribution of SHIFT"<<endl;
						break;
					case 3:
						outfile<<"the distribution of SLIDE"<<endl;
						break;
					case 4:
						outfile<<"the distribution of TILT"<<endl;
						break;
					case 5:
						outfile<<"the distribution of TWIST"<<endl;
						break;
				}
				outfile<<"******************************************************************"<<endl;
				//
				for(int m=0;m<size;m++)
				{
					for(int n=0;n<filesize;n++)
					{
						vect[m*filesize+n]=totaldata[i][m][n];
					}
				}
				//把二维的数据转化为一维的数据!
				
				Distribution(vect,size*filesize,output);
				outfile<<"******************************************************************"<<endl;
			}
		   cout<<"finished the calculation of distribution !"<<endl;
		   cout<<"the output write in the file "<<output<<" !"<<endl;
			outfile.close();
			free_f3tensor(totaldata,0,5,0,size-1,0,filesize-1);
			// finished the calculation !



		}

		if(choose=='J')
		{
			double ***totaldata;
			struct	Filelist *fl;
			struct Backbone *spt;
			int N=0;
			fl=Readlist(listfile);
			spt=J_part(fl->file);
			int filesize=Getfilelen(fl);	
			int size=GetBackbonelen(spt);
			if(segment!="all")
			{
				size=segment_e - segment_b+1;
			}
			if(segment=="all")
			{
				segment_b=1;
				segment_e=size;
			}
			totaldata=f3tensor(0,13,0,size-1,0,filesize-1);
			ofstream outfile(output.c_str(),ios::app);

			outfile<<"******************************************************************"<<endl;
		//output the input file!
			ifstream infile(inputfile);
			string s;
			getline(infile,s);
			 while(!infile.fail())
			{
				outfile<<"#"<<s<<endl;
				getline(infile,s);
			}
			 outfile<<TIME<<endl; //输出当前时间
			infile.close();
//

			while(fl!=NULL)
			{
				struct Backbone *sp;
				sp=J_part(fl->file);
		//		int size=GetBackbonelen(sp);
				double **data;
				data=dmatrix(0,13,0,size-1);
				struct Namelist *name;
				name=(struct Namelist *)malloc(sizeof(struct Namelist));
				Backbone2double(sp,data,name,segment_b,segment_e);

				for(int i=0;i<14;i++)
				{
					for(int j=0;j<size;j++)
					{
						totaldata[i][j][N]=data[i][j];
					}
				}
				free_dmatrix(data,0,13,0,size-1);
				cout<<"Read file "<<fl->file<<" finished!"<<endl;//输出提示
				fl=fl->next;
				N++;
			}

			double *vect;
			vect=dvector(0, size*filesize-1) ;  
			for(int i=0;i<14;i++)
			{
				outfile<<"******************************************************************"<<endl;
				switch(i)
				{
					case 0:
						outfile<<"the distribution of ALPHA"<<endl;
						break;
					case 1:
						outfile<<"the distribution of AMPLI"<<endl;
						break;
					case 2:
						outfile<<"the distribution of BETA"<<endl;
						break;
					case 3:
						outfile<<"the distribution of C1'"<<endl;
						break;
					case 4:
						outfile<<"the distribution of C1'-C2'"<<endl;
						break;
					case 5:
						outfile<<"the distribution of C2'"<<endl;
						break;
					case 6:
						outfile<<"the distribution of C2'-C3'"<<endl;
						break;
				    case 7:
						outfile<<"the distribution of C3'"<<endl;
						break;
					case 8:
						outfile<<"the distribution of CHI"<<endl;
						break;
					case 9:
						outfile<<"the distribution of DELTA"<<endl;
						break;
					case 10:
						outfile<<"the distribution of ESPIL"<<endl;
						break;
					case 11:
						outfile<<"the distribution of GAMMA"<<endl;
						break;
					case 12:
						outfile<<"the distribution of PHASE"<<endl;
						break;
					case 13:
						outfile<<"the distribution of ZETA"<<endl;
						break;
					}
				outfile<<"******************************************************************"<<endl;
				//
				for(int m=0;m<size;m++)
				{
					for(int n=0;n<filesize;n++)
					{
						vect[m*filesize+n]=totaldata[i][m][n];
					}
				}
				//把二维的数据转化为一维的数据!
				
				Distribution(vect,size*filesize,output);
				outfile<<"******************************************************************"<<endl;
			}
		   cout<<"finished the calculation of distribution !"<<endl;
		   cout<<"the output write in the file "<<output<<" !"<<endl;
			outfile.close();
			free_f3tensor(totaldata,0,13,0,size-1,0,filesize-1);
			// finished the calculation !
		}

	}
/*计算刚性*/
	
	if(operate=="stiffness")
	{
		/*get the data*/
		if(choose=='E'||choose=='F'||choose=='G'||choose=='H')
		{
			double ***totaldata;
			struct	Filelist *fl;
			struct Paramater *spt;
			int N=0;
			ofstream outfile(output.c_str(),ios::app);
			fl=Readlist(listfile);
			switch(choose)
			{
			case 'E':
				spt=E_part(fl->file);
				break;
			case 'F':
				spt=F_part(fl->file);
				break;
			case 'G':
				spt=G_part(fl->file);
				break;
			case 'H':
				spt=H_part(fl->file);
				break;
			}
			int filesize=Getfilelen(fl);	
			int size=GetParamaterlen(spt);
			if(segment!="all")
			{
				size=segment_e - segment_b+1;
			}
			if(segment=="all")
			{
				segment_b=1;
				segment_e=size;
			}
			totaldata=f3tensor(0,5,0,size-1,0,filesize-1);
			outfile<<"******************************************************************"<<endl;

			//output the input file!
			ifstream infile(inputfile);
			string s;
			 getline(infile,s);
			while(!infile.fail())
			{
				outfile<<"#"<<s<<endl;
				getline(infile,s);
			}
		    outfile<<TIME<<endl;  //输出当前时间
			infile.close();

//
			while(fl!=NULL)
			{
				struct Paramater *sp; 
				switch(choose)
				{
					case 'E':
						sp=E_part(fl->file);
					break;
					case 'F':
						sp=F_part(fl->file);
					break;
					case 'G':
						sp=G_part(fl->file);
					break;
					case 'H':
						sp=H_part(fl->file);
					break;
				}
		//		int size=GetParamaterlen(sp);
				double **data;
				data=dmatrix(0,5,0,size-1);
				struct Namelist *name;
				name=(struct Namelist *)malloc(sizeof(struct Namelist));
				Paramater2double(sp,data,name,segment_b,segment_e);

				for(int i=0;i<6;i++)
				{
					for(int j=0;j<size;j++)
					{
						totaldata[i][j][N]=data[i][j];
					}
				}
				free_dmatrix(data,0,5,0,size-1);
				cout<<"Read file "<<fl->file<<" finished!"<<endl;//输出提示
				fl=fl->next;
				N++;
			}
// finished the input data
			/*calculate the stiffness! */
			double **stiff;
			double **matrix;
			double **inve_matrix;

			/*output the title */
				outfile<<"******************************************************************"<<endl;
				outfile<<"calculate the stiffness of part "<<choose<<endl;
				outfile<<"******************************************************************"<<endl;
				
		for(int x=segment_b-1;x<segment_e;x++)   /* the loop for segment  */
		{
			stiff=dmatrix(0,5,0, filesize-1) ;  /* hold the space!*/
			matrix=dmatrix(0,5,0,5);
			inve_matrix=dmatrix(0,5,0,5);

			for(int i=0;i<6;i++)
			{
					for(int n=0;n<filesize;n++)
					{
						stiff[i][n]=totaldata[i][x][n];
					}			
			}

			Getmatrix(stiff,matrix,filesize);  /*cteate the helical matrix!*/
			free_dmatrix(stiff,0,5,0,filesize-1);
			inverse_matrix(matrix, inve_matrix,6);
			free_dmatrix(matrix,0,5,0,5);

			outfile<<"the stiffness of segment "<<x+1<<endl;
			outfile<<"******************************************************************"<<endl;
			outfile<<"\t"<<"rise"<<"\t"<<"roll"<<"\t"<<"shift"<<"\t"<<"slide"<<"\t"<<"tilt"<<"\t"<<"twist"<<endl;
			outfile<<fixed<<showpoint;
			for(int i=0;i<6;i++)
			{
				switch(i)
				{
				case 0:
					outfile<<"rise"<<"\t";
					break;
				case 1:
					outfile<<"roll"<<"\t";
					break;
				case 2:
					outfile<<"shift"<<"\t";
					break;
				case 3:
					outfile<<"slide"<<"\t";
					break;
				case 4:
					outfile<<"tilt"<<"\t";
					break;
				case 5:
					outfile<<"twist"<<"\t";
					break;
				}
				for(int j=0;j<6;j++)
				{
					outfile<<setprecision(2)<<R*temperature*inve_matrix[i][j]<<"\t";
				}
				outfile<<endl;
			}
			outfile<<"******************************************************************"<<endl;
		}
		cout<<"finished the calculation of stiffness !"<<endl;
		cout<<"the output write in the file "<<"\""<<output<<"\"  !"<<endl;
		outfile.close();
		free_f3tensor(totaldata,0,5,0,size-1,0,filesize-1);
			// finished the calculation !

		}
		else
		{
			cout<<"wrong input, please check!"<<endl;
			exit(0);
		}

	}


	if(operate!="stiffness"&&operate!="average"&&operate!="distribution")
	{
		cout<<"Input a wrong operate. the correct oprtate is 'average/distribution/stiffness'"<<endl;
		exit(0);
	}
	return 0;
}