int main( int argc, char* argv[] ) {
	MPI_Comm CommWorld;
	int rank;
	int numProcessors;
	int procToWatch;
	Dictionary* dictionary;
	AbstractContext* abstractContext;
	
	/* Initialise MPI, get world info */
	MPI_Init( &argc, &argv );
	MPI_Comm_dup( MPI_COMM_WORLD, &CommWorld );
	MPI_Comm_size( CommWorld, &numProcessors );
	MPI_Comm_rank( CommWorld, &rank );
	
	BaseFoundation_Init( &argc, &argv );
	BaseIO_Init( &argc, &argv );
	BaseContainer_Init( &argc, &argv );
	BaseAutomation_Init( &argc, &argv );
	BaseExtensibility_Init( &argc, &argv );
	BaseContext_Init( &argc, &argv );
	
	stream =  Journal_Register( InfoStream_Type, "myStream" );

	if( argc >= 2 ) {
		procToWatch = atoi( argv[1] );
	}
	else {
		procToWatch = 0;
	}
	if( rank == procToWatch ) Journal_Printf( (void*) stream, "Watching rank: %i\n", rank );
	
	/* Read input */
	dictionary = Dictionary_New();
	
	/* Build the context */
	abstractContext = _AbstractContext_New( 
		sizeof(AbstractContext), 
		"TestContext", 
		MyDelete, 
		MyPrint, 
		NULL,
		NULL, 
		NULL, 
		_AbstractContext_Build, 
		_AbstractContext_Initialise, 
		_AbstractContext_Execute, 
		_AbstractContext_Destroy, 
		"context", 
		True, 
		MySetDt, 
		0, 
		10, 
		CommWorld, 
		dictionary );

	/* add hooks to existing entry points */
	ContextEP_ReplaceAll( abstractContext, AbstractContext_EP_Build, MyBuild );
	ContextEP_ReplaceAll( abstractContext, AbstractContext_EP_Initialise, MyInitialConditions );
	ContextEP_ReplaceAll( abstractContext, AbstractContext_EP_Solve, MySolve );
	ContextEP_ReplaceAll( abstractContext, AbstractContext_EP_Dt, MyDt );

	if( rank == procToWatch ) {
		Journal_Printf( 
			(void*)stream, 
			"abstractContext->entryPointList->_size: %lu\n", 
			abstractContext->entryPoint_Register->_size );
		Journal_Printf( 
			(void*)stream, 
			"abstractContext->entryPointList->count: %u\n", 
			abstractContext->entryPoint_Register->count );
	}
	
	ContextEP_Append( abstractContext, AbstractContext_EP_Solve, MySolve2 );
	ContextEP_ReplaceAll( abstractContext, AbstractContext_EP_Initialise, MyInitialConditions2 ); 

	if( rank == procToWatch ) {
		stream = Journal_Register( InfoStream_Type, AbstractContext_Type );
		AbstractContext_PrintConcise( abstractContext, stream );
		
		Journal_Printf( 
			(void*)stream, 
			"abstractContext->entryPointList->_size: %lu\n", 
			abstractContext->entryPoint_Register->_size );
		Journal_Printf( 
			(void*)stream, 
			"abstractContext->entryPointList->count: %u\n", 
			abstractContext->entryPoint_Register->count );
	}

	/* Run the context */
	if( rank == procToWatch ) {
		Stg_Component_Build( abstractContext, 0 /* dummy */, False );
		Stg_Component_Initialise( abstractContext, 0 /* dummy */, False );
		Stg_Component_Execute( abstractContext, 0 /* dummy */, False );
		Stg_Component_Destroy( abstractContext, 0 /* dummy */, False );
	}
	
	/* Stg_Class_Delete stuff */
	Stg_Class_Delete( abstractContext );
	Stg_Class_Delete( dictionary );
	
	BaseContext_Finalise();
	BaseExtensibility_Finalise();
	BaseAutomation_Finalise();
	BaseContainer_Finalise();
	BaseIO_Finalise();
	BaseFoundation_Finalise();
	
	/* Close off MPI */
	MPI_Finalize();
	
	return 0; /* success */
}
void StGermain_SingleAttractor_UpdatePositions( DomainContext* context ) {
	Cell_LocalIndex			lCell_I;
	Particle_InCellIndex		cParticle_I;
	Particle* 	        	currParticle;
	Index				dim_I;
	Swarm*                          swarm = (Swarm*) LiveComponentRegister_Get( context->CF->LCRegister, (Name)"swarm"  );
	Coord                           attractorPoint;
	Mesh*				mesh;
	Stream*                         stream = Journal_Register( Info_Type, (Name)"particleUpdate"  );
	unsigned int                    movementSpeedDivisor = 0;
	int                             movementSign = 1;
	unsigned int                    explosionPeriod = 20;
	double				minCrd[3], maxCrd[3];

	Stream_SetPrintingRank( stream, Dictionary_GetUnsignedInt_WithDefault( context->dictionary, "procToWatch", 0 ) );
	movementSpeedDivisor = Dictionary_GetDouble_WithDefault( context->dictionary, (Dictionary_Entry_Key)"movementSpeedDivisor", 10 );
	
	mesh = (Mesh* )LiveComponentRegister_Get( context->CF->LCRegister, (Name)"mesh-linear"  );
	Mesh_GetGlobalCoordRange( mesh, minCrd, maxCrd );
	for ( dim_I=0; dim_I < 3; dim_I++ ) {
		attractorPoint[dim_I] = (maxCrd[dim_I] - minCrd[dim_I]) / 3;
	}
	Journal_Printf( stream, "Calculated attractor point is at (%f,%f,%f):\n", attractorPoint[0], attractorPoint[1], attractorPoint[2] );
	
	/* Now decide if we are attracting or repelling */
	if ( ( ( (context->timeStep - 1) / explosionPeriod ) % 2 ) == 0 ) {
		Journal_Printf( stream, "Timestep %d - Implosive mode\n", context->timeStep );
		movementSign = 1;
	}
	else {
		Journal_Printf( stream, "Timestep %d - Explosive mode\n", context->timeStep );
		movementSign = -1;
	}	

	
	for ( lCell_I=0; lCell_I < swarm->cellLocalCount; lCell_I++ ) {
		Journal_Printf( stream, "\tUpdating Particles positions in local cell %d:\n", lCell_I );
		for ( cParticle_I=0; cParticle_I < swarm->cellParticleCountTbl[lCell_I]; cParticle_I++ ) {
			Coord movementVector = {0,0,0};
			Coord newParticleCoord = {0,0,0};
			Coord* oldCoord;

			currParticle = (Particle*)Swarm_ParticleInCellAt( swarm, lCell_I, cParticle_I );
			oldCoord = &currParticle->coord;
			Journal_Printf( stream, "\t\tUpdating particleInCell %d:\n", cParticle_I );

			for ( dim_I=0; dim_I < 3; dim_I++ ) {
				movementVector[dim_I] = ( attractorPoint[dim_I] - (*oldCoord)[dim_I] ) /
					movementSpeedDivisor;
				movementVector[dim_I] *= movementSign;	
				if ( movementSign == -1 ) {
					movementVector[dim_I] *= (float)movementSpeedDivisor / (movementSpeedDivisor-1); 
				}
				newParticleCoord[dim_I] = (*oldCoord)[dim_I] + movementVector[dim_I];
			}
			memcpy( currParticle->velocity, movementVector, 3*sizeof(double) ); 

			Journal_Printf( stream, "\t\tChanging its coords from (%f,%f,%f) to (%f,%f,%f):\n",
				(*oldCoord)[0], (*oldCoord)[1], (*oldCoord)[2],
				newParticleCoord[0], newParticleCoord[1], newParticleCoord[2] );

			for ( dim_I=0; dim_I < 3; dim_I++ ) {
				currParticle->coord[dim_I] = newParticleCoord[dim_I];
			}
		}
	}

	Swarm_UpdateAllParticleOwners( swarm );
}
void AllNodesVCSuite_TestAllNodesVC( AllNodesVCSuiteData* data ) {
   unsigned                    nDomains;
   unsigned                    nDims = 3;
   unsigned                    meshSize[3] = {3, 3, 3};
   int                         procToWatch;
   double                      minCrds[3] = {0.0, 0.0, 0.0};
   double                      maxCrds[3] = {1.0, 1.0, 1.0};
   double*                     array[7];
   char*                       vcKey = "AllNodesVC";
   char*                       varName[] = {"x", "y", "z", "vx", "vy", "vz", "temp"};
   char                        input_file[PCU_PATH_MAX];
   char                        expected_file[PCU_PATH_MAX];
   Mesh*                       mesh;
   Variable_Register*          variable_Register;
   ConditionFunction*          quadCF;
   ConditionFunction_Register* conFunc_Register;
   ExtensionManager_Register*  extensionMgr_Register;
   Dictionary*                 dictionary;
   Dictionary*                 sources;
   Stream*                     stream;
   XML_IO_Handler*             io_handler;
   Variable*                   var[7];
   VariableCondition*          vc; 
   Index                       i, j, k;

   procToWatch = data->nProcs >=2 ? 1 : 0;

   io_handler = XML_IO_Handler_New();

    stream = Journal_Register( Info_Type, (Name)"AllNodesVCStream"  );
   Stream_RedirectFile( stream, "testAllNodesVC.dat" );

   dictionary = Dictionary_New();
   sources = Dictionary_New();
   Dictionary_Add( dictionary, (Dictionary_Entry_Key)"outputPath", Dictionary_Entry_Value_FromString("./output") );

   /* Input file */
   pcu_filename_input( "allVC.xml", input_file );
   IO_Handler_ReadAllFromFile( io_handler, input_file, dictionary, sources );
   fflush( stdout );

   extensionMgr_Register = ExtensionManager_Register_New(); 

    /* Create a mesh. */
   mesh = (Mesh*) AllNodesVCSuite_buildMesh( nDims, meshSize, minCrds, maxCrds, extensionMgr_Register );
   nDomains = Mesh_GetDomainSize( mesh, MT_VERTEX );

   /* Create CF stuff */
   quadCF = ConditionFunction_New( AllNodesVCSuite_quadratic, (Name)"quadratic", NULL);
   conFunc_Register = ConditionFunction_Register_New( );
   ConditionFunction_Register_Add(conFunc_Register, quadCF);

   /* Create variable register */
   variable_Register = Variable_Register_New();

   /* Create variables */
   for (i = 0; i < 6; i++) {
      array[i] = Memory_Alloc_Array( double, nDomains, "array[i]" );
      var[i] = Variable_NewScalar( varName[i], NULL, Variable_DataType_Double, (Index*)&nDomains, NULL, (void**)&array[i], 0  );
      Variable_Register_Add(variable_Register, var[i]);
   }
   array[6] = Memory_Alloc_Array( double, nDomains*5, "array[6]" );
   var[6] = Variable_NewVector( varName[6], NULL, Variable_DataType_Double, 5, &nDomains, NULL, (void**)&array[6], 0 );
   Variable_Register_Add(variable_Register, var[6]);
   Variable_Register_BuildAll(variable_Register);

   /* Create AllVC */
   vc = (VariableCondition*)AllNodesVC_New( "AllNodesVC", NULL, vcKey, variable_Register, conFunc_Register, dictionary, mesh );
   Stg_Component_Build( vc, 0, False );

   for (j = 0; j < 6; j++)
      memset(array[j], 0, sizeof(double)*nDomains);
   memset(array[6], 0, sizeof(double)*nDomains*5);
   VariableCondition_Apply(vc, NULL);

   if (data->rank == procToWatch) {
      Journal_Printf( stream,"Testing for %s\n", vcKey);
      for (j = 0; j < 6; j++) {
         Journal_Printf( stream, "\nvar[%u]: %.2lf", j, array[j][0]) ;
         for (k = 1; k < nDomains; k++)
            Journal_Printf( stream, ", %.2lf", array[j][k] );
      }
      Journal_Printf( stream, "\nvar[6]: %.2lf", array[6][0] );
      for (j = 1; j < nDomains*5; j++)
         Journal_Printf( stream, ", %.2lf", array[6][j] );
      Journal_Printf( stream, "\n\n" );

      for (j = 0; j < 7; j++) {
         for (k = 0; k < nDomains; k++)
            Journal_Printf( stream, "%s ", VariableCondition_IsCondition(vc, k, j) ? "True " : "False" );
         Journal_Printf( stream, "\n" );
      } Journal_Printf( stream, "\n" );

      for (j = 0; j < 7; j++) {
         for (k = 0; k < nDomains; k++) {
            VariableCondition_ValueIndex  valIndex;

            valIndex = VariableCondition_GetValueIndex(vc, k, j);
            if (valIndex != (unsigned)-1)
               Journal_Printf( stream, "%03u ", valIndex);
            else
               Journal_Printf( stream, "XXX ");
         } Journal_Printf( stream, "\n" );
      } Journal_Printf( stream, "\n" );

      pcu_filename_expected( "testAllNodesVC.expected", expected_file );
      pcu_check_fileEq( "testAllNodesVC.dat", expected_file );
      remove( "testAllNodesVC.dat" );
   }

   Stg_Class_Delete(vc);
   Stg_Class_Delete(variable_Register);

   for (i = 0; i < 7; i++) {
      Stg_Class_Delete(var[i]);
      if (array[i]) Memory_Free(array[i]);
   }

   Stg_Class_Delete(extensionMgr_Register);
   Stg_Class_Delete(io_handler);
   Stg_Class_Delete(conFunc_Register);
   Stg_Class_Delete(dictionary);
   Stg_Class_Delete(sources);
   FreeObject( mesh );
}
void WeightsSuite_TestElementIntegral(
   PICelleratorContext* context,
   Name                 funcName,
   Index                count,   // was SampleSize - defaults to 5000
   double               meanTolerance,
   double               stdDevTolerance,
   double               expectedMean,
   double               expectedStdDev ) 
{
   Swarm*             integrationSwarm = (Swarm*)LiveComponentRegister_Get( context->CF->LCRegister, (Name)"integrationSwarm" );
   Swarm*             materialSwarm    = (Swarm*)LiveComponentRegister_Get( context->CF->LCRegister, (Name)"materialPoints" );
   FeMesh*            mesh             = (FeMesh*)LiveComponentRegister_Get( context->CF->LCRegister, (Name)"linearMesh" );
   WeightsCalculator* weights          = (WeightsCalculator*)LiveComponentRegister_Get( context->CF->LCRegister, (Name)"weights"  );
   FeVariable*        feVariable;
   Element_LocalIndex lElement_I       = 0;
   double             analyticValue    = 0.0;
   double             integral         = 0.0;
   double             error;
   double             errorSquaredSum  = 0.0;
   double             errorSum         = 0.0;
   double             mean;
   double             standardDeviation;
   Index              loop_I;
   void*              data;
   double             differenceMean, differenceStdDev;   

   /* Create FeVariable */
   feVariable = FeVariable_New_Full(
      "feVariable", 
      (DomainContext*)context,
      mesh,
      NULL,
      NULL,
      NULL,
      NULL,
      NULL, 
      1,
      context->dim,
      False,
      False,
      False,
      MPI_COMM_WORLD,
      context->fieldVariable_Register );

   Journal_Firewall( (funcName!=NULL), Journal_Register( Error_Type, (Name)"ConstantWeightsSuite"  ),
      "Error, function name input to %s is NULL", __func__ );

   if ( strcasecmp( funcName, "ShapeFunction" ) == 0 ) {
      feVariable->_interpolateWithinElement = shapeFunction;
      analyticValue = 4.0;
   }
   else if ( strcasecmp( funcName, "ConstantFunction" ) == 0 ) {
      feVariable->_interpolateWithinElement = constantFunction;
      analyticValue = -12.0;
   }
   else if ( strcasecmp( funcName, "LinearFunction" ) == 0 ) {
      feVariable->_interpolateWithinElement = linearFunction;
      analyticValue = 8.0;
   }
   else if ( strcasecmp( funcName, "QuadraticFunction" ) == 0 ) {
      feVariable->_interpolateWithinElement = quadraticFunction;
      analyticValue = 16.0/3.0;
   }
   else if ( strcasecmp( funcName, "PolynomialFunction" ) == 0 ) {
      feVariable->_interpolateWithinElement = polynomialFunction;
      analyticValue = 148.0/3.0;
   }
   else if ( strcasecmp( funcName, "ExponentialFunction" ) == 0 ) {
      feVariable->_interpolateWithinElement = exponentialFunction;
      analyticValue = 0.0 /*TODO*/;
      abort();
   }
   else if ( strcasecmp( funcName, "ExponentialInterface" ) == 0 ) {
      feVariable->_interpolateWithinElement = exponentialInterface;
      analyticValue = 0.05 * (exp(2) - exp(-2)) + 2.0;
   }
   else if ( strcasecmp( funcName, "CircleInterface" ) == 0 ) {
      feVariable->_interpolateWithinElement = circleInterface;
      analyticValue = M_PI;
   }
   else 
      Journal_Firewall( False,
         Journal_Register( Error_Type, (Name)"ConstantWeightsSuite"  ),
         "Cannot understand function name '%s'\n", funcName );

   for ( loop_I = 0 ; loop_I < count ; loop_I++ ) {
      Swarm_Random_Seed( (long)loop_I );
      /* Layout Particles */
      _Swarm_InitialiseParticles( materialSwarm, data );

      _IntegrationPointsSwarm_UpdateHook( NULL, integrationSwarm );
      
      WeightsCalculator_CalculateCell( weights, integrationSwarm, lElement_I );

      /* Evaluate Integral */
      integral = FeVariable_IntegrateElement( feVariable, integrationSwarm, lElement_I );

      /* Calculate Error */
      error = fabs( integral - analyticValue )/fabs( analyticValue );
      errorSum += error;
      errorSquaredSum += error*error;
   }

   /* Calculate Mean and Standard Deviation */
   mean = errorSum / (double)count;
   standardDeviation = sqrt( errorSquaredSum / (double)count - mean * mean );

   //printf( "Func: %s - Mean = %g; SD = %g\n", funcName, mean, standardDeviation );

   /* compare the mean and standard deviation */
   differenceMean = fabs(mean - expectedMean);
   differenceStdDev = fabs(standardDeviation - expectedStdDev);
   pcu_check_le( differenceMean, meanTolerance );
   pcu_check_le( differenceStdDev, stdDevTolerance );
}
unsigned GeneralSwarm_IntegrationPointMap( void* _self, void* _intSwarm, unsigned elementId, unsigned intPtCellId ){
    GeneralSwarm* self  = (GeneralSwarm*)_self;
    IntegrationPointsSwarm*	intSwarm = (IntegrationPointsSwarm*)_intSwarm;
    Mesh*	                intMesh  = (Mesh*)intSwarm->mesh;
    SwarmMap* map = NULL;

    // first, lets check if the int swarm is mirroring a general swarm
    if (intSwarm->mirroredSwarm == (Swarm*)self)
    {
        // ok, it is a mirrored swarm
        return Swarm_ParticleCellIDtoLocalID(
                                        self,
                                        CellLayout_MapElementIdToCellId( self->cellLayout, elementId ),
                                        intPtCellId );
    } else if ( self->previousIntSwarmMap && self->previousIntSwarmMap->swarm==intSwarm ) { /* next check if previous swarmmap */
        map = self->previousIntSwarmMap;
    } else {
        /* ok, previous is not our guy, check other existing: */
        int ii;
        for (ii=0; ii<List_GetSize(self->intSwarmMapList); ii++) {
            map = *(SwarmMap**)List_GetItem(self->intSwarmMapList, ii);
            if ( map->swarm==intSwarm ){
                self->previousIntSwarmMap = map;
                break;
            }
        }
        // if we've gotten to this point, there is no corresponding map.. let's create one */
        map = SwarmMap_New( intSwarm );
        // add to list
        List_Append( self->intSwarmMapList, (void*)&map );
        self->previousIntSwarmMap = map;
        // also add to int swarm incase it moves
        List_Append( intSwarm->swarmsMappedTo, (void*)&map );

    }
    
    unsigned matPointLocalIndex;
    if ( SwarmMap_Map(map,elementId,intPtCellId,&matPointLocalIndex) ) {
        /* ok, map found, return value */
        return matPointLocalIndex;
    } else {
        /* not found... damn.. lets go ahead and find nearest neighbour */
        
        /* lets check some things */
        Journal_Firewall(
            Stg_Class_IsInstance( self->cellLayout, ElementCellLayout_Type ),
            NULL,
            "Error In func %s: %s expects a materialSwarm with cellLayout of type ElementCellLayout.",
            __func__, self->type
        );

        Journal_Firewall(
            intSwarm->mesh==(FeMesh*)((ElementCellLayout*)self->cellLayout)->mesh,
            Journal_Register( Error_Type, (Name)self->type  ),
            "Error - in %s(): Mapper requires both the MaterialSwarm and\n"
            "the IntegrationSwarm to live on the same mesh.\n"
            "Here the MaterialSwarm %s lives in the mesh %s\n"
            "and the IntegrationSwarm %s lives in the mesh %s.",
            self->name, ((ElementCellLayout*)self->cellLayout)->mesh->name,
            intSwarm->name, intSwarm->mesh->name
        );
        
        Cell_Index cell_I = CellLayout_MapElementIdToCellId( intSwarm->cellLayout, elementId );
        Cell_Index cell_M = CellLayout_MapElementIdToCellId(     self->cellLayout, elementId );

        IntegrationPoint* integrationPoint = (IntegrationPoint*)Swarm_ParticleInCellAt( intSwarm, cell_I, intPtCellId );
        
        /* Convert integration point local to global coordinates */
        Coord global;
        FeMesh_CoordLocalToGlobal( intMesh, elementId, integrationPoint->xi, (double*) &global );

        /* now lets sweep material points to find our closest friend */
        double         distance2_min = DBL_MAX;
        double         distance2;
        Particle_Index particle_M;
        unsigned cellPartCount = self->cellParticleCountTbl[ cell_M ];
        
        Journal_Firewall( cellPartCount,
            Journal_Register( Error_Type, (Name)self->type  ),
            "Error - in %s(): There doesn't appear to be any particles\n"
            "within the current cell (%u).\n",
            self->name, cell_M );

        for ( particle_M = 0; particle_M < cellPartCount; particle_M++ ) {
            GlobalParticle* materialPoint = (GlobalParticle*)Swarm_ParticleInCellAt( self, cell_M, particle_M );
            distance2 = pow( global[0] - materialPoint->coord[0], 2 ) + pow( global[1] - materialPoint->coord[1], 2 );
            if( self->dim == 3 )
                distance2 += pow( global[2] - materialPoint->coord[2], 2 );
            if ( distance2 < distance2_min ){
                distance2_min = distance2;
                matPointLocalIndex = Swarm_ParticleCellIDtoLocalID( self, cell_M, particle_M );
            }
        }
        
        /* ok, we've found our nearest friend. record to mapping */
        SwarmMap_Insert(map,elementId,intPtCellId,matPointLocalIndex);

    }
    
    return matPointLocalIndex;
}
int main( int argc, char* argv[] ) {
	Node_LocalIndex		nodeIndex;
	double				speedOfSound;
	Mass				mass000, mass100, mass110, mass111;
	Mass				inertialMass000, inertialMass100, inertialMass110, inertialMass111;
	Force				force000, force100, force110, force111;
	Force				balance000, balance100, balance110, balance111;
	Stream*				stream;
	
	SnacTest_SetUp( argc, argv );
	
	stream = Journal_Register (Info_Type, "myStream");

	SnacTest_PrintElementZeroInfo();
	
/*	Snac_Material_Print( &snacContext->materialProperty[Snac_Element_At( snacContext, 0 )->material_I], stream ); */
	
	SnacTest_UpdateElementsNodes( &speedOfSound );
	
	/* obtain the first corner node's info */
	nodeIndex = RegularMeshUtils_Node_Local3DTo1D( (HexaMD*)snacContext->mesh->layout->decomp, 0, 0, 0 );
	Snac_Force( (Context*)snacContext, nodeIndex, speedOfSound, &mass000, &inertialMass000, &force000, &balance000 );
	Snac_UpdateNodeMomentum( (Context*)snacContext, nodeIndex, inertialMass000, force000 );
	printf( "Corner Node %u (0,0,0): balance: (%g %g %g)\n", nodeIndex, balance000[0], balance000[1], balance000[2] );
	
	/* obtain the first edge node's info */
	nodeIndex = RegularMeshUtils_Node_Local3DTo1D( (HexaMD*)snacContext->mesh->layout->decomp, 1, 0, 0 );
	Snac_Force( (Context*)snacContext, nodeIndex, speedOfSound, &mass100, &inertialMass100, &force100, &balance100 );
	Snac_UpdateNodeMomentum( (Context*)snacContext, nodeIndex, inertialMass100, force100 );
	printf( "Edge Node %u (1,0,0): balance: (%g %g %g)\n", nodeIndex, balance100[0], balance100[1], balance100[2] );
	
	/* obtain the first suface node's info */
	nodeIndex = RegularMeshUtils_Node_Local3DTo1D( (HexaMD*)snacContext->mesh->layout->decomp, 1, 1, 0 );
	Snac_Force( (Context*)snacContext, nodeIndex, speedOfSound, &mass110, &inertialMass110, &force110, &balance110 );
	Snac_UpdateNodeMomentum( (Context*)snacContext, nodeIndex, inertialMass110, force110 );
	printf( "Surface Node %u (1,1,0): balance: (%g %g %g)\n", nodeIndex, balance110[0], balance110[1], balance110[2] );
	
	/* obtain the first internal node's info */
	nodeIndex = RegularMeshUtils_Node_Local3DTo1D( (HexaMD*)snacContext->mesh->layout->decomp, 1, 1, 1 );
	Snac_Force( (Context*)snacContext, nodeIndex, speedOfSound, &mass111, &inertialMass111, &force111, &balance111 );
	Snac_UpdateNodeMomentum( (Context*)snacContext, nodeIndex, inertialMass111, force111 );
	printf( "Internal Node %u (1,1,1): balance: (%g %g %g)\n", nodeIndex, balance111[0], balance111[1], balance111[2] );
	
	
	/* For each node, compare to the appropriate node */
	for( nodeIndex = 1; nodeIndex < snacContext->mesh->nodeLocalCount; nodeIndex++ ) {
		IJK		ijk;
		const IJK	s = { 	((HexaMD*)snacContext->mesh->layout->decomp)->nodeLocal3DCounts[rank][0] - 1,
					((HexaMD*)snacContext->mesh->layout->decomp)->nodeLocal3DCounts[rank][1] - 1,
					((HexaMD*)snacContext->mesh->layout->decomp)->nodeLocal3DCounts[rank][2] - 1 };
		
		RegularMeshUtils_Node_Local1DTo3D( (HexaMD*)snacContext->mesh->layout->decomp, nodeIndex, &ijk[0], &ijk[1], 
			&ijk[2] );
		if( (ijk[0] == 0 || ijk[0] == s[0]) && (ijk[1] == 0 || ijk[1] == s[1]) && (ijk[2] == 0 || ijk[2] == s[2]) ) {
			Bool		error;
			Mass		mass;
			Mass		inertialMass;
			Force		force;
			Force		balance;
			
			error = False;
			Snac_Force( (Context*)snacContext, nodeIndex, speedOfSound, &mass, &inertialMass, &force, &balance );
			Snac_UpdateNodeMomentum( (Context*)snacContext, nodeIndex, inertialMass, force );
			if( balance[0] != balance000[0] || balance[1] != balance000[1] || balance[2] != balance000[2] ) {
				printf( "Corner Node %u: balance: (%g %g %g)\n", nodeIndex, balance[0], balance[1], balance[2] );
				error = True;
			}
			
			if( error ) {
				printf( "Corner Node %u: Gives a differing answer from node {0, 0, 0}.\n", nodeIndex );
			}
			else {
				printf( "Corner Node %u: has same values as node {0, 0, 0}.\n", nodeIndex );
			}
		}
		else if( ((ijk[0] == 0 || ijk[0] == s[0]) && (ijk[1] == 0 || ijk[1] == s[1])) ||
			((ijk[0] == 0 || ijk[0] == s[0]) && (ijk[2] == 0 || ijk[2] == s[2])) ||
			((ijk[1] == 0 || ijk[1] == s[1]) && (ijk[2] == 0 || ijk[2] == s[2])) )
		{
			Bool		error;
			Mass		mass;
			Mass		inertialMass;
			Force		force;
			Force		balance;
			
			error = False;
			Snac_Force( (Context*)snacContext, nodeIndex, speedOfSound, &mass, &inertialMass, &force, &balance );
			Snac_UpdateNodeMomentum( (Context*)snacContext, nodeIndex, inertialMass, force );
			if( balance[0] != balance100[0] || balance[1] != balance100[1] || balance[2] != balance100[2] ) {
				printf( "Edge Node %u: balance: (%g %g %g)\n", nodeIndex, balance[0], balance[1], balance[2] );
				error = True;
			}
			
			if( error ) {
				printf( "Edge Node %u: Gives a differing answer from node {1, 0, 0}.\n", nodeIndex );
			}
			else {
				printf( "Edge Node %u: has same values as node {1, 0, 0}.\n", nodeIndex );
			}
		}
		else if( (ijk[0] == 0 || ijk[0] == s[0]) || (ijk[1] == 0 || ijk[1] == s[1]) || (ijk[2] == 0 || ijk[2] == s[2]) ) {
			Bool		error;
			Mass		mass;
			Mass		inertialMass;
			Force		force;
			Force		balance;
			
			error = False;
			Snac_Force( (Context*)snacContext, nodeIndex, speedOfSound, &mass, &inertialMass, &force, &balance );
			Snac_UpdateNodeMomentum( (Context*)snacContext, nodeIndex, inertialMass, force );
			if( balance[0] != balance110[0] || balance[1] != balance110[1] || balance[2] != balance110[2]  ) {
				printf( "Surface Node %u: balance: (%g %g %g)\n", nodeIndex, balance[0], balance[1], balance[2] );
				error = True;
			}
			
			if( error ) {
				printf( "Surface Node %u: Gives a differing answer from node {1, 1, 0}.\n", nodeIndex );
			}
			else {
				printf( "Surface Node %u: has same values as node {1, 1, 0}.\n", nodeIndex );
			}
		}
		else {
			Bool		error;
			Mass		mass;
			Mass		inertialMass;
			Force		force;
			Force		balance;
			
			error = False;
			Snac_Force( (Context*)snacContext, nodeIndex, speedOfSound, &mass, &inertialMass, &force, &balance );
			Snac_UpdateNodeMomentum( (Context*)snacContext, nodeIndex, inertialMass, force );
			if( balance[0] != balance111[0] || balance[1] != balance111[1] || balance[2] != balance111[2] ) {
				printf( "Internal Node %u: balance: (%g %g %g)\n", nodeIndex, balance[0], balance[1], balance[2] );
				error = True;
			}
			
			if( error ) {
				printf( "Internal Node %u: Gives a differing answer from node {1, 1, 1}.\n", nodeIndex );
			}
			else {
				printf( "Internal Node %u: has same values as node {1, 1, 1}.\n", nodeIndex );
			}
		}
	}
	
	SnacTest_TearDown();
	
	return 0; /* success */
}
Example #7
0
Bool DiscretisationUtils_Finalise( void ) {
	Journal_Printf( Journal_Register( DebugStream_Type, "Context" ), "In: %s\n", __func__ ); /* DO NOT CHANGE OR REMOVE */
	
	return True;
}
void _Trubitsyn2006_Init( 
   Trubitsyn2006* self, 
   FeVariable*    velocityField,
   FeVariable*    pressureField,
   double         Ra,
   double         T0,
   int            wavenumberX,
   int            wavenumberY,
   char*          viscosityType )
{
   self->velocityField = velocityField;
   self->pressureField = pressureField;
   self->Ra = Ra;
   self->T0 = T0;
   self->wavenumberX = wavenumberX;
   self->wavenumberY = wavenumberY;   

   if ( strcasecmp( viscosityType, "Isoviscous" ) == 0 ) {
      self->viscosityFunc = AnalyticFunction_New(
         _Trubitsyn2006_ViscosityFunc_Isoviscous,
         (Name)"_Trubitsyn2006_ViscosityFunc_Isoviscous" );

      self->viscosityDerivativeFunc = AnalyticFunction_New(
         _Trubitsyn2006_ViscosityDerivativeFunc_Isoviscous,
         (Name)"_Trubitsyn2006_ViscosityDerivativeFunc_Isoviscous" );
   }
   else if ( strcasecmp( viscosityType, "Model1" ) == 0 ) {
      self->viscosityFunc = AnalyticFunction_New(
         _Trubitsyn2006_ViscosityFunc_Model1,
         (Name)"_Trubitsyn2006_ViscosityFunc_Model1" );

      self->viscosityDerivativeFunc = AnalyticFunction_New(
         _Trubitsyn2006_ViscosityDerivativeFunc_Model1,
         (Name)"_Trubitsyn2006_ViscosityDerivativeFunc_Model1" );
   }
   else if ( strcasecmp( viscosityType, "Model2" ) == 0 ) {
      self->viscosityFunc = AnalyticFunction_New(
         _Trubitsyn2006_ViscosityFunc_Model2,
         (Name)"_Trubitsyn2006_ViscosityFunc_Model2" );

      self->viscosityDerivativeFunc = AnalyticFunction_New(
         _Trubitsyn2006_ViscosityDerivativeFunc_Model2,
         (Name)"_Trubitsyn2006_ViscosityDerivativeFunc_Model2" );
   }
   else if ( strcasecmp( viscosityType, "Model3" ) == 0 ) {
      self->viscosityFunc = AnalyticFunction_New(
         _Trubitsyn2006_ViscosityFunc_Model3,
         (Name)"_Trubitsyn2006_ViscosityFunc_Model3" );

      self->viscosityDerivativeFunc = AnalyticFunction_New(
         _Trubitsyn2006_ViscosityDerivativeFunc_Model3,
         (Name)"_Trubitsyn2006_ViscosityDerivativeFunc_Model3" ); 
   }
   else {
      Journal_Printf(
         Journal_Register( Error_Type, (Name)viscosityType ),
         "Cannot understand viscosity type = '%s'\n",
         viscosityType );
      abort();
   }
}    
Example #9
0
Variable* Mesh_GenerateENMapVar( void* mesh ) {
    /* Returns a Variable that stores the mapping of 
     * [local element] [global node indices]
     * Assumes the mapping never changes.
     */

    Mesh* self = (Mesh*)mesh;
    char* name;
    int n_i, e_i, nNbr, localElements, localtotal;
    unsigned buffy_tvs;     // buffer for global node indices
    unsigned dim, *nbr, temp;
    int *numberNodesPerEl = NULL;
    IArray* inc = NULL;
    Stream* error = Journal_Register( Error_Type, (Name)self->type );

    // if variable already exists return it
    if( self->enMapVar ) return self->enMapVar;

    /* go over local elementNode map to get size of data */
    inc = IArray_New( );
    self->localtotalNodes=0;
    dim = Mesh_GetDimSize( self );
    localElements = Mesh_GetLocalSize( self, dim );
    numberNodesPerEl = Memory_Alloc_Array( int, localElements, "Mesh::numberNodesPerEl" );

    for( e_i=0 ; e_i < localElements; e_i++ ) {
        Mesh_GetIncidence( self, dim, (unsigned)e_i, MT_VERTEX, inc );
        nNbr = IArray_GetSize( inc );
        nbr = IArray_GetPtr( inc );

        numberNodesPerEl[e_i] = nNbr;
        self->localtotalNodes += nNbr;
    }
    
    /* Create the Variable data structure, int[nbrNodesPerEl*local element count]
     * Note: this is stored in a 1D array - so whatever read or writes to this variable 
     * needs to know how to parse it. */ 
    self->e_n = Memory_Alloc_Array( int, self->localtotalNodes, "Mesh::nodeConn" );
    Stg_asprintf( &name, "%s-%s", self->name, "nodeConn" );
    self->enMapVar = Variable_NewScalar( name, NULL, Variable_DataType_Int, &self->localtotalNodes, NULL, (void**)&self->e_n, NULL );
    Stg_Component_Build(self->enMapVar, NULL, False);
    Stg_Component_Initialise(self->enMapVar, NULL, False);
    free(numberNodesPerEl);
    free(name);

    // Evaluate the global indices for the local nodes
    localtotal=0;
    for( e_i=0; e_i<localElements; e_i++ ) {
        Mesh_GetIncidence( self, dim, (unsigned)e_i, MT_VERTEX, inc );
        nNbr = IArray_GetSize( inc );
        nbr = IArray_GetPtr( inc );
        for( n_i=0; n_i< nNbr; n_i++ ) {
            buffy_tvs = Mesh_DomainToGlobal( self, MT_VERTEX, nbr[n_i] );
            Variable_SetValue( self->enMapVar, localtotal, (void*)&buffy_tvs );
            localtotal++;
        }
    }

    Stg_Class_Delete( inc );

    // return new variable
    return self->enMapVar;
}
void ComplexVectorMathSuite_TestComplexVectorMathBasic( ComplexVectorMathSuiteData* data ) {
   unsigned procToWatch;
   Stream*  stream = Journal_Register( Info_Type, (Name)"VectorMathBasicStream" );
   char     expected_file[PCU_PATH_MAX];

   procToWatch = data->nProcs >=2 ? 1 : 0;

   if (data->rank == procToWatch ) {
      CoordC a, b, c;
      CoordC d = { {1.0, 1.0}, {1.0, 0.0}, {0.0, 1.0} };
      CoordC e = { {1.0, 0.0}, {2.0, 2.0}, {-3.0, -1.0} };
      Cmplx  value = {1.0, 1.0}; 
      Cmplx  c1 = {1.0, 0.0};
      Cmplx  c2 = {2.0, 1.0};
      Cmplx  c3 = {1.5, 1.0};

      Stream_RedirectFile( stream, "testComplexVectorMathBasic.dat" );

      Journal_Printf( stream, "Basic tests:\n" );
      Journal_Printf( stream, "d = \n");
      Journal_PrintCmplx( stream, d[0]);
      Journal_PrintCmplx( stream, d[1]);
      Journal_PrintCmplx( stream, d[2]);
       
      Journal_Printf( stream, "Set Complex Scalar\n");
      ComplexVector_SetScalar( c1, c2, c3, d );
      Journal_Printf( stream, "d = \n");
      Journal_PrintCmplx( stream, d[0]);
      Journal_PrintCmplx( stream, d[1]);
      Journal_PrintCmplx( stream, d[2]);

      Journal_Printf( stream, "Set c = d\n");
      ComplexVector_Set( d, c );
      Journal_Printf( stream, "c = \n");
      Journal_PrintCmplx( stream, c[0]);
      Journal_PrintCmplx( stream, c[1]);
      Journal_PrintCmplx( stream, c[2]);

      ComplexVector_Add(c, d, b );
      Journal_Printf( stream, "b = c + d \n");
      Journal_Printf( stream, "b = \n");
      Journal_PrintCmplx( stream, b[0]);
      Journal_PrintCmplx( stream, b[1]);
      Journal_PrintCmplx( stream, b[2]);

      ComplexVector_Sub( b, d, a );
      Journal_Printf( stream, "a = b - d \n");
      Journal_Printf( stream, "a = \n");
      Journal_PrintCmplx( stream, a[0]);
      Journal_PrintCmplx( stream, a[1]);
      Journal_PrintCmplx( stream, a[2]);

      ComplexVector_Cross( a, e, d );      
      Journal_Printf( stream, "d = a x e \n");
      Journal_Printf( stream, "e = \n");
      Journal_PrintCmplx( stream, e[0]);
      Journal_PrintCmplx( stream, e[1]);
      Journal_PrintCmplx( stream, e[2]);      
      Journal_Printf( stream, "d = \n");
      Journal_PrintCmplx( stream, d[0]);
      Journal_PrintCmplx( stream, d[1]);
      Journal_PrintCmplx( stream, d[2]);
      
      ComplexVector_Dot( a, e, value );
      Journal_Printf( stream, "value = a . e \n");
      Journal_PrintCmplx( stream, value);
      
      value[REAL_PART] = 2.0;
      value[IMAG_PART] = 1.0;
      Journal_Printf( stream, "b = \n");
      Journal_PrintCmplx( stream, b[0]);
      Journal_PrintCmplx( stream, b[1]);
      Journal_PrintCmplx( stream, b[2]);      
      ComplexVector_Mult( b, value, b);
      Journal_Printf( stream, "b = (2 + i) * b \n");
      Journal_Printf( stream, "b = \n");
      Journal_PrintCmplx( stream, b[0]);
      Journal_PrintCmplx( stream, b[1]);
      Journal_PrintCmplx( stream, b[2]);
      
      ComplexVector_MultReal(b, 3.0, b);
      Journal_Printf( stream, "b = 3 * b \n");
      Journal_Printf( stream, "b = \n");
      Journal_PrintCmplx( stream, b[0]);
      Journal_PrintCmplx( stream, b[1]);
      Journal_PrintCmplx( stream, b[2]);   

      b[0][REAL_PART] = 0.0; b[0][IMAG_PART] = 1.0; 
      b[1][REAL_PART] = 1.0; b[1][IMAG_PART] = 1.0;
      b[2][REAL_PART] = 0.0; b[2][IMAG_PART] = 1.0;
      
      Journal_Printf( stream, "b = \n");
      Journal_PrintCmplx( stream, b[0]);
      Journal_PrintCmplx( stream, b[1]);
      Journal_PrintCmplx( stream, b[2]);

      Journal_Printf( stream, "|b| = %g\n", ComplexVector_Mag(b));
            
      ComplexVector_Proj(a, b, d);
      Journal_Printf( stream, "d = proj a onto b \n");
      Journal_Printf( stream, "d = \n");
      Journal_PrintCmplx( stream, d[0]);
      Journal_PrintCmplx( stream, d[1]);
      Journal_PrintCmplx( stream, d[2]);         
      
      ComplexVector_Div(a, value, e);
      Journal_Printf( stream, "e = a / value \n");
      Journal_PrintCmplx( stream, value);
      Journal_Printf( stream, "e = \n");
      Journal_PrintCmplx( stream, e[0]);
      Journal_PrintCmplx( stream, e[1]);
      Journal_PrintCmplx( stream, e[2]);

      Journal_Printf( stream, "b = \n");
      Journal_PrintCmplx( stream, b[0]);
      Journal_PrintCmplx( stream, b[1]);
      Journal_PrintCmplx( stream, b[2]);
      ComplexVector_Norm( b, b );
      Journal_Printf( stream, "Norm(b) = \n");
      Journal_PrintCmplx( stream, b[0]);
      Journal_PrintCmplx( stream, b[1]);
      Journal_PrintCmplx( stream, b[2]);
   
      Journal_Printf( stream, "|b| = %g\n", ComplexVector_Mag(b));
      
      Journal_Printf( stream, "a  = \n");
      Journal_PrintCmplx( stream, a[0]);
      Journal_PrintCmplx( stream, a[1]);
      Journal_PrintCmplx( stream, a[2]);
      
      ComplexVector_Swizzle(a, K_AXIS, I_AXIS, J_AXIS, a);
      Journal_Printf( stream, "swizzle(a)(k, i, j) = \n");
      Journal_PrintCmplx( stream, a[0]);
      Journal_PrintCmplx( stream, a[1]);
      Journal_PrintCmplx( stream, a[2]);

      pcu_filename_expected( "testComplexVectorMathBasic.expected", expected_file );
      pcu_check_fileEq( "testComplexVectorMathBasic.dat", expected_file );
      remove( "testComplexVectorMathBasic.dat" );

      Stream_CloseAndFreeFile( stream );
   }
}
		 self->GNx = ReallocArray2D( self->GNx, double, dim, elementNodeCount );
		 self->Ni = ReallocArray( self->Ni, double, elementNodeCount );
	}
	
	
	GNx = self->GNx;
	Ni = self->Ni;
#endif
	Dtilda_B = self->Dtilda_B;

	/* Get number of particles per element */
	cell_I            = CellLayout_MapElementIdToCellId( swarm->cellLayout, lElement_I );
	cellParticleCount = swarm->cellParticleCountTbl[ cell_I ];

	/* Determine whether this is the first solve for not */
	Journal_Firewall( sle != NULL, Journal_Register( Error_Type, (Name)ConstitutiveMatrix_Type  ), 
			"In func %s: SLE is NULL.\n", __func__ );

	/* Note: we may have deliberately set the previousSolutionExists flag to true in the
		parent ConstitutiveMatrix constructor if in restart mode, even if the SLE hasn't executed yet
		in this run - so only update to the sle's value when SLE is confirming it has
		executed */
		
	if ( True == sle->hasExecuted ) {
		self->previousSolutionExists = sle->hasExecuted;
	}
	
	self->sleNonLinearIteration_I = sle->nonLinearIteration_I;
	
	/* Shape functions at the element centre for "underintegration" of the penalty term */
	
void ComplexVectorMathSuite_TestComplexVectorMathOperations( ComplexVectorMathSuiteData* data ) {
   unsigned procToWatch;
   Stream*  stream = Journal_Register( Info_Type, (Name)"VectorMathOperationsStream" );
   char     expected_file[PCU_PATH_MAX];

   procToWatch = data->nProcs >=2 ? 1 : 0;

   if (data->rank == procToWatch ) {
      #define STG_COMPLEXVECTOR_TOL 1e-16;
      
      Cmplx  i[] = {{1.00000000, 0.000000000},{0.00000000, 0.000000000},{0.000000000, 0.00000000}};
      Cmplx  j[] = {{0.00000000, 0.00000000},{1.0000000, 0.00000000},{0.00000000, 0.0000000}};
      Cmplx  k[] = {{0.00000000, 0.000000000},{0.00000000, 0.000000000},{1.000000000, 0.000000000}};
      Cmplx  A[] = {{7.4, 1.0}, {  2, 0.0}, {  5, 1.0}, { 1, 0.0}, {  3, 2.0}, {  -42, 0.0}};
      Cmplx  B[] = {{  4, 2.0}, {2.3, 0.0}, {5.8, 0.0}, { 6, 0.0}, {-12, 0.0}, {39289, 0.0}};
      Cmplx  C[] = {{23, 0.0}, {  5, 0.0}, {-14, 0.0}, {32, 0.0}, {-21, 1.0}, {   78, 0.0}};
      Cmplx  D[] = {{23, 0.0}, {  5, 0.0}, {-14, 0.0}, {32, 0.0}, {-21, 0.0}, {   78, 0.0}};
      double angle;
      Cmplx  **matrix;
      Cmplx  vector[6], differenceVector[6];
      Cmplx  *coordList[4];
      int    d;
      double realVector[3], tolerance;
      Cmplx  dotProductResult;
      Cmplx  value;
      
      Stream_RedirectFile( stream, "testComplexVectorMathOperations.dat" );

      tolerance = STG_COMPLEXVECTOR_TOL;
      
      coordList[0] = A;
      coordList[1] = B;
      coordList[2] = C;
      coordList[3] = D;
      Journal_Printf( stream, "****************************\n");
      Journal_Printf(stream, "Vectors - A, B, C, and D\n");
      
      StGermain_PrintNamedComplexVector( stream, A, 6 );
      StGermain_PrintNamedComplexVector( stream, B, 6 );
      StGermain_PrintNamedComplexVector( stream, C, 6 );
      StGermain_PrintNamedComplexVector( stream, D, 6 );

      /* Check Rotation functions */
      Journal_Printf( stream, "\n****************************\n");

      StGermain_PrintNamedComplexVector( stream, i, 3 );
      StGermain_PrintNamedComplexVector( stream, j, 3 );
      StGermain_PrintNamedComplexVector( stream, k, 3 );
      
      angle = M_PI / 2.0;
      
      Journal_Printf(stream, "Axis Rotation\n");            
      StGermain_RotateCoordinateAxisComplex( k, I_AXIS, angle, vector ) ;
      Journal_Printf( stream, "K Rotated %g radians around I axis - \n", angle);
      Cmplx_Subtract(vector[0], j[0], differenceVector[0]);
      Cmplx_Subtract(vector[1], j[1], differenceVector[1]);
      Cmplx_Subtract(vector[2], j[2], differenceVector[2]);
      
      if ( (Cmplx_Modulus(differenceVector[0]) < tolerance) && (Cmplx_Modulus(differenceVector[1]) < tolerance) &&
          (Cmplx_Modulus(differenceVector[2]) < tolerance) ) {
         Journal_Printf( stream, "Answer within tolerance %g of expected result: ", tolerance);
         StGermain_PrintNamedComplexVector( stream, j, 3);
      }
      else {
         Journal_Printf( stream, "Answer not within tolerance %g of expected result: ", tolerance);
         StGermain_PrintNamedComplexVector( stream, j, 3);
      }
      
      Journal_Printf(stream, "Angle Rotation\n");      
      StGermain_RotateComplexVector(k, angle,0.0, 0.0, vector);
      Journal_Printf( stream, "K Rotated %g radians around I axis - \n", angle); 
      Cmplx_Subtract(vector[0], j[0], differenceVector[0]);
      Cmplx_Subtract(vector[1], j[1], differenceVector[1]);
      Cmplx_Subtract(vector[2], j[2], differenceVector[2]);
      
      if ( (Cmplx_Modulus(differenceVector[0]) < tolerance) && (Cmplx_Modulus(differenceVector[1]) < tolerance) &&
          (Cmplx_Modulus(differenceVector[2]) < tolerance) ) {
         Journal_Printf( stream, "Answer within tolerance %g of expected result: ", tolerance);
         StGermain_PrintNamedComplexVector( stream, j, 3);
      }
      else {
         Journal_Printf( stream, "Answer not within tolerance %g of expected result: ", tolerance);
         StGermain_PrintNamedComplexVector( stream, j, 3);
      }
      
      Journal_Printf(stream, "Axis Rotation\n");      
      StGermain_RotateCoordinateAxisComplex( i, J_AXIS, angle, vector );
      Journal_Printf( stream, "I Rotated %g radians around J axis - \n", angle); 
      Cmplx_Subtract(vector[0], k[0], differenceVector[0]);
      Cmplx_Subtract(vector[1], k[1], differenceVector[1]);
      Cmplx_Subtract(vector[2], k[2], differenceVector[2]);
      
      if ( (Cmplx_Modulus(differenceVector[0]) < tolerance) && (Cmplx_Modulus(differenceVector[1]) < tolerance) &&
          (Cmplx_Modulus(differenceVector[2]) < tolerance) ) {
         Journal_Printf( stream, "Answer within tolerance %g of expected result: ", tolerance);
         StGermain_PrintNamedComplexVector( stream, k, 3);
      }
      else {
         Journal_Printf( stream, "Answer not within tolerance %g of expected result: ", tolerance);
         StGermain_PrintNamedComplexVector( stream, k, 3);
      }
      
      Journal_Printf(stream, "Angle Rotation\n");
      StGermain_RotateComplexVector(i, 0.0, angle, 0.0, vector );
      Journal_Printf( stream, "I Rotated %g radians around J axis - \n", angle); 
      Cmplx_Subtract(vector[0], k[0], differenceVector[0]);
      Cmplx_Subtract(vector[1], k[1], differenceVector[1]);
      Cmplx_Subtract(vector[2], k[2], differenceVector[2]);
      
      if ( (Cmplx_Modulus(differenceVector[0]) < tolerance) && (Cmplx_Modulus(differenceVector[1]) < tolerance) &&
          (Cmplx_Modulus(differenceVector[2]) < tolerance) ) {
         Journal_Printf( stream, "Answer within tolerance %g of expected result: ", tolerance);
         StGermain_PrintNamedComplexVector( stream, k, 3);
      }
      else {
         Journal_Printf( stream, "Answer not within tolerance %g of expected result: ", tolerance);
         StGermain_PrintNamedComplexVector( stream, k, 3);
      }
      
      Journal_Printf(stream, "Axis Rotation\n");      
      StGermain_RotateCoordinateAxisComplex( j, K_AXIS, angle, vector );
      Journal_Printf( stream, "J Rotated %g radians around K axis - \n", angle); 
      Cmplx_Subtract(vector[0], i[0], differenceVector[0]);
      Cmplx_Subtract(vector[1], i[1], differenceVector[1]);
      Cmplx_Subtract(vector[2], i[2], differenceVector[2]);
      
      if ( (Cmplx_Modulus(differenceVector[0]) < tolerance) && (Cmplx_Modulus(differenceVector[1]) < tolerance) &&
          (Cmplx_Modulus(differenceVector[2]) < tolerance) ) {
         Journal_Printf( stream, "Answer within tolerance %g of expected result: ", tolerance);
         StGermain_PrintNamedComplexVector( stream, i, 3);
      }
      else {
         Journal_Printf( stream, "Answer not within tolerance %g of expected result: ", tolerance);
         StGermain_PrintNamedComplexVector( stream, i, 3);
      }

      Journal_Printf(stream, "Angle Rotation\n");
      StGermain_RotateComplexVector( j, 0.0, 0.0, angle, vector );
      Journal_Printf( stream, "J Rotated %g radians around K axis - \n", angle); 
      Cmplx_Subtract(vector[0], i[0], differenceVector[0]);
      Cmplx_Subtract(vector[1], i[1], differenceVector[1]);
      Cmplx_Subtract(vector[2], i[2], differenceVector[2]);
      
      if ( (Cmplx_Modulus(differenceVector[0]) < tolerance) && (Cmplx_Modulus(differenceVector[1]) < tolerance) &&
          (Cmplx_Modulus(differenceVector[2]) < tolerance) ) {
         Journal_Printf( stream, "Answer within tolerance %g of expected result: ", tolerance);
         StGermain_PrintNamedComplexVector( stream, i, 3);
      }
      else {
         Journal_Printf( stream, "Answer not within tolerance %g of expected result: ", tolerance);
         StGermain_PrintNamedComplexVector( stream, i, 3);
      }

      angle = M_PI / 4.0;

      StGermain_RotateComplexVector(i, 0.0, angle, angle, vector );
      Journal_Printf( stream, "I Rotated %g radians around J axis "
      "and %2g radians around K axis: \n", angle, angle);
      StGermain_PrintNamedComplexVector( stream, vector, 3 );

      StGermain_RotateComplexVector(j, angle, 0.0, angle, vector );
      Journal_Printf( stream, "J Rotated %g radians around I axis "
      "and %g radians around K axis: \n", angle, angle); 
      StGermain_PrintNamedComplexVector( stream, vector, 3 );

      StGermain_RotateComplexVector(k, angle, angle, 0.0, vector );
      Journal_Printf( stream, "K Rotated %g radians around I axis "
      "and %g radians around J axis: \n", angle, angle); 
      StGermain_PrintNamedComplexVector( stream, vector, 3 );

      /* Check addition function */
      Journal_Printf( stream, "\n****************************\n");
      Journal_Printf( stream, "vector = A + B\n");
      for ( d = 0 ; d <= 6 ; d++ ) {
         StGermain_ComplexVectorAddition( vector, A, B, d );
         StGermain_PrintNamedComplexVector( stream, vector, d );
      }

      /* Check subtraction function */
      Journal_Printf( stream, "\n****************************\n");
      Journal_Printf( stream, "vector = A - B\n");
      for ( d = 0 ; d <= 6 ; d++ ) {
         StGermain_ComplexVectorSubtraction( vector, A, B, d );
         StGermain_PrintNamedComplexVector( stream, vector, d );
      }
   
      /* Check Magnitude Function */
      Journal_Printf( stream, "\n****************************\n");
      Journal_Printf( stream, "Check Magnitude Function\n");
      for ( d = 0 ; d <= 6 ; d++ ) {
         Journal_Printf( stream, "dim = %d magnitude A = %2.3f\n", d, StGermain_ComplexVectorMagnitude( A, d ) );
         Journal_Printf( stream, "dim = %d magnitude B = %2.3f\n", d, StGermain_ComplexVectorMagnitude( B, d ) );
      }

      /* Check Dot Product */
      Journal_Printf( stream, "\n****************************\n");
      Journal_Printf( stream, "Check Dot Product Function\n");
      Journal_Printf( stream, "value = A . B \n");
      
      for (d = 0; d <=6; d++) {
      StGermain_ComplexVectorDotProduct(A, B, d, dotProductResult);         
      Journal_Printf( stream, "dim = %d dot product = %2.3f + %2.3f i\n",
         d, dotProductResult[0], dotProductResult[1] );
      }

      /* Check Cross Product */
      /* Tested against http://www.engplanet.com/redirect.html?3859 */
      Journal_Printf( stream, "\n****************************\n");
      Journal_Printf( stream, "Check Cross Product Function\n");
      Journal_Printf( stream, " A x B in 3-D\n");
      StGermain_ComplexVectorCrossProduct( vector, A, B );
      StGermain_PrintNamedComplexVector( stream, vector, 3 );

      /* Checking centroid function */
      Journal_Printf( stream, "\n****************************\n");
      Journal_Printf( stream, "Checking centroid function\n");
      for ( d = 0 ; d <= 6 ; d++ ) {
         StGermain_ComplexTriangleCentroid( vector, A, B, C, d );
         StGermain_PrintNamedComplexVector( stream, vector, d );
      }

      /* Check Normalisation Function */
      Journal_Printf( stream, "\n****************************\n");
      Journal_Printf( stream, "Check Normalisation Function\n");
      
      Journal_Printf( stream, "2-D\n\n");
      d = 2;
      StGermain_PrintNamedComplexVector( stream, A, d );
      StGermain_ComplexVectorNormalise( A, d );
      StGermain_PrintNamedComplexVector( stream, A, d);
      Journal_Printf( stream, "mag = %2.3f\n", StGermain_ComplexVectorMagnitude( A, d ) );

      Journal_Printf( stream, "3-D\n\n");
      d = 3;
      StGermain_PrintNamedComplexVector( stream, B, d );
      StGermain_ComplexVectorNormalise( B, d );
      StGermain_PrintNamedComplexVector( stream, B, d);
      Journal_Printf( stream, "mag = %2.3f\n", StGermain_ComplexVectorMagnitude( B, d ) );

      Journal_Printf( stream, "5-D\n\n");
      d = 5;
      StGermain_PrintNamedComplexVector( stream, C, d );
      StGermain_ComplexVectorNormalise( C, d );
      StGermain_PrintNamedComplexVector( stream, C, d);
      Journal_Printf( stream, "mag = %2.3f\n", StGermain_ComplexVectorMagnitude( C, d ) );

      Journal_Printf( stream, "\n****************************\n");
      Journal_Printf( stream, "Check StGermain_ComplexVectorCrossProductMagnitude\n");
      A[0][REAL_PART] = 1.0; A[0][IMAG_PART] = 1.0; 
      A[1][REAL_PART] = 2.0; A[1][IMAG_PART] = 0.0;
      A[2][REAL_PART] = 3.0; A[2][IMAG_PART] = 0.0;
      B[0][REAL_PART] = 4.0; B[0][IMAG_PART] = 0.0;
      B[1][REAL_PART] = 5.0; B[1][IMAG_PART] = 0.0;
      B[2][REAL_PART] = 6.0; B[2][IMAG_PART] = 3.0;
      StGermain_PrintNamedComplexVector( stream, A, 3);
      StGermain_PrintNamedComplexVector( stream, B, 3);
      
      StGermain_ComplexVectorCrossProductMagnitude(A, B, 2, value ) ;
      Journal_Printf( stream, "mag = %2.3g + %2.3g i (2D)\n", value[REAL_PART], value[IMAG_PART] );
      
      StGermain_ComplexVectorCrossProductMagnitude(A, B, 3, value ) ;
      Journal_Printf( stream, "mag = %2.3g + %2.3g i (3D)\n", value[REAL_PART], value[IMAG_PART] );

      Journal_Printf( stream, "\n****************************\n");
      Journal_Printf( stream, "Check StGermain_ComplexScalarTripleProduct \n");
      
      matrix = Memory_Alloc_2DArray( Cmplx, 3, 3, (Name)"matrix"  );
      
      matrix[0][0][REAL_PART] = 1.0;  matrix[0][0][IMAG_PART] = 1.0;
      matrix[0][1][REAL_PART] = 2.0;  matrix[0][1][IMAG_PART] = 0.0; 
      matrix[0][2][REAL_PART] = 3.0;  matrix[0][2][IMAG_PART] = 2.0;
      matrix[1][0][REAL_PART] = 4.0;  matrix[1][0][IMAG_PART] = 0.0;
      matrix[1][1][REAL_PART] = 5.0;  matrix[1][1][IMAG_PART] = 3.0; 
      matrix[1][2][REAL_PART] = 6.0;  matrix[1][2][IMAG_PART] = 0.0;
      matrix[2][0][REAL_PART] = 7.0;  matrix[2][0][IMAG_PART] = 1.0;
      matrix[2][1][REAL_PART] = 8.0;  matrix[2][1][IMAG_PART] = 0.0;
      matrix[2][2][REAL_PART] = 11.0; matrix[2][2][IMAG_PART] = 1.0;
      StGermain_PrintNamedComplexVector( stream, matrix[0], 3);
      StGermain_PrintNamedComplexVector( stream, matrix[1], 3);
      StGermain_PrintNamedComplexVector( stream, matrix[2], 3);

      StGermain_ComplexScalarTripleProduct( matrix[0], matrix[1], matrix[2], value );
      Journal_Printf( stream, "scalar triple product: ");
      Journal_PrintCmplx( stream, value );
      
      StGermain_ComplexScalarTripleProduct( matrix[2], matrix[0], matrix[1], value );
      Journal_Printf( stream, "scalar triple product: ");
      Journal_PrintCmplx( stream, value );
      StGermain_ComplexScalarTripleProduct( matrix[1], matrix[2], matrix[0], value );
      Journal_Printf( stream, "scalar triple product: ");
      Journal_PrintCmplx( stream, value );
      
      Journal_Printf( stream, "\n****************************\n");
      Journal_Printf( stream, "Check Vector_ToComplexVector function \n");
      
      realVector[0] = 1.0; realVector[1] = 2.0; realVector[2] = 3.0;
      
      StGermain_PrintNamedVector(stream, realVector, 3);
      Vector_ToComplexVector(realVector, 3, matrix[0]) ;
      StGermain_PrintNamedComplexVector( stream, matrix[0], 3);

      Journal_Printf( stream, "\n****************************\n");
      Journal_Printf( stream, "Check ComplexVector_ToVector function \n");   
      
      matrix[0][0][REAL_PART] = 5.0; matrix[0][0][IMAG_PART] = 0.0;
      matrix[0][1][REAL_PART] = 6.0; matrix[0][1][IMAG_PART] = 0.0; 
      matrix[0][2][REAL_PART] = 7.0; matrix[0][2][IMAG_PART] = 0.0;
      
      StGermain_PrintNamedComplexVector( stream, matrix[0], 3);
      ComplexVector_ToVector(matrix[0], 3, realVector) ;
      StGermain_PrintNamedVector(stream, realVector, 3);

      pcu_filename_expected( "testComplexVectorMathOperations.expected", expected_file );
      pcu_check_fileEq( "testComplexVectorMathOperations.dat", expected_file );
      remove( "testComplexVectorMathOperations.dat" );

      Memory_Free( matrix );
      Stream_CloseAndFreeFile( stream );
   }
}
Example #13
0
double Stg_MemMonitor_End( Stg_MemMonitor* tm ) {
	double memAvgDiff = 0.0;
#ifdef MEMORY_STATS
	long memDiff;
	long memMaxDiff;
	long memMinDiff;
	long memSumDiff;
	long memMax;
	
	int rank;
	int size;
	
	tm->t2 = stgMemory->stamp;
	MemoryField_UpdateAsSumOfSubFields( stgMemory->types );
	tm->totalMem2 = stgMemory->types->currentAllocation;
	memDiff = tm->totalMem2 - tm->totalMem1;
	
	MPI_Comm_size( tm->comm, &size );
	/*
	MPI_Reduce( &memDiff, &memMaxDiff, 1, MPI_LONG, MPI_MAX, 0, tm->comm );
	MPI_Reduce( &memDiff, &memMinDiff, 1, MPI_LONG, MPI_MIN, 0, tm->comm );
	MPI_Allreduce( &memDiff, &memSumDiff, 1, MPI_LONG, MPI_SUM, tm->comm );
	MPI_Reduce( &tm->totalMem2, &memMax, 1, MPI_LONG, MPI_MAX, 0, tm->comm );
	
	memAvgDiff = (double)memSumDiff / size;
	*/
	/* Above is commented and replaced with below. See TimeMonitor.c for reason */
	memMaxDiff = memDiff;
	memMinDiff = memDiff;
	memSumDiff = memDiff;
	memMax = tm->totalMem2;
	memAvgDiff = (double)memDiff;
	
	/* Note: maybe Stg_Components should store rank and comm??? how do the find their comm? */
	
	MPI_Comm_rank( tm->comm, &rank );
	if( rank == 0 && tm->print ) {
		if( !tm->criteria || (double)memMaxDiff > Stg_MemoryWatchCriteria * memMax ) {
			void* args[3];
			SizeT threshold = (SizeT)(Stg_MemoryWatchCriteria * memMax);
			
			if( size == 1 ) {
				Journal_Printf( 
					Journal_Register( Info_Type, Stg_MemMonitor_InfoStreamName ),
					"\t%s(%s): ms: %.2gmb, dt(%.2f%%): %.2gmb\n", 
					Stg_MemMonitor_InfoStreamName,
					tm->tag,
					(double)memMax / 1048576,
					(memAvgDiff) / memMax * 100.0,
					(double)memDiff / 1048576 );
			}
			else {
				Journal_Printf( 
					Journal_Register( Info_Type, Stg_MemMonitor_InfoStreamName ),
					"\t%s(%s): ms: %.2gmb, dt(%.f%%): %.2g/%.2g/%.2gmb\n", 
					Stg_MemMonitor_InfoStreamName,
					tm->tag,
					(double)memMax / 1048576,
					(memAvgDiff) / memMax * 100.0,
					(double)memMaxDiff / 1048576,
					(double)memMinDiff / 1048576,
					(double)memAvgDiff / 1048576 );
			}
			args[0] = &threshold;
			args[1] = &tm->t1;
			args[2] = &tm->t2;
			BTree_ParseTree( stgMemory->pointers, _Memory_Print_AllocsAboveThreshold_Helper, (void*)args );
		}
	}
	
#endif
	return memAvgDiff;
}
Example #14
0
Bool StgDomainGeometry_Init( int* argc, char** argv[] ) {
	Journal_Printf( Journal_Register( DebugStream_Type, (Name)"Context"  ), "In: %s\n", __func__ ); /* DO NOT CHANGE OR REMOVE */
	
	return True;
}
Example #15
0
int main( int argc, char* argv[] ) {
	
	Stream*				stream = NULL;
	Dictionary*			dictionary;
	Dictionary_Entry_Value*		tmpVal0;
	Dictionary_Entry_Value*		tmpVal1; 
	
	MPI_Init( &argc, &argv );
	BaseFoundation_Init( &argc, &argv );
	BaseIO_Init( &argc, &argv );
	stream = Journal_Register (Info_Type, "myStream");

	dictionary = Dictionary_New();

	tmpVal0 = Dictionary_Entry_Value_NewStruct();
	tmpVal1 = Dictionary_Entry_Value_NewStruct();
	Dictionary_Entry_Value_AddMember( tmpVal1, "name", Dictionary_Entry_Value_FromString( "bill" ) );
	Dictionary_Entry_Value_AddMember( tmpVal1, "value", Dictionary_Entry_Value_FromDouble( 1.0f ) );
	Dictionary_Entry_Value_AddMember( tmpVal0, "inside", tmpVal1 );
	tmpVal1 = Dictionary_Entry_Value_NewList();
	Dictionary_Entry_Value_AddElement( tmpVal1, Dictionary_Entry_Value_FromString( "bottom" ) );
	Dictionary_Entry_Value_AddElement( tmpVal1, Dictionary_Entry_Value_FromString( "top" ) );
	Dictionary_Entry_Value_AddMember( tmpVal0, "list_one", tmpVal1 );
	Dictionary_Add( dictionary, "one", tmpVal0 );
	
	tmpVal0 = Dictionary_Entry_Value_NewStruct();
	tmpVal1 = Dictionary_Entry_Value_NewStruct();
	Dictionary_Entry_Value_AddMember( tmpVal1, "new_name", Dictionary_Entry_Value_FromString( "frank" ) );
	Dictionary_Entry_Value_AddMember( tmpVal1, "value", Dictionary_Entry_Value_FromDouble( 2.0f ) );
	Dictionary_Entry_Value_AddMember( tmpVal0, "inside", tmpVal1 );
	tmpVal1 = Dictionary_Entry_Value_NewList();
	Dictionary_Entry_Value_AddElement( tmpVal1, Dictionary_Entry_Value_FromString( "left" ) );
	Dictionary_Entry_Value_AddElement( tmpVal1, Dictionary_Entry_Value_FromString( "right" ) );
	Dictionary_Entry_Value_AddMember( tmpVal0, "list_one", tmpVal1 );
	Dictionary_AddMerge( dictionary, "one", tmpVal0, Dictionary_MergeType_Append );
	
	Print( dictionary, stream );
	Stg_Class_Delete( dictionary );
	
	dictionary = Dictionary_New();
	
	tmpVal0 = Dictionary_Entry_Value_NewStruct();
	tmpVal1 = Dictionary_Entry_Value_NewStruct();
	Dictionary_Entry_Value_AddMember( tmpVal1, "name", Dictionary_Entry_Value_FromString( "bill" ) );
	Dictionary_Entry_Value_AddMember( tmpVal1, "value", Dictionary_Entry_Value_FromDouble( 1.0f ) );
	Dictionary_Entry_Value_AddMember( tmpVal0, "inside", tmpVal1 );
	tmpVal1 = Dictionary_Entry_Value_NewList();
	Dictionary_Entry_Value_AddElement( tmpVal1, Dictionary_Entry_Value_FromString( "bottom" ) );
	Dictionary_Entry_Value_AddElement( tmpVal1, Dictionary_Entry_Value_FromString( "top" ) );
	Dictionary_Entry_Value_AddMember( tmpVal0, "list_one", tmpVal1 );
	Dictionary_Add( dictionary, "one", tmpVal0 );
	
	tmpVal0 = Dictionary_Entry_Value_NewStruct();
	tmpVal1 = Dictionary_Entry_Value_NewStruct();
	Dictionary_Entry_Value_AddMember( tmpVal1, "new_name", Dictionary_Entry_Value_FromString( "frank" ) );
	Dictionary_Entry_Value_AddMember( tmpVal1, "value", Dictionary_Entry_Value_FromDouble( 2.0f ) );
	Dictionary_Entry_Value_AddMember( tmpVal0, "inside", tmpVal1 );
	tmpVal1 = Dictionary_Entry_Value_NewList();
	Dictionary_Entry_Value_AddElement( tmpVal1, Dictionary_Entry_Value_FromString( "left" ) );
	Dictionary_Entry_Value_AddElement( tmpVal1, Dictionary_Entry_Value_FromString( "right" ) );
	Dictionary_Entry_Value_AddMember( tmpVal0, "list_one", tmpVal1 );
	Dictionary_AddMerge( dictionary, "one", tmpVal0, Dictionary_MergeType_Merge );
	
	Print( dictionary, stream );
	Stg_Class_Delete( dictionary );
	
	dictionary = Dictionary_New();
	
	tmpVal0 = Dictionary_Entry_Value_NewStruct();
	tmpVal1 = Dictionary_Entry_Value_NewStruct();
	Dictionary_Entry_Value_AddMember( tmpVal1, "name", Dictionary_Entry_Value_FromString( "bill" ) );
	Dictionary_Entry_Value_AddMember( tmpVal1, "value", Dictionary_Entry_Value_FromDouble( 1.0f ) );
	Dictionary_Entry_Value_AddMember( tmpVal0, "inside", tmpVal1 );
	tmpVal1 = Dictionary_Entry_Value_NewList();
	Dictionary_Entry_Value_AddElement( tmpVal1, Dictionary_Entry_Value_FromString( "bottom" ) );
	Dictionary_Entry_Value_AddElement( tmpVal1, Dictionary_Entry_Value_FromString( "top" ) );
	Dictionary_Entry_Value_AddMember( tmpVal0, "list_one", tmpVal1 );
	Dictionary_Add( dictionary, "one", tmpVal0 );
	
	tmpVal0 = Dictionary_Entry_Value_NewStruct();
	tmpVal1 = Dictionary_Entry_Value_NewStruct();
	Dictionary_Entry_Value_AddMember( tmpVal1, "new_name", Dictionary_Entry_Value_FromString( "frank" ) );
	Dictionary_Entry_Value_AddMember( tmpVal1, "value", Dictionary_Entry_Value_FromDouble( 2.0f ) );
	Dictionary_Entry_Value_AddMember( tmpVal0, "inside", tmpVal1 );
	tmpVal1 = Dictionary_Entry_Value_NewList();
	Dictionary_Entry_Value_AddElement( tmpVal1, Dictionary_Entry_Value_FromString( "left" ) );
	Dictionary_Entry_Value_AddElement( tmpVal1, Dictionary_Entry_Value_FromString( "right" ) );
	Dictionary_Entry_Value_AddMember( tmpVal0, "list_one", tmpVal1 );
	Dictionary_AddMerge( dictionary, "one", tmpVal0, Dictionary_MergeType_Replace );
	
	Print( dictionary, stream );
	Stg_Class_Delete( dictionary );
	
	BaseIO_Finalise();
	BaseFoundation_Finalise();
	MPI_Finalize();
	
	return EXIT_SUCCESS;
}
Example #16
0
int main(int argc, char *argv[])
{
	int			rank;
	int			procCount;
	int			procToWatch;
	Stream*			stream;

	/* Initialise MPI, get world info */
	MPI_Init(&argc, &argv);
	MPI_Comm_size(MPI_COMM_WORLD, &procCount);
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);

	BaseFoundation_Init( &argc, &argv );

	RegressionTest_Init( "Base/Foundation/ObjectList" );

	stream = Journal_Register( "info", "myStream" );
	
	if( argc >= 2 ) {
		procToWatch = atoi( argv[1] );
	}
	else {
		procToWatch = 0;
	}

	if ( rank == procToWatch ) {
		Index  nTestValues = 7;
		double testValues[] = {
			0.0,
			3.4562e-30,
			9.7324,
			97.654,
			104.321,
			-13762.1,
			0.0043253 };
		double tolerances[] = {
			1e-40,
			1e-40,
			1e-12,
			1e-12,
			1e-12,
			1e-12,
			1e-12 };
		double expectedRoundedToDecPlaces[7][4] = {
			{ 0.0, 0.0, 0.0, 0.0 },
			{ 0.0, 0.0, 0.0, 0.0 },
			{ 10., 9.7, 9.73, 9.732 },
			{ 98., 97.7, 97.65, 97.654 },
			{ 104., 104.3, 104.32, 104.321 },
			{ -13762., -13762.1, -13762.10, -13762.100 },
			{ 0.,    0.0, 0.00, 0.004 } };
		double expectedRoundedToSigFigs[7][4] = {
			{ 0.0, 0.0, 0.0, 0.0 },
			{ 0.0, 3e-30, 3.5e-30, 3.46e-30 },
			{ 0., 10, 9.7, 9.73 },
			{ 0., 100, 98, 97.7 },
			{ 0., 100, 100, 104 },
			{ 0., -10000, -14000, -13800 },
			{ 0., 0.004, 0.0043, 0.00433 } };
		double roundedValue;
		double errorMargin;
		Index testValue_I;
		Index nDecPlaces;
		Index nSigFigs;
		
		TestLMS( stream, "Acrobat", "BOAT", True );
		TestLMS( stream, "Abracadabra", "Yabbadabbadoo", True );
		TestLMS( stream, "Abracadabra", "Yabbadabbadoo", False );
		TestLMS( stream, "Python", "PythonShape", False );
		
		TestIsStringNumeric( stream, "nan" );
		TestIsStringNumeric( stream, "567" );
		TestIsStringNumeric( stream, "1.0e90" );
		TestIsStringNumeric( stream, "1e90e80" );
		TestIsStringNumeric( stream, ".asdfasdf" );
		TestIsStringNumeric( stream, ".0032" );
		TestIsStringNumeric( stream, ".0032.00" );
		
		TestIsStringEmpty( stream, "\t \n" );
		TestIsStringEmpty( stream, "asdf" );
		TestIsStringEmpty( stream, "    " );
		TestIsStringEmpty( stream, "    \n" );
		TestIsStringEmpty( stream, "  sdf  \n" );

		printf("\nTesting rounding to certain number of decimal places:\n");
		for ( testValue_I = 0; testValue_I < nTestValues; testValue_I++ ) {
			for ( nDecPlaces = 0; nDecPlaces <=3; nDecPlaces++ ) {
				roundedValue = StG_RoundDoubleToNDecimalPlaces(
					testValues[testValue_I], nDecPlaces );
				errorMargin = fabs( roundedValue -
					expectedRoundedToDecPlaces[testValue_I][nDecPlaces] );

				if ( errorMargin <= tolerances[testValue_I] ) {
					printf( "Value %8g rounded to %u dec places was within "
						"tolerance of expected value %8g.\n",
						testValues[testValue_I], nDecPlaces,
						expectedRoundedToDecPlaces[testValue_I][nDecPlaces] );
				}
				else {
					printf( "Value %8g rounded to %u dec places was not within "
						"tolerance of expected value %8g.\n",
						testValues[testValue_I], nDecPlaces,
						expectedRoundedToDecPlaces[testValue_I][nDecPlaces] );
					printf( "(error margin was %.8g)\n", errorMargin );
				}
			}
		}

		printf("\nTesting rounding to certain number of significant figures:\n");
		for ( testValue_I = 0; testValue_I < nTestValues; testValue_I++ ) {
			for ( nSigFigs = 1; nSigFigs <=3; nSigFigs++ ) {
				roundedValue = StG_RoundDoubleToNSigFigs(
					testValues[testValue_I], nSigFigs );
				errorMargin = fabs( roundedValue -
					expectedRoundedToSigFigs[testValue_I][nSigFigs] );
				if ( errorMargin <= tolerances[testValue_I] ) {
					printf( "Value %8g rounded to %u sig. figures was within "
						"tolerance of expected value %8g.\n",
						testValues[testValue_I], nSigFigs,
						expectedRoundedToSigFigs[testValue_I][nSigFigs] );
				}
				else {
					printf( "Value %8g rounded to %u sig. figures was not within "
						"tolerance of expected value %8g.\n",
						testValues[testValue_I], nSigFigs,
						expectedRoundedToSigFigs[testValue_I][nSigFigs] );
					printf( "(error margin was %.8g)\n", errorMargin );
				}
			}
		}
	}

	RegressionTest_Finalise();

	BaseFoundation_Finalise();
	
	/* Close off MPI */
	MPI_Finalize();
	
	return 0; /* success */
}
Example #17
0
int main( int argc, char* argv[] ) {
	MPI_Comm			CommWorld;
	int				rank;
	int				numProcessors;
	int				procToWatch;
	int **keys;
	
	MaxHeap *heap;
	int i = 0;
	Stream *myStream = NULL;
	
	/* Initialise MPI, get world info */
	MPI_Init( &argc, &argv );
	MPI_Comm_dup( MPI_COMM_WORLD, &CommWorld );
	MPI_Comm_size( CommWorld, &numProcessors );
	MPI_Comm_rank( CommWorld, &rank );

	BaseFoundation_Init( &argc, &argv );
	BaseIO_Init( &argc, &argv );
	BaseContainer_Init( &argc, &argv );

	if( argc >= 2 ) {
		procToWatch = atoi( argv[1] );
	}
	else {
		procToWatch = 0;
	}
	
	if( rank == procToWatch ) {
		
		myStream = Journal_Register( InfoStream_Type, "LinkedListStream" );
		data = Memory_Alloc_Array_Unnamed( int, NUM_DATA );
		keys = Memory_Alloc_Array_Unnamed( int*, NUM_INITIAL_DATA );
		
		Journal_Printf( myStream, "\nCreating the Heap\n" );
		for(i=0; i<NUM_INITIAL_DATA; i++){
			data[i] = i;
			keys[i] = &(data[i]);
		}
		
		heap = MaxHeap_New(
					(void**)(keys), sizeof(int),
					NUM_INITIAL_DATA,
					keySwap,
					compareFunction,
					extendArray );

		Journal_Printf( myStream, "\nPrinting the Heap\n" );
		Stg_Class_Print( heap, myStream );
		
		Journal_Printf( myStream, "\nInserting more entries into the Heap\n" );
		for( i=50; i<NUM_DATA; i++ ){
			data[i] = i;
			MaxHeap_Insert( heap, &(data[i]) );
		}
		
		Journal_Printf( myStream, "\nPrinting the Heap\n" );
		Stg_Class_Print( heap, myStream );
		
		Journal_Printf( myStream, "\nExtracting all the entries in the Heap\n" );
		for( i=0; i<NUM_DATA; i++ ){
			printf( "Heap Max %d\n", *(int*)MaxHeap_Extract( (_Heap*)heap ) );
		}
		
		Journal_Printf( myStream, "\nPrinting the Heap\n" );
		Stg_Class_Print( heap, myStream );
	
		Journal_Printf( myStream, "\nDeleting the Heap\n" );
		Stg_Class_Delete( (void*)heap );
		
		Memory_Free( data );
	}
Example #18
0
void StGermain_Bouncer_UpdatePositions( DomainContext* context ) {
	Cell_LocalIndex			lCell_I;
	Particle_InCellIndex		cParticle_I;
	Particle* 	        	currParticle;
	Index				dim_I;
	Swarm*                          swarm = (Swarm*) LiveComponentRegister_Get( context->CF->LCRegister, (Name)"swarm"  );
	BlockGeometry*                  blockGeom;
	Stream*                         stream = Journal_Register( Debug_Type, (Name)"particleUpdate"  );
	unsigned int                    movementSpeedDivisor = 5;
	Particle_Index                  lParticle_I = 0;

	Stream_SetPrintingRank( stream, Dictionary_GetUnsignedInt_WithDefault( context->dictionary, "procToWatch", 0 ) );
	
	blockGeom = (BlockGeometry*) LiveComponentRegister_Get( context->CF->LCRegister, (Name)"geometry" );

	if ( context->timeStep == 1  ) {
		/* for each particle, set a random velocity */
		for ( lParticle_I=0; lParticle_I < swarm->particleLocalCount; lParticle_I++ ) {
			currParticle = (Particle*)Swarm_ParticleAt( swarm, lParticle_I );
			for ( dim_I=0; dim_I < 3; dim_I++ ) {
				currParticle->velocity[dim_I] = ((double) ( rand() - (double)(RAND_MAX)/2 )) / RAND_MAX * 0.1;
			}	
		}
	}
	
	for ( lCell_I=0; lCell_I < swarm->cellLocalCount; lCell_I++ ) {
		Journal_Printf( stream, "\tUpdating Particles positions in local cell %d:\n", lCell_I );
		for ( cParticle_I=0; cParticle_I < swarm->cellParticleCountTbl[lCell_I]; cParticle_I++ ) {
			Coord movementVector = {0,0,0};
			Coord newParticleCoord = {0,0,0};
			Coord* oldCoord;

			currParticle = (Particle*)Swarm_ParticleInCellAt( swarm, lCell_I, cParticle_I );
			oldCoord = &currParticle->coord;
			Journal_Printf( stream, "\t\tUpdating particleInCell %d:\n", cParticle_I );

			for ( dim_I=0; dim_I < 3; dim_I++ ) {
				movementVector[dim_I] = currParticle->velocity[dim_I] / movementSpeedDivisor;
				if ( ( currParticle->velocity[dim_I] < 0 ) 
					&& ( fabs(currParticle->velocity[dim_I] ) > ((*oldCoord)[dim_I] - blockGeom->min[dim_I]) ) )
				{
					Journal_Printf( stream, "\t\tFlipping vel in %d dir\n", dim_I );
					movementVector[dim_I] *= -1;
					currParticle->velocity[dim_I] *= -1;
				}	
				if ( ( currParticle->velocity[dim_I] > 0 ) 
					&& ( fabs(currParticle->velocity[dim_I] ) > ( blockGeom->max[dim_I] - (*oldCoord)[dim_I] ) ) )
				{
					Journal_Printf( stream, "\t\tFlipping vel in %d dir\n", dim_I );
					movementVector[dim_I] *= -1;
					currParticle->velocity[dim_I] *= -1;
				}	
				
				newParticleCoord[dim_I] = (*oldCoord)[dim_I] + movementVector[dim_I];
			}

			Journal_Printf( stream, "\t\tChanging its coords from (%f,%f,%f) to (%f,%f,%f):\n",
				(*oldCoord)[0], (*oldCoord)[1], (*oldCoord)[2],
				newParticleCoord[0], newParticleCoord[1], newParticleCoord[2] );

			for ( dim_I=0; dim_I < 3; dim_I++ ) {
				currParticle->coord[dim_I] = newParticleCoord[dim_I];
			}
		}
	}

	Swarm_UpdateAllParticleOwners( swarm );
}
Bool earthbyte_additions_Components_Finalise( void )
{
   Journal_Printf( Journal_Register( Debug_Type, (Name)"Context"  ), "In: %s\n", __func__ ); /* DO NOT CHANGE OR REMOVE */

   return True;
}
Example #20
0
Bool BaseExtensibility_Finalise( void ) {
	Journal_Printf( Journal_Register( DebugStream_Type, "Context" ), "In: %s\n", __func__ ); /* DO NOT CHANGE OR REMOVE */
	
	return True;
}
void IsoviscousStiffness2D( IsoviscousStiffnessData* data ) {
   StiffnessMatrix*      stiffnessMatrix;
   Dictionary*           dictionary;
   FiniteElementContext* context;
   Stg_ComponentFactory* cf;
   PetscViewer           expViewer;
   PetscReal             matrixNorm, errorNorm, test;
   Mat                   expected;
   char                  expected_file[PCU_PATH_MAX];
   char                  *filename, *matrixName;
   double                tolerance;
   char                  xml_input[PCU_PATH_MAX];
   Stream*               infoStream = Journal_Register( Info_Type, (Name)CURR_MODULE_NAME );
   char                  rFile[PCU_PATH_MAX];
   int                   err;

   pcu_docstring( "This test compares a Stiffness matrix against a previously generated stiffness matrix"
      "The stiffness matrix is generated from a 2D FEM model for an isoviscous fluid flow." 
      "See testIsoviscous.xml for the actual xml used" );

   /* read in the xml input file */
   pcu_filename_input( "IsoviscousStiffnessMatrix.xml", xml_input );
   cf = stgMainInitFromXML( xml_input, MPI_COMM_WORLD, NULL );
   context = (FiniteElementContext*)LiveComponentRegister_Get( cf->LCRegister, (Name)"context" );
   data->context = context;
   dictionary = context->dictionary;

   stgMainBuildAndInitialise( cf );

   /* Test is to check the relative error between an
       1 ) expected stiffness matrix, (made years ago)
       2) the current stiffness matrix.

       both matricies are built using only an Arrhenius rheology 
    */

   /* get the tolerance */
   tolerance = Dictionary_GetDouble( dictionary, "StiffnessMatrixCompareTolerance" );

   /* Get Matrix */
   matrixName = Dictionary_GetString( dictionary, (Dictionary_Entry_Key)"CompareStiffnessMatrix"  );
   Journal_Printf( infoStream, "Comparing stiffness matrix '%s'\n", matrixName );
   stiffnessMatrix = (StiffnessMatrix*) LiveComponentRegister_Get( context->CF->LCRegister, (Name)matrixName );
   assert( stiffnessMatrix  );

   StiffnessMatrix_Assemble( stiffnessMatrix, False, NULL, context );

   /* Get Stored Matrix from file */
   filename = Dictionary_GetString( dictionary, (Dictionary_Entry_Key)"StiffnessMatrixCompareFilename"  );
   Journal_Printf( infoStream, "Checking with file '%s'\n", filename );

   pcu_filename_expected( filename, expected_file );
   PetscViewerBinaryOpen( context->communicator, expected_file, FILE_MODE_READ, &expViewer );

   Stg_MatLoad( expViewer, MATAIJ, &expected );

   MatNorm( expected, NORM_FROBENIUS, &matrixNorm );
   assert( matrixNorm != 0 );

   MatAXPY( expected, -1, (stiffnessMatrix->matrix) , DIFFERENT_NONZERO_PATTERN );
   MatNorm( expected, NORM_FROBENIUS, &errorNorm );
   test = errorNorm / matrixNorm;

   pcu_check_lt( test, tolerance );

   /* Check tolerance */
   /*
   stream = Journal_Register( Info_Type, (Name)"StiffnessMatrixComparison"  );
   Stream_RedirectFile_WithPrependedPath( stream, context->outputPath, "StiffnessMatrixCompare.dat" );
   Journal_PrintValue( infoStream, tolerance );
   Journal_Printf( stream, "Comparison between stiffness matrix '%s' %s with tolerance %4g.\n", 
         matrixName, 
         ( errorNorm/matrixNorm < tolerance ? "passed" : "failed" ),
         tolerance );
         */

   /* 
   Stream_CloseFile( stream );
       To view the expected and computed matricies uncomment this
   PetscViewerASCIIOpen(context->communicator, "numerical.dat",&currViewer);
   PetscViewerASCIIOpen(context->communicator, "expected.dat",&parallelViewer);
   MatView( stiffnessMatrix->matrix, currViewer ); //PETSC_VIEWER_STDOUT_WORLD );
   MatView( expected, parallelViewer ); //PETSC_VIEWER_STDOUT_WORLD );
   Stg_PetscViewerDestroy(&currViewer);
   Stg_PetscViewerDestroy(&parallelViewer);
   */
   if( data->context->rank == 0 ) {
      /* Now clean output path */
      sprintf(rFile, "%s/input.xml", data->context->outputPath );
      err = remove( rFile );
      if( err == -1 ) printf("Error in %s, can't delete the input.xml\n", __func__);
   }
   stgMainDestroy( cf );
}
int main( int argc, char* argv[] )
{
	MPI_Comm CommWorld;
	int rank;
	int numProcessors;
	int procToWatch;
	
	Stream* stream;

	double*		one2d;
	Index i, j;

	/* Initialise MPI, get world info */
	MPI_Init( &argc, &argv );
	MPI_Comm_dup( MPI_COMM_WORLD, &CommWorld );
	MPI_Comm_size( CommWorld, &numProcessors );
	MPI_Comm_rank( CommWorld, &rank );
	
	BaseFoundation_Init( &argc, &argv );
	
	stream = Journal_Register ( "info", "MyInfo" );
	
	if( argc >= 2 )
	{
		procToWatch = atoi( argv[1] );
	}
	else
	{
		procToWatch = 0;
	}
	if( rank == procToWatch )
	{
		Journal_Printf( stream,  "Watching rank: %i\n", rank );
	}

	Journal_Printf( stream, "2D as 1D\n" );
	one2d = Memory_Alloc_2DArrayAs1D_Unnamed( double, 3, 2 );

	Memory_Print();

	/* write */	
	for ( i = 0; i < 3; ++i )
	{
		for ( j = 0; j < 2; ++j )
		{
			Memory_Access2D( one2d, i, j, 2 ) = i + (j / 10.0);
		}
	}

	/* read */
	for ( i = 0; i < 3; ++i )
	{
		for ( j = 0; j < 2; ++j )
		{
			Journal_Printf( stream, "%lf ", Memory_Access2D( one2d, i, j, 2 ) );
		}
		Journal_Printf( stream, "\n" );
	}

	one2d = Memory_Realloc_2DArrayAs1D( one2d, double, 3, 2, 4, 4 );

	Memory_Print();

	/* read again */
	for ( i = 0; i < 3; ++i )
	{
		for ( j = 0; j < 2; ++j )
		{
			Journal_Printf( stream, "%lf ", Memory_Access2D( one2d, i, j, 4 ) );
		}
		Journal_Printf( stream, "\n" );
	}
	
	/* write */	
	for ( i = 0; i < 4; ++i )
	{
		for ( j = 0; j < 4; ++j )
		{
			Memory_Access2D( one2d, i, j, 4 ) = i + (j / 10.0);
		}
	}

	/* read */
	for ( i = 0; i < 4; ++i )
	{
		for ( j = 0; j < 4; ++j )
		{
			Journal_Printf( stream, "%lf ", Memory_Access2D( one2d, i, j, 4 ) );
		}
		Journal_Printf( stream, "\n" );
	}


	Memory_Free( one2d );

	Memory_Print();

	BaseFoundation_Finalise();
	
	/* Close off MPI */
	MPI_Finalize();

	return 0; /* success */
}
Example #23
0
void _VariableAllVC_ReadDictionary( void* variableCondition, void* dictionary ) {
	VariableAllVC*			self = (VariableAllVC*)variableCondition;
	Dictionary_Entry_Value*		vcDictVal;
	Dictionary_Entry_Value		_vcDictVal;
	Dictionary_Entry_Value*		varsVal;
	VariableAllVC_Entry_Index	entry_I;
	
	/* Find dictionary entry */
	if (self->_dictionaryEntryName)
		vcDictVal = Dictionary_Get( dictionary, self->_dictionaryEntryName );
	else
	{
		vcDictVal = &_vcDictVal;
		Dictionary_Entry_Value_InitFromStruct( vcDictVal, dictionary );
	}
	
	if (vcDictVal)
	{
		/* Obtain the variable entries */
		self->_entryCount = Dictionary_Entry_Value_GetCount(Dictionary_Entry_Value_GetMember(vcDictVal, "variables"));
		self->_entryTbl = Memory_Alloc_Array( VariableAllVC_Entry, self->_entryCount, "VariableAllVC->_entryTbl" );
		varsVal = Dictionary_Entry_Value_GetMember(vcDictVal, "variables");
		
		for (entry_I = 0; entry_I < self->_entryCount; entry_I++)
		{
			char*			valType;
			Dictionary_Entry_Value*	valueEntry;
			Dictionary_Entry_Value*	varDictListVal;
			
			varDictListVal = Dictionary_Entry_Value_GetElement(varsVal, entry_I);
			valueEntry = Dictionary_Entry_Value_GetMember(varDictListVal, "value");
			
			self->_entryTbl[entry_I].varName = Dictionary_Entry_Value_AsString(
				Dictionary_Entry_Value_GetMember(varDictListVal, "name"));
				
			valType = Dictionary_Entry_Value_AsString(Dictionary_Entry_Value_GetMember(varDictListVal, "type"));
			if (!strcasecmp(valType, "func"))
			{
				char*	funcName = Dictionary_Entry_Value_AsString(valueEntry);
				
				self->_entryTbl[entry_I].value.type = VC_ValueType_CFIndex;
				self->_entryTbl[entry_I].value.as.typeCFIndex = ConditionFunction_Register_GetIndex(
					self->conFunc_Register, funcName);
			}
			else if (!strcasecmp(valType, "array"))
			{
				Dictionary_Entry_Value*	valueElement;
				Index			i;

				self->_entryTbl[entry_I].value.type = VC_ValueType_DoubleArray;
				self->_entryTbl[entry_I].value.as.typeArray.size = Dictionary_Entry_Value_GetCount(valueEntry);
				self->_entryTbl[entry_I].value.as.typeArray.array = Memory_Alloc_Array( double,
					self->_entryTbl[entry_I].value.as.typeArray.size,"VariableAllVC->_entryTbl[].value.as.typeArray.array" );
					
				for (i = 0; i < self->_entryTbl[entry_I].value.as.typeArray.size; i++)
				{
					valueElement = Dictionary_Entry_Value_GetElement(valueEntry, i);
					self->_entryTbl[entry_I].value.as.typeArray.array[i] = 
						Dictionary_Entry_Value_AsDouble(valueElement);
				}
			}
			else if( !strcasecmp( valType, "double" ) || !strcasecmp( valType, "d" ) || !strcasecmp( valType, "float" ) || !strcasecmp( valType, "f" ) ) {
				self->_entryTbl[entry_I].value.type = VC_ValueType_Double;
				self->_entryTbl[entry_I].value.as.typeDouble = Dictionary_Entry_Value_AsDouble( valueEntry );
			}
			else if( !strcasecmp( valType, "integer" ) || !strcasecmp( valType, "int" ) || !strcasecmp( valType, "i" ) ) {
				self->_entryTbl[entry_I].value.type = VC_ValueType_Int;
				self->_entryTbl[entry_I].value.as.typeInt = Dictionary_Entry_Value_AsUnsignedInt( valueEntry );
			}
			else if( !strcasecmp( valType, "short" ) || !strcasecmp( valType, "s" ) ) {
				self->_entryTbl[entry_I].value.type = VC_ValueType_Short;
				self->_entryTbl[entry_I].value.as.typeShort = Dictionary_Entry_Value_AsUnsignedInt( valueEntry );
			}
			else if( !strcasecmp( valType, "char" ) || !strcasecmp( valType, "c" ) ) {
				self->_entryTbl[entry_I].value.type = VC_ValueType_Char;
				self->_entryTbl[entry_I].value.as.typeChar = Dictionary_Entry_Value_AsUnsignedInt( valueEntry );
			}
			else if( !strcasecmp( valType, "pointer" ) || !strcasecmp( valType, "ptr" ) || !strcasecmp( valType, "p" ) ) {
				self->_entryTbl[entry_I].value.type = VC_ValueType_Ptr;
				self->_entryTbl[entry_I].value.as.typePtr = (void*) ( (ArithPointer) Dictionary_Entry_Value_AsUnsignedInt( valueEntry ));
			}
			else {
				/* Assume double */
				Journal_DPrintf( Journal_Register( InfoStream_Type, "myStream" ), "Type to variable on variable condition not given, assuming double\n" );
				self->_entryTbl[entry_I].value.type = VC_ValueType_Double;
				self->_entryTbl[entry_I].value.as.typeDouble = Dictionary_Entry_Value_AsDouble( valueEntry );
			}
		}
/**	Multiplies TensorArray by SymmetricTensor, and gives answer in a TensorArray:
	A * symB */
void TensorArray_MultiplyBySymmetricTensor(	TensorArray tensorArray, SymmetricTensor symmetricTensor,
											Dimension_Index dim, TensorArray result)
{
switch (dim) {
        case 3:
            result[FT3D_00] = 	tensorArray[FT3D_00] * symmetricTensor[ST3D_00] 
							+ 	tensorArray[FT3D_01] * symmetricTensor[ST3D_01]
							+ 	tensorArray[FT3D_02] * symmetricTensor[ST3D_02];
		
            result[FT3D_01] =	tensorArray[FT3D_00] * symmetricTensor[ST3D_01]
							+	tensorArray[FT3D_01] * symmetricTensor[ST3D_11]
							+	tensorArray[FT3D_02] * symmetricTensor[ST3D_12];
        
			result[FT3D_02] =	tensorArray[FT3D_00] * symmetricTensor[ST3D_02]
							+	tensorArray[FT3D_01] * symmetricTensor[ST3D_12]
							+ 	tensorArray[FT3D_02] * symmetricTensor[ST3D_22];

            result[FT3D_10] =	tensorArray[FT3D_10] * symmetricTensor[ST3D_00]
							+	tensorArray[FT3D_11] * symmetricTensor[ST3D_01]
							+	tensorArray[FT3D_12] * symmetricTensor[ST3D_02];
		
            result[FT3D_11] =	tensorArray[FT3D_10] * symmetricTensor[ST3D_01]
							+ 	tensorArray[FT3D_11] * symmetricTensor[ST3D_11]
							+	tensorArray[FT3D_12] * symmetricTensor[ST3D_12];
        
			result[FT3D_12] =	tensorArray[FT3D_10] * symmetricTensor[ST3D_02]
							+ 	tensorArray[FT3D_11] * symmetricTensor[ST3D_12]
							+	tensorArray[FT3D_12] * symmetricTensor[ST3D_22];

            result[FT3D_20] =	tensorArray[FT3D_20] * symmetricTensor[ST3D_00]
							+	tensorArray[FT3D_21] * symmetricTensor[ST3D_01]
							+	tensorArray[FT3D_22] * symmetricTensor[ST3D_02];
							
            result[FT3D_21]	=	tensorArray[FT3D_20] * symmetricTensor[ST3D_01]
							+	tensorArray[FT3D_21] * symmetricTensor[ST3D_11]
							+	tensorArray[FT3D_22] * symmetricTensor[ST3D_12];
							
            result[FT3D_22] =	tensorArray[FT3D_20] * symmetricTensor[ST3D_02]
							+	tensorArray[FT3D_21] * symmetricTensor[ST3D_12]
							+	tensorArray[FT3D_22] * symmetricTensor[ST3D_22];
            return;
        case 2:
            result[FT2D_00]	=	tensorArray[FT2D_00] * symmetricTensor[ST2D_00] 
							+ 	tensorArray[FT2D_01] * symmetricTensor[ST2D_01];
		
            result[FT2D_01]	=	tensorArray[FT2D_00] * symmetricTensor[ST2D_01]
							+ 	tensorArray[FT2D_01] * symmetricTensor[ST2D_11];

            result[FT2D_10]	=	tensorArray[FT2D_10] * symmetricTensor[ST2D_00]
							+	tensorArray[FT2D_11] * symmetricTensor[ST2D_01];
		
            result[FT2D_11]	=	tensorArray[FT2D_10] * symmetricTensor[ST2D_01]
							+	tensorArray[FT2D_11] * symmetricTensor[ST2D_11];
            return;
        default: {
           Stream* error = Journal_Register( ErrorStream_Type, (Name)"TensorMultMath"  );
           Journal_Printf( error, "Cannot read tensor for dimension %d in %s.\n", dim, __func__);
           	Journal_Firewall( dim, Journal_Register( Error_Type, (Name)"TensorMultMath"  ),
				"In func '%s' don't understand dim = %u\n", __func__, dim );;
            }
		}
}
void TimeIntegrand_FourthOrder( void* timeIntegrand, Variable* startValue, double dt ) {
	TimeIntegrand*	self           = (TimeIntegrand*)timeIntegrand;
	Variable*       variable       = self->variable;
	double*         arrayDataPtr;
	double*         startDataPtr;
	double*         timeDeriv;
	double*         finalTimeDeriv;
	double*         startData;
	Index           component_I; 
	Index           componentCount = *variable->dataTypeCounts;
	Index           array_I; 
	Index           arrayCount;
	double          startTime      = TimeIntegrator_GetTime( self->timeIntegrator );
	Bool            successFlag = False;
	Stream*         errorStream = Journal_Register( Error_Type, (Name)self->type  );

	timeDeriv      = Memory_Alloc_Array( double, componentCount, "Time Deriv" );
	startData      = Memory_Alloc_Array( double, componentCount, "StartData" );
	finalTimeDeriv = Memory_Alloc_Array( double, componentCount, "StartData" );
	memset( timeDeriv,      0, componentCount * sizeof( double ) );
	memset( startData,      0, componentCount * sizeof( double ) );
	memset( finalTimeDeriv, 0, componentCount * sizeof( double ) );
	
	/* Update Variables */
	Variable_Update( variable );
	Variable_Update( startValue );
	arrayCount     = variable->arraySize;
	
	for ( array_I = 0 ; array_I < arrayCount ; array_I++ ) {
		arrayDataPtr = Variable_GetPtrDouble( variable, array_I );
		startDataPtr = Variable_GetPtrDouble( startValue, array_I );
		
		TimeIntegrator_SetTime( self->timeIntegrator, startTime );

		/* Store Original Value in case startValue == self->variable */
		memcpy( startData, startDataPtr, sizeof( double ) * componentCount );

		/* Do first Step - store K1 in finalTimeDeriv and update for next step */
		successFlag = TimeIntegrand_CalculateTimeDeriv( self, array_I, finalTimeDeriv );
		Journal_Firewall( True == successFlag, errorStream,
			"Error - in %s(), for TimeIntegrand \"%s\" of type %s: When trying to find time "
			"deriv for item %u in step %u, *failed*.\n",
			__func__, self->name, self->type, array_I, 1 );

		for ( component_I = 0 ; component_I < componentCount ; component_I++ ) 
			arrayDataPtr[ component_I ] = startData[ component_I ] + 0.5 * dt * finalTimeDeriv[ component_I ];
		TimeIntegrand_Intermediate( self, array_I );

		TimeIntegrator_SetTime( self->timeIntegrator, startTime + 0.5 * dt );

		/* Do Second Step - add 2xK2 value to finalTimeDeriv and update for next step */
		successFlag = TimeIntegrand_CalculateTimeDeriv( self, array_I, timeDeriv );
		if ( True == successFlag ) {
			for ( component_I = 0 ; component_I < componentCount ; component_I++ ) {
				arrayDataPtr[ component_I ] = startData[ component_I ] + 0.5 * dt * timeDeriv[ component_I ];
				finalTimeDeriv[ component_I ] += 2.0 * timeDeriv[ component_I ];
			}
			TimeIntegrand_Intermediate( self, array_I );
		}
		else {
			Journal_Firewall( True == self->allowFallbackToFirstOrder, errorStream,
				"Error - in %s(), for TimeIntegrand \"%s\" of type %s: When trying to find time "
				"deriv for item %u in step %u, *failed*, and self->allowFallbackToFirstOrder "
				"not enabled.\n", __func__, self->name, self->type, array_I, 2 );
				
			_TimeIntegrand_RewindToStartAndApplyFirstOrderUpdate( self,
				arrayDataPtr, startData, startTime, dt,
				timeDeriv, array_I );
		}

		/* Do Third Step - add 2xK3 value to finalTimeDeriv and update for next step */
		successFlag = TimeIntegrand_CalculateTimeDeriv( self, array_I, timeDeriv );
		if ( True == successFlag ) {
			for ( component_I = 0 ; component_I < componentCount ; component_I++ ) {
				arrayDataPtr[ component_I ] = startData[ component_I ] + dt * timeDeriv[ component_I ];
				finalTimeDeriv[ component_I ] += 2.0 * timeDeriv[ component_I ];
			}
			TimeIntegrand_Intermediate( self, array_I );
		}
		else {
			Journal_Firewall( True == self->allowFallbackToFirstOrder, errorStream,
				"Error - in %s(), for TimeIntegrand \"%s\" of type %s: When trying to find time "
				"deriv for item %u in step %u, *failed*, and self->allowFallbackToFirstOrder "
				"not enabled.\n", __func__, self->name, self->type, array_I, 3 );
				
			_TimeIntegrand_RewindToStartAndApplyFirstOrderUpdate( self,
				arrayDataPtr, startData, startTime, dt,
				timeDeriv, array_I );
		}

		TimeIntegrator_SetTime( self->timeIntegrator, startTime + dt );

		/* Do Fourth Step - 'K1 + 2K2 + 2K3' and K4 finalTimeDeriv to find final value */
		successFlag = TimeIntegrand_CalculateTimeDeriv( self, array_I, timeDeriv );
		if ( True == successFlag ) {
			for ( component_I = 0 ; component_I < componentCount ; component_I++ ) {
				arrayDataPtr[ component_I ] = startData[ component_I ] + 
					dt/6.0 * (timeDeriv[ component_I ] + finalTimeDeriv[ component_I ] );
			}		
			TimeIntegrand_Intermediate( self, array_I );
		}
		else {
			Journal_Firewall( True == self->allowFallbackToFirstOrder, errorStream,
				"Error - in %s(), for TimeIntegrand \"%s\" of type %s: When trying to find time "
				"deriv for item %u in step %u, *failed*, and self->allowFallbackToFirstOrder "
				"not enabled.\n", __func__, self->name, self->type, array_I, 4 );
				
			_TimeIntegrand_RewindToStartAndApplyFirstOrderUpdate( self,
				arrayDataPtr, startData, startTime, dt,
				timeDeriv, array_I );
		}
	}

	Memory_Free( timeDeriv );
	Memory_Free( startData );
	Memory_Free( finalTimeDeriv );
}
Bool PICellerator_Utils_Finalise( void ) {
	Journal_Printf( Journal_Register( DebugStream_Type, (Name)"Context"  ), "In: %s\n", __func__ ); /* DO NOT CHANGE OR REMOVE */
	
	return True;
}
Example #27
0
double Stg_TimeMonitor_End( Stg_TimeMonitor* tm ) {
	double dt;
	double maxdt;
	double mindt;
	double sumdt;
	double avedt;
	double maxt;
	int rank;
	int size;
	
	tm->t2 = MPI_Wtime();
	dt = tm->t2 - tm->t1;
	MPI_Comm_size( tm->comm, &size );
	/*
	MPI_Reduce( &dt, &maxdt, 1, MPI_DOUBLE, MPI_MAX, 0, tm->comm );
	MPI_Reduce( &dt, &mindt, 1, MPI_DOUBLE, MPI_MIN, 0, tm->comm );
	MPI_Allreduce( &dt, &sumdt, 1, MPI_DOUBLE, MPI_SUM, tm->comm );
	MPI_Reduce( &tm->t2, &maxt, 1, MPI_DOUBLE, MPI_MAX, 0, tm->comm );
	avedt = sumdt / size;
	*/
	/* Note: Above is commented out because cannot use MPI_Reduce functions unless we are sure
	 * that ALL procs will call end(). This is currently not the case with Stg_Component_Initialise()
	 * phase as some procs will have more/less variables to call Initialise() on via Variable_Condition
	 * due to decomposition and Wall boundary conditions */
	maxdt = dt;
	mindt = dt;
	sumdt = dt * size;
	avedt = (double)dt;
	maxt = tm->t2;

	/* Note: maybe Stg_Components should store rank and comm??? how do the find their comm? */
	
	MPI_Comm_rank( tm->comm, &rank );
	if( rank == 0 && tm->print ) {
		if( !tm->criteria || maxdt > Stg_TimerWatchCriteria * (maxt - Stg_TimeMonitor_t0) ) {
			if( size == 1 ) {
				Journal_Printf( 
					Journal_Register( Info_Type, Stg_TimeMonitor_InfoStreamName ),
					"\t%s(%s):  ts: %.2g (secs), dt(%.2g%%): %.2gs\n", 
					Stg_TimeMonitor_InfoStreamName,
					tm->tag,
					maxt - Stg_TimeMonitor_t0,
					(avedt) / (maxt - Stg_TimeMonitor_t0) * 100.0,
					avedt  );
			}
			else {
				Journal_Printf( 
					Journal_Register( Info_Type, Stg_TimeMonitor_InfoStreamName ),
					"\t%s(%s):  ts: %.2g (secs), dt(%.g%%): %.2g/%.2g/%.2gs\n", 
					Stg_TimeMonitor_InfoStreamName,
					tm->tag,
					maxt - Stg_TimeMonitor_t0,
					(avedt) / (maxt - Stg_TimeMonitor_t0) * 100.0,
					maxdt,
					mindt,
					avedt );
			}
		}
	}
	
	return avedt;
}
Example #28
0
int
BMI_Initialize (const char *config_file, BMI_Model ** handle)
{

    BMI_Model          *self;

	MPI_Comm           CommWorld;
	int                rank;
	int                numProcessors;
	int                procToWatch;
	char*              filename;

    if (!handle)
        return BMI_FAILURE;
    
    self = malloc( sizeof(BMI_Model) );

	/* Initialise MPI, get world info */
	MPI_Init( NULL, NULL ); 	/* MPI_Init( &argc, &argv ); */
	MPI_Comm_dup( MPI_COMM_WORLD, &CommWorld );
	MPI_Comm_size( CommWorld, &numProcessors );
	MPI_Comm_rank( CommWorld, &rank );
    
    /* Hardwire the process to watch to 0. 
       Note that it doesn't have to be 0 when multiple processrs are used. */ 
    procToWatch = 0;
#if 0
	if( argc >= 3 ) {
		procToWatch = atoi( argv[2] );
	}
	else {
		procToWatch = 0;
	}
#endif
	if( rank == procToWatch ) printf( "Watching rank: %i\n", rank );
	
	/* if (!Snac_Init( &argc, &argv )) { */
	if (!Snac_Init( NULL, NULL )) {
		fprintf(stderr, "Error initialising StGermain, exiting.\n" );
		exit(EXIT_FAILURE);
	}
	
	/* Snac's init message */
    {
        int tmp	= Stream_GetPrintingRank( Journal_Register( InfoStream_Type, "Context" ) );
        Stream_SetPrintingRank( Journal_Register( InfoStream_Type, "Context" ), 0 );
        Journal_Printf( /* DO NOT CHANGE OR REMOVE */
                       Journal_Register( InfoStream_Type, "Context" ), 
                       "Snac. Copyright (C) 2003-2005 Caltech, VPAC & University of Texas.\n" );
        Stream_Flush( Journal_Register( InfoStream_Type, "Context" ) );
        Stream_SetPrintingRank( Journal_Register( InfoStream_Type, "Context" ), tmp );
    }

    /* Ensures copyright info always come first in output */
	MPI_Barrier( CommWorld );
    
	
	/* Create the dictionary, and some fixed values */
    /* Hardwirred to the one-processor scenario for now. */
	self->dictionary = Dictionary_New();
	Dictionary_Add( self->dictionary, "rank", Dictionary_Entry_Value_FromUnsignedInt( 0 ) );
	Dictionary_Add( self->dictionary, "numProcessors", Dictionary_Entry_Value_FromUnsignedInt( 1 ) );
	
	/* Read input */
	self->ioHandler = XML_IO_Handler_New();
    filename = strdup( config_file );
	if ( False == IO_Handler_ReadAllFromFile( self->ioHandler, filename, self->dictionary ) )
        {
            fprintf( stderr, "Error: Snac couldn't find specified input file %s. Exiting.\n", filename );
            exit( EXIT_FAILURE );
        }
	Journal_ReadFromDictionary( self->dictionary );
    free( filename );
    
    /* This is the handle to the SNAC's model data. */
	self->snacContext = Snac_Context_New( 0.0f, 0.0f, sizeof(Snac_Node), sizeof(Snac_Element), CommWorld, self->dictionary );
	if( rank == procToWatch ) Dictionary_PrintConcise( self->dictionary, self->snacContext->verbose );
    
	/* Construction phase -----------------------------------------------------------------------------------------------*/
	Stg_Component_Construct( self->snacContext, 0 /* dummy */, &(self->snacContext), True );
	
	/* Building phase ---------------------------------------------------------------------------------------------------*/
	Stg_Component_Build( self->snacContext, 0 /* dummy */, False );
	
	/* Initialisaton phase ----------------------------------------------------------------------------------------------*/
	Stg_Component_Initialise( self->snacContext, 0 /* dummy */, False );
	if( rank == procToWatch ) Context_PrintConcise( self->snacContext, self->snacContext->verbose );

    /* pass the pointer to Snac_Context to handle */
    *handle = self;
   
    return BMI_SUCCESS;
}
void ModulesManager_Load( void* modulesManager, void* _dictionary, Name contextName ) {
   ModulesManager*         self = (ModulesManager*)modulesManager;
   Dictionary*             dictionary = (Dictionary*)_dictionary;
   unsigned int            entryCount;
   unsigned int            entry_I;
   Dictionary_Entry_Value* modulesVal;

   /* 
    * First add the directory list onto LD_LIBRARY_PATH so that it can potentially
    * resolve the unknown symbols */
   #ifndef NOSHARED
   char* curEnvPath;
   char* newEnvPath;
   Index newEnvPathLength;
   Index dir_I;
   Index i, count;
   char* dir;

   newEnvPathLength = 0;

   if( dictionary ) {
      Dictionary_Entry_Value* localLibDirList = Dictionary_Get( dictionary, "LD_LIBRARY_PATH" );

      if( localLibDirList ) {
         count = Dictionary_Entry_Value_GetCount( localLibDirList );
         for( i = 0; i < count; ++i ) {
            dir = Dictionary_Entry_Value_AsString( Dictionary_Entry_Value_GetElement( localLibDirList, i ) );
            ModulesManager_AddDirectory( "FromDictionary", dir );
         }
      }
   }
   
   for( dir_I = 0; dir_I < moduleDirectories->count; ++dir_I ) {
      newEnvPathLength += strlen( (char*)Stg_ObjectList_ObjectAt( moduleDirectories, dir_I ) );
      /* Add one make space for the ':' inbetween the directories */
      newEnvPathLength += 1; 
   }
   curEnvPath = getenv("LD_LIBRARY_PATH");
   if( curEnvPath ) {
      newEnvPathLength += strlen( curEnvPath );
   }

   if( newEnvPathLength > 0 ) {
      /* Add one to make space for the Null Terminator '\0' */
      newEnvPathLength += 1;
      
      newEnvPath = Memory_Alloc_Array( char, newEnvPathLength, "LD_LIBRARY_PATH" );
      newEnvPath[0] = '\0';
      for( dir_I = 0; dir_I < moduleDirectories->count; ++dir_I ) {
         strcat( newEnvPath, (char*)Stg_ObjectList_ObjectAt( moduleDirectories, dir_I ) );
         strcat( newEnvPath, ":" );
      }
      if( curEnvPath ) {
         strcat( newEnvPath, curEnvPath );
      }
      setenv( "LD_LIBRARY_PATH", newEnvPath, 1 );

      Journal_Printf(
         Journal_Register( Debug_Type, self->type ),
         "Using LD_LIBRARY_PATH=%s\n",
         newEnvPath );
      Memory_Free( newEnvPath );
   }
void _BelowHeightField_DistanceFromCenterAxis( void* shape, Coord coord, double* disVec ){
   Stg_Shape* self = (Stg_Shape*)shape;

   Journal_Firewall( False, Journal_Register( Error_Type, (Name)self->type  ),
      "Error in function %s: This functions hasn't been implemented.", __func__ );
}