/** Execute the algorithm.
 */
void VesuvioL1ThetaResolution::exec() {
  // Load the instrument workspace
  loadInstrument();

  const std::string l1DistributionWsName = getPropertyValue("L1Distribution");
  const std::string thetaDistributionWsName =
      getPropertyValue("ThetaDistribution");
  const size_t numHist = m_instWorkspace->getNumberHistograms();
  const int numEvents = getProperty("NumEvents");

  // Create output workspace of resolution
  m_outputWorkspace =
      WorkspaceFactory::Instance().create("Workspace2D", 4, numHist, numHist);

  // Set vertical axis to statistic labels
  auto specAxis = new TextAxis(4);
  specAxis->setLabel(0, "l1_Mean");
  specAxis->setLabel(1, "l1_StdDev");
  specAxis->setLabel(2, "theta_Mean");
  specAxis->setLabel(3, "theta_StdDev");
  m_outputWorkspace->replaceAxis(1, specAxis);

  // Set X axis to spectrum numbers
  m_outputWorkspace->getAxis(0)->setUnit("Label");
  auto xAxis = boost::dynamic_pointer_cast<Units::Label>(
      m_outputWorkspace->getAxis(0)->unit());
  if (xAxis)
    xAxis->setLabel("Spectrum Number");

  // Create output workspaces for distributions if required
  if (!l1DistributionWsName.empty()) {
    m_l1DistributionWs = WorkspaceFactory::Instance().create(
        m_instWorkspace, numHist, numEvents, numEvents);

    // Set Y axis
    m_l1DistributionWs->setYUnitLabel("Events");

    // Set X axis
    auto distributionXAxis = m_l1DistributionWs->getAxis(0);
    distributionXAxis->setUnit("Label");
    auto labelUnit =
        boost::dynamic_pointer_cast<Units::Label>(distributionXAxis->unit());
    if (labelUnit)
      labelUnit->setLabel("l1");
  }

  if (!thetaDistributionWsName.empty()) {
    m_thetaDistributionWs = WorkspaceFactory::Instance().create(
        m_instWorkspace, numHist, numEvents, numEvents);

    // Set Y axis
    m_thetaDistributionWs->setYUnitLabel("Events");

    // Set X axis
    auto distributionXAxis = m_thetaDistributionWs->getAxis(0);
    distributionXAxis->setUnit("Label");
    auto labelUnit =
        boost::dynamic_pointer_cast<Units::Label>(distributionXAxis->unit());
    if (labelUnit)
      labelUnit->setLabel("theta");
  }

  // Set up progress reporting
  Progress prog(this, 0.0, 1.0, numHist);
  const int seed(getProperty("Seed"));
  std::mt19937 randEngine(static_cast<std::mt19937::result_type>(seed));
  std::uniform_real_distribution<> flatDistrib(0.0, 1.0);
  std::function<double()> flatVariateGen(
      [&randEngine, &flatDistrib]() { return flatDistrib(randEngine); });

  const auto &spectrumInfo = m_instWorkspace->spectrumInfo();
  // Loop for all detectors
  for (size_t i = 0; i < numHist; i++) {
    std::vector<double> l1;
    std::vector<double> theta;
    const auto &det = spectrumInfo.detector(i);

    // Report progress
    std::stringstream report;
    report << "Detector " << det.getID();
    prog.report(report.str());
    g_log.information() << "Detector ID " << det.getID() << '\n';

    // Do simulation
    calculateDetector(det, flatVariateGen, l1, theta);

    // Calculate statistics for L1 and theta
    Statistics l1Stats = getStatistics(l1);
    Statistics thetaStats = getStatistics(theta);

    g_log.information() << "l0: mean=" << l1Stats.mean
                        << ", std.dev.=" << l1Stats.standard_deviation
                        << "\ntheta: mean=" << thetaStats.mean
                        << ", std.dev.=" << thetaStats.standard_deviation
                        << '\n';

    // Set values in output workspace
    const int specNo = m_instWorkspace->getSpectrum(i).getSpectrumNo();
    m_outputWorkspace->mutableX(0)[i] = specNo;
    m_outputWorkspace->mutableX(1)[i] = specNo;
    m_outputWorkspace->mutableX(2)[i] = specNo;
    m_outputWorkspace->mutableX(3)[i] = specNo;
    m_outputWorkspace->mutableY(0)[i] = l1Stats.mean;
    m_outputWorkspace->mutableY(1)[i] = l1Stats.standard_deviation;
    m_outputWorkspace->mutableY(2)[i] = thetaStats.mean;
    m_outputWorkspace->mutableY(3)[i] = thetaStats.standard_deviation;

    // Process data for L1 distribution
    if (m_l1DistributionWs) {
      auto &x = m_l1DistributionWs->mutableX(i);

      std::sort(l1.begin(), l1.end());
      std::copy(l1.begin(), l1.end(), x.begin());

      m_l1DistributionWs->mutableY(i) = 1.0;

      auto &spec = m_l1DistributionWs->getSpectrum(i);
      spec.setSpectrumNo(specNo);
      spec.addDetectorID(det.getID());
    }

    // Process data for theta distribution
    if (m_thetaDistributionWs) {
      auto &x = m_thetaDistributionWs->mutableX(i);

      std::sort(theta.begin(), theta.end());
      std::copy(theta.begin(), theta.end(), x.begin());

      m_thetaDistributionWs->mutableY(i) = 1.0;

      auto &spec = m_thetaDistributionWs->getSpectrum(i);
      spec.setSpectrumNo(specNo);
      spec.addDetectorID(det.getID());
    }
  }

  // Process the L1 distribution workspace
  if (m_l1DistributionWs) {
    const double binWidth = getProperty("L1BinWidth");
    setProperty("L1Distribution",
                processDistribution(m_l1DistributionWs, binWidth));
  }

  // Process the theta distribution workspace
  if (m_thetaDistributionWs) {
    const double binWidth = getProperty("ThetaBinWidth");
    setProperty("ThetaDistribution",
                processDistribution(m_thetaDistributionWs, binWidth));
  }

  setProperty("OutputWorkspace", m_outputWorkspace);
}
예제 #2
0
파일: warmup2.c 프로젝트: adityadani/CS-402
void *arrivalThread(void *id)
{
	My402ListElem *elem;
	Packet *pkt;
	int i;
	long pkt_sleep, pkt_service;
	int pkt_token;
	long sleep_time;
	long prev_pkt_time=0, instant_time;
	long avg_ia=0;


	for (i=0;i<num_packets;i++) {


		getStatistics(&pkt_sleep,&pkt_service,&pkt_token,i);		
		if(pkt_sleep > 10000000)
			pkt_sleep = 10000000;
		if(pkt_service > 1000000)
			pkt_service = 10000000;
				
		taend=getinstanttime();
		sleep_time = pkt_sleep - (taend-tastart);
		usleep(sleep_time);
		
		// Creating the Packet
		
		pkt = (Packet *)malloc(sizeof(struct tagPacket));
		pkt->pkt_id = i;
		pkt->num_tokens = pkt_token;
		pkt->service_time = pkt_service;

		pkt->sys_enter = tastart = getinstanttime();
		if(pkt->num_tokens > B) {
			// Drop the packet
			pkts_to_arrive--;
			PrintStat(getinstanttime());
			fprintf(stdout, "p%d arrives, Invalid token requirement, p%d Dropped!!\n", 
				pkt->pkt_id, pkt->pkt_id);
			continue;
		}
		else {
			instant_time = getinstanttime();
			if(prev_pkt_time==0) {
				prev_pkt_time = pkt->inter_arrival_time = (instant_time - temulation_start);
				prev_pkt_time = instant_time;
			}
			else {
				pkt->inter_arrival_time = instant_time - prev_pkt_time;
				prev_pkt_time = instant_time;
			}
			PrintStat(instant_time);
			avg_ia += pkt->inter_arrival_time;
			fprintf(stdout, "p%d arrives, needs %d tokens, inter-arrival time = %.3fms\n",
				pkt->pkt_id,pkt->num_tokens,(double)(pkt->inter_arrival_time)/1000);
		}

		pthread_mutex_lock(&my_mutex);
		if(My402ListEmpty(&queue1)){
			My402ListAppend(&queue1,pkt);
			pkt->q1_enter = getinstanttime();
			PrintStat(getinstanttime());
			fprintf(stdout,"p%d enters Q1\n", pkt->pkt_id);
			if(!My402ListEmpty(&queue2)) {
				pthread_cond_signal(&queue2_cond);
			}
			else {
				if(token_bucket >= pkt->num_tokens) {
					elem = My402ListFirst(&queue1);
					pkt = (Packet *)elem->obj;					

					My402ListUnlink(&queue1,elem);
					pkt->q1_exit = getinstanttime();
					token_bucket-=pkt->num_tokens;
					PrintStat(getinstanttime());
					fprintf(stdout, "p%d leaves Q1, time in Q1 = %.3fms, token bucket now has %d tokens\n", 
						pkt->pkt_id, (double)(pkt->q1_exit - pkt->q1_enter)/1000, token_bucket);
					avg_pkt_q1 += (pkt->q1_exit - pkt->q1_enter);
					pkts_left_q1++;
					My402ListAppend(&queue2,pkt);
					pkt->q1_enter = 0;
					pkt->q1_exit = 0;
					pkt->q2_enter = getinstanttime();
					PrintStat(getinstanttime());
					fprintf(stdout,"p%d enters Q2\n", pkt->pkt_id);
					pthread_cond_signal(&queue2_cond);
				}
			}
		}
		else {
			My402ListAppend(&queue1,pkt);
			pkt->q1_enter = getinstanttime();
			PrintStat(getinstanttime());
			fprintf(stdout,"p%d enters Q1\n", pkt->pkt_id);
		}
		pthread_mutex_unlock(&my_mutex);
	}
	pthread_mutex_lock(&my_mutex);
	pthread_cond_signal(&queue2_cond); // This can also be a false signal just to wake up server, if
	pthread_mutex_unlock(&my_mutex);   // say last packet is dropped and there is no pkt to be queued to q2.
	if(i==-1) {
		avg_inter_arrival = 0;
		pkt_drop_prob = 0;
	}
	else {
		avg_inter_arrival = (double)((double)avg_ia/(double)((i+1)*1000000));
		pkt_drop_prob = (double)(num_packets - pkts_to_arrive)/(i+1);
	}
	pthread_exit(NULL);
}
예제 #3
0
파일: reader_cip.c 프로젝트: gorhan/LFOS
/** problem reading method of reader */
static
SCIP_DECL_READERREAD(readerReadCip)
{  /*lint --e{715}*/

   CIPINPUT cipinput;
   SCIP_Real objscale;
   SCIP_Real objoffset;
   SCIP_Bool initialconss;
   SCIP_Bool dynamicconss;
   SCIP_Bool dynamiccols;
   SCIP_Bool dynamicrows;
   SCIP_Bool initialvar;
   SCIP_Bool removablevar;
   SCIP_RETCODE retcode;

   if( NULL == (cipinput.file = SCIPfopen(filename, "r")) )
   {
      SCIPerrorMessage("cannot open file <%s> for reading\n", filename);
      SCIPprintSysError(filename);
      return SCIP_NOFILE;
   }

   cipinput.len = 131071;
   SCIP_CALL( SCIPallocBufferArray(scip, &(cipinput.strbuf), cipinput.len) );

   cipinput.linenumber = 0;
   cipinput.section = CIP_START;
   cipinput.haserror = FALSE;
   cipinput.endfile = FALSE;
   cipinput.readingsize = 65535;

   SCIP_CALL( SCIPcreateProb(scip, filename, NULL, NULL, NULL, NULL, NULL, NULL, NULL) );

   SCIP_CALL( SCIPgetBoolParam(scip, "reading/initialconss", &initialconss) );
   SCIP_CALL( SCIPgetBoolParam(scip, "reading/dynamiccols", &dynamiccols) );
   SCIP_CALL( SCIPgetBoolParam(scip, "reading/dynamicconss", &dynamicconss) );
   SCIP_CALL( SCIPgetBoolParam(scip, "reading/dynamicrows", &dynamicrows) );

   initialvar = !dynamiccols;
   removablevar = dynamiccols;

   objscale = 1.0;
   objoffset = 0.0;

   while( cipinput.section != CIP_END && !cipinput.haserror )
   {
      /* get next input string */
      SCIP_CALL( getInputString(scip, &cipinput) );

      if( cipinput.endfile )
         break;

      switch( cipinput.section )
      {
      case CIP_START:
         getStart(scip, &cipinput);
         break;
      case CIP_STATISTIC:
         SCIP_CALL( getStatistics(scip, &cipinput) );
         break;
      case CIP_OBJECTIVE:
         SCIP_CALL( getObjective(scip, &cipinput, &objscale, &objoffset) );
         break;
      case CIP_VARS:
         retcode = getVariable(scip, &cipinput, initialvar, removablevar, objscale);

         if( retcode == SCIP_READERROR )
         {
            cipinput.haserror = TRUE;
            goto TERMINATE;
         }
         SCIP_CALL(retcode);

         break;
      case CIP_FIXEDVARS:
         retcode = getFixedVariable(scip, &cipinput);

         if( retcode == SCIP_READERROR )
         {
            cipinput.haserror = TRUE;
            goto TERMINATE;
         }
         SCIP_CALL(retcode);

         break;
      case CIP_CONSTRAINTS:
         retcode = getConstraint(scip, &cipinput, initialconss, dynamicconss, dynamicrows);

         if( retcode == SCIP_READERROR )
         {
            cipinput.haserror = TRUE;
            goto TERMINATE;
         }
         SCIP_CALL(retcode);

         break;
      default:
         SCIPerrorMessage("invalid CIP state\n");
         SCIPABORT();
         return SCIP_INVALIDDATA;  /*lint !e527*/
      } /*lint !e788*/ 
   }

   if( !SCIPisZero(scip, objoffset) && !cipinput.haserror )
   {
      SCIP_VAR* objoffsetvar;

      objoffset *= objscale;
      SCIP_CALL( SCIPcreateVar(scip, &objoffsetvar, "objoffset", objoffset, objoffset, 1.0, SCIP_VARTYPE_CONTINUOUS,
         TRUE, TRUE, NULL, NULL, NULL, NULL, NULL) );
      SCIP_CALL( SCIPaddVar(scip, objoffsetvar) );
      SCIP_CALL( SCIPreleaseVar(scip, &objoffsetvar) );
      SCIPdebugMessage("added variables <objoffset> for objective offset of <%g>\n", objoffset);
   }

   if( cipinput.section != CIP_END && !cipinput.haserror )
   {
      SCIPerrorMessage("unexpected EOF\n");
   }

 TERMINATE:
   /* close file stream */
   SCIPfclose(cipinput.file);

   SCIPfreeBufferArray(scip, &cipinput.strbuf);

   if( cipinput.haserror )
      return SCIP_READERROR;

   /* successfully parsed cip format */
   *result = SCIP_SUCCESS;
   return SCIP_OKAY;
}
예제 #4
0
bool ViewData::handleEvent( const eq::ConfigEvent* event )
{
    switch( event->data.type )
    {
      case eq::Event::CHANNEL_POINTER_BUTTON_RELEASE:
      {
          const eq::PointerEvent& releaseEvent = 
              event->data.pointerButtonRelease;
          if( releaseEvent.buttons == eq::PTR_BUTTON_NONE )
          {
              if( releaseEvent.button == eq::PTR_BUTTON1 )
              {
                  _spinX = releaseEvent.dy;
                  _spinY = releaseEvent.dx;
                  return true;
              }
              if( releaseEvent.button == eq::PTR_BUTTON2 )
              {
                  _advance = -releaseEvent.dy;
                  return true;
              }
          }
          return false;
      }
      case eq::Event::CHANNEL_POINTER_MOTION:
          switch( event->data.pointerMotion.buttons )
          {
            case eq::PTR_BUTTON1:
                _spinX = 0;
                _spinY = 0;
                spinModel( -0.005f * event->data.pointerMotion.dy,
                           -0.005f * event->data.pointerMotion.dx, 0.f );
                return true;

            case eq::PTR_BUTTON2:
                _advance = -event->data.pointerMotion.dy;
                moveModel( 0.f, 0.f, .005f * _advance );
                return true;

            case eq::PTR_BUTTON3:
                moveModel(  .0005f * event->data.pointerMotion.dx,
                           -.0005f * event->data.pointerMotion.dy, 0.f );
                return true;

            default:
                return false;
          }

      case eq::Event::WINDOW_POINTER_WHEEL:
          moveModel( -0.05f * event->data.pointerWheel.yAxis, 0.f,
                      0.05f * event->data.pointerWheel.xAxis );
          return true;

      case eq::Event::MAGELLAN_AXIS:
          _spinX = 0;
          _spinY = 0;
          _advance = 0;
          spinModel(  0.0001f * event->data.magellan.zRotation,
                     -0.0001f * event->data.magellan.xRotation,
                     -0.0001f * event->data.magellan.yRotation );
          moveModel(  0.0001f * event->data.magellan.xAxis,
                     -0.0001f * event->data.magellan.zAxis,
                      0.0001f * event->data.magellan.yAxis );
          return true;

      case eq::Event::KEY_PRESS:
          switch( event->data.keyPress.key )
          {
            case 's':
                showStatistics( !getStatistics( ));
                return true;
          }
          return false;

      default:
          return false;
    }
}
예제 #5
0
int cli_show_stats_out_dedup(int client_fd, char **parameters, int numparameters) {
        char msg[MAX_BUFFER_SIZE] = { 0 };
        sprintf(msg,"------------------------------------------------------------------\n");
        cli_send_feedback(client_fd, msg);
	Statistics ds, dsAggregate;
        int si;
        memset(&dsAggregate,0,sizeof(dsAggregate));
        for (si=0;si<get_workers(); si++) {
		getStatistics(get_worker_decompressor(si),&ds);
		dsAggregate.inputBytes += ds.inputBytes;
		dsAggregate.outputBytes += ds.outputBytes;
		dsAggregate.processedPackets += ds.processedPackets;
		dsAggregate.uncompressedPackets += ds.uncompressedPackets;
		dsAggregate.errorsMissingFP += ds.errorsMissingFP;
		dsAggregate.errorsMissingPacket += ds.errorsMissingPacket;
		dsAggregate.errorsPacketFormat += ds.errorsPacketFormat;
		dsAggregate.errorsPacketHash += ds.errorsPacketHash;
         }
	memset(msg, 0, MAX_BUFFER_SIZE);
	sprintf(msg,"Decompressor statistics\n");
	cli_send_feedback(client_fd, msg);
	sprintf(msg,"total_input_bytes.value %" PRIu64 " \n", dsAggregate.inputBytes);
	cli_send_feedback(client_fd, msg);
	sprintf(msg,"total_output_bytes.value %" PRIu64 "\n", dsAggregate.outputBytes);
	cli_send_feedback(client_fd, msg);
	sprintf(msg,"processed_packets.value %" PRIu64 "\n", dsAggregate.processedPackets);
	cli_send_feedback(client_fd, msg);
	sprintf(msg,"uncompressed_packets.value %" PRIu64 "\n",dsAggregate.uncompressedPackets);
	cli_send_feedback(client_fd, msg);
	sprintf(msg,"FP_entries_not_found.value %" PRIu64 "\n",dsAggregate.errorsMissingFP);
	cli_send_feedback(client_fd, msg);
	sprintf(msg,"packet_hashes_not_found.value %" PRIu64 "\n",dsAggregate.errorsMissingPacket);
	cli_send_feedback(client_fd, msg);
	sprintf(msg,"bad_packet_format.value %" PRIu64 "\n", dsAggregate.errorsPacketFormat);
	cli_send_feedback(client_fd, msg);
	sprintf(msg,"bad_packet_hash.value %" PRIu64 "\n", dsAggregate.errorsPacketHash);
	cli_send_feedback(client_fd, msg);
	sprintf(msg,"------------------------------------------------------------------\n");
	cli_send_feedback(client_fd, msg);
/***
        char msg[MAX_BUFFER_SIZE] = { 0 };
        sprintf(msg,"------------------------------------------------------------------\n");
        cli_send_feedback(client_fd, msg);

                        Statistics ds;
			int si;
			for (si=0;si<get_workers();si++) {
	                        getStatistics(get_worker_decompressor(si),&ds);
	                        memset(msg, 0, MAX_BUFFER_SIZE);
	                        sprintf(msg,"Decompressor statistics (thread %d)\n",si);
	                        cli_send_feedback(client_fd, msg);
	                        sprintf(msg,"total_input_bytes.value %" PRIu64 " \n", ds.inputBytes);
	                        cli_send_feedback(client_fd, msg);
	                        sprintf(msg,"total_output_bytes.value %" PRIu64 "\n", ds.outputBytes);
	                        cli_send_feedback(client_fd, msg);
	                        sprintf(msg,"processed_packets.value %" PRIu64 "\n", ds.processedPackets);
	                        cli_send_feedback(client_fd, msg);
	                        sprintf(msg,"uncompressed_packets.value %" PRIu64 "\n", ds.uncompressedPackets);
	                        cli_send_feedback(client_fd, msg);
	                        sprintf(msg,"FP_entries_not_found.value %" PRIu64 "\n", ds.errorsMissingFP);
	                        cli_send_feedback(client_fd, msg);
	                        sprintf(msg,"packet_hashes_not_found.value %" PRIu64 "\n", ds.errorsMissingPacket);
	                        cli_send_feedback(client_fd, msg);
	                        sprintf(msg,"bad_packet_format.value %" PRIu64 "\n", ds.errorsPacketFormat);
	                        cli_send_feedback(client_fd, msg);
	                        sprintf(msg,"------------------------------------------------------------------\n");
	                        cli_send_feedback(client_fd, msg);
	
			}
***/
        return 0;
}
void CSoundCardRepeaterTXRXThread::run()
{
	// Wait here until we have the essentials to run
	while (!m_killed && (m_soundcard == NULL  || m_protocolHandler == NULL || m_rptCallsign.IsEmpty() || m_rptCallsign.IsSameAs(wxT("        ")) || m_controller == NULL))
		::wxMilliSleep(500UL);		// 1/2 sec

	if (m_killed)
		return;

	m_stopped = false;

	m_controller->setActive(false);
	m_controller->setRadioTransmit(false);

	m_pollTimer.start();

	wxDateTime dateTime = wxDateTime::Now();
	m_lastHour = dateTime.GetHour();

	m_inBuffer.clear();

	wxLogMessage(wxT("Starting the sound card transmitter and receiver thread"));

	unsigned int count = 0U;

	wxStopWatch timer;

	while (!m_killed) {
		timer.Start();

		// Process the incoming D-Star transmission
		receiveRadio();

		// Process network traffic
		receiveNetwork();

		repeaterStateMachine();

		// Send the network poll if needed and restart the timer
		if (m_pollTimer.hasExpired()) {
#if defined(__WINDOWS__)
			m_protocolHandler->writePoll(wxT("win_sound-") + VERSION);
#else
			m_protocolHandler->writePoll(wxT("linux_sound-") + VERSION);
#endif
			m_pollTimer.reset();
		}

		// Clock the heartbeat output every one second
		count++;
		if (count == 50U) {
			m_controller->setHeartbeat();
			count = 0U;
		}

		// Set the output state
		if (m_tx || (m_activeHangTimer.isRunning() && !m_activeHangTimer.hasExpired())) {
			m_controller->setActive(true);
		} else {
			m_controller->setActive(false);
			m_activeHangTimer.stop();
		}

		// Check the shutdown state, state changes are done here to bypass the state machine which is
		// frozen when m_disable is asserted
		m_disable = m_controller->getDisable();
		if (m_disable) {
			if (m_rptState != DSRS_SHUTDOWN) {
				m_watchdogTimer.stop();
				m_activeHangTimer.stop();
				m_hangTimer.stop();
				m_networkBuffer.clear();
				m_bitBuffer.clear();
				m_networkRun = 0U;
				m_networkStarted = false;
				m_controller->setActive(false);
				m_controller->setRadioTransmit(false);
				m_rptState = DSRS_SHUTDOWN;
			}
		} else {
			if (m_rptState == DSRS_SHUTDOWN) {
				m_watchdogTimer.stop();
				m_hangTimer.stop();
				m_rptState = DSRS_LISTENING;
				m_protocolHandler->reset();
			}
		}

		// Send the output data
		if (m_networkStarted)
			transmitNetwork();
		else if (m_networkRun >= NETWORK_RUN_FRAME_COUNT)
			transmitNetwork();
		else
			transmit();

		getStatistics();

		unsigned int ms = timer.Time();
		clock(ms);
	}

	writeStatistics();

	wxLogMessage(wxT("Stopping the sound card transmitter and receiver thread"));

	m_controller->setActive(false);
	m_controller->setRadioTransmit(false);
	m_controller->close();
	delete m_controller;

	m_soundcard->close();
	delete m_soundcard;

	delete m_audioDelay;
	delete m_pttDelay;

	if (m_reader != NULL) {
		m_reader->close();
		delete m_reader;
	}

	m_protocolHandler->close();
	delete m_protocolHandler;

#if defined(TX_TO_WAV_FILE)
	if (m_writer != NULL) {
		m_writer->close();
		delete m_writer;
	}
#endif
}
void PipelineComposer::composeViewport(Viewport *port)
{
    // setup viewport
    GLint 
        pl=port->calcPixelLeft(), 
        pr=port->calcPixelRight(),
        pb=port->calcPixelBottom(), 
        pt=port->calcPixelTop();
    GLint pw=pr-pl+1,ph=pt-pb+1;
    bool full = port->calcIsFullWindow();
    glViewport(pl, pb, pw, ph);
    glScissor(pl, pb, pw, ph);
    if(! full)
        glEnable(GL_SCISSOR_TEST);

    GLboolean depth = glIsEnabled(GL_DEPTH_TEST);
    GLboolean blend = glIsEnabled(GL_BLEND);

//    glDisable(GL_DEPTH_TEST);
    glPushMatrix();
    glLoadIdentity();
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
    glOrtho(0, port->calcPixelWidth(),
            0, port->calcPixelHeight(),-1,1);
    if(getAlpha())
    {
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    }

    // only one buffer for the client
    if(isClient())
        _composeTilePtr = _readTilePtr;

    _readTilesX = (port->calcPixelWidth()  - 1) / getTileSize() + 1;
    _readTilesY = (port->calcPixelHeight() - 1) / getTileSize() + 1;

    _tileBufferSize = getTileSize()*getTileSize()*8+sizeof(TileBuffer);
    _workingTile.resize(_tileBufferSize);

    // resize
    _readTilePtr->resize(_tileBufferSize * _readTilesX * _readTilesY);

    if(isClient())
    {
        while(_groupInfo.size() < serverCount())
        {
            _groupInfoPool.push_back(GroupInfo());
            _groupInfo.push_back(&(*_groupInfoPool.rbegin()));
        }
        _groupInfo.resize(serverCount());
    }
    
    _statistics.bytesIn  = 0;
    _statistics.bytesOut = 0;
    _statistics.occluded = 0;
    _statistics.noDepth  = 0;
    _statistics.noGeo    = 0;
    _statistics.clipped  = 0;

    if(!getPipelined())
    {
        _composeTilesX  = _readTilesX;
        _composeTilesY  = _readTilesY;
    }
    if(getShort())
    {
        UInt16 colorDummy;
//        UInt16 depthDummy;
        UInt32 depthDummy;
//        _depthType   = GL_UNSIGNED_SHORT;
        _depthType   = GL_UNSIGNED_INT;
        _colorFormat = GL_RGB;
        _colorType   = GL_UNSIGNED_SHORT_5_6_5;
        
        readBuffer(depthDummy,colorDummy,port);
        if(!getPipelined() || isClient())
            composeBuffer(depthDummy,colorDummy);
    }
    else
    {
        if(getAlpha())
        {
            UInt32 colorDummy;
            UInt32 depthDummy;
            _depthType   = GL_UNSIGNED_INT;
            _colorFormat = GL_RGBA;
            _colorType   = GL_UNSIGNED_BYTE;
            readBuffer(depthDummy,colorDummy,port);
            if(!getPipelined() || isClient())
                composeBuffer(depthDummy,colorDummy);
        }
        else
        {
            RGBValue colorDummy;
            UInt32   depthDummy;
            _depthType   = GL_UNSIGNED_INT;
            _colorFormat = GL_RGB;
            _colorType   = GL_UNSIGNED_BYTE;
            readBuffer(depthDummy,colorDummy,port);
            if(!getPipelined() || isClient())
                composeBuffer(depthDummy,colorDummy);
        }
    }

    if(getStatistics())
    {
        if(isClient())
        {
            double      pixelReadTime = 0;
            double      sortTime      = 0;
            UInt32      maxIn      = _statistics.bytesIn;
            UInt32      maxOut     = _statistics.bytesOut;
            UInt32      maxIO      = maxIn + maxOut;
            UInt32      sumOut     = _statistics.bytesOut;
            UInt32      clipped    = 0;
            Connection::Channel channel;
            GroupConnection *server;
            Statistics  statistics;
            server = clusterWindow()->getNetwork()->getMainGroupConnection();
            for(UInt32 i=0 ; i<serverCount() ;++i)
            {
                channel = server->selectChannel();
                server->subSelection(channel);
                server->get(&statistics,sizeof(Statistics));
                sumOut += statistics.bytesOut;
                if(statistics.pixelReadTime > pixelReadTime) {
                    pixelReadTime = statistics.pixelReadTime;
                    sortTime = statistics.sortTime;
                }
                if(statistics.bytesOut > maxOut)
                    maxOut = statistics.bytesOut;
                if(statistics.bytesIn > maxIn)
                    maxIn = statistics.bytesIn;
                if(statistics.bytesIn + statistics.bytesOut > maxIO)
                    maxIO = statistics.bytesIn + statistics.bytesOut;
                clipped += statistics.clipped;
            }
            server->resetSelection();
            printf("pixel read time  : %1.5lf\n",pixelReadTime);
            printf("sort Time        : %1.5lf\n",sortTime);
            printf("compose Time     : %1.5lf\n",_statistics.composeTime);
            printf("Transfered bytes : %10d\n",sumOut);
            printf("Max out          : %10d\n",maxOut);
            printf("Max in           : %10d\n",maxIn);
            printf("Max io           : %10d\n",maxIO);
            printf("occluded         : %10d\n",_statistics.occluded);
            printf("Layerd           : %10d\n",_statistics.noDepth);
            printf("Empty            : %10d\n",_statistics.noGeo-clipped);
            printf("Clipped          : %10d\n",clipped);
            printf("DepthAndColor    : %10d\n",serverCount()*_composeTilesX*_composeTilesY-
                   _statistics.occluded-
                   _statistics.noDepth-
                   _statistics.noGeo);
        }
        else
        {
            Connection *client = clusterWindow()->getNetwork()->getMainConnection();
            client->put(&_statistics,sizeof(Statistics));
            client->flush();
        }
    }

    glPopMatrix();
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();
    glEnable(GL_DEPTH_TEST);

    // reset state
    if(depth && !glIsEnabled(GL_DEPTH_TEST))
        glEnable(GL_DEPTH_TEST);
    if(!blend && glIsEnabled(GL_BLEND))
        glDisable(GL_BLEND);
}
예제 #8
0
int cli_show_stats_in_dedup(int client_fd, char **parameters, int numparameters) {
        char msg[MAX_BUFFER_SIZE] = { 0 };
        sprintf(msg,"------------------------------------------------------------------\n");
        cli_send_feedback(client_fd, msg);

	Statistics cs, csAggregate;
	int si;
	memset(&csAggregate,0,sizeof(csAggregate));
	for (si = 0; si < get_workers(); si++) {
		getStatistics(get_worker_compressor(si),&cs);
		csAggregate.inputBytes += cs.inputBytes;		
		csAggregate.outputBytes += cs.outputBytes;		
		csAggregate.processedPackets += cs.processedPackets;		
		csAggregate.compressedPackets += cs.compressedPackets;		
		csAggregate.numOfFPEntries += cs.numOfFPEntries;		
		csAggregate.lastPktId += cs.lastPktId;		
		csAggregate.numberOfFPHashCollisions += cs.numberOfFPHashCollisions;		
		csAggregate.numberOfFPCollisions += cs.numberOfFPCollisions;		
		csAggregate.numberOfShortPkts += cs.numberOfShortPkts;		
	}
	memset(msg, 0, MAX_BUFFER_SIZE);
	sprintf(msg,"Compressor statistics\n");
	cli_send_feedback(client_fd, msg);
	sprintf(msg,"total_input_bytes.value %" PRIu64 " \n", csAggregate.inputBytes);
	cli_send_feedback(client_fd, msg);
	sprintf(msg,"total_output_bytes.value %" PRIu64 "\n", csAggregate.outputBytes);
	cli_send_feedback(client_fd, msg);
	sprintf(msg,"processed_packets.value %" PRIu64 "\n", csAggregate.processedPackets);
	cli_send_feedback(client_fd, msg);
	sprintf(msg,"compressed_packets.value %" PRIu64 "\n", csAggregate.compressedPackets);
	cli_send_feedback(client_fd, msg);
	sprintf(msg,"FP_entries.value %" PRIu64 "\n", csAggregate.numOfFPEntries);
	cli_send_feedback(client_fd, msg);
	sprintf(msg,"last_pktId.value %" PRIu64 "\n", csAggregate.lastPktId);
	cli_send_feedback(client_fd, msg);
	sprintf(msg,"FP_hash_collisions.value %" PRIu64 "\n", csAggregate.numberOfFPHashCollisions);
	cli_send_feedback(client_fd, msg);
	sprintf(msg,"FP_collisions.value %" PRIu64 "\n", csAggregate.numberOfFPCollisions);
	cli_send_feedback(client_fd, msg);
	sprintf(msg,"short_packets.value %" PRIu64 "\n", csAggregate.numberOfShortPkts);
	cli_send_feedback(client_fd, msg);
	sprintf	(msg,"------------------------------------------------------------------\n");
	cli_send_feedback(client_fd, msg);
/*
                        Statistics cs;
			int si;
			for (si = 0; si < get_workers(); si++) {
	                        getStatistics(get_worker_compressor(si),&cs);
	                        memset(msg, 0, MAX_BUFFER_SIZE);
	                        sprintf(msg,"Compressor statistics (thread %d)\n",si);
	                        cli_send_feedback(client_fd, msg);
	                        sprintf(msg,"total_input_bytes.value %" PRIu64 " \n", cs.inputBytes);
	                        cli_send_feedback(client_fd, msg);
	                        sprintf(msg,"total_output_bytes.value %" PRIu64 "\n", cs.outputBytes);
	                        cli_send_feedback(client_fd, msg);
	                        sprintf(msg,"processed_packets.value %" PRIu64 "\n", cs.processedPackets);
	                        cli_send_feedback(client_fd, msg);
	                        sprintf(msg,"compressed_packets.value %" PRIu64 "\n", cs.compressedPackets);
	                        cli_send_feedback(client_fd, msg);
	                        sprintf(msg,"FP_entries.value %" PRIu64 "\n", cs.numOfFPEntries);
	                        cli_send_feedback(client_fd, msg);
	                        sprintf(msg,"last_pktId.value %" PRIu64 "\n", cs.lastPktId);
	                        cli_send_feedback(client_fd, msg);
	                        sprintf(msg,"FP_hash_collisions.value %" PRIu64 "\n", cs.numberOfFPHashCollisions);
	                        cli_send_feedback(client_fd, msg);
	                        sprintf(msg,"FP_collisions.value %" PRIu64 "\n", cs.numberOfFPCollisions);
	                        cli_send_feedback(client_fd, msg);
	                        sprintf(msg,"short_packets.value %" PRIu64 "\n", cs.numberOfShortPkts);
	                        cli_send_feedback(client_fd, msg);
	                        sprintf(msg,"------------------------------------------------------------------\n");
	                        cli_send_feedback(client_fd, msg);
			}

*/
        return 0;
}
예제 #9
0
DepthFirstStateAction::ResultE
DepthFirstStateAction::traverseEnter(void)
{
    ResultE              result          = NewActionTypes::Continue;
    NodePtr              pNode;
    Int32                nodePass;        // pass over current node
    UInt32               multiPasses;     // requested passes over current node
    StateRefCountStoreIt itStateRefCount; // state for current node

    while((_nodeStack.empty() == false) && !(result & NewActionTypes::Quit))
    {
        pNode           = _nodeStack.back().getNode         ();
        nodePass        = _nodeStack.back().getPassCount    ();
        itStateRefCount = _nodeStack.back().getStateRefCount();

#ifdef OSG_NEWACTION_STATISTICS
        getStatistics()->getElem(statNodesEnter)->inc();
#endif /* OSG_NEWACTION_STATISTICS */

        if(itStateRefCount != _itActiveState)
        {
#ifdef OSG_NEWACTION_STATISTICS
            getStatistics()->getElem(statStateRestores)->inc();
#endif /* OSG_NEWACTION_STATISTICS */

            setState(itStateRefCount);

            // gained refs: active
            incRefCount(itStateRefCount);

            // lost refs: active
            decRefCount(_itActiveState);

            _itActiveState = itStateRefCount;
        }

        _stateClonedFlag = false;

        getChildrenList().setParentNode(pNode);

        result      = enterNode   (pNode, static_cast<UInt32>(nodePass - 1));
        multiPasses = getNumPasses(                                        );

        _nodeStack.pop_back();

        // only initial pass (nodePass == 1) can request multiPasses
        if((nodePass == 1) && (multiPasses > 1))
        {
            for(; multiPasses > 1; --multiPasses)
            {
                // gained refs: additional pass
                incRefCount(_itActiveState);
                
                _nodeStack.push_back(
                    NodeStackEntry(pNode, _itActiveState, multiPasses));
            }
        }
        
        pushChildren(pNode, result);

        // lost refs: current node
        decRefCount(_itActiveState);
    }

    return result;
}
예제 #10
0
DepthFirstStateAction::ResultE
DepthFirstStateAction::traverseEnterLeave(void)
{
    ResultE              result          = NewActionTypes::Continue;
    Int32                nodePass;        // pass over current node
    UInt32               multiPasses;     // requested passes over current node
    NodePtr              pNode;
    StateRefCountStoreIt itStateRefCount;

    while((_nodeStack.empty() == false) && !(result & NewActionTypes::Quit))
    {
        pNode           = _nodeStack.back().getNode         ();
        nodePass        = _nodeStack.back().getPassCount    ();
        itStateRefCount = _nodeStack.back().getStateRefCount();

        if(itStateRefCount != _itActiveState)
        {
#ifdef OSG_NEWACTION_STATISTICS
            getStatistics()->getElem(statStateRestores)->inc();
#endif /* OSG_NEWACTION_STATISTICS */

            setState(itStateRefCount);

            // gained refs: active
            incRefCount(itStateRefCount);

            // lost refs: active
            decRefCount(_itActiveState);

            _itActiveState = itStateRefCount;
        }

        getChildrenList().setParentNode(pNode);

        if(nodePass > 0)
        {
            // positive pass -> enter node
            
#ifdef OSG_NEWACTION_STATISTICS
            getStatistics()->getElem(statNodesEnter)->inc();
#endif /* OSG_NEWACTION_STATISTICS */
            
            _stateClonedFlag = false;

            result      = enterNode   (pNode, static_cast<UInt32>(nodePass - 1));
            multiPasses = getNumPasses(                                        );

            // only initial pass (nodePass == 1) can request multiPass.
            if((nodePass == 1) && (multiPasses > 1))
            {
                // remove current node from stack
                _nodeStack.pop_back();
                
                for(; multiPasses > 1; -- multiPasses)
                {
                    // gained refs: addtional passs
                    incRefCount(_itActiveState);
                    
                    _nodeStack.push_back(
                        NodeStackEntry(pNode, _itActiveState, multiPasses));
                }
                
                // readd current node - with negative pass -> leave
                _nodeStack.push_back(
                    NodeStackEntry(pNode, _itActiveState, -nodePass));
            }
            else
            {
                // change current node passCount to negative -> leave
                _nodeStack.back().setPassCount(-nodePass);
            }
            
            pushChildren(pNode, result);
        }
        else
        {
            // negative pass -> leave node

#ifdef OSG_NEWACTION_STATISTICS
            getStatistics()->getElem(statNodesLeave)->inc();
#endif /* OSG_NEWACTION_STATISTICS */
            
            _stateClonedFlag = true;

            result = leaveNode(pNode, static_cast<UInt32>(-nodePass - 1));

            _nodeStack.pop_back();

            // lost refs: current node
            decRefCount(_itActiveState);
        }
    }

    return result;
}
예제 #11
0
/** Generate a list of peaks that meets= all the requirements for fitting offset
  * @param peakslist :: table workspace as the output of FindPeaks
  * @param wi :: workspace index of the spectrum
  * @param peakPositionRef :: reference peaks positions
  * @param peakPosToFit :: output of reference centres of the peaks used to fit
 * offset
  * @param peakPosFitted :: output of fitted centres of the peaks used to fit
 * offset
  * @param peakHeightFitted :: heights of the peaks used to fit offset
  * @param chisq :: chi squares of the peaks used to fit offset
  * @param useFitWindows :: boolean whether FitWindows is used
  * @param fitWindowsToUse :: fit windows
  * @param minD :: minimum d-spacing of the spectrum
  * @param maxD :: minimum d-spacing of the spectrum
  * @param deltaDovD :: delta(d)/d of the peak for fitting
  * @param dev_deltaDovD :: standard deviation of delta(d)/d of all the peaks in
 * the spectrum
  */
void GetDetOffsetsMultiPeaks::generatePeaksList(
    const API::ITableWorkspace_sptr &peakslist, int wi,
    const std::vector<double> &peakPositionRef,
    std::vector<double> &peakPosToFit, std::vector<double> &peakPosFitted,
    std::vector<double> &peakHeightFitted, std::vector<double> &chisq,
    bool useFitWindows, const std::vector<double> &fitWindowsToUse,
    const double minD, const double maxD, double &deltaDovD,
    double &dev_deltaDovD) {
  // FIXME - Need to make sure that the peakPositionRef and peakslist have the
  // same order of peaks

  // Check
  size_t numrows = peakslist->rowCount();
  if (numrows != peakPositionRef.size())
    throw std::runtime_error("Number of peaks in PeaksList (from FindPeaks) is "
                             "not same as number of "
                             "referenced peaks' positions. ");

  std::vector<double> vec_widthDivPos;
  std::vector<double> vec_offsets;

  for (size_t i = 0; i < peakslist->rowCount(); ++i) {
    // Get peak value
    double centre = peakslist->getRef<double>("centre", i);
    double width = peakslist->getRef<double>("width", i);
    double height = peakslist->getRef<double>("height", i);
    double chi2 = peakslist->getRef<double>("chi2", i);

    // Identify whether this peak would be accepted to optimize offset
    // - peak position within D-range
    if (centre <= minD || centre >= maxD) {
      std::stringstream dbss;
      dbss << " wi = " << wi << " c = " << centre << " out of D-range ";
      g_log.debug(dbss.str());
      continue;
    }

    // - rule out of peak with wrong position
    if (useFitWindows) {
      // outside peak fit window o
      if (centre <= fitWindowsToUse[2 * i] ||
          centre >= fitWindowsToUse[2 * i + 1]) {
        std::stringstream dbss;
        dbss << " wi = " << wi << " c = " << centre << " out of fit window ";
        g_log.debug(dbss.str());
        continue;
      }
    }

    // - check chi-square
    if (chi2 > m_maxChiSq || chi2 < 0) {
      std::stringstream dbss;
      dbss << " wi = " << wi << " c = " << centre << " chi2 = " << chi2
           << ": Too large";
      g_log.debug(dbss.str());
      continue;
    }

    // - check peak height
    if (height < m_minPeakHeight) {
      g_log.debug() << " wi = " << wi << " c = " << centre << " h = " << height
                    << ": Too low "
                    << "\n";
      continue;
    }

    // - check peak's resolution
    double widthdevpos = width / centre;
    if (m_hasInputResolution) {
      double recres = m_inputResolutionWS->readY(wi)[0];
      double resmax = recres * m_maxResFactor;
      double resmin = recres * m_minResFactor;
      if (widthdevpos < resmin || widthdevpos > resmax) {
        std::stringstream dbss;
        dbss << " wi = " << wi << " c = " << centre
             << " Delta(d)/d = " << widthdevpos
             << " too far away from suggested value " << recres;
        g_log.debug(dbss.str());
        continue;
      }
    }

    // background value
    double back_intercept = peakslist->getRef<double>("backgroundintercept", i);
    double back_slope = peakslist->getRef<double>("backgroundslope", i);
    double back_quad = peakslist->getRef<double>("A2", i);
    double background =
        back_intercept + back_slope * centre + back_quad * centre * centre;

    // Continue to identify whether this peak will be accepted
    // (e) peak signal/noise ratio
    if (height * FWHM_TO_SIGMA / width < 5.)
      continue;

    // (f) ban peaks that are not outside of error bars for the background
    if (height < 0.5 * std::sqrt(height + background))
      continue;

    // - calcualte offsets as to determine the (z-value)
    double offset = fabs(peakPositionRef[i] / centre - 1);
    if (offset > m_maxOffset) {
      std::stringstream dbss;
      dbss << " wi = " << wi << " c = " << centre
           << " exceeds maximum offset. ";
      g_log.debug(dbss.str());
      continue;
    } else
      vec_offsets.push_back(offset);

    // (g) calculate width/pos as to determine the (z-value) for constant
    // "width" - (delta d)/d
    // double widthdevpos = width/centre;
    vec_widthDivPos.push_back(widthdevpos);

    // g_log.debug() << " h:" << height << " c:" << centre << " w:" <<
    // (width/(2.*std::sqrt(2.*std::log(2.))))
    //               << " b:" << background << " chisq:" << chi2 << "\n";

    // Add peak to vectors
    double refcentre = peakPositionRef[i];
    peakPosFitted.push_back(centre);
    peakPosToFit.push_back(refcentre);
    peakHeightFitted.push_back(height);
    chisq.push_back(chi2);
  }

  // Remove by Z-score on delta d/d
  std::vector<size_t> banned;
  std::vector<double> Zscore = getZscore(vec_widthDivPos);
  std::vector<double> Z_offset = getZscore(vec_offsets);
  for (size_t i = 0; i < peakPosFitted.size(); ++i) {
    if (Zscore[i] > 2.0 || Z_offset[i] > 2.0) {
      g_log.debug() << "Banning peak at " << peakPosFitted[i]
                    << " in wkspindex = (no show)" // << wi
                    << " sigma/d = " << vec_widthDivPos[i] << "\n";
      banned.push_back(i);
      continue;
    }
  }

  // Delete banned peaks
  if (!banned.empty()) {
    g_log.debug() << "Deleting " << banned.size() << " of "
                  << peakPosFitted.size() << " peaks in wkspindex = ??? "
                  << "\n"; // << wi << "\n";

    deletePeaks(banned, peakPosToFit, peakPosFitted, peakHeightFitted, chisq,
                vec_widthDivPos);
  }

  Statistics widthDivPos = getStatistics(vec_widthDivPos);
  deltaDovD = widthDivPos.mean;
  dev_deltaDovD = widthDivPos.standard_deviation;

  return;
}
void BinarySwapComposer::composeViewport(Viewport *port)
{
    // setup viewport
    GLint 
        pl=port->calcPixelLeft(), 
        pr=port->calcPixelRight(),
        pb=port->calcPixelBottom(), 
        pt=port->calcPixelTop();
    GLint pw=pr-pl+1,ph=pt-pb+1;
    bool full = port->calcIsFullWindow();
    glViewport(pl, pb, pw, ph);
    glScissor(pl, pb, pw, ph);
    if(! full)
        glEnable(GL_SCISSOR_TEST);

    GLboolean depth = glIsEnabled(GL_DEPTH_TEST);
    GLboolean blend = glIsEnabled(GL_BLEND);

    glDisable(GL_DEPTH_TEST);
    glPushMatrix();
    glLoadIdentity();
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
    glOrtho(0, port->calcPixelWidth(),
            0, port->calcPixelHeight(),-1,1);

//    printf("max %x,%x\n",_intDepthMax,_shortDepthMax);

    if(getAlpha())
    {
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    }
    _tilesX = port->calcPixelWidth()  / getTileSize() + 1;
    _tilesY = port->calcPixelHeight() / getTileSize() + 1;

    _tileBufferSize = getTileSize()*getTileSize()*8+sizeof(TileBuffer);
    _readTile.resize(_tileBufferSize);

    _statistics.bytesIn  = 0;
    _statistics.bytesOut = 0;

    if(isClient())
    {
        if(getShort())
        {
            UInt16 colorDummy;
            UInt32 depthDummy;
            recvFromServers(depthDummy,colorDummy,
                            GL_RGB,
                            GL_UNSIGNED_SHORT_5_6_5,
                            port);
        }
        else
        {
            if(getAlpha())
            {
                UInt32 colorDummy;
                UInt32 depthDummy;
                recvFromServers(depthDummy,colorDummy,
                                GL_RGBA,
                                GL_UNSIGNED_BYTE,
                                port);
            }
            else
            {
                RGBValue colorDummy;
                UInt32   depthDummy;
                recvFromServers(depthDummy,colorDummy,
                                GL_RGB,
                                GL_UNSIGNED_BYTE,
                                port);
            }
        }
        if(getStatistics())
        {
            UInt32      maxIn   = _statistics.bytesIn;
            UInt32      maxOut  = _statistics.bytesOut;
            UInt32      maxIO   = maxIn + maxOut;
            UInt32      sumOut  = _statistics.bytesOut;
            UInt32      missing = _usableServers;
            double      composeTime = 1e32;
            
            Connection *server;
            Statistics  statistics;
            for(UInt32 i=0 ; i<_usableServers ;++i)
            {
                server = clusterWindow()->getNetwork()->getConnection(i);
                server->selectChannel();
                server->get(&statistics,sizeof(Statistics));
                sumOut += statistics.bytesOut;
                if(statistics.composeTime < composeTime)
                    composeTime = statistics.composeTime;
                if(statistics.bytesOut > maxOut)
                    maxOut = statistics.bytesOut;
                if(statistics.bytesIn > maxIn)
                    maxIn = statistics.bytesIn;
                if(statistics.bytesIn + statistics.bytesOut > maxIO)
                    maxIO = statistics.bytesIn + statistics.bytesOut;
                missing--;
            }
            printf("compose Time     : %1.5lf\n",composeTime);
            printf("Transfered bytes : %10d\n",sumOut);
            printf("Max out          : %10d\n",maxOut);
            printf("Max in           : %10d\n",maxIn);
            printf("Max io           : %10d\n",maxIO);
        }
    }
    else
    {
        if(clusterId() < _usableServers)
        {
            _statistics.composeTime = -getSystemTime();
            _tile.resize(_tileBufferSize * _tilesX * _tilesY);
            if(getShort())
            {
                UInt16 colorDummy;
                UInt32 depthDummy=_shortDepthMax;
//                UInt32 depthDummy=_intDepthMax;
                startReader(depthDummy,colorDummy,
//                            GL_UNSIGNED_SHORT,
                            GL_UNSIGNED_INT,
                            GL_RGB,
                            GL_UNSIGNED_SHORT_5_6_5,
                            port);
            }
            else
            {
                if(getAlpha())
                {
                    UInt32 colorDummy;
                    UInt32 depthDummy=_intDepthMax;
                    startReader(depthDummy,colorDummy,
                                GL_UNSIGNED_INT,
                                GL_RGBA,
                                GL_UNSIGNED_BYTE,
                                port);
                }
                else
                {
                    RGBValue colorDummy;
                    UInt32   depthDummy=_intDepthMax;
                    startReader(depthDummy,colorDummy,
                                GL_UNSIGNED_INT,
                                GL_RGB,
                                GL_UNSIGNED_BYTE,
                                port);
                }
            }
            _statistics.composeTime += getSystemTime();
            if(getStatistics())
            {
                Connection *client = clusterWindow()->getNetwork()->getConnection(serverCount());
                client->put(&_statistics,sizeof(Statistics));
                client->flush();
            }
        }
/*
        // max depth value !! find a better way
        glClear(GL_DEPTH_BUFFER_BIT);
        glReadPixels(0, 0, 1, 1, 
                     GL_DEPTH_COMPONENT, GL_UNSIGNED_INT,
                     &_intDepthMax);
        glReadPixels(0, 0, 1, 1, 
                     GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT,
                     &_shortDepthMax);
*/
    }

    glPopMatrix();
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();
    glEnable(GL_DEPTH_TEST);

    // reset state
    if(depth && !glIsEnabled(GL_DEPTH_TEST))
        glEnable(GL_DEPTH_TEST);
    if(!blend && glIsEnabled(GL_BLEND))
        glDisable(GL_BLEND);
}
예제 #13
0
Action::ResultE ShadingAction::stop(ResultE res)
{
    if(!_ownStat)
       getStatistics()->getElem(statDrawTime)->start();

#if 0    
    UInt32 i;

//    dump(_pRoot, 0);
//    dump(_pMatRoot, 0);
//    dump(_pTransMatRoot, 0);

#if defined(OSG_OPT_DRAWTREE)
    //    _pNodeFactory->printStat();    
#endif

    for(i = 0; i < _vLights.size(); i++)
    {
        glLoadMatrixf(_vLights[i].second.getValues());
        _vLights[i].first->activate(this, i);
    }

    draw(_pMatRoot->getFirstChild());

    if(!_bZWriteTrans)
        glDepthMask(false);

    draw(_pTransMatRoot->getFirstChild());

    if(!_bZWriteTrans)
        glDepthMask(true);

    if(_pActiveState != NULL)
    {
        _pActiveState->deactivate(this);
    }

    for(i = 0; i < _vLights.size(); i++)
    {
        _vLights[i].first->deactivate(this, i);
    }

    if(!_ownStat)
    {
        glFinish();
        getStatistics()->getElem(statDrawTime)->stop();

        getStatistics()->getElem(statNMaterials      )->set(
            _uiNumMaterialChanges);
        getStatistics()->getElem(statNMatrices       )->set(
            _uiNumMatrixChanges);
        getStatistics()->getElem(statNGeometries     )->set(
            _uiNumGeometries);
        getStatistics()->getElem(statNTransGeometries)->set(
            _uiNumTransGeometries);
    }
    

//    FINFO (("Material %d Matrix %d Geometry %d Transparent %d\r",
//            _uiNumMaterialChanges, 
//            _uiNumMatrixChanges, 
//            _uiNumGeometries,
//            _uiNumTransGeometries));
#endif

    Inherited::stop(res);
    return res;
}
예제 #14
0
int _fextract_calc(fextract_t *fex, mx_real_t *features, dsp_sample_t *signal, char *pfile) {
	mx_real_t *pitch=NULL, *hnr=NULL;
	mx_real_t **_mfcc_series, **_energy_series;
	mx_real_t overall_max=0, overall_max_ind=0;
	int nframes=0, i, j, n_voiced_frames, max;
	int last_max=0, last_min=0, ser=0, max_sum=0, en_mean=0, fcount=0;
	fextract_series_t * serie=NULL;
	
	if (fex->frame_len==0) {
		rs_warning("Cannot compute features for segment of size 0!");
		return -1;
	}
	
	fex->n_features=V1_N_FEATURES;
	
	_mfcc_series= (mx_real_t **) rs_malloc(MFCC_FEATURES * sizeof(mx_real_t *), "mfcc feature series");
	for (i=0;i<MFCC_FEATURES;i++)
		_mfcc_series[i]= (mx_real_t *) rs_malloc(MAX_FRAMES * sizeof(mx_real_t), "mfcc features");
	_energy_series= (mx_real_t **) rs_malloc(ENERGY_FEATURES * sizeof(mx_real_t *), "energy feature series");
	for (i=0;i<3;i++)
		_energy_series[i]= (mx_real_t *) rs_malloc(MAX_FRAMES * sizeof(mx_real_t), "energy features");

	if (pfile) {
		FILE *pfile_fp= fopen(pfile,"r");
		if (!pfile_fp)
			rs_warning("pitch file %s not found!",pfile);
		/* read external pitch values */
		pitch = (mx_real_t *) rs_malloc(MAX_FRAMES * sizeof(mx_real_t),"external pitch values");
		j=MAX_FRAMES;
		i=0;
		while (fscanf(pfile_fp,"%g",&pitch[i])==1) {
			if (j == i+1) {
				j+=MAX_FRAMES;
				pitch = (mx_real_t *) rs_realloc(pitch,j*sizeof(mx_real_t),"external pitch values");
			}
			i++;
		}
		nframes=i;
		fclose(pfile_fp);
	}
	else {
		pitch= pitch_calc (fex->pitch,signal,fex->frame_len);
		nframes=fex->pitch->nframes;
	}

	if (!pitch) {
		for (;fcount<STATS*9+7;fcount++)
			features[fcount]=-1.0;
		n_voiced_frames=-1.0;
	}
	else {
		const int series_size=9;
		// @begin_change_johannes
		//fextract_series_t *serien[series_size];
		fextract_series_t *serien[9];
		// @end_change_johannes
	
//		printRawXML(pitch,nframes,"pitch");

		pitch_frame_candidates_destroy(fex->pitch);
		for (i=0;i<series_size;i++)
			serien[i]=series_create(MAX_SERIES);
	
		if (pitch[0]!=0)
			series_add(serien[0],pitch[0]);
	
		for (i=1;i<nframes-1;i++) {
			if (pitch[i]!=0)
				series_add(serien[0],pitch[i]);
	    
			if (pitch[i-1]<pitch[i] && pitch[i]>pitch[i+1]) {
				series_add(serien[1],pitch[i]);
				if (pitch[i] > overall_max) {
					overall_max=pitch[i];
					overall_max_ind=i;
				}
				series_add(serien[2],i-last_min);
				series_add(serien[3],pitch[i]-pitch[last_min]);
				series_add(serien[4],(pitch[i]-pitch[last_min])/(i-last_min));
				last_max=i;
			}
			else
				if (pitch[i-1]>pitch[i] && pitch[i]<pitch[i+1]) {
				series_add(serien[5],pitch[i]);
				series_add(serien[6],i-last_max);
				series_add(serien[7],pitch[i]-pitch[last_max]);
				series_add(serien[8],(pitch[i]-pitch[last_max])/(i-last_max));
				last_min=i;
				}
		}
	
		overall_max_ind = 1.0 * (overall_max_ind+1) / nframes;
	
		if (nframes >1 && pitch[nframes-1]!=0)
			series_add(serien[0],pitch[nframes-1]);
	
		for (i=0; i<series_size; i++) {
			getStatistics(features+fcount,serien[i]->series,serien[i]->nSeries); //pitch statistics features
			fcount+=STATS;
		}
      
	// normierter Mittelwert, normierter Median, normiertes 1. Quartil, normiertes 3. Quartil
		if (features[1]-features[2]) {
			features[fcount++]=(features[0]-features[2])/(features[1]-features[2]);
			features[fcount++]=(features[5]-features[2])/(features[1]-features[2]);
			features[fcount++]=(features[6]-features[2])/(features[1]-features[2]);
			features[fcount++]=(features[7]-features[2])/(features[1]-features[2]);
		}
		else {
			features[fcount++]=0;
			features[fcount++]=0;
			features[fcount++]=0;
			features[fcount++]=0;
		}
	
		features[fcount++]=1.0 * serien[1]->nSeries/nframes; // Anzahl Maxima pro Frames pro Segment
		features[fcount++]=1.0 * serien[5]->nSeries/nframes; // Anzahl Minima pro Frames pro Segment
		features[fcount++]=overall_max_ind; // Position des Maximums
		n_voiced_frames=serien[0]->nSeries;
	
		for (i=0;i<series_size;i++)
			series_destroy(serien[i]);
	}

	getEnergy_and_MFCC(fex->mfcc, signal, fex->frame_len, &_energy_series, &_mfcc_series, &ser);
//  ser=0;
	if (ser) {
		const int series_size = 8;
		// @begin_change_johannes
		//fextract_series_t *serien[series_size];
		fextract_series_t *serien[8];
		// @end_change_johannes
		for (i=0;i<series_size;i++)
			serien[i]=series_create(MAX_SERIES);

		fcount+=getMFCCFeatures(features+fcount, _mfcc_series,ser);

		/* Energie-Merkmale: */

		last_max=last_min=0;

		for (i=1;i<ser-1;i++) {
			if (_energy_series[0][i-1]<_energy_series[0][i] && _energy_series[0][i]>_energy_series[0][i+1]) {
				series_add(serien[0], _energy_series[0][i]); //Maxima
				max_sum += _energy_series[0][i];
				series_add(serien[1], i-last_min); // Laenge der Maxima
				series_add(serien[2], _energy_series[0][i]-_energy_series[0][last_min]); // Groesse der Maxima
				series_add(serien[3], (_energy_series[0][i]-_energy_series[0][last_min])/(i-last_min)); // Steigung der Maxima
				last_max=i;
			}
			else
				if (_energy_series[0][i-1]>_energy_series[0][i] && _energy_series[0][i]<_energy_series[0][i+1]) {
				series_add(serien[4], _energy_series[0][i]); //Maxima
				series_add(serien[5], i-last_max); // Laenge der Maxima
				series_add(serien[6], _energy_series[0][i]-_energy_series[0][last_max]); // Groesse der Maxima
				series_add(serien[7], (_energy_series[0][i]-_energy_series[0][last_min])/(i-last_max)); // Steigung der Maxima
				last_max=i;
				}
		}

		getStatistics(features+fcount,_energy_series[0],ser); // energy statistics
		en_mean=features[fcount+1];
		fcount+=STATS;

		for (i=0;i<series_size;i++) {
			getStatistics(features+fcount,serien[i]->series,serien[i]->nSeries);
			fcount+=STATS;
		}

		max=serien[0]->nSeries;

		for (j=1;j<3;j++) {

			series_reset(serien[0]); series_reset(serien[1]);

			for (i=1;i<ser-1;i++) {
				if (_energy_series[j][i-1]<_energy_series[j][i] && _energy_series[j][i]>_energy_series[j][i+1]) {
					series_add(serien[0], _energy_series[j][i]);
				}
				else
					if (_energy_series[j][i-1]>_energy_series[j][i] && _energy_series[j][i]<_energy_series[j][i+1]) {
					series_add(serien[1], _energy_series[j][i]);
					}
			}

			getStatistics(features+fcount,_energy_series[j],ser); // energy delta statistics
			fcount+=STATS;
			getStatistics(features+fcount,serien[0]->series,serien[0]->nSeries);
			fcount+=STATS;
			getStatistics(features+fcount,serien[1]->series,serien[1]->nSeries);
			fcount+=STATS;
		}


  
		features[fcount++]= max? (1.0 * max_sum/max) - en_mean:0; // Mittelwert der Maxima minus globaler Mittelwert
		features[fcount++]= (1.0 * max)/ser; // Anzahl Maxima pro Frames pro Segment
		for (i=0;i<series_size;i++)
			series_destroy(serien[i]);
	} 
	else {
		for (;fcount < 141*STATS+9;fcount++)
			features[fcount]=-1;
	}

	/* Voiced/Unvoiced-Merkmal: */
	features[fcount++]=nframes ? (1.0 * n_voiced_frames)/nframes : -1;  // Anzahl stimmloser Frames pro Frames pro Segment
  
	/* Spectral Center of gravity-Merkmale: */
	serie = getOnlyCoG(signal,fex->frame_len);
	if (serie) {
		getStatistics(features+fcount,serie->series,serie->nSeries);
		series_destroy(serie);
		fcount+=STATS;
	}
	else
		for (;fcount< 142*STATS+10;fcount++)
			features[fcount]=-1;

	/* Dauer-Merkmal: */
	features[fcount++]=fex->frame_len;

	/* Harmonics-to-Noise-Ratio-Merkmale: */
	hnr=hnr_calc(fex->hnr,signal,fex->frame_len);
	nframes=fex->hnr->nframes;

	if (!hnr) 
		for (;fcount<145*STATS+11;fcount++) 
			features[fcount]=-1.0;
	else {
		const int series_size=3;
		// @begin_change_johannes
		//fextract_series_t *serien[series_size];
		fextract_series_t *serien[3];
		// @end_change_johannes

		pitch_frame_candidates_destroy(fex->hnr);
		for (i=0;i<series_size;i++)
			serien[i]=series_create(MAX_SERIES);

		if (hnr[0]!=0)
			series_add(serien[0],hnr[0]);

		for (i=1;i<nframes-1;i++) {
			if (hnr[i]!=-200) {
				series_add(serien[0],hnr[i]);
 
				if ((hnr[i-1]!=-200) && (hnr[i+1]!=200)) { // stimmlose Bereiche nicht beruecksichtigen
					if (hnr[i-1]<hnr[i] && hnr[i]>hnr[i+1])
						series_add(serien[1],hnr[i]);
					else
						if (hnr[i-1]>hnr[i] && hnr[i]<hnr[i+1])
							series_add(serien[2],hnr[i]);
				}
			}
		}

		if (nframes >1 && hnr[nframes-1]!=0)
			series_add(serien[0],hnr[nframes-1]);

		for (i=0; i<series_size; i++) {
			getStatistics(features+fcount,serien[i]->series,serien[i]->nSeries); //hnr statistics features
			fcount+=STATS;
		}
	}
  
	/* Aufraeumen... */
	for (i=0;i<MFCC_FEATURES;i++)
		if (_mfcc_series[i])
			rs_free(_mfcc_series[i]);
	if (_mfcc_series)
		rs_free(_mfcc_series);
  
	for (i=0;i<ENERGY_FEATURES;i++)
		if (_energy_series[i])
			rs_free(_energy_series[i]);
	if (_energy_series)
		rs_free(_energy_series);

	if (pitch)
		rs_free(pitch);
	if (hnr)
		rs_free(hnr);

	/*   for (;fcount<V1_N_FEATURES;fcount++) */
	/*       features[fcount]=0.0; */

	if (fcount != V1_N_FEATURES)
		rs_error("number of features is not correct (%d expected, %d calculated)!",V1_N_FEATURES,fcount);

	return V1_N_FEATURES;
} 
예제 #15
0
 /**
  * Called when a mouse button is released
  *
  * @param p
  * @param s
  */
 void StatisticsTool::mouseButtonRelease(QPoint p, Qt::MouseButton s) {
   if(s == Qt::LeftButton) {
     getStatistics(p);
   }
 }