Пример #1
0
// a function for testing one call to s2d
static void testOne(uint32_t in)
{
  // first let the hardware do the work
  float f = (*(float *) &in);
  double d = f;

  // now call s2d
  uint64_t out = s2d(in);

  // show the input and the s2d result
  

  // did s2d produce the same bits as the hardware?
  if ((*(uint64_t *) &d) == out)
  {
    //printf("PASSED\n");
  }
  else
  {
     printf("%08" PRIx32 " --> %016" PRIx64 " ", in, out);
    // if not, show the bits the hardware produced
    printf("FAILED (%016" PRIx64 ")\n", (*(uint64_t *) &d));
    printf("You need to fix something!\n" );
    exit( -1 );
  }
}
Пример #2
0
/* ======================================================================== */
void s2d_vec(double *d_vec,short *s_vec, int n)
{
 int i;
 for(i=0;i<n;i++){  
    *(d_vec+i)= s2d(*(s_vec+i));
  }
}
Пример #3
0
static int cmd_gnp(int argc, char** argv)
{
    int err = 0;
    unsigned long number;
    double prob;

    err = s2ul(argv[0],&number);
    if(err) goto ret;

    err = s2d(argv[1],&prob);
    if(err) goto ret;

    g_p = ggen_generate_erdos_gnp(rng,number,prob);
    if(g_p == NULL)
        err = 1;
ret:
    return err;
}
Пример #4
0
static int cmd_lbl(int argc, char** argv)
{
    int err = 0;
    unsigned long n,l;
    double p;

    err = s2ul(argv[0],&n);
    if(err) goto ret;

    err = s2ul(argv[1],&l);
    if(err) goto ret;

    err = s2d(argv[2],&p);
    if(err) goto ret;

    g_p = ggen_generate_erdos_lbl(rng,n,p,l);
    if(g_p == NULL)
        err = 1;
ret:
    return err;
}
  void SoftwareRendererImp::rasterize_image( float x0, float y0,
                                             float x1, float y1,
                                             Texture& tex ) {
    // Problem: a slight offset from ref solution
    // Task ?:
    // Implement image rasterization
    //printf("(x0, y0, x1, y1): (%f, %f, %f, %f)\n", x0, y0, x1, y1);
    float x_start = floor(x0) + 0.5;
    float y_start = floor(y0) + 0.5;
    float x_end   = ceil(x1)  - 0.5;
    float y_end   = ceil(y1)  - 0.5;
    float scale_u = 1 / (x1 - x0);
    float scale_v = 1 / (y1 - y0);
    //printf("scale_u = %f, scale_v = %f\n", scale_u, scale_v);
    float u00, v00, u01, v01, u10, v10;
    float dux, dvx, duy, dvy;
    int d;
    Color c;
    //Sampler2DImp s2d (NEAREST);
    Sampler2DImp s2d (BILINEAR);
    Matrix3x3 scale;
    scale(0,0) = scale_u; scale(0,1) = 0.0     ; scale(0,2) = 0.0;
    scale(1,0) = 0.0    ; scale(1,1) = scale_v ; scale(1,2) = 0.0;
    scale(2,0) = 0.0    ; scale(2,1) = 0.0     ; scale(2,2) = 1.0;
    //std::cout << "scale: \n" << scale << std::endl;

    //change to identity
    Matrix3x3 move = Matrix3x3::identity();
    move(0,2) = 0 - x0;
    move(1,2) = 0 - y0;
    //std::cout << "move: \n" << move << std::endl;

    /* for debug
    for ( float x = x_start; x <= x_start + 2; x++ ) {
      for (float y = y_start; y <= y_start + 2; y++ ) {
      */
    for ( float x = x_start; x <= x_end - 1.0; x++ ) {
      for (float y = y_start; y <= y_end - 1.0; y++ ) {
        //printf("tex.width = %zu\n", tex.width);

        Vector3D s_space0 (x, y, 1.0);
        Vector3D t_space0 = scale * move * s_space0;
        u00 = t_space0.x / t_space0.z;
        v00 = t_space0.y / t_space0.z;
        Vector3D s_space1 (x + 1, y, 1.0);
        Vector3D t_space1 = scale * move * s_space1;
        u10 = t_space1.x / t_space1.z;
        v10 = t_space1.y / t_space1.z;
        Vector3D s_space2 (x, y + 1, 1.0);
        Vector3D t_space2 = scale * move * s_space2;
        u01 = t_space2.x / t_space2.z;
        v01 = t_space2.y / t_space2.z;
        //printf("(u00, v00), (u10, v10), (u01, v01): \n(%f, %f), (%f, %f), (%f, %f)\n", u00, v00, u10, v10, u01, v01);
        dux = u10 - u00;
        duy = u01 - u00;
        dvx = v10 - v00;
        dvy = v01 - v00;
        d = (int) log2(ceil(max(sqrt(dux * dux + dvx * dvx), sqrt(duy * duy + dvy * dvy))));
        //printf("level d: %d\n", d);
        u00 = (x - x0) * scale_u;
        v00 = (y - y0) * scale_v;
        //c = s2d.sample_nearest(tex, u00, v00, d);
        c = s2d.sample_bilinear(tex, u00, v00, d);
        rasterize_point(x, y, c);
      }
    }
}
Пример #6
0
//------------------------------------------------------------------------------
int main( int argc, char * argv[] )
{
    //--------------------------------------------------------------------------
    const unsigned    geomDeg   = 1;
    const unsigned    dim       = 2;
    // degrees of lowest-order TH element
    const unsigned    fieldDegU = 2; 
    const unsigned    fieldDegP = 1;

    const unsigned    tiOrder   = 1;
    typedef  base::time::BDF<tiOrder> MSM;
    
    const base::Shape shape     = base::SimplexShape<dim>::value;
    const base::Shape surfShape = base::SimplexShape<dim-1>::value;

    //--------------------------------------------------------------------------
    if ( argc != 2 ) {
        std::cout << "Usage:  " << argv[0] << " input.dat \n\n";
        return -1;
    }

    const std::string inputFile = boost::lexical_cast<std::string>( argv[1] );

    //--------------------------------------------------------------------------
    std::string meshFile, surfFile;
    double viscosity, density, tolerance, penaltyFactor, stepSize;
    unsigned maxIter, numSteps;
    {    
        //Feed properties parser with the variables to be read
        base::io::PropertiesParser prop;
        prop.registerPropertiesVar( "meshFile",         meshFile );
        prop.registerPropertiesVar( "surfFile",         surfFile );
        prop.registerPropertiesVar( "viscosity",        viscosity );
        prop.registerPropertiesVar( "density",          density );
        prop.registerPropertiesVar( "maxIter",          maxIter );
        prop.registerPropertiesVar( "tolerance",        tolerance );
        prop.registerPropertiesVar( "penaltyFactor",    penaltyFactor );
        prop.registerPropertiesVar( "stepSize",         stepSize );
        prop.registerPropertiesVar( "numSteps",         numSteps );

        // Read variables from the input file
        std::ifstream inp( inputFile.c_str()  );
        VERIFY_MSG( inp.is_open(), "Cannot open input file" );
        prop.readValues( inp );
        inp.close( );

        // Make sure all variables have been found
        if ( not prop.isEverythingRead() ) {
            prop.writeUnread( std::cerr );
            VERIFY_MSG( false, "Could not find above variables" );
        }
    }

    const std::string baseName = base::io::baseName( meshFile, ".smf" );

    //--------------------------------------------------------------------------
    typedef base::Unstructured<shape,geomDeg>     Mesh;

    Mesh mesh;
    {
        std::ifstream smf( meshFile.c_str() );
        VERIFY_MSG( smf.is_open(), "Cannot open mesh file" );
        base::io::smf::readMesh( smf, mesh );
        smf.close();
    }

    //--------------------------------------------------------------------------
    // Surface mesh
    typedef base::Unstructured<surfShape,1,dim>    SurfMesh;

    SurfMesh surfMesh;
    {
        std::ifstream smf( surfFile.c_str() );
        base::io::smf::readMesh( smf, surfMesh );
        smf.close();
    }

    //--------------------------------------------------------------------------
    // Compute the level set data
    typedef base::cut::LevelSet<dim> LevelSet;
    std::vector<LevelSet> levelSet;
    const bool isSigned = true;
    base::cut::bruteForce( mesh, surfMesh, isSigned, levelSet );

    const unsigned kernelDegEstimate = 5;

    //--------------------------------------------------------------------------
    // Make cut cell structure
    typedef base::cut::Cell<shape> Cell;
    std::vector<Cell> cells;
    base::cut::generateCutCells( mesh, levelSet, cells );

    // Quadrature 
    typedef base::cut::Quadrature<kernelDegEstimate,shape> CutQuadrature;
    CutQuadrature quadrature( cells, true );

    // for surface
    typedef base::SurfaceQuadrature<kernelDegEstimate,shape> SurfaceQuadrature;
    SurfaceQuadrature surfaceQuadrature;

    //------------------------------------------------------------------------------
    // Finite element bases
    const unsigned    nHist = MSM::numSteps;
    
    const unsigned    doFSizeU = dim;
    typedef base::fe::Basis<shape,fieldDegU>                FEBasisU;
    typedef base::cut::ScaledField<FEBasisU,doFSizeU,nHist> Velocity;
    Velocity velocity;
    base::dof::generate<FEBasisU>( mesh, velocity );
    
    const unsigned    doFSizeP = 1;
    typedef base::fe::Basis<shape,fieldDegP>                FEBasisP;
    typedef base::cut::ScaledField<FEBasisP,doFSizeP,nHist> Pressure;
    Pressure pressure;
    base::dof::generate<FEBasisP>( mesh, pressure );

    const unsigned    doFSizeS = dim;
    typedef base::fe::Basis<surfShape,1>              FEBasisS;
    typedef base::Field<FEBasisS,doFSizeS>            SurfField;
    SurfField surfVelocity, surfForces;
    base::dof::generate<FEBasisS>( surfMesh, surfVelocity );
    base::dof::generate<FEBasisS>( surfMesh, surfForces   );

    // set initial condition to the identity 
    base::dof::setField( surfMesh, surfVelocity,
                         boost::bind( &surfaceVelocity<dim,
                                      SurfField::DegreeOfFreedom>, _1, _2 ) );


    // boundary datum    
    base::cut::TransferSurfaceDatum<SurfMesh,SurfField,Mesh::Element>
        s2d( surfMesh, surfVelocity, levelSet );
    
    //--------------------------------------------------------------------------
    //  surface mesh
    typedef base::mesh::BoundaryMeshBinder<Mesh>::Type BoundaryMesh;
    BoundaryMesh boundaryMesh, immersedMesh;

    // from boundary
    {
        // identify list of element boundary faces
        base::mesh::MeshBoundary meshBoundary;
        meshBoundary.create( mesh.elementsBegin(), mesh.elementsEnd() );

        // generate a mesh from that list (with a filter)
        base::mesh::generateBoundaryMesh( meshBoundary.begin(),
                                          meshBoundary.end(),
                                          mesh, boundaryMesh,
                                          boost::bind( &boundaryFilter<dim>, _1 ) );

        // make a surface mesh from the implicit surface
        base::cut::generateSurfaceMesh<Mesh,Cell>( mesh, cells, immersedMesh );
    }

    // the composite field with geometry, velocity and pressure
    typedef base::asmb::FieldBinder<Mesh,Velocity,Pressure> Field;
    Field field( mesh, velocity, pressure );

    // define the system blocks (U,U), (U,P), and (P,U)
    typedef Field::TupleBinder<1,1,1>::Type TopLeft;
    typedef Field::TupleBinder<1,2>::Type   TopRight;
    typedef Field::TupleBinder<2,1>::Type   BotLeft;


    std::vector<double> supportsU, supportsP;
    std::size_t numDoFsU = std::distance( velocity.doFsBegin(), velocity.doFsEnd() );
    supportsU.resize( numDoFsU );
    std::size_t numDoFsP = std::distance( pressure.doFsBegin(), pressure.doFsEnd() );
    supportsP.resize( numDoFsP );

    base::cut::supportComputation( mesh, velocity, quadrature, supportsU );
    base::cut::supportComputation( mesh, pressure, quadrature, supportsP );

    velocity.scaleAndTagBasis( supportsU, 1.e-8 );
    pressure.scaleAndTagBasis( supportsP, 1.e-8 ); 
    //velocity.tagBasis( supportsU, 1.e-8 );
    //pressure.tagBasis( supportsP, 1.e-8 ); 

    // Fix one pressure dof
    // Pressure::DoFPtrIter pIter = pressure.doFsBegin();
    // std::advance( pIter, std::distance( pressure.doFsBegin(), pressure.doFsEnd() )/5 );
    // (*pIter) -> constrainValue( 0, 0.0 );

    // Number of DoFs after constraint application!
    numDoFsU =
        base::dof::numberDoFsConsecutively( velocity.doFsBegin(), velocity.doFsEnd() );
    std::cout << "# Number of velocity dofs " << numDoFsU << std::endl;

    numDoFsP =
        base::dof::numberDoFsConsecutively( pressure.doFsBegin(), pressure.doFsEnd(),
            numDoFsU );
    std::cout << "# Number of pressure dofs " << numDoFsP << std::endl;

    // kernels
    typedef fluid::StressDivergence<  TopLeft::Tuple>  StressDivergence;
    typedef fluid::Convection<        TopLeft::Tuple>  Convection;
    typedef fluid::PressureGradient<  TopRight::Tuple> GradP;
    typedef fluid::VelocityDivergence<BotLeft::Tuple>  DivU;

    StressDivergence stressDivergence( viscosity );
    Convection       convection(       density );
    GradP            gradP;
    DivU             divU( true );

    // for surface fields
    typedef base::asmb::SurfaceFieldBinder<BoundaryMesh,Velocity,Pressure> SurfaceFieldBinder;
    typedef SurfaceFieldBinder::TupleBinder<1,1,1>::Type STBUU;
    typedef SurfaceFieldBinder::TupleBinder<1,2  >::Type STBUP;
    SurfaceFieldBinder   boundaryFieldBinder(  boundaryMesh, velocity, pressure );
    SurfaceFieldBinder   immersedFieldBinder(  immersedMesh, velocity, pressure );

    std::ofstream forces( "forces.dat" );

    for ( unsigned step = 0; step < numSteps; step++ ) {

        const double time = step * stepSize;
        const double factor = ( time < 1.0 ? time : 1.0 );
    
        std::cout << step << ":  time=" << time << ", factor=" << factor
                  << "\n";

        //base::dof::clearDoFs( velocity );
        //base::dof::clearDoFs( pressure );
        
        //--------------------------------------------------------------------------
        // Nonlinear iterations
        unsigned iter = 0;
        while( iter < maxIter ) {

            // Create a solver object
            typedef base::solver::Eigen3           Solver;
            Solver solver( numDoFsU + numDoFsP );

            std::cout << "* Iteration " << iter << std::flush;

            // compute inertia terms, d/dt, due to time integration
            base::time::computeInertiaTerms<TopLeft,MSM>( quadrature, solver,
                                                          field, stepSize, step,
                                                          density );
    
            // Compute system matrix
            base::asmb::stiffnessMatrixComputation<TopLeft>( quadrature, solver,
                                                             field, stressDivergence );

            base::asmb::stiffnessMatrixComputation<TopLeft>( quadrature, solver,
                                                             field, convection );

            base::asmb::stiffnessMatrixComputation<TopRight>( quadrature, solver,
                                                              field, gradP );

            base::asmb::stiffnessMatrixComputation<BotLeft>( quadrature, solver,
                                                             field, divU );
            // compute residual forces
            base::asmb::computeResidualForces<TopLeft >( quadrature, solver, field,
                                                         stressDivergence );
            base::asmb::computeResidualForces<TopLeft >( quadrature, solver, field, convection );
            base::asmb::computeResidualForces<TopRight>( quadrature, solver, field, gradP );
            base::asmb::computeResidualForces<BotLeft >( quadrature, solver, field, divU );
        
            // Parameter classes
            base::nitsche::OuterBoundary ob( viscosity );
            base::nitsche::ImmersedBoundary<Cell> ib( viscosity, cells );

            // Penalty method
            base::nitsche::penaltyLHS<STBUU>( surfaceQuadrature, solver,
                                              boundaryFieldBinder, ob, penaltyFactor );
        
            base::nitsche::penaltyRHS<STBUU>( surfaceQuadrature, solver, boundaryFieldBinder, 
                                              boost::bind( &dirichlet<dim>, _1, factor),
                                              ob, penaltyFactor );

            base::nitsche::penaltyLHS<STBUU>( surfaceQuadrature, solver,
                                              immersedFieldBinder, ib, penaltyFactor );
        
            base::nitsche::penaltyRHS2<STBUU>( surfaceQuadrature, solver, immersedFieldBinder,
                                               s2d, ib, penaltyFactor );

            // Nitsche terms
            base::nitsche::primalEnergyLHS<STBUU>( stressDivergence, surfaceQuadrature, solver,
                                                   boundaryFieldBinder, ob );
            base::nitsche::dualEnergyLHS<STBUU>( stressDivergence, surfaceQuadrature, solver,
                                                 boundaryFieldBinder, ob );
            base::nitsche::energyRHS<STBUU>( stressDivergence, surfaceQuadrature, solver,
                                             boundaryFieldBinder,
                                             boost::bind( &dirichlet<dim>, _1, factor),
                                             ob );
        
            base::nitsche::primalEnergyLHS<STBUP>( gradP, surfaceQuadrature, solver,
                                                   boundaryFieldBinder, ob );
            base::nitsche::dualEnergyLHS<STBUP>( gradP, surfaceQuadrature, solver,
                                                 boundaryFieldBinder, ob );
         
            base::nitsche::energyRHS<STBUP>( gradP, surfaceQuadrature, solver,
                                             boundaryFieldBinder,
                                             boost::bind( &dirichlet<dim>, _1, factor), ob );

            base::nitsche::energyResidual<STBUU>( stressDivergence, surfaceQuadrature, solver,
                                                  boundaryFieldBinder, ob );
            
            base::nitsche::energyResidual<STBUP>( gradP, surfaceQuadrature, solver,
                                                  boundaryFieldBinder, ob );

            base::nitsche::primalEnergyLHS<STBUU>( stressDivergence, surfaceQuadrature, solver,
                                                   immersedFieldBinder, ib );
            base::nitsche::dualEnergyLHS<STBUU>( stressDivergence, surfaceQuadrature, solver,
                                                 immersedFieldBinder, ib );

            base::nitsche::energyRHS2<STBUU>( stressDivergence, surfaceQuadrature, solver,
                                              immersedFieldBinder, s2d, ib );
            
            base::nitsche::primalEnergyLHS<STBUP>( gradP, surfaceQuadrature, solver,
                                                   immersedFieldBinder, ib );
            base::nitsche::dualEnergyLHS<STBUP>( gradP, surfaceQuadrature, solver,
                                                 immersedFieldBinder, ib );

            base::nitsche::energyRHS2<STBUP>( gradP, surfaceQuadrature, solver,
                                              immersedFieldBinder, s2d, ib );

            base::nitsche::energyResidual<STBUU>( stressDivergence, surfaceQuadrature, solver,
                                                  immersedFieldBinder, ib );

            base::nitsche::energyResidual<STBUP>( gradP, surfaceQuadrature, solver,
                                                  immersedFieldBinder, ib );
        
            // Finalise assembly
            solver.finishAssembly();

            // check convergence via solver norms
            const double residualNorm = solver.norm();
            std::cout << " |R| = " << residualNorm << std::flush;

            if ( residualNorm < tolerance * viscosity) {
                std::cout << std::endl;
                break;
            }

            // Solve
            solver.superLUSolve();

            // distribute results back to dofs
            base::dof::addToDoFsFromSolver( solver, velocity );
            base::dof::addToDoFsFromSolver( solver, pressure );
            //base::dof::setDoFsFromSolver( solver, pressure );
        
            // check convergence via solver norms
            const double incrementNorm = solver.norm(0, numDoFsU );
            std::cout << " |dU| = " << incrementNorm << std::endl;

            // push history
            base::dof::pushHistory( velocity );
            base::dof::pushHistory( pressure );
        
            if ( incrementNorm < tolerance ) break;

            iter++;

        }

        writeVTKFile( baseName, step, mesh, velocity, pressure, levelSet, viscosity );
        {
            base::Vector<dim>::Type sumOfForces = base::constantVector<dim>( 0. );
            
            typedef Field::TupleBinder<1,2>::Type UP;
            //typedef fluid::Stress<UP::Tuple> Stress;
            //Stress stress( viscosity );
            typedef fluid::Traction<UP::Tuple> Traction;
            Traction traction( viscosity );
                
            base::cut::ComputeSurfaceForces<SurfMesh,SurfField,
                                            SurfaceQuadrature,STBUP::Tuple,Traction>
                computeSurfaceForces( surfMesh, surfForces, surfaceQuadrature, levelSet, traction );

            SurfaceFieldBinder::FieldIterator first = immersedFieldBinder.elementsBegin();
            SurfaceFieldBinder::FieldIterator  last = immersedFieldBinder.elementsEnd();
            for ( ; first != last; ++first ) {
                
                sumOfForces +=
                    computeSurfaceForces( STBUP::makeTuple( *first ) );
                
            }

            writeSurfaceVTKFile( baseName, step, surfMesh, surfVelocity, surfForces );


            std::cout << "  F= " << sumOfForces.transpose() << " \n";

            forces << time << " " << sumOfForces.transpose() << std::endl;;
        }

    }

    forces.close();

    return 0;
}
Пример #7
0
MapInfo SpringUnitSync::_GetMapInfoEx( const wxString& mapname )
{
  MapInfo info;

  if ( m_mapinfo_cache.TryGet( mapname, info ) ) return info;

  wxArrayString cache;
  try {
      try
      {
        cache = GetCacheFile( GetFileCachePath( mapname, m_maps_unchained_hash[mapname], false ) + _T(".infoex") );

		ASSERT_EXCEPTION( cache.GetCount() >= 11, _T("not enough lines found in cache info ex") );
        info.author = cache[0];
        info.tidalStrength =  s2l( cache[1] );
        info.gravity = s2l( cache[2] );
        info.maxMetal = s2d( cache[3] );
        info.extractorRadius = s2d( cache[4] );
        info.minWind = s2l( cache[5] );
        info.maxWind = s2l( cache[6] );
        info.width = s2l( cache[7] );
        info.height = s2l( cache[8] );
		wxArrayString posinfo = wxStringTokenize( cache[9], _T(' '), wxTOKEN_RET_EMPTY );
		for ( unsigned int i = 0; i < posinfo.GetCount(); i++)
        {
           StartPos position;
           position.x = s2l( posinfo[i].BeforeFirst( _T('-') ) );
           position.y = s2l( posinfo[i].AfterFirst( _T('-') ) );
           info.positions.push_back( position );
        }

        unsigned int LineCount = cache.GetCount();
		for ( unsigned int i = 10; i < LineCount; i++ ) info.description << cache[i] << _T('\n');

      }
      catch (...)
      {
		info = susynclib().GetMapInfoEx( m_unsorted_map_array.Index(mapname), 1 );

        cache.Add ( info.author );
        cache.Add( TowxString( info.tidalStrength ) );
        cache.Add( TowxString( info.gravity ) );
        cache.Add( TowxString( info.maxMetal ) );
        cache.Add( TowxString( info.extractorRadius ) );
        cache.Add( TowxString( info.minWind ) );
        cache.Add( TowxString( info.maxWind )  );
        cache.Add( TowxString( info.width ) );
        cache.Add( TowxString( info.height ) );

        wxString postring;
		for ( unsigned int i = 0; i < info.positions.size(); i++)
        {
           postring << TowxString( info.positions[i].x ) << _T('-') << TowxString( info.positions[i].y ) << _T(' ');
        }
        cache.Add( postring );

        wxArrayString descrtoken = wxStringTokenize( info.description, _T('\n') );
        unsigned int desclinecount = descrtoken.GetCount();
        for ( unsigned int count = 0; count < desclinecount; count++ ) cache.Add( descrtoken[count] );

        SetCacheFile( GetFileCachePath( mapname, m_maps_unchained_hash[mapname], false ) + _T(".infoex"), cache );
      }
  }
  catch ( ... ) {
      info.width = 1;
      info.height = 1;
  }

  m_mapinfo_cache.Add( mapname, info );

  return info;
}