Beispiel #1
0
	double stddev( vd v)
	{
		double avg = average(v);

		return( stddev(v, avg) );
	}
Beispiel #2
0
static void flatten_volume_closure_tree(ShaderData *sd,
                                        const OSL::ClosureColor *closure, float3 weight = make_float3(1.0f, 1.0f, 1.0f))
{
	/* OSL gives us a closure tree, we flatten it into arrays per
	 * closure type, for evaluation, sampling, etc later on. */

	if (closure->type == OSL::ClosureColor::COMPONENT) {
		OSL::ClosureComponent *comp = (OSL::ClosureComponent *)closure;
		CClosurePrimitive *prim = (CClosurePrimitive *)comp->data();

		if (prim) {
			ShaderClosure sc;

#ifdef OSL_SUPPORTS_WEIGHTED_CLOSURE_COMPONENTS
			weight = weight*TO_FLOAT3(comp->w);
#endif
			sc.weight = weight;

			prim->setup();

			switch (prim->category) {
				case CClosurePrimitive::Volume: {
					CVolumeClosure *volume = (CVolumeClosure *)prim;
					/* sample weight */
					float sample_weight = fabsf(average(weight));

					sc.sample_weight = sample_weight;
					sc.type = volume->sc.type;
					sc.data0 = volume->sc.data0;
					sc.data1 = volume->sc.data1;

					/* add */
					if(sc.sample_weight > CLOSURE_WEIGHT_CUTOFF &&
					   sd->num_closure < MAX_CLOSURE) {
						sd->closure[sd->num_closure++] = sc;
						sd->flag |= volume->shaderdata_flag();
					}
					break;
				}
				case CClosurePrimitive::Emissive: {
					/* sample weight */
					float sample_weight = fabsf(average(weight));

					sc.sample_weight = sample_weight;
					sc.type = CLOSURE_EMISSION_ID;
					sc.data0 = 0.0f;
					sc.data1 = 0.0f;
					sc.prim = NULL;

					/* flag */
					if(sd->num_closure < MAX_CLOSURE) {
						sd->closure[sd->num_closure++] = sc;
						sd->flag |= SD_EMISSION;
					}
					break;
				}
				case CClosurePrimitive::Holdout:
					break; /* not implemented */
				case CClosurePrimitive::Background:
				case CClosurePrimitive::BSDF:
				case CClosurePrimitive::BSSRDF:
				case CClosurePrimitive::AmbientOcclusion:
					break; /* not relevant */
			}
		}
	}
	else if (closure->type == OSL::ClosureColor::MUL) {
		OSL::ClosureMul *mul = (OSL::ClosureMul *)closure;
		flatten_volume_closure_tree(sd, mul->closure, TO_FLOAT3(mul->weight) * weight);
	}
	else if (closure->type == OSL::ClosureColor::ADD) {
		OSL::ClosureAdd *add = (OSL::ClosureAdd *)closure;
		flatten_volume_closure_tree(sd, add->closureA, weight);
		flatten_volume_closure_tree(sd, add->closureB, weight);
	}
}
Field<vector> volumeAverageFunctionObject::process(const word& fieldName,vector preset)
{
    return average(fieldName,preset);
}
Beispiel #4
0
int main(int argn, char *argc[])
{
    //Program parameters : argc[1] : HostName or Host IP
    //					   argc[2] : Server Program Number
    //					   argc[3] : Number of test call
    //					   other arguments depend on test case

    //run_mode can switch into stand alone program or program launch by shell script
    //1 : stand alone, debug mode, more screen information
    //0 : launch by shell script as test case, only one printf -> result status
    int run_mode = 0;
    int test_status = 0; //Default test result set to FAILED
    int i;
    double *resultTbl;
    struct timeval tv1,tv2;
    struct timezone tz;
    long long diff;
    double rslt;
    int progNum = atoi(argc[2]);
    CLIENT *client = NULL;
    struct netconfig *nconf = NULL;
    struct netbuf svcaddr;
    char addrbuf[ADDRBUFSIZE];
    enum clnt_stat cs;
    int var_snd = 0;
    int var_rec = -1;
    struct timeval tv;

    //Test initialisation
    maxIter = atoi(argc[3]);
    resultTbl = (double *)malloc(maxIter * sizeof(double));

    tv.tv_sec = 0;
    tv.tv_usec = 100;

    nconf = getnetconfigent("udp");
    if (nconf == (struct netconfig *) NULL)
    {
        //syslog(LOG_ERR, "getnetconfigent for udp failed");
        fprintf(stderr, "err nconf\n");
        printf("5\n");
        exit(1);
    }

    svcaddr.len = 0;
    svcaddr.maxlen = ADDRBUFSIZE;
    svcaddr.buf = addrbuf;

    if (svcaddr.buf == (char *)NULL)
    {
        /* if malloc() failed, print error messages and exit */
        printf("5\n");
        exit(1);
    }

    //printf("svcaddr reserved (%s)\n", argc[1]);

    if (!rpcb_getaddr(progNum, VERSNUM, nconf,
                      &svcaddr, argc[1]))
    {
        fprintf(stderr, "rpcb_getaddr failed!!\n");
        printf("5\n");
        exit(1);
    }
    //printf("svc get\n");

    client = clnt_dg_create(RPC_ANYFD, &svcaddr,
                            progNum, VERSNUM, 1024, 1024);

    if (client == (CLIENT *)NULL)
    {
        clnt_pcreateerror("ERR");
        exit(1);
    }

    //Call tested function several times
    for (i = 0; i < maxIter; i++)
    {
        //Tic
        gettimeofday(&tv1, &tz);

        //Call function
        cs = clnt_call(client, PROCNUM,
                       (xdrproc_t)xdr_int, (char *)&var_snd,
                       (xdrproc_t)xdr_int, (char *)&var_rec,
                       tv);

        //Toc
        gettimeofday(&tv2, &tz);

        //Add function execution time (toc-tic)
        diff = (tv2.tv_sec-tv1.tv_sec) * 1000000L + (tv2.tv_usec-tv1.tv_usec);
        rslt = (double)diff / 1000;

        if (cs == RPC_SUCCESS)
        {
            resultTbl[i] = rslt;
        }
        else
        {
            test_status = 1;
            break;
        }


        if (run_mode)
        {
            fprintf(stderr, "lf time  = %lf usecn\n", resultTbl[i]);
        }
    }

    //This last printf gives the result status to the tests suite
    //normally should be 0: test has passed or 1: test has failed
    printf("%d\n", test_status);
    printf("%lf %d\n", average(resultTbl), maxIter);
    printf("%lf\n", mini(resultTbl));
    printf("%lf\n", maxi(resultTbl));

    return test_status;
}
Type Foam::sampledSurface::average(const tmp<Field<Type> >& field) const
{
    Type value = average(field());
    field.clear();
    return value;
}
Beispiel #6
0
double CProfileNode::GetTurnMallocs() const
{
	return average(mallocs_per_turn);
}
Beispiel #7
0
static void flatten_volume_closure_tree(ShaderData *sd,
                                        const OSL::ClosureColor *closure, float3 weight = make_float3(1.0f, 1.0f, 1.0f))
{
	/* OSL gives us a closure tree, we flatten it into arrays per
	 * closure type, for evaluation, sampling, etc later on. */

#if OSL_LIBRARY_VERSION_CODE < 10700
	switch(closure->type) {
#else
	switch(closure->id) {
#endif
		case OSL::ClosureColor::MUL: {
			OSL::ClosureMul *mul = (OSL::ClosureMul *)closure;
			flatten_volume_closure_tree(sd, mul->closure, TO_FLOAT3(mul->weight) * weight);
			break;
		}
		case OSL::ClosureColor::ADD: {
			OSL::ClosureAdd *add = (OSL::ClosureAdd *)closure;
			flatten_volume_closure_tree(sd, add->closureA, weight);
			flatten_volume_closure_tree(sd, add->closureB, weight);
			break;
		}
		default: {
			OSL::ClosureComponent *comp = (OSL::ClosureComponent *)closure;
			CClosurePrimitive *prim = (CClosurePrimitive *)comp->data();

			if(prim) {
				ShaderClosure sc;

#ifdef OSL_SUPPORTS_WEIGHTED_CLOSURE_COMPONENTS
				weight = weight*TO_FLOAT3(comp->w);
#endif
				sc.weight = weight;

				prim->setup();

				switch(prim->category) {
					case CClosurePrimitive::Volume: {
						CVolumeClosure *volume = (CVolumeClosure *)prim;
						/* sample weight */
						float sample_weight = fabsf(average(weight));

						sc.sample_weight = sample_weight;
						sc.type = volume->sc.type;
						sc.data0 = volume->sc.data0;
						sc.data1 = volume->sc.data1;

						/* add */
						if((sc.sample_weight > CLOSURE_WEIGHT_CUTOFF) &&
						   (sd->num_closure < MAX_CLOSURE))
						{
							sd->closure[sd->num_closure++] = sc;
							sd->flag |= volume->shaderdata_flag();
						}
						break;
					}
					case CClosurePrimitive::Emissive: {
						/* sample weight */
						float sample_weight = fabsf(average(weight));

						sc.sample_weight = sample_weight;
						sc.type = CLOSURE_EMISSION_ID;
						sc.data0 = 0.0f;
						sc.data1 = 0.0f;
						sc.prim = NULL;

						/* flag */
						if(sd->num_closure < MAX_CLOSURE) {
							sd->closure[sd->num_closure++] = sc;
							sd->flag |= SD_EMISSION;
						}
						break;
					}
					case CClosurePrimitive::Holdout:
						break; /* not implemented */
					case CClosurePrimitive::Background:
					case CClosurePrimitive::BSDF:
					case CClosurePrimitive::BSSRDF:
					case CClosurePrimitive::AmbientOcclusion:
						break; /* not relevant */
				}
			}
		}
	}
}

void OSLShader::eval_volume(KernelGlobals *kg, ShaderData *sd, PathState *state, int path_flag, ShaderContext ctx)
{
	/* setup shader globals from shader data */
	OSLThreadData *tdata = kg->osl_tdata;
	shaderdata_to_shaderglobals(kg, sd, state, path_flag, tdata);

	/* execute shader */
	OSL::ShadingSystem *ss = (OSL::ShadingSystem*)kg->osl_ss;
	OSL::ShaderGlobals *globals = &tdata->globals;
	OSL::ShadingContext *octx = tdata->context[(int)ctx];
	int shader = sd->shader & SHADER_MASK;

	if(kg->osl->volume_state[shader]) {
#if OSL_LIBRARY_VERSION_CODE < 10600
		ss->execute(*octx, *(kg->osl->volume_state[shader]), *globals);
#else
		ss->execute(octx, *(kg->osl->volume_state[shader]), *globals);
#endif
	}
	
	/* flatten closure tree */
	if(globals->Ci)
		flatten_volume_closure_tree(sd, globals->Ci);
}
Beispiel #8
0
double improve(double x)
{
  return (average (x, 11/x));
}
int main(int argc, char *argv[])
{
#   include "setRootCase.H"
#   include "createTime.H"
#   include "createMesh.H"
#   include "createFields.H"
#   include "createHistory.H"

// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

    Info<< "\nStarting time loop\n" << endl;

    Info<< "Note: the results must be written for every time-step"
        << " as they are used to calculate the current stress" << endl;

    lduMatrix::debug = 0;
    scalar m = 0.5;
    surfaceVectorField n = mesh.Sf()/mesh.magSf();

    for (runTime++; !runTime.end(); runTime++)
    {
        Info<< "Time: " << runTime.timeName() << nl << endl;

#       include "readSolidMechanicsControls.H"

        volScalarField mu = rheology.mu(m*runTime.deltaT().value());
        volScalarField lambda = rheology.lambda(m*runTime.deltaT().value());
        surfaceScalarField muf = fvc::interpolate(mu);
        surfaceScalarField lambdaf = fvc::interpolate(lambda);
        Info << "average mu = " << average(muf.internalField()) << endl;
        Info << "average lambda = " << average(lambdaf.internalField()) << endl;

        int iCorr = 0;
        lduMatrix::solverPerformance solverPerf;
        scalar initialResidual = 1.0;
        scalar residual = 1.0;
        surfaceSymmTensorField DSigmaCorrf = fvc::interpolate(DSigmaCorr);

    //label nCrackedFaces = 0;
    // cracking loop if you use cohesive boundaries
    //do
    //{
    do
    {
        surfaceTensorField sGradDU =
            (I - n*n)&fvc::interpolate(gradDU);

        DU.storePrevIter();

        fvVectorMatrix DUEqn
            (
                rho*fvm::d2dt2(DU)
                ==
                fvm::laplacian(2*muf+lambdaf, DU, "laplacian(DDU,DU)")
                + fvc::div
                (
                    mesh.magSf()
                    *(
                        - (muf + lambdaf)*(fvc::snGrad(DU)&(I - n*n))
                        + lambdaf*tr(sGradDU&(I - n*n))*n
                        + muf*(sGradDU&n)
                        + (n&DSigmaCorrf)
                        )
                    )
                );

//          // add an increment of gravity on the first time-step
//          if (runTime.timeIndex() == 1)
//            {
//              DUEqn -= (rho*g);
//            }

        solverPerf = DUEqn.solve();

        DU.relax();

        if (iCorr == 0)
        {
            initialResidual = solverPerf.initialResidual();
        }

        gradDU = fvc::grad(DU);

#       include "calculateDSigma.H"
#       include "calcResidual.H"

        if (iCorr % infoFrequency == 0)
        {
            Info<< "\tTime " << runTime.value()
                << ", Corrector " << iCorr
                << ", Solving for " << U.name()
                << " using " << solverPerf.solverName()
                << ", res = " << solverPerf.initialResidual()
                << ", rel res = " << residual
                << ", inner iters = " << solverPerf.nIterations() << endl;
        }
    }
    while
        (
            // solverPerf.initialResidual() > convergenceTolerance
            residual > convergenceTolerance
            && ++iCorr < nCorr
            );

    Info<< "Solving for " << DU.name() << " using "
        << solverPerf.solverName() << " solver"
        << ", Initial residula = " << initialResidual
        << ", Final residual = " << solverPerf.initialResidual()
        << ", No outer iterations " << iCorr
        << ", Relative error: " << residual << endl;

    //#           include "updateCrack.H"
    //}
    //while(nCrackedFaces > 0);

    U += DU;

#   include "calculateSigma.H"
#   include "writeFields.H"
#   include "writeHistory.H"

    Info<< "ExecutionTime = "
        << runTime.elapsedCpuTime()
        << " s\n\n" << endl;
    }

    Info<< "End\n" << endl;

    return(0);
}
void LinearRegressionAnalyzer::DoAnalyze() {
    BaseAnalyzer::DoAnalyze();

    QList<double> yList = matrix[0];
    QList<QList<double> > xMatrix;
    for (int i=1;i<matrix.size();i++) {
        xMatrix.append(matrix[i]);
    }

    QList<QList<double> > xNMatrix;
    for (int i=0;i<xMatrix.size();i++) {
        QList<double> xNiMatrix;
        double avg = average(xMatrix[i]);
        QList<double> razn;
        for (int j=0;j<xMatrix[i].size();j++) {
            razn.append(fabs(xMatrix[i][j] - avg));
        }
        double R = maxElement(razn);
        for (int j=0;j<xMatrix[i].size();j++)
            xNiMatrix.append((xMatrix[i][j] - avg)/R);
        xNMatrix.append(xNiMatrix);
    }

    QList<double> bMatrix;
    double temp = 0.0;
    for (int i=0;i<yList.size();i++)
        temp += yList[i];
    bMatrix.append(temp);
    for (int i=0;i<xNMatrix.size();i++) {
        temp = 0.0;
        for (int j=0;j<xNMatrix[i].size();j++) {
            temp += yList[j] * xNMatrix[i][j];
        }
        bMatrix.append(temp);
    }

    QList<QList<double> > aMatrix;
    QList<double> firstRow;
    firstRow.append(yList.size());
    for (int i=0;i<xNMatrix.size();i++)
        firstRow.append(sumElements(xNMatrix[i]));
    aMatrix.append(firstRow);
    for (int row=0;row<xNMatrix.size();row++) {
        QList<double> tempRow;
        for (int col=0;col<bMatrix.size();col++) {
            if (col<=row) {
                tempRow.append(0.0);
            }
            else {
                if (col>0) {
                    tempRow.append(sumListsElements(xNMatrix[col-1], xNMatrix[row]));
                }
            }
        }
        aMatrix.append(tempRow);
    }

    for (int row = 0;row<aMatrix.size();row++) {
        for (int col = 0; col < aMatrix[row].size();col++) {
            if (row <= col)
                continue;
            aMatrix[row][col] = aMatrix[col][row];
        }
    }

    results = Gauss(aMatrix, bMatrix);


    QList<double> y2List;
    for (int i=0;i<xNMatrix[0].size();i++) {
        temp = 0.0;
        for (int j= 0;j<results.size();j++) {
            if (j<results.size()-1)
                temp += results[j] * xNMatrix[j][i];
            else
                temp += results[j];
        }
        y2List.append(temp);
    }

    double y2Avg = average(y2List);
    double yAvg = average(yList);

    double RUp = 0.0, RDown = 0.0;
    for (int i=0;i<yList.size();i++) {
        RUp += (y2List[i]-y2Avg)*(y2List[i]-y2Avg);
        RDown += (yList[i] - yAvg)*(yList[i] - yAvg);
    }

    R2 = RUp/RDown;
}
Foam::capillarityModels::pcIppisch::pcIppisch
(
    const word& name,
    const dictionary& transportProperties,
    const volScalarField& Sb
)
    :
    capillarityModel(name, transportProperties,Sb),
    pcIppischCoeffs_(transportProperties.subDict(typeName + "Coeffs")),
    Smin_
    (
        IOobject
        (
            Sb_.name()+"min",
            Sb_.time().timeName(),
            Sb_.db(),
            IOobject::READ_IF_PRESENT,
            IOobject::NO_WRITE
        ),
        Sb.mesh(),
        transportProperties.lookupOrDefault(Sb_.name()+"min",dimensionedScalar(Sb_.name()+"min",dimless,0))
    ),
    Smax_
    (
        IOobject
        (
            Sb_.name()+"max",
            Sb_.time().timeName(),
            Sb_.db(),
            IOobject::READ_IF_PRESENT,
            IOobject::NO_WRITE
        ),
        Sb.mesh(),
        transportProperties.lookupOrDefault(Sb_.name()+"max",dimensionedScalar(Sb_.name()+"min",dimless,0))
    ),
    m_
    (
        IOobject
        (
            "m",
            Sb_.time().timeName(),
            Sb_.db(),
            IOobject::READ_IF_PRESENT,
            IOobject::NO_WRITE
        ),
        Sb.mesh(),
        dimensionedScalar("m",dimless,pcIppischCoeffs_.lookupOrDefault<scalar>("m",0))
    ),
    n_(1/(1-m_)),
    alpha_
    (
        IOobject
        (
            "alpha",
            Sb_.time().timeName(),
            Sb_.db(),
            IOobject::READ_IF_PRESENT,
            IOobject::NO_WRITE
        ),
        Sb.mesh(),
        dimensionedScalar("alpha",dimless,pcIppischCoeffs_.lookupOrDefault<scalar>("alpha",GREAT))
    ),
    tau_
    (
        IOobject
        (
            "tau",
            Sb_.time().timeName(),
            Sb_.db(),
            IOobject::READ_IF_PRESENT,
            IOobject::NO_WRITE
        ),
        Sb.mesh(),
        dimensionedScalar("tau",dimless,pcIppischCoeffs_.lookupOrDefault<scalar>("tau",1.))
    ),
    he_
    (
        IOobject
        (
            "he",
            Sb_.time().timeName(),
            Sb_.db(),
            IOobject::READ_IF_PRESENT,
            IOobject::NO_WRITE
        ),
        Sb.mesh(),
        dimensionedScalar("he",dimless,pcIppischCoeffs_.lookupOrDefault<scalar>("he",1.))
    ),
    Se_((Sb_-Smin_)/(Smax_-Smin_)),
    Sc_(pow(1+pow(alpha_*he_,n_),-m_))
{
    if (gMin(m_) == 0) FatalErrorIn("Foam::capillarityModels::pcIppisch::pcIppisch") << "m = 0 in pcIppisch" << abort(FatalError);
    Info << "Ippisch parameters for capillary pressure model" << nl << "{" << endl;
    Info << "    m ";
    if (m_.headerOk()) { Info << "read file" << endl;}
    else {Info << average(m_).value() << endl;}
    Info <<  "    n ";
    if (n_.headerOk()) { Info << "read file" << endl;}
    else {Info << average(n_).value() << endl;}
        Info <<  "    alpha ";
    if (alpha_.headerOk()) { Info << "read file" << endl;}
    else {Info << average(alpha_).value() << endl;}
        Info <<  "    tau ";
    if (tau_.headerOk()) { Info << "read file" << endl;}
    else {Info << average(tau_).value() << endl;}
    Info <<  "    he ";
    if (he_.headerOk()) { Info << "read file" << endl;}
    else {Info << average(he_).value() << endl;}
    Info << "} \n" << endl;     
}
Beispiel #12
0
void
Metric::stats(ostream &os ) const
{
  os << "Metric Stats= max: " << max() 
    << " avg: " << average() << std::endl;
}
Beispiel #13
0
bool TerragenDataset::write_header()
{
    char szHeader[16];
    memcpy(szHeader, "TERRAGENTERRAIN ", sizeof(szHeader));

    if(1 != VSIFWriteL( reinterpret_cast<void *>( szHeader ), sizeof(szHeader), 1, m_fp ))
    {
        CPLError( CE_Failure, CPLE_FileIO,
                  "Couldn't write to Terragen file %s.\n"
                  "Is file system full?",
                  m_pszFilename );
        VSIFCloseL( m_fp );

        return false;
    }

// --------------------------------------------------------------------
//      Write out the heightfield dimensions, etc.
// --------------------------------------------------------------------

    const int nXSize = GetRasterXSize();
    const int nYSize = GetRasterYSize();

    write_next_tag( "SIZE" );
    put( static_cast<GInt16>( std::min( nXSize, nYSize ) - 1 ) );
    pad( sizeof(GInt16) );

    if(nXSize != nYSize)
    {
        write_next_tag( "XPTS" );
        put( static_cast<GInt16>( nXSize ) );
        pad( sizeof(GInt16) );
        write_next_tag( "YPTS" );
        put( static_cast<GInt16>( nYSize ) );
        pad( sizeof(GInt16) );
    }

    if(m_bIsGeo)
    {
        /*
          With a geographic projection (degrees),
          m_dGroundScale will be in degrees and
          m_dMetersPerGroundUnit is undefined.
          So we're going to estimate a m_dMetersPerGroundUnit
          value here (i.e., meters per degree).

          We figure out the degree size of one
          pixel, and then the latitude degrees
          of the heightfield's center. The circumference of
          the latitude's great circle lets us know how
          wide the pixel is in meters, and we
          average that with the pixel's meter breadth,
          which is based on the polar circumference.
        */

        /* const double m_dDegLongPerPixel =
              fabs(m_adfTransform[1]); */

        const double m_dDegLatPerPixel = std::abs(m_adfTransform[5]);

        /* const double m_dCenterLongitude =
              m_adfTransform[0] +
              (0.5 * m_dDegLongPerPixel * (nXSize-1)); */

        const double m_dCenterLatitude =
            m_adfTransform[3] +
            (0.5 * m_dDegLatPerPixel * (nYSize-1));

        const double dLatCircum = kdEarthCircumEquat
            * std::sin( degrees_to_radians( 90.0 - m_dCenterLatitude ) );

        const double dMetersPerDegLongitude = dLatCircum / 360;
        /* const double dMetersPerPixelX =
              (m_dDegLongPerPixel / 360) * dLatCircum; */

        const double dMetersPerDegLatitude =
            kdEarthCircumPolar / 360;
        /* const double dMetersPerPixelY =
              (m_dDegLatPerPixel / 360) * kdEarthCircumPolar; */

        m_dMetersPerGroundUnit =
            average(dMetersPerDegLongitude, dMetersPerDegLatitude);
    }

    m_dSCAL = m_dGroundScale * m_dMetersPerGroundUnit;

    if(m_dSCAL != 30.0)
    {
        const float sc = static_cast<float>( m_dSCAL );
        write_next_tag( "SCAL" );
        put( sc );
        put( sc );
        put( sc );
    }

    if( !write_next_tag( "ALTW" ) )
    {
        CPLError( CE_Failure, CPLE_FileIO,
                  "Couldn't write to Terragen file %s.\n"
                  "Is file system full?",
                  m_pszFilename );
        VSIFCloseL( m_fp );

        return false;
    }

    // Compute physical scales and offsets.
    m_span_m[0] = m_dLogSpan[0] * m_dMetersPerElevUnit;
    m_span_m[1] = m_dLogSpan[1] * m_dMetersPerElevUnit;

    m_span_px[0] = m_span_m[0] / m_dSCAL;
    m_span_px[1] = m_span_m[1] / m_dSCAL;

    const double span_px = m_span_px[1] - m_span_px[0];
    m_nHeightScale = static_cast<GInt16>( span_px );
    if(m_nHeightScale == 0)
        m_nHeightScale++;

// TODO(schwehr): Make static functions.
#define P2L_PX(n, hs, bh) (static_cast<double>( n ) / 65536.0 * (hs) + (bh))

#define L2P_PX(n, hs, bh) (static_cast<int>( ((n)-(bh)) * 65536.0 / (hs) ) )

    // Increase the heightscale until the physical span
    // fits within a 16-bit range. The smaller the logical span,
    // the more necessary this becomes.
    int hs = m_nHeightScale;
    int bh = 0;
    for( ; hs <= 32767; hs++)
    {
        double prevdelta = 1.0e30;
        for( bh = -32768; bh <= 32767; bh++ )
        {
            const int nValley = L2P_PX(m_span_px[0], hs, bh);
            if(nValley < -32768) continue;
            const int nPeak = L2P_PX(m_span_px[1], hs, bh);
            if(nPeak > 32767) continue;

            // now see how closely the baseheight gets
            // to the pixel span.
            const double d = P2L_PX(nValley, hs, bh);
            const double delta = std::abs(d - m_span_px[0]);
            if(delta < prevdelta) // Converging?
                prevdelta = delta;
            else
            {
                // We're diverging, so use the previous bh
                // and stop looking.
                bh--;
                break;
            }
        }
        if(bh != 32768) break;
    }
    if(hs == 32768)
    {
        CPLError( CE_Failure, CPLE_FileIO,
                  "Couldn't write to Terragen file %s.\n"
                  "Cannot find adequate heightscale/baseheight combination.",
                  m_pszFilename );
        VSIFCloseL( m_fp );

        return false;
    }

    m_nHeightScale = static_cast<GInt16>( hs );
    m_nBaseHeight = static_cast<GInt16>( bh );


    // m_nHeightScale is the one that gives us the
    // widest use of the 16-bit space. However, there
    // might be larger heightscales that, even though
    // the reduce the space usage, give us a better fit
    // for preserving the span extents.

    return put(m_nHeightScale) && put(m_nBaseHeight);
}
Beispiel #14
0
int main()
{

	cli();	// Clear interrupts
	PORTB |= TRIAC; //Turn off the Triac
	DDRB = 0b00010100;

	//ADC conf
	ADMUX = (1<<ADLAR) | (1<<MUX1) | (1<<MUX0);
	ADCSRA = (1<<ADEN) | (1<<ADPS1) | (1<<ADPS0);
	sei();//Enable interrupts
	
	enum 
	{
		OFF, 
		PREHEAT, 
		REFLOW
	} state = OFF;

	uint8_t last_sense = 0;
	uint16_t counter = 0;
	uint16_t last_voltage = 0;
	uint8_t heater_request = 0;

	//Application loop
	while (1)
	{
		//Wait for button pressing 
		while (SWITCH & PINB)
		{
			counter ++;
			if (counter & 0x10) PORTB |= LED else PORTB &= ~LED;
			_delay_ms(4);
		}

		state = PREHEAT;
		PORTB |= LED;
		counter = 0;

		while (state != OFF)
		{
			if (PINB & SENSE)
			{
				last_sense = 1;
			}
			else //on falling edge
			{
				if (last_sense)//turn on for this whole cycle
				{
					if (heater_request)
					{
						PORTB &= ~TRIAC;
						_delay_us(50);
						PORTB |= TRIAC;
						_delay_ms(10);
						PORTB &= ~TRIAC;
						_delay_us(50);
						PORTB |= TRIAC;
					}
					else
					{
						_delay_ms(11);
					}
					counter ++;
					if (state == PREHEAT) PORTB ^= LED; //blink the led
				}
				last_sense = 0;
			}
			//about 19ms to do measurement and user interaction
			
			ADCSRA |= (1<<ADSC); //start conversion
			while (ADCSRA & (1<<ADSC));//wait it to complete
			last_voltage = average(last_voltage, ADC);//get the content

			switch(state)
			{
				case OFF:
					PORTB &= ~LED;
					break;
				case PREHEAT:
					if (last_voltage < 41200) heater_request = 0; else heater_request = 1;
					if (counter > 3500)
					{
						state = REFLOW;
						PORTB |= LED;
						counter = 0;
					}
					break;
				case REFLOW:
					if (last_voltage < 36000) heater_request = 0; else heater_request = 1;
					if (counter > 4500)
					{
						state = OFF;
						counter = 0;
						heater_request = 0;
					}
					break;
			}
			
			_delay_ms(1);
		}
	}
}
Beispiel #15
0
double CProfileNode::GetTurnTime() const
{
	return average(time_per_turn);
}
Beispiel #16
0
TEST(averageTEST, result_int_case){
  int array[] = {3,4,5};
  EXPECT_EQ(4,average(array, 3));
}
Beispiel #17
0
double CProfileNode::GetFrameMallocs() const
{
	return average(mallocs_per_frame);
}
Beispiel #18
0
TEST(averageTEST, result_double_case){
  int array[] = {1,2,3,4};
  EXPECT_EQ( 10.0/4 ,average(array, 4));
}
Beispiel #19
0
static void flatten_surface_closure_tree(ShaderData *sd, int path_flag,
                                         const OSL::ClosureColor *closure, float3 weight = make_float3(1.0f, 1.0f, 1.0f))
{
	/* OSL gives us a closure tree, we flatten it into arrays per
	 * closure type, for evaluation, sampling, etc later on. */

#if OSL_LIBRARY_VERSION_CODE < 10700
	switch(closure->type) {
#else
	switch(closure->id) {
#endif
		case OSL::ClosureColor::MUL: {
			OSL::ClosureMul *mul = (OSL::ClosureMul *)closure;
			flatten_surface_closure_tree(sd, path_flag, mul->closure, TO_FLOAT3(mul->weight) * weight);
			break;
		}
		case OSL::ClosureColor::ADD: {
			OSL::ClosureAdd *add = (OSL::ClosureAdd *)closure;
			flatten_surface_closure_tree(sd, path_flag, add->closureA, weight);
			flatten_surface_closure_tree(sd, path_flag, add->closureB, weight);
			break;
		}
		default: {
			OSL::ClosureComponent *comp = (OSL::ClosureComponent *)closure;
			CClosurePrimitive *prim = (CClosurePrimitive *)comp->data();

			if(prim) {
				ShaderClosure sc;

#ifdef OSL_SUPPORTS_WEIGHTED_CLOSURE_COMPONENTS
				weight = weight*TO_FLOAT3(comp->w);
#endif
				sc.weight = weight;

				prim->setup();

				switch(prim->category) {
					case CClosurePrimitive::BSDF: {
						CBSDFClosure *bsdf = (CBSDFClosure *)prim;
						int scattering = bsdf->scattering();

						/* caustic options */
						if((scattering & LABEL_GLOSSY) && (path_flag & PATH_RAY_DIFFUSE)) {
							KernelGlobals *kg = sd->osl_globals;

							if((!kernel_data.integrator.caustics_reflective && (scattering & LABEL_REFLECT)) ||
							   (!kernel_data.integrator.caustics_refractive && (scattering & LABEL_TRANSMIT)))
							{
								return;
							}
						}

						/* sample weight */
						float sample_weight = fabsf(average(weight));

						sc.sample_weight = sample_weight;

						sc.type = bsdf->sc.type;
						sc.N = bsdf->sc.N;
						sc.T = bsdf->sc.T;
						sc.data0 = bsdf->sc.data0;
						sc.data1 = bsdf->sc.data1;
						sc.data2 = bsdf->sc.data2;
						sc.prim = bsdf->sc.prim;

						/* add */
						if(sc.sample_weight > CLOSURE_WEIGHT_CUTOFF && sd->num_closure < MAX_CLOSURE) {
							sd->closure[sd->num_closure++] = sc;
							sd->flag |= bsdf->shaderdata_flag();
						}
						break;
					}
					case CClosurePrimitive::Emissive: {
						/* sample weight */
						float sample_weight = fabsf(average(weight));

						sc.sample_weight = sample_weight;
						sc.type = CLOSURE_EMISSION_ID;
						sc.data0 = 0.0f;
						sc.data1 = 0.0f;
						sc.data2 = 0.0f;
						sc.prim = NULL;

						/* flag */
						if(sd->num_closure < MAX_CLOSURE) {
							sd->closure[sd->num_closure++] = sc;
							sd->flag |= SD_EMISSION;
						}
						break;
					}
					case CClosurePrimitive::AmbientOcclusion: {
						/* sample weight */
						float sample_weight = fabsf(average(weight));

						sc.sample_weight = sample_weight;
						sc.type = CLOSURE_AMBIENT_OCCLUSION_ID;
						sc.data0 = 0.0f;
						sc.data1 = 0.0f;
						sc.data2 = 0.0f;
						sc.prim = NULL;

						if(sd->num_closure < MAX_CLOSURE) {
							sd->closure[sd->num_closure++] = sc;
							sd->flag |= SD_AO;
						}
						break;
					}
					case CClosurePrimitive::Holdout: {
						sc.sample_weight = 0.0f;
						sc.type = CLOSURE_HOLDOUT_ID;
						sc.data0 = 0.0f;
						sc.data1 = 0.0f;
						sc.data2 = 0.0f;
						sc.prim = NULL;

						if(sd->num_closure < MAX_CLOSURE) {
							sd->closure[sd->num_closure++] = sc;
							sd->flag |= SD_HOLDOUT;
						}
						break;
					}
					case CClosurePrimitive::BSSRDF: {
						CBSSRDFClosure *bssrdf = (CBSSRDFClosure *)prim;
						float sample_weight = fabsf(average(weight));

						if(sample_weight > CLOSURE_WEIGHT_CUTOFF && sd->num_closure+2 < MAX_CLOSURE) {
							sc.sample_weight = sample_weight;

							sc.type = bssrdf->sc.type;
							sc.N = bssrdf->sc.N;
							sc.data1 = bssrdf->sc.data1;
							sc.T.x = bssrdf->sc.T.x;
							sc.prim = NULL;

							/* disable in case of diffuse ancestor, can't see it well then and
							 * adds considerably noise due to probabilities of continuing path
							 * getting lower and lower */
							if(path_flag & PATH_RAY_DIFFUSE_ANCESTOR)
								bssrdf->radius = make_float3(0.0f, 0.0f, 0.0f);

							/* create one closure for each color channel */
							if(fabsf(weight.x) > 0.0f) {
								sc.weight = make_float3(weight.x, 0.0f, 0.0f);
								sc.data0 = bssrdf->radius.x;
								sc.data1 = 0.0f;
								sd->flag |= bssrdf_setup(&sc, sc.type);
								sd->closure[sd->num_closure++] = sc;
							}

							if(fabsf(weight.y) > 0.0f) {
								sc.weight = make_float3(0.0f, weight.y, 0.0f);
								sc.data0 = bssrdf->radius.y;
								sc.data1 = 0.0f;
								sd->flag |= bssrdf_setup(&sc, sc.type);
								sd->closure[sd->num_closure++] = sc;
							}

							if(fabsf(weight.z) > 0.0f) {
								sc.weight = make_float3(0.0f, 0.0f, weight.z);
								sc.data0 = bssrdf->radius.z;
								sc.data1 = 0.0f;
								sd->flag |= bssrdf_setup(&sc, sc.type);
								sd->closure[sd->num_closure++] = sc;
							}
						}
						break;
					}
					case CClosurePrimitive::Background:
					case CClosurePrimitive::Volume:
						break; /* not relevant */
				}
			}
			break;
		}
	}
}

void OSLShader::eval_surface(KernelGlobals *kg, ShaderData *sd, PathState *state, int path_flag, ShaderContext ctx)
{
	/* setup shader globals from shader data */
	OSLThreadData *tdata = kg->osl_tdata;
	shaderdata_to_shaderglobals(kg, sd, state, path_flag, tdata);

	/* execute shader for this point */
	OSL::ShadingSystem *ss = (OSL::ShadingSystem*)kg->osl_ss;
	OSL::ShaderGlobals *globals = &tdata->globals;
	OSL::ShadingContext *octx = tdata->context[(int)ctx];
	int shader = sd->shader & SHADER_MASK;

	if(kg->osl->surface_state[shader]) {
#if OSL_LIBRARY_VERSION_CODE < 10600
		ss->execute(*octx, *(kg->osl->surface_state[shader]), *globals);
#else
		ss->execute(octx, *(kg->osl->surface_state[shader]), *globals);
#endif
	}

	/* flatten closure tree */
	if(globals->Ci)
		flatten_surface_closure_tree(sd, path_flag, globals->Ci);
}
Beispiel #20
0
int main(int argn, char *argc[])
{
	//Program parameters : argc[1] : HostName or Host IP
	//					   argc[2] : Server Program Number
	//					   argc[3] : Number of test call
	//					   other arguments depend on test case

	//run_mode can switch into stand alone program or program launch by shell script
	//1 : stand alone, debug mode, more screen information
	//0 : launch by shell script as test case, only one printf -> result status
	int run_mode = 0;
	int test_status = 0; //Default test result set to FAILED
	int i;
	double *resultTbl;
	struct timeval tv1,tv2;
    struct timezone tz;
    long long diff;
    double rslt;
	int progNum = atoi(argc[2]);
	enum clnt_stat cs;
	int varSnd = 10;
	int varRec = -1;

	//Test initialisation
    maxIter = atoi(argc[3]);
    resultTbl = (double *)malloc(maxIter * sizeof(double));

	//Call tested function several times
	for (i = 0; i < maxIter; i++)
	{
		//Tic
		gettimeofday(&tv1, &tz);

		//Call function
		cs = callrpc(argc[1], progNum, VERSNUM, PROCNUM,
				   	 (xdrproc_t)xdr_int, (char *)&varSnd,
				   	 (xdrproc_t)xdr_int, (char *)&varRec);

		if (cs != RPC_SUCCESS)
			clnt_perrno(cs);

		//Toc
		gettimeofday(&tv2, &tz);

		//Add function execution time (toc-tic)
		diff = (tv2.tv_sec-tv1.tv_sec) * 1000000L + (tv2.tv_usec-tv1.tv_usec);
		rslt = (double)diff / 1000;

    	if (cs == RPC_SUCCESS)
    	{
    		resultTbl[i] = rslt;
    	}
    	else
    	{
    		test_status = 1;
    		break;
    	}

    	if (run_mode)
    	{
    		fprintf(stderr, "lf time  = %lf usecn\n", resultTbl[i]);
    	}
	}

	//This last printf gives the result status to the tests suite
	//normally should be 0: test has passed or 1: test has failed
	printf("%d\n", test_status);
	printf("%lf %d\n", average(resultTbl), maxIter);
	printf("%lf\n", mini(resultTbl));
	printf("%lf\n", maxi(resultTbl));

	return test_status;
}
Beispiel #21
0
INLINE T average_metric(Few<T, n> ms) {
  return delinearize_metric(average(linearize_metrics(ms)));
}
int main(int argc, char *argv[])
{
    timeSelector::addOptions();
    #include "setRootCase.H"
#   include "createTime.H"
    instantList timeDirs = timeSelector::select0(runTime, args);
#   include "createMesh.H"

    forAll(timeDirs, timeI)
    {
        runTime.setTime(timeDirs[timeI], timeI);
        Info<< "Time = " << runTime.timeName() << endl;
        fvMesh::readUpdateState state = mesh.readUpdate();

        // Wall distance
        if (timeI == 0 || state != fvMesh::UNCHANGED)
        {
            Info<< "Calculating wall distance\n" << endl;
            wallDist y(mesh, true);
            Info<< "Writing wall distance to field "
                << y.name() << nl << endl;
            y.write();
        }


        volScalarField yPlus
        (
            IOobject
            (
                "yPlus",
                runTime.timeName(),
                mesh,
                IOobject::NO_READ,
                IOobject::NO_WRITE
            ),
            mesh,
            dimensionedScalar("yPlus", dimless, 0.0)
        );

        Info<< "Reading field U\n" << endl;
        volVectorField U
        (
            IOobject
            (
                "U",
                runTime.timeName(),
                mesh,
                IOobject::MUST_READ,
                IOobject::NO_WRITE
            ),
            mesh
        );

#       include "createPhi.H"

        singlePhaseTransportModel laminarTransport(U, phi);

        autoPtr<incompressible::LESModel> sgsModel
        (
            incompressible::LESModel::New(U, phi, laminarTransport)
        );

        volScalarField::GeometricBoundaryField d = nearWallDist(mesh).y();
        volScalarField nuEff = sgsModel->nuEff();

        const fvPatchList& patches = mesh.boundary();

        forAll(patches, patchi)
        {
            const fvPatch& currPatch = patches[patchi];

            if (currPatch.isWall())
            {
                yPlus.boundaryField()[patchi] =
                    d[patchi]
                   *sqrt
                    (
                        nuEff.boundaryField()[patchi]
                       *mag(U.boundaryField()[patchi].snGrad())
                    )
                   /sgsModel->nu().boundaryField()[patchi];
                const scalarField& Yp = yPlus.boundaryField()[patchi];

                Info<< "Patch " << patchi
                    << " named " << currPatch.name()
                    << " y+ : min: " << min(Yp) << " max: " << max(Yp)
                    << " average: " << average(Yp) << nl << endl;
            }
        }

        Info<< "Writing yPlus to field "
            << yPlus.name() << nl << endl;

        yPlus.write();
    }
Beispiel #23
0
 double average( const item_t& item ) const { return average( &item ); }
Beispiel #24
0
double CProfileNode::GetFrameCalls() const
{
	return average(calls_per_frame);
}
Beispiel #25
0
static void flatten_surface_closure_tree(ShaderData *sd, int path_flag,
                                         const OSL::ClosureColor *closure, float3 weight = make_float3(1.0f, 1.0f, 1.0f))
{
	/* OSL gives us a closure tree, we flatten it into arrays per
	 * closure type, for evaluation, sampling, etc later on. */

	if (closure->type == OSL::ClosureColor::COMPONENT) {
		OSL::ClosureComponent *comp = (OSL::ClosureComponent *)closure;
		CClosurePrimitive *prim = (CClosurePrimitive *)comp->data();

		if (prim) {
			ShaderClosure sc;

#ifdef OSL_SUPPORTS_WEIGHTED_CLOSURE_COMPONENTS
			weight = weight*TO_FLOAT3(comp->w);
#endif
			sc.weight = weight;

			prim->setup();

			switch (prim->category) {
				case CClosurePrimitive::BSDF: {
					CBSDFClosure *bsdf = (CBSDFClosure *)prim;
					int scattering = bsdf->scattering();

					/* no caustics option */
					if(scattering == LABEL_GLOSSY && (path_flag & PATH_RAY_DIFFUSE)) {
						KernelGlobals *kg = sd->osl_globals;
						if(kernel_data.integrator.no_caustics)
							return;
					}

					/* sample weight */
					float sample_weight = fabsf(average(weight));

					sc.sample_weight = sample_weight;

					sc.type = bsdf->sc.type;
					sc.N = bsdf->sc.N;
					sc.T = bsdf->sc.T;
					sc.data0 = bsdf->sc.data0;
					sc.data1 = bsdf->sc.data1;
					sc.prim = bsdf->sc.prim;

#ifdef __HAIR__
					sc.offset = bsdf->sc.offset;
#endif

					/* add */
					if(sc.sample_weight > CLOSURE_WEIGHT_CUTOFF && sd->num_closure < MAX_CLOSURE) {
						sd->closure[sd->num_closure++] = sc;
						sd->flag |= bsdf->shaderdata_flag();
					}
					break;
				}
				case CClosurePrimitive::Emissive: {
					/* sample weight */
					float sample_weight = fabsf(average(weight));

					sc.sample_weight = sample_weight;
					sc.type = CLOSURE_EMISSION_ID;
					sc.data0 = 0.0f;
					sc.data1 = 0.0f;
					sc.prim = NULL;

					/* flag */
					if(sd->num_closure < MAX_CLOSURE) {
						sd->closure[sd->num_closure++] = sc;
						sd->flag |= SD_EMISSION;
					}
					break;
				}
				case CClosurePrimitive::AmbientOcclusion: {
					/* sample weight */
					float sample_weight = fabsf(average(weight));

					sc.sample_weight = sample_weight;
					sc.type = CLOSURE_AMBIENT_OCCLUSION_ID;
					sc.data0 = 0.0f;
					sc.data1 = 0.0f;
					sc.prim = NULL;

					if(sd->num_closure < MAX_CLOSURE) {
						sd->closure[sd->num_closure++] = sc;
						sd->flag |= SD_AO;
					}
					break;
				}
				case CClosurePrimitive::Holdout: {
					sc.sample_weight = 0.0f;
					sc.type = CLOSURE_HOLDOUT_ID;
					sc.data0 = 0.0f;
					sc.data1 = 0.0f;
					sc.prim = NULL;

					if(sd->num_closure < MAX_CLOSURE) {
						sd->closure[sd->num_closure++] = sc;
						sd->flag |= SD_HOLDOUT;
					}
					break;
				}
				case CClosurePrimitive::BSSRDF: {
					CBSSRDFClosure *bssrdf = (CBSSRDFClosure *)prim;
					float sample_weight = fabsf(average(weight));

					if(sample_weight > CLOSURE_WEIGHT_CUTOFF && sd->num_closure+2 < MAX_CLOSURE) {
						sc.sample_weight = sample_weight;

						sc.type = bssrdf->sc.type;
						sc.N = bssrdf->sc.N;
						sc.data1 = bssrdf->sc.data1;
						sc.T.x = bssrdf->sc.T.x;
						sc.prim = NULL;

						/* disable in case of diffuse ancestor, can't see it well then and
						 * adds considerably noise due to probabilities of continuing path
						 * getting lower and lower */
						if(path_flag & PATH_RAY_DIFFUSE_ANCESTOR)
							bssrdf->radius = make_float3(0.0f, 0.0f, 0.0f);

						/* create one closure for each color channel */
						if(fabsf(weight.x) > 0.0f) {
							sc.weight = make_float3(weight.x, 0.0f, 0.0f);
							sc.data0 = bssrdf->radius.x;
							sd->flag |= bssrdf_setup(&sc, sc.type);
							sd->closure[sd->num_closure++] = sc;
						}

						if(fabsf(weight.y) > 0.0f) {
							sc.weight = make_float3(0.0f, weight.y, 0.0f);
							sc.data0 = bssrdf->radius.y;
							sd->flag |= bssrdf_setup(&sc, sc.type);
							sd->closure[sd->num_closure++] = sc;
						}

						if(fabsf(weight.z) > 0.0f) {
							sc.weight = make_float3(0.0f, 0.0f, weight.z);
							sc.data0 = bssrdf->radius.z;
							sd->flag |= bssrdf_setup(&sc, sc.type);
							sd->closure[sd->num_closure++] = sc;
						}
					}
					break;
				}
				case CClosurePrimitive::Background:
				case CClosurePrimitive::Volume:
					break; /* not relevant */
			}
		}
	}
	else if (closure->type == OSL::ClosureColor::MUL) {
		OSL::ClosureMul *mul = (OSL::ClosureMul *)closure;
		flatten_surface_closure_tree(sd, path_flag, mul->closure, TO_FLOAT3(mul->weight) * weight);
	}
	else if (closure->type == OSL::ClosureColor::ADD) {
		OSL::ClosureAdd *add = (OSL::ClosureAdd *)closure;
		flatten_surface_closure_tree(sd, path_flag, add->closureA, weight);
		flatten_surface_closure_tree(sd, path_flag, add->closureB, weight);
	}
}
Beispiel #26
0
double CProfileNode::GetFrameTime() const
{
	return average(time_per_frame);
}
scalarField volumeAverageFunctionObject::process(const word& fieldName,scalar preset)
{
    return average(fieldName,preset);
}
Beispiel #28
0
double CProfileNode::GetTurnCalls() const
{
	return average(calls_per_turn);
}
Field<sphericalTensor> volumeAverageFunctionObject::process(const word& fieldName,sphericalTensor preset)
{
    return average(fieldName,preset);
}
Beispiel #30
0
	double SumSquaredDifferences( vd v )
	{
		double avg = average(v);

		return(SumSquaredDifferences(v, avg));
	}