Esempio n. 1
0
/***********************************************************************//**
 * @brief Test CTA Npred computation
 *
 * Tests the Npred computation for the diffuse source model. This is done
 * by loading the model from the XML file and by calling the
 * GCTAObservation::npred method which in turn calls the
 * GCTAResponse::npred_diffuse method. The test takes a few seconds.
 ***************************************************************************/
void TestGCTAResponse::test_response_npred_diffuse(void)
{
    // Set reference value
    double ref = 11212.26274;

    // Set parameters
    double src_ra  = 201.3651;
    double src_dec = -43.0191;
    double roi_rad =   4.0;

    // Setup ROI centred on Cen A with a radius of 4 deg
    GCTARoi     roi;
    GCTAInstDir instDir;
    instDir.radec_deg(src_ra, src_dec);
    roi.centre(instDir);
    roi.radius(roi_rad);

    // Setup pointing on Cen A
    GSkyDir skyDir;
    skyDir.radec_deg(src_ra, src_dec);
    GCTAPointing pnt;
    pnt.dir(skyDir);

    // Setup dummy event list
    GGti     gti;
    GEbounds ebounds;
    GTime    tstart(0.0);
    GTime    tstop(1800.0);
    GEnergy  emin;
    GEnergy  emax;
    emin.TeV(0.1);
    emax.TeV(100.0);
    gti.append(tstart, tstop);
    ebounds.append(emin, emax);
    GCTAEventList events;
    events.roi(roi);
    events.gti(gti);
    events.ebounds(ebounds);

    // Setup dummy CTA observation
    GCTAObservation obs;
    obs.ontime(1800.0);
    obs.livetime(1600.0);
    obs.deadc(1600.0/1800.0);
    obs.response(cta_irf, cta_caldb);
    obs.events(&events);
    obs.pointing(pnt);

    // Load models for Npred computation
    GModels models(cta_rsp_xml);

    // Perform Npred computation
    double npred = obs.npred(models, NULL);

    // Test Npred
    test_value(npred, ref, 1.0e-5, "Diffuse Npred computation");

    // Return
    return;
}
Esempio n. 2
0
/***********************************************************************//**
 * @brief Print event cube information
 ***************************************************************************/
std::string GCTAEventCube::print(void) const
{
    // Initialise result string
    std::string result;

    // Append header
    result.append("=== GCTAEventCube ===");
    result.append("\n"+parformat("Number of events")+str(number()));
    result.append("\n"+parformat("Number of elements")+str(size()));
    result.append("\n"+parformat("Number of pixels")+str(npix()));
    result.append("\n"+parformat("Number of energy bins")+str(ebins()));

    // Append skymap definition
    result.append("\n"+m_map.print());
    
    // Append GTI intervals
    result.append("\n"+parformat("Time interval"));
    if (gti().size() > 0) {
        result.append(str(tstart().secs())+" - "+str(tstop().secs())+" sec");
    }
    else {
        result.append("not defined");
    }
    
    // Append energy intervals
    if (ebounds().size() > 0) {
        result.append("\n"+ebounds().print());
    }
    else {
        result.append("\n"+parformat("Energy intervals")+"not defined");
    }

    // Return result
    return result;
}
Esempio n. 3
0
unsigned long WINAPI threadrun(void * var)
{
    unsigned i;
    thrdmem_t *t = (thrdmem_t *)var;

    int tnum = t->threadnum;
    int k = tnum;
    int k1;
    int counterA = tnum;

    Lock(k);
#ifdef _WIN32
    Sleep(100);
#else
    sleep(1);
#endif

    tstart(&t->_tstart);

    for(i = 0; i < maxcount; i++) {
        k1 = k + 1;
        if(k1 >= ncrits)
            k1 = 0;
        Lock(k1);
        Unlock(k);
        if(showme) {
            if(showme > 1) {
                printf("T%d\n",tnum); fflush(stdout);
            }
            else if (showme > 2) {
                printf("T%d: i=%d %d\n", tnum,i,counterA); fflush(stdout);
            }
        }
        counterA += nthreads;

        k = k1;
        t->tcounter++;
    }
    Unlock(k);
    tend(&t->_tend);

    if(showme > 0) {
        // Don't let my printf's interfere with the timing of other threads.
        SLEEP(2+(nthreads/40));
        double tim = tval(&t->_tstart, &t->_tend);

        printf("%lu %s/thread Context switches in %7.3f sec ",
            maxcount, facility, tim);

        printf("%7.3f usec/cswitch",
            (tim*1e6)/(maxcount*nthreads));
        printf("\n");
        fflush(stdout);
    }
#ifdef _WIN32
    ExitThread(0);
#endif
    return 0;
}
Esempio n. 4
0
void FalconCubeTest::runFunction()
{
	if(!m_falconDevice->runIOLoop()){
		std::cout << "Error in runIOLoop" << std::endl;
        return;
    }

	boost::array<double, 3> pos = m_falconDevice->getPosition();

	if(m_isInitializing)
	{
		if(!m_hasPrintedInitMsg)
		{
			std::cout << "Move the end effector all the way out" << std::endl;
			m_hasPrintedInitMsg = true;
		}
		if(pos[2] > .170)
		{
			std::cout << "Starting cube simulation..." << std::endl;
			m_isInitializing = false;
			tstart();
		}
		m_lastLoopCount = m_falconDevice->getFalconFirmware()->getLoopCount();
		return;
	}

	boost::array<double, 3> force;

	double dist = 10000;
	int closest = -1, outside=3, axis;

	// For each axis, check if the end effector is inside
	// the cube.  Record the distance to the closest wall.

	for (axis=0; axis<3; axis++)
	{
		force[axis] = 0;
		if (pos[axis] > m_cornerA[axis] && pos[axis] < m_cornerB[axis])
		{
			double dA = pos[axis]-m_cornerA[axis];
			double dB = pos[axis]-m_cornerB[axis];
			if (fabs(dA) < fabs(dist)) { dist = dA; closest = axis; }
			if (fabs(dB) < fabs(dist)) { dist = dB; closest = axis; }
			outside--;
		}
	}

	// If so, add a proportional force to kick it back
	// outside from the nearest wall.

	if (closest > -1 && !outside)
		force[closest] = -m_stiffness*dist;
	m_falconDevice->setForce(force);
}
Esempio n. 5
0
/***********************************************************************//**
 * @brief Print event cube information
 *
 * @param[in] chatter Chattiness.
 * @return String containing event cube information.
 ***************************************************************************/
std::string GCTAEventCube::print(const GChatter& chatter) const
{
    // Initialise result string
    std::string result;

    // Continue only if chatter is not silent
    if (chatter != SILENT) {

        // Append header
        result.append("=== GCTAEventCube ===");
        result.append("\n"+gammalib::parformat("Number of events") +
                      gammalib::str(number()));
        result.append("\n"+gammalib::parformat("Number of elements") +
                      gammalib::str(size()));
        result.append("\n"+gammalib::parformat("Number of pixels") +
                      gammalib::str(npix()));
        result.append("\n"+gammalib::parformat("Number of energy bins") +
                      gammalib::str(ebins()));

        // Append GTI intervals
        result.append("\n"+gammalib::parformat("Time interval"));
        if (gti().size() > 0) {
            result.append(gammalib::str(tstart().secs()) +
                          " - " +
                          gammalib::str(tstop().secs())+" sec");
        }
        else {
            result.append("not defined");
        }
    
        // Append energy intervals
        if (gammalib::reduce(chatter) > SILENT) {
            if (ebounds().size() > 0) {
                result.append("\n"+ebounds().print(gammalib::reduce(chatter)));
            }
            else {
                result.append("\n"+gammalib::parformat("Energy intervals") +
                              "not defined");
            }
        }

        // Append skymap definition
        if (gammalib::reduce(chatter) > SILENT) {
            result.append("\n"+m_map.print(gammalib::reduce(chatter)));    
        }

    } // endif: chatter was not silent

    // Return result
    return result;
}
Esempio n. 6
0
bool PathFinding::generatePathSimple(VectorPath& path, const Vector& start, const Vector& end, unsigned int step /* = 0 */, unsigned int obs /* = 0 */)
{
	if(obs == OT_EMPTY)
		obs = OT_BLOCKING;

	SearchGridRaw grid((ObsType)obs);
	JPS::PathVector p;
	TileVector tstart(start);
	TileVector tend(end);
	if(!JPS::findPath(p, grid, tstart.x, tstart.y, tend.x, tend.y, step))
		return false;

	generateVectorPath(p, path, 0, 0);
	molestPath(path);
	return true;
}
Esempio n. 7
0
/***********************************************************************//**
 * @brief Write Good Time Intervals into XML element
 *
 * @param[in] xml XML element.
 *
 * Writes Good Time Intervals into an XML element. The format of the Good
 * Time Intervals is
 *
 *     <parameter name="GoodTimeIntervals" tmin="..." tmax="..."/>
 *
 * The units of the @a tmin and @a tmax parameters are seconds.
 *
 * The method also writes the time reference as parameter in the @p xml
 * element.
 *
 * This method does nothing if the Good Time Intervals are empty.
 ***************************************************************************/
void GGti::write(GXmlElement& xml) const
{
    // Continue only if there are GTIs
    if (!is_empty()) {

        // Get parameter
        GXmlElement* par = gammalib::xml_need_par(G_WRITE_XML, xml, "GoodTimeIntervals");

        // Write time interval
        par->attribute("tmin", gammalib::str(tstart().convert(m_reference)));
        par->attribute("tmax", gammalib::str(tstop().convert(m_reference)));

        // Write time reference
        m_reference.write(xml);

    } // endif: GTIs were not empty

    // Return
    return;
}
Esempio n. 8
0
static int do_step_cloth(Object *ob, ClothModifierData *clmd, DerivedMesh *result, int framenr)
{
	ClothVertex *verts = NULL;
	Cloth *cloth;
	ListBase *effectors = NULL;
	MVert *mvert;
	unsigned int i = 0;
	int ret = 0;

	/* simulate 1 frame forward */
	cloth = clmd->clothObject;
	verts = cloth->verts;
	mvert = result->getVertArray(result);

	/* force any pinned verts to their constrained location. */
	for(i = 0; i < clmd->clothObject->numverts; i++, verts++) {
		/* save the previous position. */
		copy_v3_v3(verts->xold, verts->xconst);
		copy_v3_v3(verts->txold, verts->x);

		/* Get the current position. */
		copy_v3_v3(verts->xconst, mvert[i].co);
		mul_m4_v3(ob->obmat, verts->xconst);
	}

	effectors = pdInitEffectors(clmd->scene, ob, NULL, clmd->sim_parms->effector_weights);
	
	tstart();

	/* call the solver. */
	if(solvers [clmd->sim_parms->solver_type].solver)
		ret = solvers[clmd->sim_parms->solver_type].solver(ob, framenr, clmd, effectors);

	tend();

	pdEndEffectors(&effectors);

	// printf ( "%f\n", ( float ) tval() );
	
	return ret;
}
Esempio n. 9
0
/* afs_osi_TimedSleep
 * 
 * Arguments:
 * event - event to sleep on
 * ams --- max sleep time in milliseconds
 * aintok - 1 if should sleep interruptibly
 *
 * Returns 0 if timeout and EINTR if signalled.
 */
int
afs_osi_TimedSleep(void *event, afs_int32 ams, int aintok)
{
    int code = 0;
    struct afs_event *evp;
    struct timestruc_t ticks;
    struct trb *trb;
    int rc;

    ticks.tv_sec = ams / 1000;
    ticks.tv_nsec = (ams - (ticks.tv_sec * 1000)) * 1000000;


    evp = afs_getevent(event);

    trb = talloc();
    if (trb == NULL)
	osi_Panic("talloc returned NULL");
    trb->flags = 0;
    trb->func = AfsWaitHack;
    trb->eventlist = EVENT_NULL;
    trb->ipri = INTTIMER;
    trb->func_data = thread_self();
    trb->timeout.it_value = ticks;

    e_assert_wait(&evp->cond, aintok);
    AFS_GUNLOCK();
    tstart(trb);
    rc = e_block_thread();
    while (tstop(trb));
    if (rc == THREAD_INTERRUPTED)
	code = EINTR;
    tfree(trb);
    AFS_GLOCK();

    relevent(evp);
    return code;
}
Esempio n. 10
0
/***********************************************************************//**
 * @brief Print Good Time Intervals
 *
 * @param[in] chatter Chattiness (defaults to NORMAL).
 * @return String containing Good Time Interval information.
 ***************************************************************************/
std::string GGti::print(const GChatter& chatter) const
{
    // Initialise result string
    std::string result;

    // Continue only if chatter is not silent
    if (chatter != SILENT) {

        // Append header
        result.append("=== GGti ===");

        // Append GTI information
        result.append("\n"+gammalib::parformat("Number of intervals"));
        result.append(gammalib::str(size()));
        result.append("\n"+gammalib::parformat("Ontime"));
        result.append(gammalib::str(ontime())+" sec");
        result.append("\n"+gammalib::parformat("Elapsed time"));
        result.append(gammalib::str(telapse())+" sec");
        result.append("\n"+gammalib::parformat("Time range"));
        result.append(gammalib::str(tstart().convert(m_reference)));
        result.append(" - ");
        result.append(gammalib::str(tstop().convert(m_reference)));
        result.append(" "+reference().timeunit());
        result.append(" ("+reference().timesys()+")");
        result.append("\n"+gammalib::parformat("Reference MDJ"));
        result.append(gammalib::str(reference().mjdref()));

        // EXPLICIT: Append time reference information
        if (chatter >= EXPLICIT) {
            result.append("\n"+reference().print(chatter));
        }

    } // endif: chatter was not silent

    // Return result
    return result;
}
Esempio n. 11
0
void feedback(int n, int m, int p, int q, int nb, int output_level, int nn, int input, char *ifn, char *ofn)
{
  dcmplx A[n][n], B[n][m], C[p][n];
  dcmplx s[nn], Is[n][n], Is_A[n][n], tmp[p][n], M[p][m];  
  double a[nn*2], b[nn*p*m*2], *points, *planes, r;
  int i, j, k, start, nbsols;
  FILE *ifp, *ofp;
  timer t_phc;

 ofp=fopen(ofn, "w"); /*open for writing*/
 fprintf(ofp, "n=%d\n", n);
 fprintf(ofp, "m=%d\n", m);
 fprintf(ofp, "p=%d\n", p);
 fprintf(ofp, "q=%d\n", q);
 
 if(input == 0)
 {
  ifp=fopen(ifn, "r"); /*open for reading*/
  skip(ifp);

  read_dcmatrix0(n, n, A, ifp);
  printf( "The given matrix A(%d*%d) is:\n", n, n);
  print_dcmatrix(n, n, A);

  read_dcmatrix0(n, m, B, ifp);
  printf("The given matrix B(%d*%d) is:\n", n, m);
  print_dcmatrix(n, m, B);

  read_dcmatrix0(p, n, C, ifp);
  printf("The given matrix C(%d*%d) is:\n", p, n);
  print_dcmatrix(p, n, C); 
  
  for(i=0; i<n+q; i++)
    read_dcmplx0(&s[i], ifp);
  for(i=n+q; i<nn; i++)     /*generate more poles as interpolation points */
  {
    s[i] = create1(cos(rand()));
    if(s[i].re>0)
      s[i] = min_dcmplx(s[i]);  
  } 
  fclose(ifp);
 }

 if(input == 1)
 {
  ifp=fopen(ifn, "r"); /*open for reading*/
  skip(ifp);

  read_dcmatrix2(n, n, A, ifp);
  printf( "The given matrix A(%d*%d) is:\n", n, n);
  print_dcmatrix(n, n, A);

  read_dcmatrix2(n, m, B, ifp);
  printf("The given matrix B(%d*%d) is:\n", n, m);
  print_dcmatrix(n, m, B);

  read_dcmatrix2(p, n, C, ifp);
  printf("The given matrix C(%d*%d) is:\n", p, n);
  print_dcmatrix(p, n, C); 
  
  for(i=0; i<n+q; i++)
    read_dcmplx1(&s[i], ifp);
  for(i=n+q; i<nn; i++)     /*generate more poles as interpolation points */
  {
    s[i] = create1(cos(rand()));
    if(s[i].re>0)
      s[i] = min_dcmplx(s[i]);  
  } 
  fclose(ifp);
 }

 if(input==2)
 {

  random_dcmatrix ( n, n, A);
  printf("\nThe random generated matrix A is:\n");
  print_dcmatrix(n, n, A);

  random_dcmatrix ( n, m, B);
  printf("\nThe random generated matrix B is:\n");
  print_dcmatrix(n, m, B);

  random_dcmatrix ( p, n, C);
  printf("\nThe random generated matrix C is:\n");
  print_dcmatrix(p, n, C);

  s[0] = create2(-0.23423423423, 0);  /* fix one pole for testing realization */
  for(i=1; i<nn; i++)
  {
    r = rand();
    s[i] = create2(cos(r), sin(r));
    if(s[i].re>0)
      s[i] = min_dcmplx(s[i]); 
    s[++i] = conjugate(s[i]);
    if(i==(nn-2))
    {
       if((nn%2)==0)
          s[++i] = create1(-1.0); 
    }  
  }
  printf("\nThe random generated poles are:\n");
  for(i=0; i<nn; i++)
    writeln_dcmplx(s[i]);
 }

 if(input==3)
 {

  random_dcmatrix0 ( n, n, A);
  printf("\nThe random generated matrix A is:\n");
  print_dcmatrix(n, n, A);

  random_dcmatrix0 ( n, m, B);
  printf("\nThe random generated matrix B is:\n");
  print_dcmatrix(n, m, B);

  random_dcmatrix0 ( p, n, C);
  printf("\nThe random generated matrix C is:\n");
  print_dcmatrix(p, n, C);

  s[0] = create2(-0.23423423423, 0);  /* fix one pole for test */
  for(i=1; i<nn; i++)
  {
    r = rand();
    s[i] = create2(cos(r), sin(r));
    if(s[i].re>0)
      s[i] = min_dcmplx(s[i]);
    s[++i] = conjugate(s[i]);
    if(i==(nn-2))
    {
       if((nn%2)==0)
          s[++i] = create1(-1.0);
    }
  }
  printf("\nThe random generated poles are:\n");
  for(i=0; i<nn; i++)
    writeln_dcmplx(s[i]);
 }

 if(input == 4)
 {
  ifp=fopen(ifn, "r"); /*open for reading*/
  skip(ifp);

  read_dcmatrix0(n, n, A, ifp);
  printf( "The given matrix A(%d*%d) is:\n", n, n);
  print_dcmatrix(n, n, A);

  read_dcmatrix0(n, m, B, ifp);
  printf("The given matrix B(%d*%d) is:\n", n, m);
  print_dcmatrix(n, m, B);

  read_dcmatrix0(p, n, C, ifp);
  printf("The given matrix C(%d*%d) is:\n", p, n);
  print_dcmatrix(p, n, C);

  for(i=0; i<n+q; i++)
    read_dcmplx1(&s[i], ifp);
  for(i=n+q; i<nn; i++)     /*generate more poles as interpolation points */
  {
    s[i] = create1(cos(rand()));
    if(s[i].re>0)
      s[i] = min_dcmplx(s[i]);
  }
  fclose(ifp);
 }


 /* print the input matrices in matlab format for further study */
  fprintf(ofp,"A=[\n");  print_dcmatrix1(n, n, A, ofp); fprintf(ofp,"]\n");
  fprintf(ofp,"B=[\n");  print_dcmatrix1(n, m, B, ofp); fprintf(ofp,"]\n");
  fprintf(ofp,"C=[\n");  print_dcmatrix1(p, n, C, ofp); fprintf(ofp,"]\n");

  fprintf(ofp, "\nPoles=[");
  for(i=0; i<nn; i++)
  {
    write_dcmplx1(s[i], ofp);
    if(i!=(nn-1)) fprintf(ofp, ",");
  }
  fprintf(ofp, "]\n");

 /* end of input */



  j = 0;
  for(i=0; i<nn; i++)
  {
    a[j++] = s[i].re;
    a[j++] = s[i].im;
  }

  start = 0;
  for(k=0; k<n+q; k++)
  { 
    for(i=0; i<n; i++)
      for(j=0; j<n; j++)
      {
        if(i==j) Is[i][j] = s[k];
        else Is[i][j] = zero;
      }
   sub_dcmatrix(n, n, Is, A, Is_A);

   dcinverse(n, Is_A);

   multiply_dcmatrix(p, n, n, C, Is_A, tmp);
   multiply_dcmatrix(p, n, m, tmp, B, M);
   c2ada_dc_matrix( p, m, M, nn*p*m*2, b, start);
   start = start + p*m*2;  
    
  }

  /* generate some random planes */
  for( i=start ; i<nn*p*m*2; i++ )
  {
    b[i++] = cos(rand()); 
    b[i] = 0.0;
  }
 
  fflush(stdout);
  fflush(ofp); 

  printf("\nComputing the feedback law with PHC ...\n");
  tstart(&t_phc);
  adainit();
  nbsols = _ada_pieri_solver(m, p, q, nb, output_level, a, b, ofn);
  adafinal();
  tstop(&t_phc);
  /* This subroutine spends almost all the time */
  tprint(t_phc);

  printf("\nSee %s for the realization of the output feedbacks.\n", ofn);

  fclose(ofp);
}
Esempio n. 12
0
int main(int ac, char *av[])
{
  size_t i, t, f, prnd;
  struct SshTimeMeasureRec tmit = SSH_TIME_MEASURE_INITIALIZER;

#if !defined(HAVE_LIBM) && !defined(HAVE_MATH_H)
  exit(0);
#endif

  /* Initialize the number of failures. */
  f = 0;

  printf("Running quick tests for sshrand.\n");
  if (quick_test_1() == 0) f++, printf(" ** test 1 failed.\n");
  if (quick_test_2() == 0) f++, printf(" ** test 2 failed.\n");

  printf("Running timing tests for sshrand "
         "(and for other available generators).\n");

  /* Generating a megawords of randomness. */
  prnd = 1024 * 1024;

#define OK_CRAND   0x01d80000
#define OK_GNURAND 0x3e17b13d
#define OK_SSHRAND 0x2405164b

  tstart(&tmit, "Initialization of C rand.");
  srand(1001);
  tstop(&tmit, "C rand initialized.");

  tstart(&tmit, "Generating %u bytes of prandom data with C rand.",
         prnd);

  for (i = 0, t = 0; i < prnd; i++)
    {
      t += rand();
    }

  tstop(&tmit, "C rand stopped with checksum %s (%08x)",
        (t == OK_CRAND) ? "ok" : "failed",
        t);

  if (t != OK_CRAND) f++;

  tstart(&tmit, "Initialization of GNU random.");
  ssh_rand_seed(1001);
  tstop(&tmit, "GNU random initialized.");

  tstart(&tmit, "Generating %u bytes of prandom data with GNU random.",
         prnd);

  for (i = 0, t = 0; i < prnd; i++)
    {
      t += ssh_rand();
    }

  tstop(&tmit, "GNU random stopped with checksum %s (%08x).",
        (t == OK_GNURAND) ? "ok" : "failed",
        t);

  if (t != OK_GNURAND) f++;

  tstart(&tmit, "Initialization of SSH rand.");
  ssh_rand_seed(1001);
  tstop(&tmit, "SSH random initialized.");

  tstart(&tmit, "Generating %u bytes of prandom data with SSH rand.",
         prnd);

  for (i = 0, t = 0; i < prnd; i++)
    {
      t += ssh_rand();
    }

  tstop(&tmit, "SSH rand stopped with checksum %s (%08x).",
        (t == OK_SSHRAND) ? "ok" : "failed",
        t);

  if (t != OK_SSHRAND) f++;

  printf("%u failures.\n", f);

  if (f > 0)
    {
      printf(""
"Caution. This program has detected a failure(s). Any of the following may\n"
"         be the cause of this failure (more exact indication of error\n"
"         might have appeared above);\n"
"          1. the C rand or GNU random libraries may have generated\n"
"             checksum that was not verified.\n"
"          2. the sshrand library may have generated a checksum that\n"
"             did not match. This is a fatal error and should be\n"
"             investigated carefully.\n"
"          3. one or more of the quick tests failed. These indicate\n"
"             statistical weakness in the generator. Such problems can\n"
"             be due to compilation, platform or even inherent error in\n"
"             the sshrand library. This is a fatal error and should be\n"
"             investigated carefully.\n"
"\n"
"        In case of an fatal error you may wish to consult the support at\n"
"        SFNT Finland Oy.\n");
    }

  ssh_util_uninit();
  return f;
}
Esempio n. 13
0
/***********************************************************************//**
 * @brief Test CTA IRF computation for diffuse source model
 *
 * Tests the IRF computation for the diffuse source model. This is done
 * by calling the GCTAObservation::model method which in turn calls the
 * GCTAResponse::irf_diffuse method. The test is done for a small counts
 * map to keep the test executing reasonably fast.
 ***************************************************************************/
void TestGCTAResponse::test_response_irf_diffuse(void)
{
    // Set reference value
    double ref = 13803.800313356;

    // Set parameters
    double src_ra  = 201.3651;
    double src_dec = -43.0191;
    int    nebins  = 5;

    // Setup pointing on Cen A
    GSkyDir skyDir;
    skyDir.radec_deg(src_ra, src_dec);
    GCTAPointing pnt;
    pnt.dir(skyDir);

    // Setup skymap (10 energy layers)
    GSkymap map("CAR", "CEL", src_ra, src_dec, 0.5, 0.5, 10, 10, nebins);

    // Setup time interval
    GGti  gti;
    GTime tstart(0.0);
    GTime tstop(1800.0);
    gti.append(tstart, tstop);

    // Setup energy boundaries
    GEbounds ebounds;
    GEnergy  emin;
    GEnergy  emax;
    emin.TeV(0.1);
    emax.TeV(100.0);
    ebounds.setlog(emin, emax, nebins);

    // Setup event cube centered on Cen A
    GCTAEventCube cube(map, ebounds, gti);

    // Setup dummy CTA observation
    GCTAObservation obs;
    obs.ontime(1800.0);
    obs.livetime(1600.0);
    obs.deadc(1600.0/1800.0);
    obs.response(cta_irf, cta_caldb);
    obs.events(&cube);
    obs.pointing(pnt);

    // Load model for IRF computation
    GModels models(cta_rsp_xml);

    // Reset sum
    double sum = 0.0;

    // Iterate over all bins in event cube
    for (int i = 0; i < obs.events()->size(); ++i) {

        // Get event pointer
        const GEventBin* bin = (*(static_cast<const GEventCube*>(obs.events())))[i];

        // Get model and add to sum
        double model = obs.model(models, *bin, NULL) * bin->size();
        sum += model;

    }

    // Test sum
    test_value(sum, ref, 1.0e-5, "Diffuse IRF computation");

    // Return
    return;
}
Esempio n. 14
0
void draw_volume(ARegion *ar, GPUTexture *tex, float *min, float *max, int res[3], float dx, GPUTexture *tex_shadow)
{
	RegionView3D *rv3d= ar->regiondata;

	float viewnormal[3];
	int i, j, n, good_index;
	float d /*, d0 */ /* UNUSED */, dd, ds;
	float *points = NULL;
	int numpoints = 0;
	float cor[3] = {1.,1.,1.};
	int gl_depth = 0, gl_blend = 0;

	/* draw slices of smoke is adapted from c++ code authored by: Johannes Schmid and Ingemar Rask, 2006, [email protected] */
	float cv[][3] = {
		{1.0f, 1.0f, 1.0f}, {-1.0f, 1.0f, 1.0f}, {-1.0f, -1.0f, 1.0f}, {1.0f, -1.0f, 1.0f},
		{1.0f, 1.0f, -1.0f}, {-1.0f, 1.0f, -1.0f}, {-1.0f, -1.0f, -1.0f}, {1.0f, -1.0f, -1.0f}
	};

	// edges have the form edges[n][0][xyz] + t*edges[n][1][xyz]
	float edges[12][2][3] = {
		{{1.0f, 1.0f, -1.0f}, {0.0f, 0.0f, 2.0f}},
		{{-1.0f, 1.0f, -1.0f}, {0.0f, 0.0f, 2.0f}},
		{{-1.0f, -1.0f, -1.0f}, {0.0f, 0.0f, 2.0f}},
		{{1.0f, -1.0f, -1.0f}, {0.0f, 0.0f, 2.0f}},

		{{1.0f, -1.0f, 1.0f}, {0.0f, 2.0f, 0.0f}},
		{{-1.0f, -1.0f, 1.0f}, {0.0f, 2.0f, 0.0f}},
		{{-1.0f, -1.0f, -1.0f}, {0.0f, 2.0f, 0.0f}},
		{{1.0f, -1.0f, -1.0f}, {0.0f, 2.0f, 0.0f}},

		{{-1.0f, 1.0f, 1.0f}, {2.0f, 0.0f, 0.0f}},
		{{-1.0f, -1.0f, 1.0f}, {2.0f, 0.0f, 0.0f}},
		{{-1.0f, -1.0f, -1.0f}, {2.0f, 0.0f, 0.0f}},
		{{-1.0f, 1.0f, -1.0f}, {2.0f, 0.0f, 0.0f}}
	};

	/* Fragment program to calculate the view3d of smoke */
	/* using 2 textures, density and shadow */
	const char *text = "!!ARBfp1.0\n"
					"PARAM dx = program.local[0];\n"
					"PARAM darkness = program.local[1];\n"
					"PARAM f = {1.442695041, 1.442695041, 1.442695041, 0.01};\n"
					"TEMP temp, shadow, value;\n"
					"TEX temp, fragment.texcoord[0], texture[0], 3D;\n"
					"TEX shadow, fragment.texcoord[0], texture[1], 3D;\n"
					"MUL value, temp, darkness;\n"
					"MUL value, value, dx;\n"
					"MUL value, value, f;\n"
					"EX2 temp, -value.r;\n"
					"SUB temp.a, 1.0, temp.r;\n"
					"MUL temp.r, temp.r, shadow.r;\n"
					"MUL temp.g, temp.g, shadow.r;\n"
					"MUL temp.b, temp.b, shadow.r;\n"
					"MOV result.color, temp;\n"
					"END\n";
	GLuint prog;

	
	float size[3];

	if(!tex) {
		printf("Could not allocate 3D texture for 3D View smoke drawing.\n");
		return;
	}

	tstart();

	sub_v3_v3v3(size, max, min);

	// maxx, maxy, maxz
	cv[0][0] = max[0];
	cv[0][1] = max[1];
	cv[0][2] = max[2];
	// minx, maxy, maxz
	cv[1][0] = min[0];
	cv[1][1] = max[1];
	cv[1][2] = max[2];
	// minx, miny, maxz
	cv[2][0] = min[0];
	cv[2][1] = min[1];
	cv[2][2] = max[2];
	// maxx, miny, maxz
	cv[3][0] = max[0];
	cv[3][1] = min[1];
	cv[3][2] = max[2];

	// maxx, maxy, minz
	cv[4][0] = max[0];
	cv[4][1] = max[1];
	cv[4][2] = min[2];
	// minx, maxy, minz
	cv[5][0] = min[0];
	cv[5][1] = max[1];
	cv[5][2] = min[2];
	// minx, miny, minz
	cv[6][0] = min[0];
	cv[6][1] = min[1];
	cv[6][2] = min[2];
	// maxx, miny, minz
	cv[7][0] = max[0];
	cv[7][1] = min[1];
	cv[7][2] = min[2];

	copy_v3_v3(edges[0][0], cv[4]); // maxx, maxy, minz
	copy_v3_v3(edges[1][0], cv[5]); // minx, maxy, minz
	copy_v3_v3(edges[2][0], cv[6]); // minx, miny, minz
	copy_v3_v3(edges[3][0], cv[7]); // maxx, miny, minz

	copy_v3_v3(edges[4][0], cv[3]); // maxx, miny, maxz
	copy_v3_v3(edges[5][0], cv[2]); // minx, miny, maxz
	copy_v3_v3(edges[6][0], cv[6]); // minx, miny, minz
	copy_v3_v3(edges[7][0], cv[7]); // maxx, miny, minz

	copy_v3_v3(edges[8][0], cv[1]); // minx, maxy, maxz
	copy_v3_v3(edges[9][0], cv[2]); // minx, miny, maxz
	copy_v3_v3(edges[10][0], cv[6]); // minx, miny, minz
	copy_v3_v3(edges[11][0], cv[5]); // minx, maxy, minz

	// printf("size x: %f, y: %f, z: %f\n", size[0], size[1], size[2]);
	// printf("min[2]: %f, max[2]: %f\n", min[2], max[2]);

	edges[0][1][2] = size[2];
	edges[1][1][2] = size[2];
	edges[2][1][2] = size[2];
	edges[3][1][2] = size[2];

	edges[4][1][1] = size[1];
	edges[5][1][1] = size[1];
	edges[6][1][1] = size[1];
	edges[7][1][1] = size[1];

	edges[8][1][0] = size[0];
	edges[9][1][0] = size[0];
	edges[10][1][0] = size[0];
	edges[11][1][0] = size[0];

	glGetBooleanv(GL_BLEND, (GLboolean *)&gl_blend);
	glGetBooleanv(GL_DEPTH_TEST, (GLboolean *)&gl_depth);

	glLoadMatrixf(rv3d->viewmat);
	// glMultMatrixf(ob->obmat);	

	glDepthMask(GL_FALSE);
	glDisable(GL_DEPTH_TEST);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	/*
	printf("Viewinv:\n");
	printf("%f, %f, %f\n", rv3d->viewinv[0][0], rv3d->viewinv[0][1], rv3d->viewinv[0][2]);
	printf("%f, %f, %f\n", rv3d->viewinv[1][0], rv3d->viewinv[1][1], rv3d->viewinv[1][2]);
	printf("%f, %f, %f\n", rv3d->viewinv[2][0], rv3d->viewinv[2][1], rv3d->viewinv[2][2]);
	*/

	// get view vector
	copy_v3_v3(viewnormal, rv3d->viewinv[2]);
	normalize_v3(viewnormal);

	// find cube vertex that is closest to the viewer
	for (i=0; i<8; i++) {
		float x,y,z;

		x = cv[i][0] - viewnormal[0];
		y = cv[i][1] - viewnormal[1];
		z = cv[i][2] - viewnormal[2];

		if ((x>=min[0])&&(x<=max[0])
			&&(y>=min[1])&&(y<=max[1])
			&&(z>=min[2])&&(z<=max[2])) {
			break;
		}
	}

	if(i >= 8) {
		/* fallback, avoid using buffer over-run */
		i= 0;
	}

	// printf("i: %d\n", i);
	// printf("point %f, %f, %f\n", cv[i][0], cv[i][1], cv[i][2]);

	if (GL_TRUE == glewIsSupported("GL_ARB_fragment_program"))
	{
		glEnable(GL_FRAGMENT_PROGRAM_ARB);
		glGenProgramsARB(1, &prog);

		glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, prog);
		glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, (GLsizei)strlen(text), text);

		// cell spacing
		glProgramLocalParameter4fARB (GL_FRAGMENT_PROGRAM_ARB, 0, dx, dx, dx, 1.0);
		// custom parameter for smoke style (higher = thicker)
		glProgramLocalParameter4fARB (GL_FRAGMENT_PROGRAM_ARB, 1, 7.0, 7.0, 7.0, 1.0);
	}
	else
		printf("Your gfx card does not support 3D View smoke drawing.\n");

	GPU_texture_bind(tex, 0);
	if(tex_shadow)
		GPU_texture_bind(tex_shadow, 1);
	else
		printf("No volume shadow\n");

	if (!GPU_non_power_of_two_support()) {
		cor[0] = (float)res[0]/(float)larger_pow2(res[0]);
		cor[1] = (float)res[1]/(float)larger_pow2(res[1]);
		cor[2] = (float)res[2]/(float)larger_pow2(res[2]);
	}

	// our slices are defined by the plane equation a*x + b*y +c*z + d = 0
	// (a,b,c), the plane normal, are given by viewdir
	// d is the parameter along the view direction. the first d is given by
	// inserting previously found vertex into the plane equation

	/* d0 = (viewnormal[0]*cv[i][0] + viewnormal[1]*cv[i][1] + viewnormal[2]*cv[i][2]); */ /* UNUSED */
	ds = (ABS(viewnormal[0])*size[0] + ABS(viewnormal[1])*size[1] + ABS(viewnormal[2])*size[2]);
	dd = 0.05; // ds/512.0f;
	n = 0;
	good_index = i;

	// printf("d0: %f, dd: %f, ds: %f\n\n", d0, dd, ds);

	points = MEM_callocN(sizeof(float)*12*3, "smoke_points_preview");

	while(1) {
		float p0[3];
		float tmp_point[3], tmp_point2[3];

		if(dd*(float)n > ds)
			break;

		copy_v3_v3(tmp_point, viewnormal);
		mul_v3_fl(tmp_point, -dd*((ds/dd)-(float)n));
		add_v3_v3v3(tmp_point2, cv[good_index], tmp_point);
		d = dot_v3v3(tmp_point2, viewnormal);

		// printf("my d: %f\n", d);

		// intersect_edges returns the intersection points of all cube edges with
		// the given plane that lie within the cube
		numpoints = intersect_edges(points, viewnormal[0], viewnormal[1], viewnormal[2], -d, edges);

		// printf("points: %d\n", numpoints);

		if (numpoints > 2) {
			copy_v3_v3(p0, points);

			// sort points to get a convex polygon
			for(i = 1; i < numpoints - 1; i++)
			{
				for(j = i + 1; j < numpoints; j++)
				{
					if(!convex(p0, viewnormal, &points[j * 3], &points[i * 3]))
					{
						float tmp2[3];
						copy_v3_v3(tmp2, &points[j * 3]);
						copy_v3_v3(&points[j * 3], &points[i * 3]);
						copy_v3_v3(&points[i * 3], tmp2);
					}
				}
			}

			// printf("numpoints: %d\n", numpoints);
			glBegin(GL_POLYGON);
			glColor3f(1.0, 1.0, 1.0);
			for (i = 0; i < numpoints; i++) {
				glTexCoord3d((points[i * 3 + 0] - min[0] )*cor[0]/size[0], (points[i * 3 + 1] - min[1])*cor[1]/size[1], (points[i * 3 + 2] - min[2])*cor[2]/size[2]);
				glVertex3f(points[i * 3 + 0], points[i * 3 + 1], points[i * 3 + 2]);
			}
			glEnd();
		}
		n++;
	}

	tend();
	// printf ( "Draw Time: %f\n",( float ) tval() );

	if(tex_shadow)
		GPU_texture_unbind(tex_shadow);
	GPU_texture_unbind(tex);

	if(GLEW_ARB_fragment_program)
	{
		glDisable(GL_FRAGMENT_PROGRAM_ARB);
		glDeleteProgramsARB(1, &prog);
	}


	MEM_freeN(points);

	if(!gl_blend)
		glDisable(GL_BLEND);
	if(gl_depth)
	{
		glEnable(GL_DEPTH_TEST);
		glDepthMask(GL_TRUE);	
	}
}
Esempio n. 15
0
void FalconWallTest::runFunction()
{
	if(!m_falconDevice->runIOLoop())
		return;

	double *pos = m_falconDevice->getPosition();

	if(m_isInitializing)
	{
		if(!m_hasPrintedInitMsg)
		{
			std::cout << "Move the end effector out of the wall area" << std::endl;
			m_hasPrintedInitMsg = true;
		}
		if(((pos[m_axis] > m_axisBounds[m_axis]) && m_positiveForce) || ((pos[m_axis] < m_axisBounds[m_axis]) && !m_positiveForce))
		{
			std::cout << "Starting wall simulation... Press center button (circle button) to change direction of force..." << std::endl;
			m_isInitializing = false;
			tstart();
		}
		return;
	}

	//Cheap debounce
	if(m_falconDevice->getFalconGrip()->getDigitalInputs() & libnifalcon::FalconGripFourButton::BUTTON_3)
	{
		m_buttonDown = true;
	}
	else if(m_buttonDown)
	{
		m_buttonDown = false;
		std::cout << "Flipping force vector..." << std::endl;
		m_runClickCount = m_lastLoopCount;
		m_positiveForce = !m_positiveForce;
		m_hasPrintedInitMsg = false;
		m_isInitializing = true;
		return;
	}

	double force[3];

	double dist = 10000;
	int closest = -1, outside=3;

	// For each axis, check if the end effector is inside
	// the cube.  Record the distance to the closest wall.

	force[m_axis] = 0;
	if(((pos[m_axis] < m_axisBounds[m_axis]) && m_positiveForce) || ((pos[m_axis] > m_axisBounds[m_axis]) && !m_positiveForce))
	{
		double dA = pos[m_axis]-m_axisBounds[m_axis];
		dist = dA;
		closest = m_axis;
	}

	// If so, add a proportional force to kick it back
	// outside from the nearest wall.

	if (closest > -1)
		force[closest] = -m_stiffness*dist;
	m_falconDevice->setForce(force);
}
Esempio n. 16
0
/***********************************************************************//**
 * @brief Print event cube information
 *
 * @param[in] chatter Chattiness (defaults to NORMAL).
 * @return String containing event cube information.
 ***************************************************************************/
std::string GLATEventCube::print(const GChatter& chatter) const
{
    // Initialise result string
    std::string result;

    // Continue only if chatter is not silent
    if (chatter != SILENT) {

        // Append header
        result.append("=== GLATEventCube ===");

        // Append information
        result.append("\n"+gammalib::parformat("Number of elements") +
                      gammalib::str(size()));
        result.append("\n"+gammalib::parformat("Number of pixels"));
        result.append(gammalib::str(m_map.nx()) +
                      " x " +
                      gammalib::str(m_map.ny()));
        result.append("\n"+gammalib::parformat("Number of energy bins") +
                      gammalib::str(ebins()));
        result.append("\n"+gammalib::parformat("Number of events") +
                      gammalib::str(number()));

        // Append time interval
        result.append("\n"+gammalib::parformat("Time interval"));
        if (gti().size() > 0) {
            result.append(gammalib::str(tstart().secs()) +
                          " - " +
                          gammalib::str(tstop().secs())+" sec");
        }
        else {
            result.append("not defined");
        }

        // Append energy range
        result.append("\n"+gammalib::parformat("Energy range"));
        if (ebounds().size() > 0) {
            result.append(emin().print()+" - "+emax().print(chatter));
        }
        else {
            result.append("not defined");
        }

        // Append detailed information
        GChatter reduced_chatter = gammalib::reduce(chatter);
        if (reduced_chatter > SILENT) {

            // Append sky projection
            if (m_map.projection() != NULL) {
                result.append("\n"+m_map.projection()->print(reduced_chatter));
            }

            // Append source maps
            result.append("\n"+gammalib::parformat("Number of source maps"));
            result.append(gammalib::str(m_srcmap.size()));
            for (int i = 0; i < m_srcmap.size(); ++i) {
                result.append("\n"+gammalib::parformat(" "+m_srcmap_names[i]));
                result.append(gammalib::str(m_srcmap[i]->nx()));
                result.append(" x ");
                result.append(gammalib::str(m_srcmap[i]->ny()));
                result.append(" x ");
                result.append(gammalib::str(m_srcmap[i]->nmaps()));
            }

        }

    } // endif: chatter was not silent

    // Return result
    return result;
}
Esempio n. 17
0
/***********************************************************************//**
 * @brief Print spectrum
 *
 * @param[in] chatter Chattiness (defaults to NORMAL).
 * @return String containing spectrum
 ***************************************************************************/
std::string GMWLSpectrum::print(const GChatter& chatter) const
{
    // Initialise result string
    std::string result;

    // Continue only if chatter is not silent
    if (chatter != SILENT) {

        // Append header
        result.append("=== GMWLSpectrum ===");

        // Append information
        result.append("\n"+gammalib::parformat("Telescope")+m_telescope);
        result.append("\n"+gammalib::parformat("Instrument")+m_instrument);
        result.append("\n"+gammalib::parformat("Number of points"));
        result.append(gammalib::str(size()));
        result.append("\n"+gammalib::parformat("Time interval"));
        if (m_gti.size() > 0) {
            result.append(gammalib::str(tstart().secs())+" - ");
            result.append(gammalib::str(tstop().secs())+" sec");
        }
        else {
            result.append("not defined");
        }
        result.append("\n"+gammalib::parformat("Energy range"));
        if (m_ebounds.size() > 0) {
            result.append(emin().print()+" - "+emax().print());
        }
        else {
            result.append("not defined");
        }

        // EXPLICIT: Append spectral points
        if (chatter >= EXPLICIT) {
            for (int i = 0; i < size(); ++i) {

                // Build energy string
                std::string energy = m_data[i].m_eng.print();
                if (m_data[i].m_eng_err.MeV() > 0.0) {
                    energy += " +/- "+m_data[i].m_eng_err.print();
                }

                // Build flux string
                std::string flux = gammalib::str(m_data[i].m_flux);
                if (m_data[i].m_flux_err > 0.0) {
                    flux += " +/- "+gammalib::str(m_data[i].m_flux_err);
                }
                flux += " ph/cm2/s/MeV";

                // Append to string
                result.append("\n"+gammalib::parformat(energy));
                result.append(flux);

            } // endfor: looped over spectral points
            
        } // endif: EXPLICIT level

    } // endif: chatter was not silent
    
    // Return result
    return result;
}
Esempio n. 18
0
//  Geometry.
//
//++++++++++++++++++++++
void glwidget::create_geometry(){

    //
    glGenBuffers(2,_info._vbo_ids);

    /*
    //  Generate our vertices.
    //  (triangles).
    //
    QVector3D tstart(-1.8,1.8,0);
    qreal tstep=0.2;
    qreal toffset=0.05;
    int index=0;
    for(int r=0; r<19; r++){
        for(int c=0; c<19; c++){

            //  Vertex.
            //
            qreal cx = tstart.x() + tstep*c; qreal cy = tstart.y() + tstep*-r;
            _info._vertices.push_back( Vertex(cx-toffset,cy-toffset,0,1,     1.0f,0.0f,0.0f,1.0f) );
            _info._vertices.push_back( Vertex(cx+toffset,cy-toffset,0,1,     0.0f,1.0f,0.0f,1.0f) );
            _info._vertices.push_back( Vertex(cx,        cy+toffset,0,1,     0.0f,0.0f,1.0f,1.0f) );

            //  Glue.
            //
            _info._vertices.push_back( Vertex(0,0,0,1,    0,0,0,0) );
            _info._vertices.push_back( Vertex(0,0,0,1,    0,0,0,0) );
            _info._vertices.push_back( Vertex(0,0,0,1,    0,0,0,0) );

            //  Index.
            //
            _info._indices.push_back(index++);  _info._indices.push_back(index++);  _info._indices.push_back(index++);
            _info._indices.push_back(index++);  _info._indices.push_back(index++);  _info._indices.push_back(index++);
        }
    }
    _info._index_count=index;
    */


    //  Generate vertices.
    //  (piecharts).
    //
    QList<qreal> slice_percentages;
    slice_percentages.push_back(0.5);
    slice_percentages.push_back(0.2);
    slice_percentages.push_back(0.1);
    slice_percentages.push_back(0.1);
    slice_percentages.push_back(0.1);
    QVector2D tstart(1.9,1.9);
    qreal rand_0_1=0;
    int num_charts=200;
    for(int r=0; r<num_charts; r++){

        //  Random center.
        //
        rand_0_1 = qreal( qrand() / (RAND_MAX + 1.0) );
        qreal cx = tstart.x() * rand_0_1;
        rand_0_1 = qreal( qrand() / (RAND_MAX + 1.0) );
        qreal cy = tstart.y() * rand_0_1;

        //
        push_piechart( cx, cy, slice_percentages);
    }

    //
    _slider->setRange( 0, num_charts*_info._verts_in_single_chart );
    _slider->setSingleStep( _info._verts_in_single_chart );
    _slider->setPageStep( _info._verts_in_single_chart );
    _slider->setTickInterval( 5*_info._verts_in_single_chart );

    //
    check_error(20);

    //  Vertices.
    //
    glBindBuffer(GL_ARRAY_BUFFER, _info._vbo_ids[VBO_ELEMENT_VERTEX]);
    glBufferData(GL_ARRAY_BUFFER, _info._vertices.count() * sizeof(Vertex), &_info._vertices[0], GL_STATIC_DRAW);

    //  Indices.
    //
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _info._vbo_ids[VBO_ELEMENT_INDICES]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, _info._indices.count() * sizeof(GLushort), &_info._indices[0], GL_STATIC_DRAW);

    //
    check_error(21);

    //  How many vertices.
    //
    qDebug() << QString("num vertices [val:%1]")
                .arg(_info._vertices.count());

    //  How many megabytes is our vbo.
    //
    int nBufferSize = 0;
    glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &nBufferSize);
    int originalVertexArraySize = ( nBufferSize / sizeof(Vertex) );
    qDebug() << QString("vbo size [size:%1mb]")
                .arg( (qreal)originalVertexArraySize / (qreal)1000000.0 );

    //
    _info._ready_to_draw=true;
    updateGL();
}
Esempio n. 19
0
/***********************************************************************//**
 * @brief Set MC pre-computation cache
 *
 * @param[in] tmin Minimum time of time interval.
 * @param[in] tmax Maximum time of time interval.
 *
 * This method sets up an array of indices and the cumulative distribution
 * function needed for MC simulations.
 ***************************************************************************/
void GModelTemporalLightCurve::mc_update(const GTime& tmin,
                                   const GTime& tmax) const
{
    // Get light curve normalisation value to see whether it has changed
    double norm = m_norm.value();

    // Update the cache only if the time interval or normalisation has changed
    if (tmin != m_mc_tmin || tmax != m_mc_tmax || norm != m_mc_norm) {
    
        // Store new time interval and normalisation value
        m_mc_tmin = tmin;
        m_mc_tmax = tmax;
        m_mc_norm = norm;
        
        // Initialise cache
        m_mc_eff_duration = 0.0;
        m_mc_cum.clear();
        m_mc_slope.clear();
        m_mc_offset.clear();
        m_mc_time.clear();
        m_mc_dt.clear();

        // Initialise duration
        double duration = 0.0;

        // Continue only if time interval overlaps with temporal file function
        // and if time interval is valid
        if (tmax > m_tmin && tmin < m_tmax && tmax > tmin) {

            // Loop over all intervals between the nodes
            for (int i = 0; i < m_nodes.size()-1; ++i) {

                // Get start and stop time of interval
                GTime tstart(m_nodes[i], m_timeref);
                GTime tstop(m_nodes[i+1], m_timeref);

                // Make sure that we only consider the interval that overlaps
                // with the requested time interval
                if (tmin > tstart) {
                    tstart = tmin;
                }
                if (tmax < tstop) {
                    tstop = tmax;
                }

                // If time interval is empty then skip this node
                if (tstart >= tstop) {
                    continue;
                }

                // Evaluate rate at start and stop time
                double rstart = eval(tstart);
                double rstop  = eval(tstop);

                // Compute mean normalization for this interval
                double norm = 0.5 * (rstart + rstop);

                // Compute integral for this interval
                double dt  = tstop - tstart;
                double cum = norm * dt;

                // Compute slope, offset and start time of interval
                double slope  = (rstop - rstart) / dt;
                double offset = rstart;
                double renorm = (0.5 * slope * dt + offset) * dt;
                slope  /= renorm;
                offset /= renorm;

                // Update effective duration and real duration
                m_mc_eff_duration += cum;
                duration          += dt;

                // Put mean normalization and integral on stack
                m_mc_cum.push_back(cum);
                m_mc_slope.push_back(slope);
                m_mc_offset.push_back(offset);
                m_mc_time.push_back(tstart.convert(m_timeref));
                m_mc_dt.push_back(dt);

            } // endfor: next interval

            // Build cumulative distribution
            for (int i = 1; i < m_mc_cum.size(); ++i) {
                m_mc_cum[i] += m_mc_cum[i-1];
            }
            double norm = m_mc_cum[m_mc_cum.size()-1];
            for (int i = 0; i < m_mc_cum.size(); ++i) {
                m_mc_cum[i] /= norm;
            }

        } // endif: time interval overlaps
        
    } // endif: Update was required

    // Return
    return;
}
Esempio n. 20
0
void FalconSphereTest::runFunction()
{
	if(!m_falconDevice->runIOLoop())
		return;

	std::array<double, 3> pos = m_falconDevice->getPosition();

	if(m_isInitializing)
	{
		if(!m_hasPrintedInitMsg)
		{
			std::cout << "Move the end effector all the way out" << std::endl;
			m_hasPrintedInitMsg = true;
		}
		if(pos[2] > .170)
		{
			std::cout << "Starting sphere simulation..." << std::endl;
			m_isInitializing = false;
			tstart();
		} else {
			m_oldpos = pos;
		}
		m_lastLoopCount = m_falconDevice->getFalconFirmware()->getLoopCount();
		return;
	}

	// increase radius
	if(m_falconDevice->getFalconGrip()->getDigitalInputs() 
	   & libnifalcon::FalconGripFourButton::PLUS_BUTTON)
	{
		m_plusButtonDown = true;
	}
	else if(m_plusButtonDown)
	{
		m_plusButtonDown = false;
		m_radius += 0.002;
		std::cout << "Plus button pressed... radius now:" << m_radius << std::endl;
		return;
	}

	// decrease radius
	if(m_falconDevice->getFalconGrip()->getDigitalInputs() 
	   & libnifalcon::FalconGripFourButton::MINUS_BUTTON)
	{
		m_minusButtonDown = true;
	}
	else if(m_minusButtonDown)
	{
		m_minusButtonDown = false;
		m_radius -= 0.002;
		std::cout << "Minus button pressed... radius now:" << m_radius << std::endl;
		return;
	}

	if(m_falconDevice->getFalconGrip()->getDigitalInputs() 
	   & libnifalcon::FalconGripFourButton::FORWARD_BUTTON)
	{
		m_forwardButtonDown = true;
	} else{
		m_forwardButtonDown = false;
	}

	// make sphere soft radius or "slippery"
	if(m_falconDevice->getFalconGrip()->getDigitalInputs() 
	   & libnifalcon::FalconGripFourButton::CENTER_BUTTON)
	{
		if(m_forwardButtonDown)
		{
			m_stiffness = -300.0;
                } 
                else 
                {
			m_stiffness = 1000.0;
                }
	} else{
                if(m_forwardButtonDown)
                {
			m_stiffness = 500.0;
		} 
		else 
		{
			m_stiffness = 100.0;
		}
	}


	std::array<double, 3> force;
	force[0] = 0.0;
	force[1] = 0.0;
	force[2] = 0.0;
	
	// offset z 
	pos[2] -= 0.11;
	
	double dist = sqrt(pos[0]*pos[0]+pos[1]*pos[1]+pos[2]*pos[2]);

	if (dist < m_radius) {
		if (m_forwardButtonDown) {
			force[0] = (m_oldpos[0] - pos[0]) * m_stiffness * 10.0;
			force[1] = (m_oldpos[1] - pos[1]) * m_stiffness * 10.0;
			force[2] = (m_oldpos[2] - pos[2]) * m_stiffness * 10.0;
		} else {
			force[0] = (pos[0] / dist) * (m_radius - dist) * m_stiffness;
			force[1] = (pos[1] / dist) * (m_radius - dist) * m_stiffness;
			force[2] = (pos[2] / dist) * (m_radius - dist) * m_stiffness;
		} 
	}
        // dampen position update to remove noise.
	m_oldpos[0] = 0.4*m_oldpos[0]+ 0.6*pos[0];
	m_oldpos[1] = 0.4*m_oldpos[1]+ 0.6*pos[1];
	m_oldpos[2] = 0.4*m_oldpos[2]+ 0.6*pos[2];
	m_falconDevice->setForce(force);
}
Esempio n. 21
0
unsigned long WINAPI threadrun(void * var)
{
	unsigned i;
	char *p = (char *)var;

	if(equal(p,"A")) {		// Adult
#ifdef _WIN32
		HANDLE pipeA, pipeB;
#else
		struct sembuf sop;
		int pipeA, pipeB;
		int i;
#endif

#ifdef _WIN32
		pipeA = CreateNamedPipe(pipeAdult,
								PIPE_ACCESS_DUPLEX,
								PIPE_TYPE_BYTE,
								2,
								128,
								128,
								INFINITE,
								NULL);
		if(pipeA == INVALID_HANDLE_VALUE) {
			printf("CreateNamedPipe <%s> failed ERROR=%d\n", pipeAdult,Errno);
			ExitThread(1);
		}
		pipeB = pipeA;
		//
		// ConnectNamedPipe()
		//
		if(!ConnectNamedPipe(pipeA, NULL)) {
			printf("ConnectNamePipe ERROR: err=%d\n",Errno);
			ExitThread(1);
		}
#else
		pipeA = pipeAfds[1];
		pipeB = pipeBfds[0];
#endif
		tstart();
		//
		// ADULT: Writes the first byte.
		//
		for(i = 0; i < maxcount; i++) {
			counter++;
			if(!Put(pipeA))
					break;
			if(!Get(pipeB))
					break;
		}
		tend();
		double t = tval();

		printf("%d pipe/thread Context switches in %7.3f sec ",
			maxcount, t);

		printf("%7.3f usec/cswitch",
			(t*1e6)/maxcount);
		printf("\n");
#ifdef _WIN32
		ExitThread(0);
#else
		sop.sem_num = 0;
		sop.sem_op  = -1;
		sop.sem_flg = 0;
		if(semop(sema, &sop, 1) == -1) {
			printf("semop failed (waiting for threads): err=%d\n", Errno);
			return 1;
		}
#endif
	}
	else {
#ifdef _WIN32
		HANDLE pipeA, pipeB, pipeC;
#else
		struct sembuf sop;
		int pipeA, pipeB;
		int i;
#endif
#ifdef _WIN32
		//
		//
		// Here we call OpenNamedPipe or CreateFile
		//
        Sleep(1);
		pipeC = CreateFile(pipeAdult,
						GENERIC_READ|GENERIC_WRITE,
						FILE_SHARE_READ|FILE_SHARE_WRITE,
						NULL,
						OPEN_EXISTING,
						FILE_ATTRIBUTE_NORMAL,
						NULL);
		if(pipeC == INVALID_HANDLE_VALUE) {
			printf("CreateFile for pipe failed: err=%d\n",
					Errno);
			ExitThread(1);
		}
		pipeA = pipeB = pipeC;
#else
		pipeA = pipeAfds[0];
		pipeB = pipeBfds[1];
#endif

		//
		// CHILD:
		// The ALREADY_EXISTS detector will wait for the
		// thing to be incremented. The other guy will start
		// this off.
		//
		// Release pipeC and waitfor pipeA
		//
		tstart2();
		for(i = 0; i < maxcount; i++) {
			if(!Get(pipeA))
					break;
			if(!Put(pipeB))
					break;
		}
		tend2();

		double t = tval2();


		printf("%d pipe/thread Context switches in %7.3f sec ",
			maxcount, t);

		printf("%7.3f usec/cswitch",
			(t*1e6)/maxcount);
		printf("\n");
#ifdef _WIN32
		ExitThread(0);
#else
		sop.sem_num = 0;
		sop.sem_op  = -1;
		sop.sem_flg = 0;
		if(semop(sema, &sop, 1) == -1) {
			printf("semop failed (waiting for threads): err=%d\n", Errno);
			return 1;
		}
#endif
	}
	return 0;
}
Esempio n. 22
0
File: smoke.c Progetto: jinjoh/NOOR
void smokeModifier_do(SmokeModifierData *smd, Scene *scene, Object *ob, DerivedMesh *dm, int useRenderParams, int isFinalCalc)
{	
	if((smd->type & MOD_SMOKE_TYPE_FLOW))
	{
		if(scene->r.cfra >= smd->time)
			smokeModifier_init(smd, ob, scene, dm);

		if(scene->r.cfra > smd->time)
		{
			// XXX TODO
			smd->time = scene->r.cfra;

			// rigid movement support
			/*
			Mat4CpyMat4(smd->flow->mat_old, smd->flow->mat);
			Mat4CpyMat4(smd->flow->mat, ob->obmat);
			*/
		}
		else if(scene->r.cfra < smd->time)
		{
			smd->time = scene->r.cfra;
			smokeModifier_reset(smd);
		}
	}
	else if(smd->type & MOD_SMOKE_TYPE_COLL)
	{
		if(scene->r.cfra >= smd->time)
			smokeModifier_init(smd, ob, scene, dm);

		if(scene->r.cfra > smd->time)
		{
			// XXX TODO
			smd->time = scene->r.cfra;
			
			if(smd->coll->dm)
				smd->coll->dm->release(smd->coll->dm);

			smd->coll->dm = CDDM_copy(dm);

			// rigid movement support
			Mat4CpyMat4(smd->coll->mat_old, smd->coll->mat);
			Mat4CpyMat4(smd->coll->mat, ob->obmat);
		}
		else if(scene->r.cfra < smd->time)
		{
			smd->time = scene->r.cfra;
			smokeModifier_reset(smd);
		}
	}
	else if(smd->type & MOD_SMOKE_TYPE_DOMAIN)
	{
		SmokeDomainSettings *sds = smd->domain;
		float light[3];	
		PointCache *cache = NULL;
		PTCacheID pid;
		PointCache *cache_wt = NULL;
		PTCacheID pid_wt;
		int startframe, endframe, framenr;
		float timescale;
		int cache_result = 0, cache_result_wt = 0;

		framenr = scene->r.cfra;

		// printf("time: %d\n", scene->r.cfra);

		if(framenr == smd->time)
			return;

		cache = sds->point_cache[0];
		BKE_ptcache_id_from_smoke(&pid, ob, smd);
		BKE_ptcache_id_time(&pid, scene, framenr, &startframe, &endframe, &timescale);

		cache_wt = sds->point_cache[1];
		BKE_ptcache_id_from_smoke_turbulence(&pid_wt, ob, smd);

		if(!smd->domain->fluid)
		{
			BKE_ptcache_id_reset(scene, &pid, PTCACHE_RESET_OUTDATED);
			BKE_ptcache_id_reset(scene, &pid_wt, PTCACHE_RESET_OUTDATED);
		}

		if(framenr < startframe)
			return;

		if(framenr > endframe)
			return;

		if(!smd->domain->fluid && (framenr != startframe))
			return;

		// printf("startframe: %d, framenr: %d\n", startframe, framenr);

		if(!smokeModifier_init(smd, ob, scene, dm))
		{
			printf("bad smokeModifier_init\n");
			return;
		}

		/* try to read from cache */
		cache_result =  BKE_ptcache_read_cache(&pid, (float)framenr, scene->r.frs_sec);
		// printf("cache_result: %d\n", cache_result);

		if(cache_result == PTCACHE_READ_EXACT) 
		{
			cache->flag |= PTCACHE_SIMULATION_VALID;
			cache->simframe= framenr;

			if(sds->wt)
			{
				cache_result_wt = BKE_ptcache_read_cache(&pid_wt, (float)framenr, scene->r.frs_sec);
				
				if(cache_result_wt == PTCACHE_READ_EXACT) 
				{
					cache_wt->flag |= PTCACHE_SIMULATION_VALID;
					cache_wt->simframe= framenr;
				}
			}
			return;
		}

		tstart();

		smoke_calc_domain(scene, ob, smd);
		
		// set new time
		smd->time = scene->r.cfra;

		/* do simulation */

		// low res
		cache->flag |= PTCACHE_SIMULATION_VALID;
		cache->simframe= framenr;

		// simulate the actual smoke (c++ code in intern/smoke)
		// DG: interesting commenting this line + deactivating loading of noise files
		if(framenr!=startframe)
		{
			if(sds->flags & MOD_SMOKE_DISSOLVE)
				smoke_dissolve(sds->fluid, sds->diss_speed, sds->flags & MOD_SMOKE_DISSOLVE_LOG);
			smoke_step(sds->fluid, smd->time);
		}

		// create shadows before writing cache so we get nice shadows for sstartframe, too
		if(get_lamp(scene, light))
			smoke_calc_transparency(sds->shadow, smoke_get_density(sds->fluid), sds->p0, sds->p1, sds->res, sds->dx, light, calc_voxel_transp, -7.0*sds->dx);
	
		BKE_ptcache_write_cache(&pid, framenr);

		if(sds->wt)
		{
			if(framenr!=startframe)
			{
				if(sds->flags & MOD_SMOKE_DISSOLVE)
					smoke_dissolve_wavelet(sds->wt, sds->diss_speed, sds->flags & MOD_SMOKE_DISSOLVE_LOG);
				smoke_turbulence_step(sds->wt, sds->fluid);
			}

			cache_wt->flag |= PTCACHE_SIMULATION_VALID;
			cache_wt->simframe= framenr;
			BKE_ptcache_write_cache(&pid_wt, framenr);
		}

		tend();
		printf ( "Frame: %d, Time: %f\n", (int)smd->time, ( float ) tval() );
	}
}