<commit_before>#ifndef MATMETHODS_HPP
#define MATMETHODS_HPP
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/timer/timer.hpp>
#include "armadillo"

using namespace arma;
using namespace std;
using boost::timer::auto_cpu_timer;

umat GenBoot (size_t colsize, size_t bootstrapnumber){
  boost::random::mt19937 rng;

  boost::random::uniform_int_distribution<> samples(0,colsize-1);

  umat samplemat(bootstrapnumber,colsize);

  for(umat::iterator it=samplemat.begin(); it!=samplemat.end();++it){
    (*it) = samples(rng);
  }
  return(samplemat);
}

void doBoot(mat &A, mat &B,cube &C,umat &BootMat, mat &Summaries){
  auto_cpu_timer timerInd;
  timerInd.stop();
  auto_cpu_timer timerCor;

  timerCor.stop();
  auto_cpu_timer timerMedian;
  timerMedian.stop();

  if(A.n_rows!=BootMat.n_cols){

    for(int i=1; i<C.n_slices; ++i){
      cout<<"Boot(incorrect indices): "<<i<<endl;

      C.slice(i) = cor(A.rows(BootMat(i,span(0,A.n_rows))),B.rows(BootMat(i,span(0,B.n_rows))));
    }
  }
  else{

    timerInd.resume();
    mat tA = A.rows(BootMat.row(0));
    mat tB = B.rows(BootMat.row(0));
    timerInd.stop();

    timerCor.resume();
    C.slice(0) = cor(tA,tB);
    timerCor.stop();
    for(int i=0; i<C.n_slices; ++i){
      cout<<"Boot: "<<i<<endl;
      timerInd.resume();
      tA = A.rows(BootMat.row(i));
      tB = B.rows(BootMat.row(i));
      timerInd.stop();
      timerCor.resume();
      C.slice(i) = cor(tA,tB);
      timerCor.stop();
    }
  }
  timerMedian.resume();
  mat S = mat(C.n_rows,C.n_slices);
  for(int i=0; i< C.n_cols; i++){
    S = C(span::all,span(i,i),span::all);
    Summaries.col(i)=median(S,1);
  }
  timerMedian.stop();
  timerInd.report();
  timerCor.report();
  timerMedian.report();

}

uvec trainindex(const size_t totalsize,const int ksize,const int k){
  uvec returnvec(totalsize-ksize);
  int j=0;
  for(int i=0; i<totalsize; i++){
    if(i <(k*ksize)||i>((k+1)*ksize)-1){
      returnvec(j)=i;
      j++;
    }
  }
  return(returnvec);
}

uvec testindex(const size_t totalsize,const  int ksize,const  int k){
  uvec returnvec(ksize);
  int j=0;
  for( int i=0; i<totalsize; i++){
    if(i>=(k*ksize)&&i<=((k+1)*ksize-1)){
      returnvec(j)=i;
      j++;
    }
  }
  return(returnvec);
}

double RMSE(mat &Est, const mat &True){
  Est = sqrt(pow((Est-True),2));
  Est.elem(find_nonfinite(Est)).zeros();
  return(mean(mean(Est)));
}

void KfoldCV (const mat &A,const mat &B, const int kfold, const int chunknum, const int bsi,const string file){

  mat testA,testB,trainA,trainB;
  int kfoldIterations = (int) ceil((double)A.n_rows/(double)kfold);
  if(kfoldIterations<1){
    cerr<<"Must have at least one iteration of cross-validation, not "<<kfoldIterations<<endl;
    throw 12;
  }

  int iter_k = kfold;

  cout<<"Begin "<<iter_k<<"-fold cross validation. There are "<<A.n_rows<<" samples"<<endl;
  uvec testi = testindex(A.n_rows,iter_k,0);
  uvec traini = trainindex(A.n_rows,iter_k,0);

  try{
    testA = A.rows(testi);
    testB = B.rows(testi);

    trainA = A.rows(traini);
    trainB = B.rows(traini);
  } catch(...){
    cerr<<"Error indexing training and testing sets:"<<endl;
    cerr<<"Training: "<<traini<<endl;
    cerr<<"Testing: "<<testi<<endl;
    throw 4;
  }
  cout<<"Initiating variables and starting kfold: 0"<<endl;
  mat Point(A.n_cols,B.n_cols);
  mat Summaries(A.n_cols,B.n_cols);
  umat BootMat = GenBoot(trainA.n_rows,bsi);
  cube C(A.n_cols,B.n_cols,bsi);
  doBoot(trainA,trainB,C,BootMat,Summaries);
  Point = cor(trainA,trainB);
  mat TrueCor = cor(testA,testB);
  double pointSumRMSE = RMSE(Point,TrueCor);
  double bootSumRMSE = RMSE(Summaries,TrueCor);
  for(int i=1; i<kfoldIterations; i++){
    cout<<"Starting kfold: "<<i<<endl;
    testi = testindex(A.n_rows,iter_k,0);
    traini = trainindex(A.n_rows,iter_k,0);
    testA = A.rows(testi);
    testB = B.rows(testi);
    trainA = A.rows(traini);
    trainB = B.rows(traini);
    doBoot(trainA,trainB,C,BootMat,Summaries);
    Point = cor(trainA,trainB);
    TrueCor = cor(testA,testB);
    pointSumRMSE += RMSE(Point,TrueCor);
    bootSumRMSE += RMSE(Summaries,TrueCor);
  }
  pointSumRMSE = pointSumRMSE/kfoldIterations;
  bootSumRMSE = bootSumRMSE/kfoldIterations;

  ofstream outputfile;
  outputfile.open(file,std::ofstream::out|std::ofstream::app);

  if(chunknum==0){
    outputfile<<"Chunk\tSize\tbsi\tPointSumRMSE\tBootSumRMSE"<<endl;
  }
  outputfile<<chunknum<<"\t"<<Point.n_elem<<"\t"<<bsi<<"\t"<<pointSumRMSE<<"\t"<<bootSumRMSE<<endl;
  outputfile.close();
}

//void ComputeQuantiles(const running_stat_vec<rowvec> &stats, const mat &Co, mat &Quant, const vector<double> quantiles){

#endif

<commit_msg>Trace RMSE with each bootstrap iteration<commit_after>#ifndef MATMETHODS_HPP
#define MATMETHODS_HPP
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/timer/timer.hpp>
#include "armadillo"

using namespace arma;
using namespace std;
using boost::timer::auto_cpu_timer;

umat GenBoot (size_t colsize, size_t bootstrapnumber){
  boost::random::mt19937 rng;

  boost::random::uniform_int_distribution<> samples(0,colsize-1);

  umat samplemat(bootstrapnumber,colsize);

  for(umat::iterator it=samplemat.begin(); it!=samplemat.end();++it){
    (*it) = samples(rng);
  }
  return(samplemat);
}

void doBoot(mat &A, mat &B,cube &C,umat &BootMat, mat &Summaries){
  auto_cpu_timer timerInd;
  timerInd.stop();
  auto_cpu_timer timerCor;

  timerCor.stop();
  auto_cpu_timer timerMedian;
  timerMedian.stop();

  if(A.n_rows!=BootMat.n_cols){
    for(int i=1; i<C.n_slices; ++i){
      cout<<"Boot(incorrect indices): "<<i<<endl;
      C.slice(i) = cor(A.rows(BootMat(i,span(0,A.n_rows))),B.rows(BootMat(i,span(0,B.n_rows))));
    }
  }
  else{
    timerInd.resume();
    mat tA = A.rows(BootMat.row(0));
    mat tB = B.rows(BootMat.row(0));
    timerInd.stop();
    timerCor.resume();
    C.slice(0) = cor(tA,tB);
    timerCor.stop();
    for(int i=1; i<C.n_slices; ++i){
      cout<<"Boot: "<<i<<endl;
      timerInd.resume();
      tA = A.rows(BootMat.row(i));
      tB = B.rows(BootMat.row(i));
      timerInd.stop();
      timerCor.resume();
      C.slice(i) = cor(tA,tB);
      timerCor.stop();
    }
  }
  timerMedian.resume();
  for(int i=0; i<C.n_slices; i++){
    mat S = mat(C.n_rows,C.n_slices);
    for(int j=0; j< C.n_cols; j++){
      S = C(span::all,span(i,i),span(0,i));
      Summaries.slice(i).col(j)=median(S,1);
    }
  }
  timerMedian.stop();
  timerInd.report();
  timerCor.report();
  timerMedian.report();

}

uvec trainindex(const size_t totalsize,const int ksize,const int k){
  uvec returnvec(totalsize-ksize);
  int j=0;
  for(int i=0; i<totalsize; i++){
    if(i <(k*ksize)||i>((k+1)*ksize)-1){
      returnvec(j)=i;
      j++;
    }
  }
  return(returnvec);
}

uvec testindex(const size_t totalsize,const  int ksize,const  int k){
  uvec returnvec(ksize);
  int j=0;
  for( int i=0; i<totalsize; i++){
    if(i>=(k*ksize)&&i<=((k+1)*ksize-1)){
      returnvec(j)=i;
      j++;
    }
  }
  return(returnvec);
}

double RMSE(mat &Est, const mat &True){
  Est = sqrt(pow((Est-True),2));
  Est.elem(find_nonfinite(Est)).zeros();
  return(mean(mean(Est)));
}

void KfoldCV (const mat &A,const mat &B, const int kfold, const int chunknum, const int bsi,const string file){

  mat testA,testB,trainA,trainB;
  int kfoldIterations = (int) ceil((double)A.n_rows/(double)kfold);
  if(kfoldIterations<1){
    cerr<<"Must have at least one iteration of cross-validation, not "<<kfoldIterations<<endl;
    throw 12;
  }

  int iter_k = kfold;

  cout<<"Begin "<<iter_k<<"-fold cross validation. There are "<<A.n_rows<<" samples"<<endl;
  uvec testi = testindex(A.n_rows,iter_k,0);
  uvec traini = trainindex(A.n_rows,iter_k,0);

  try{
    testA = A.rows(testi);
    testB = B.rows(testi);

    trainA = A.rows(traini);
    trainB = B.rows(traini);
  } catch(...){
    cerr<<"Error indexing training and testing sets:"<<endl;
    cerr<<"Training: "<<traini<<endl;
    cerr<<"Testing: "<<testi<<endl;
    throw 4;
  }
  cout<<"Initiating variables and starting kfold: 0"<<endl;
  mat Point(A.n_cols,B.n_cols);
  cube Summaries(A.n_cols,B.n_cols,bsi);
  umat BootMat = GenBoot(trainA.n_rows,bsi);
  cube C(A.n_cols,B.n_cols,bsi);
  doBoot(trainA,trainB,C,BootMat,Summaries);
  Point = cor(trainA,trainB);
  mat TrueCor = cor(testA,testB);
  double pointSumRMSE = RMSE(Point,TrueCor);
  vector<double> bootSumRMSE(bsi);
  for(int i=0; i<bootSumRMSE.size(); i++){
    bootSumRMSE[i]=RMSE(Summaries.slice(i),TrueCor);
  }
  double bootSumRMSE = RMSE(Summaries,TrueCor);
  for(int i=1; i<kfoldIterations; i++){
    cout<<"Starting kfold: "<<i<<endl;
    testi = testindex(A.n_rows,iter_k,0);
    traini = trainindex(A.n_rows,iter_k,0);
    testA = A.rows(testi);
    testB = B.rows(testi);
    trainA = A.rows(traini);
    trainB = B.rows(traini);
    doBoot(trainA,trainB,C,BootMat,Summaries);
    Point = cor(trainA,trainB);
    TrueCor = cor(testA,testB);
    pointSumRMSE += RMSE(Point,TrueCor);
    for(int j=0; j<bootSumRMSE.size(); j++){
      bootSumRMSE[i] += RMSE(Summaries.slice(j),TrueCor);
    }
  }
  pointSumRMSE = pointSumRMSE/kfoldIterations;
  for(int j=0; j<bootSumRMSE.size(); j++){
    bootSumRMSE[i] = bootSumRMSE[i]/kfoldIterations;
  }

  ofstream outputfile;
  outputfile.open(file,std::ofstream::out|std::ofstream::app);

  if(chunknum==0){
    outputfile<<"Chunk\tSize\tbsi\tPointSumRMSE\tBootSumRMSE"<<endl;
  }
  for(int j=0; j<bootSumRMSE.size(); j++){
    outputfile<<chunknum<<"\t"<<Point.n_elem<<"\t"<<j+1<<"\t"<<pointSumRMSE<<"\t"<<bootSumRMSE[i]<<endl;
  }
  outputfile.close();
}

//void ComputeQuantiles(const running_stat_vec<rowvec> &stats, const mat &Co, mat &Quant, const vector<double> quantiles){

#endif

<|endoftext|>


<commit_before>/********************************************************************
* @file      : time_format.hpp
* @author    : zapline <zhuxianzhang@kingsoft.com>
* @date      : 2012/11/19 20:40
* @brief     : time format convert
*
*
*********************************************************************/

#ifndef _TIME_FORMAT_HPP_
#define _TIME_FORMAT_HPP_

#include <time.h>

#ifndef _FILETIME_
#define _FILETIME_
typedef struct _FILETIME
{
    DWORD dwLowDateTime;
    DWORD dwHighDateTime;
} 	FILETIME;
#endif

#define TIME_STRING_MAX_LEN 28

namespace zl
{

    FILETIME Time642FileTime(__time64_t tm)
    {
        FILETIME ft;
        LONGLONG ll;
        ll = tm*10000000 + 116444736000000000;
        ft.dwLowDateTime  = (DWORD)ll;
        ft.dwHighDateTime = (DWORD)(ll >> 32);
        return ft;
    }

    __time64_t FileTime2Time64(const FILETIME* pft)
    {
        __time64_t cTime = pft->dwHighDateTime;
        cTime = (cTime<<32) + pft->dwLowDateTime;
        return ((cTime - 116444736000000000)/10000000);
    }

    void Time2Str(const SYSTEMTIME& stTime, wchar_t* strTime /* [TIME_STRING_MAX_LEN] */ )
    {
        ::wsprintfW(strTime, L"%d-%d-%d %d:%d:%d:%d %d",
            stTime.wYear, stTime.wMonth, stTime.wDay,
            stTime.wHour, stTime.wMinute, stTime.wSecond,
            stTime.wMilliseconds, stTime.wDayOfWeek);
    }

    BOOL Str2Time(const wchar_t* strTime, SYSTEMTIME& stTime)
    {
        int nYear  = 0;
        int nMonth = 0;
        int nDay   = 0;
        int nHour  = 0;
        int nMinute = 0;
        int nSecond = 0;
        int nMilliseconds = 0;
        int nDayOfWeek = 0;
        if (::swscanf_s(strTime, L"%d-%d-%d %d:%d:%d:%d %d",
            &nYear, &nMonth, &nDay,
            &nHour, &nMinute, &nSecond,
            &nMilliseconds, &nDayOfWeek) == -1)
        {
            return FALSE;
        }
        stTime.wYear         = nYear;
        stTime.wMonth        = nMonth;
        stTime.wDayOfWeek    = nDayOfWeek;
        stTime.wDay          = nDay;
        stTime.wHour         = nHour;
        stTime.wMinute       = nMinute;
        stTime.wSecond       = nSecond;
        stTime.wMilliseconds = nMilliseconds;
        return TRUE;
    }

}

#endif
<commit_msg>add header file<commit_after>/********************************************************************
* @file      : time_format.hpp
* @author    : zapline <zhuxianzhang@kingsoft.com>
* @date      : 2012/11/19 20:40
* @brief     : time format convert
*
*
*********************************************************************/

#ifndef _TIME_FORMAT_HPP_
#define _TIME_FORMAT_HPP_

#include <time.h>
#include <stdio.h>

#ifndef _FILETIME_
#define _FILETIME_
typedef struct _FILETIME
{
    DWORD dwLowDateTime;
    DWORD dwHighDateTime;
} 	FILETIME;
#endif

#define TIME_STRING_MAX_LEN 28

namespace zl
{

    FILETIME Time642FileTime(__time64_t tm)
    {
        FILETIME ft;
        LONGLONG ll;
        ll = tm*10000000 + 116444736000000000;
        ft.dwLowDateTime  = (DWORD)ll;
        ft.dwHighDateTime = (DWORD)(ll >> 32);
        return ft;
    }

    __time64_t FileTime2Time64(const FILETIME* pft)
    {
        __time64_t cTime = pft->dwHighDateTime;
        cTime = (cTime<<32) + pft->dwLowDateTime;
        return ((cTime - 116444736000000000)/10000000);
    }

    void Time2Str(const SYSTEMTIME& stTime, wchar_t* strTime /* [TIME_STRING_MAX_LEN] */ )
    {
        ::wsprintfW(strTime, L"%d-%d-%d %d:%d:%d:%d %d",
            stTime.wYear, stTime.wMonth, stTime.wDay,
            stTime.wHour, stTime.wMinute, stTime.wSecond,
            stTime.wMilliseconds, stTime.wDayOfWeek);
    }

    BOOL Str2Time(const wchar_t* strTime, SYSTEMTIME& stTime)
    {
        int nYear  = 0;
        int nMonth = 0;
        int nDay   = 0;
        int nHour  = 0;
        int nMinute = 0;
        int nSecond = 0;
        int nMilliseconds = 0;
        int nDayOfWeek = 0;
        if (::swscanf_s(strTime, L"%d-%d-%d %d:%d:%d:%d %d",
            &nYear, &nMonth, &nDay,
            &nHour, &nMinute, &nSecond,
            &nMilliseconds, &nDayOfWeek) == -1)
        {
            return FALSE;
        }
        stTime.wYear         = nYear;
        stTime.wMonth        = nMonth;
        stTime.wDayOfWeek    = nDayOfWeek;
        stTime.wDay          = nDay;
        stTime.wHour         = nHour;
        stTime.wMinute       = nMinute;
        stTime.wSecond       = nSecond;
        stTime.wMilliseconds = nMilliseconds;
        return TRUE;
    }

}

#endif
<|endoftext|>


<commit_before>#include "Processor.h"
#include <sim/config.h>

#include <sys/time.h>
#include <ctime>

namespace Simulator
{

#define NUM_COUNTERS 18

size_t Processor::PerfCounters::GetSize() const { return NUM_COUNTERS * sizeof(Integer);  }

Result Processor::PerfCounters::Write(MemAddr /*address*/, const void * /*data*/, MemSize /*size*/, LFID /*fid*/, TID /*tid*/)
{
    return FAILED;
}

Result Processor::PerfCounters::Read(MemAddr address, void *data, MemSize size, LFID fid, TID tid, const RegAddr& /*writeback*/)
{
    if (size != sizeof(Integer) || address % sizeof(Integer) != 0 || address / sizeof(Integer) >= NUM_COUNTERS)
    {
        throw exceptf<InvalidArgumentException>(*this, "Invalid read to performance counter address by F%u/T%u: %#016llx/%u",
                                                (unsigned)fid, (unsigned)tid, (unsigned long long)address, (unsigned)size);
    }
    address /= sizeof(Integer);

    Processor& cpu = *static_cast<Processor*>(GetParent());

    const size_t placeSize  = cpu.m_familyTable[fid].placeSize;
    const size_t placeStart = (cpu.m_pid / placeSize) * placeSize;
    const size_t placeEnd   = placeStart + placeSize;
    Integer value;

    switch (address)
    {
    case 0:
    {
        // Return the number of elapsed cycles
        value = (Integer)GetKernel()->GetCycleNo();
    }
    break;
    case 1:
    {
        // Return the number of executed instructions on all cores
        Integer ops = 0;
        for (size_t i = placeStart; i < placeEnd; ++i)
        {
            ops += cpu.m_grid[i]->GetPipeline().GetOp();
        }
        value = ops;
    }
    break;
    case 2:
    {
        // Return the number of issued FP instructions on all cores
        Integer flops = 0;
        for (size_t i = placeStart; i < placeEnd; ++i)
        {
            flops += cpu.m_grid[i]->GetPipeline().GetFlop();
        }
        value = flops;
    }
    break;
    case 3:
    {
        // Return the number of completed loads on all cores
        uint64_t n = 0, dummy;
        for (size_t i = placeStart; i < placeEnd; ++i)
        {
            cpu.m_grid[i]->GetPipeline().CollectMemOpStatistics(n, dummy, dummy, dummy);
        }
        value = (Integer)n;
    }
    break;
    case 4:
    {
        // Return the number of completed stores on all cores
        uint64_t n = 0, dummy;
        for (size_t i = placeStart; i < placeEnd; ++i)
        {
            cpu.m_grid[i]->GetPipeline().CollectMemOpStatistics(dummy, n, dummy, dummy);
        }
        value = (Integer)n;
    }
    break;
    case 5:
    {
        // Return the number of successfully loaded bytes on all cores
        uint64_t n = 0, dummy;
        for (size_t i = placeStart; i < placeEnd; ++i)
        {
            cpu.m_grid[i]->GetPipeline().CollectMemOpStatistics(dummy, dummy, n, dummy);
        }
        value = (Integer)n;
    }
    break;
    case 6:
    {
        // Return the number of successfully stored bytes on all cores
        uint64_t n = 0, dummy;
        for (size_t i = placeStart; i < placeEnd; ++i)
        {
            cpu.m_grid[i]->GetPipeline().CollectMemOpStatistics(dummy, dummy, dummy, n);
        }
        value = (Integer)n;
    }
    break;
    case 7:
    {
        // Return the number of memory loads overall from L1 to L2 (cache lines)
        uint64_t n = 0, dummy;
        cpu.m_memory.GetMemoryStatistics(n, dummy, dummy, dummy, dummy, dummy);
        value = (Integer)n;
    }
    break;
    case 8:
    {
        // Return the number of memory stores overall from L1 to L2 (cache lines)
        uint64_t n = 0, dummy;
        cpu.m_memory.GetMemoryStatistics(dummy, n, dummy, dummy, dummy, dummy);
        value = (Integer)n;
    }
    break;
    case 9:
    {
        value = (Integer)placeSize;
    }
    break;
    case 10:
    {
        // Return the total cumulative allocated thread slots
        Integer alloc = 0;
        for (size_t i = placeStart; i < placeEnd; ++i)
        {
            alloc += cpu.m_grid[i]->GetTotalThreadsAllocated();
        }
        value = alloc;
    }
    break;
    case 11:
    {
        // Return the total cumulative allocated thread slots
        Integer alloc = 0;
        for (size_t i = placeStart; i < placeEnd; ++i)
        {
            alloc += cpu.m_grid[i]->GetTotalFamiliesAllocated();
        }
        value = alloc;
    }
    break;
    case 12:
    {
        // Return the total cumulative exclusive allocate queue size
        Integer alloc = 0;
        for (size_t i = placeStart; i < placeEnd; ++i)
        {
            alloc += cpu.m_grid[i]->GetTotalAllocateExQueueSize();
        }
        value = alloc;
    }
    break;
    case 13:
    {
        // Return the Unix time
        value = (Integer)time(0);
    }
    break;
    case 14:
    {
        // Return the local date as a packed struct
        // bits 0-4: day in month
        // bits 5-8: month in year
        // bits 9-31: year from 1900
        time_t c = time(0);
        struct tm * tm = gmtime(&c);
        value = (Integer)tm->tm_mday |
            ((Integer)tm->tm_mon << 5) |
            ((Integer)tm->tm_year << 9);
    }
    break;
    case 15:
    {
        // Return the local time as a packed struct
        // bits 0-14 = microseconds / 2^5  (topmost 15 bits)
        // bits 15-20 = seconds
        // bits 21-26 = minutes
        // bits 27-31 = hours
        struct timeval tv;
        gettimeofday(&tv, 0);
        struct tm * tm = gmtime(&tv.tv_sec);

        // get topmost 15 bits of precision of the usec field
        // usec is 0-999999; so it has 20 bits of value
        Integer usec = (tv.tv_usec >> (20-15)) & 0x7fff;
        value = usec | (tm->tm_sec << 15) | (tm->tm_min << 21) | (tm->tm_hour << 27);
    }
    break;
    case 16:
    {
        // Return the number of memory loads overall from external memory (cache lines)
        uint64_t n = 0, dummy;
        cpu.m_memory.GetMemoryStatistics(dummy, dummy, dummy, dummy, n, dummy);
        value = (Integer)n;
    }
    break;
    case 17:
    {
        // Return the number of memory stores overall to external memory (cache lines)
        uint64_t n = 0, dummy;
        cpu.m_memory.GetMemoryStatistics(dummy, dummy, dummy, dummy, dummy, n);
        value = (Integer)n;
    }
    break;
    case 18:
    {
        // Return the number of created families
        Integer tc = 0;
        for (size_t i = placeStart; i < placeEnd; ++i)
        {
            tc += cpu.m_grid[i]->GetTotalFamiliesCreated();
        }
        value = tc;
    }
    break;
    case 19:
    {
        // Return the number of created threads
        Integer fc = 0;
        for (size_t i = placeStart; i < placeEnd; ++i)
        {
            fc += cpu.m_grid[i]->GetTotalFamiliesCreated();
        }
        value = fc;
    }
    break;
    default:
        value = 0;
    }

    DebugIOWrite("Read counter %u by F%u/T%u: %#016llx (%llu)",
                 (unsigned)address, (unsigned)fid, (unsigned)tid,
                 (unsigned long long)value, (unsigned long long)value);

    COMMIT{
        if (address == 0)
        {
            ++m_nCycleSampleOps;
        }
        else
        {
            ++m_nOtherSampleOps;
        }
    }

    SerializeRegister(RT_INTEGER, value, data, sizeof(Integer));

    return SUCCESS;
}

Processor::PerfCounters::PerfCounters(Processor& parent, Config& config)
    : Processor::MMIOComponent("perfcounters", parent, parent.GetClock()),
      m_nCycleSampleOps(0),
      m_nOtherSampleOps(0)
{
    parent.WriteASR(ASR_NUM_PERFCOUNTERS, NUM_COUNTERS);
    parent.WriteASR(ASR_PERFCOUNTERS_BASE, config.getValue<MemAddr>(*this, "MMIO_BaseAddr"));

    RegisterSampleVariableInObject(m_nCycleSampleOps, SVC_CUMULATIVE);
    RegisterSampleVariableInObject(m_nOtherSampleOps, SVC_CUMULATIVE);
}

}
<commit_msg>Fix the sampling of the number of threads created.<commit_after>#include "Processor.h"
#include <sim/config.h>

#include <sys/time.h>
#include <ctime>

namespace Simulator
{

#define NUM_COUNTERS 18

size_t Processor::PerfCounters::GetSize() const { return NUM_COUNTERS * sizeof(Integer);  }

Result Processor::PerfCounters::Write(MemAddr /*address*/, const void * /*data*/, MemSize /*size*/, LFID /*fid*/, TID /*tid*/)
{
    return FAILED;
}

Result Processor::PerfCounters::Read(MemAddr address, void *data, MemSize size, LFID fid, TID tid, const RegAddr& /*writeback*/)
{
    if (size != sizeof(Integer) || address % sizeof(Integer) != 0 || address / sizeof(Integer) >= NUM_COUNTERS)
    {
        throw exceptf<InvalidArgumentException>(*this, "Invalid read to performance counter address by F%u/T%u: %#016llx/%u",
                                                (unsigned)fid, (unsigned)tid, (unsigned long long)address, (unsigned)size);
    }
    address /= sizeof(Integer);

    Processor& cpu = *static_cast<Processor*>(GetParent());

    const size_t placeSize  = cpu.m_familyTable[fid].placeSize;
    const size_t placeStart = (cpu.m_pid / placeSize) * placeSize;
    const size_t placeEnd   = placeStart + placeSize;
    Integer value;

    switch (address)
    {
    case 0:
    {
        // Return the number of elapsed cycles
        value = (Integer)GetKernel()->GetCycleNo();
    }
    break;
    case 1:
    {
        // Return the number of executed instructions on all cores
        Integer ops = 0;
        for (size_t i = placeStart; i < placeEnd; ++i)
        {
            ops += cpu.m_grid[i]->GetPipeline().GetOp();
        }
        value = ops;
    }
    break;
    case 2:
    {
        // Return the number of issued FP instructions on all cores
        Integer flops = 0;
        for (size_t i = placeStart; i < placeEnd; ++i)
        {
            flops += cpu.m_grid[i]->GetPipeline().GetFlop();
        }
        value = flops;
    }
    break;
    case 3:
    {
        // Return the number of completed loads on all cores
        uint64_t n = 0, dummy;
        for (size_t i = placeStart; i < placeEnd; ++i)
        {
            cpu.m_grid[i]->GetPipeline().CollectMemOpStatistics(n, dummy, dummy, dummy);
        }
        value = (Integer)n;
    }
    break;
    case 4:
    {
        // Return the number of completed stores on all cores
        uint64_t n = 0, dummy;
        for (size_t i = placeStart; i < placeEnd; ++i)
        {
            cpu.m_grid[i]->GetPipeline().CollectMemOpStatistics(dummy, n, dummy, dummy);
        }
        value = (Integer)n;
    }
    break;
    case 5:
    {
        // Return the number of successfully loaded bytes on all cores
        uint64_t n = 0, dummy;
        for (size_t i = placeStart; i < placeEnd; ++i)
        {
            cpu.m_grid[i]->GetPipeline().CollectMemOpStatistics(dummy, dummy, n, dummy);
        }
        value = (Integer)n;
    }
    break;
    case 6:
    {
        // Return the number of successfully stored bytes on all cores
        uint64_t n = 0, dummy;
        for (size_t i = placeStart; i < placeEnd; ++i)
        {
            cpu.m_grid[i]->GetPipeline().CollectMemOpStatistics(dummy, dummy, dummy, n);
        }
        value = (Integer)n;
    }
    break;
    case 7:
    {
        // Return the number of memory loads overall from L1 to L2 (cache lines)
        uint64_t n = 0, dummy;
        cpu.m_memory.GetMemoryStatistics(n, dummy, dummy, dummy, dummy, dummy);
        value = (Integer)n;
    }
    break;
    case 8:
    {
        // Return the number of memory stores overall from L1 to L2 (cache lines)
        uint64_t n = 0, dummy;
        cpu.m_memory.GetMemoryStatistics(dummy, n, dummy, dummy, dummy, dummy);
        value = (Integer)n;
    }
    break;
    case 9:
    {
        value = (Integer)placeSize;
    }
    break;
    case 10:
    {
        // Return the total cumulative allocated thread slots
        Integer alloc = 0;
        for (size_t i = placeStart; i < placeEnd; ++i)
        {
            alloc += cpu.m_grid[i]->GetTotalThreadsAllocated();
        }
        value = alloc;
    }
    break;
    case 11:
    {
        // Return the total cumulative allocated thread slots
        Integer alloc = 0;
        for (size_t i = placeStart; i < placeEnd; ++i)
        {
            alloc += cpu.m_grid[i]->GetTotalFamiliesAllocated();
        }
        value = alloc;
    }
    break;
    case 12:
    {
        // Return the total cumulative exclusive allocate queue size
        Integer alloc = 0;
        for (size_t i = placeStart; i < placeEnd; ++i)
        {
            alloc += cpu.m_grid[i]->GetTotalAllocateExQueueSize();
        }
        value = alloc;
    }
    break;
    case 13:
    {
        // Return the Unix time
        value = (Integer)time(0);
    }
    break;
    case 14:
    {
        // Return the local date as a packed struct
        // bits 0-4: day in month
        // bits 5-8: month in year
        // bits 9-31: year from 1900
        time_t c = time(0);
        struct tm * tm = gmtime(&c);
        value = (Integer)tm->tm_mday |
            ((Integer)tm->tm_mon << 5) |
            ((Integer)tm->tm_year << 9);
    }
    break;
    case 15:
    {
        // Return the local time as a packed struct
        // bits 0-14 = microseconds / 2^5  (topmost 15 bits)
        // bits 15-20 = seconds
        // bits 21-26 = minutes
        // bits 27-31 = hours
        struct timeval tv;
        gettimeofday(&tv, 0);
        struct tm * tm = gmtime(&tv.tv_sec);

        // get topmost 15 bits of precision of the usec field
        // usec is 0-999999; so it has 20 bits of value
        Integer usec = (tv.tv_usec >> (20-15)) & 0x7fff;
        value = usec | (tm->tm_sec << 15) | (tm->tm_min << 21) | (tm->tm_hour << 27);
    }
    break;
    case 16:
    {
        // Return the number of memory loads overall from external memory (cache lines)
        uint64_t n = 0, dummy;
        cpu.m_memory.GetMemoryStatistics(dummy, dummy, dummy, dummy, n, dummy);
        value = (Integer)n;
    }
    break;
    case 17:
    {
        // Return the number of memory stores overall to external memory (cache lines)
        uint64_t n = 0, dummy;
        cpu.m_memory.GetMemoryStatistics(dummy, dummy, dummy, dummy, dummy, n);
        value = (Integer)n;
    }
    break;
    case 18:
    {
        // Return the number of created families
        Integer tc = 0;
        for (size_t i = placeStart; i < placeEnd; ++i)
        {
            tc += cpu.m_grid[i]->GetTotalFamiliesCreated();
        }
        value = tc;
    }
    break;
    case 19:
    {
        // Return the number of created threads
        Integer fc = 0;
        for (size_t i = placeStart; i < placeEnd; ++i)
        {
            fc += cpu.m_grid[i]->GetTotalThreadsCreated();
        }
        value = fc;
    }
    break;
    default:
        value = 0;
    }

    DebugIOWrite("Read counter %u by F%u/T%u: %#016llx (%llu)",
                 (unsigned)address, (unsigned)fid, (unsigned)tid,
                 (unsigned long long)value, (unsigned long long)value);

    COMMIT{
        if (address == 0)
        {
            ++m_nCycleSampleOps;
        }
        else
        {
            ++m_nOtherSampleOps;
        }
    }

    SerializeRegister(RT_INTEGER, value, data, sizeof(Integer));

    return SUCCESS;
}

Processor::PerfCounters::PerfCounters(Processor& parent, Config& config)
    : Processor::MMIOComponent("perfcounters", parent, parent.GetClock()),
      m_nCycleSampleOps(0),
      m_nOtherSampleOps(0)
{
    parent.WriteASR(ASR_NUM_PERFCOUNTERS, NUM_COUNTERS);
    parent.WriteASR(ASR_PERFCOUNTERS_BASE, config.getValue<MemAddr>(*this, "MMIO_BaseAddr"));

    RegisterSampleVariableInObject(m_nCycleSampleOps, SVC_CUMULATIVE);
    RegisterSampleVariableInObject(m_nOtherSampleOps, SVC_CUMULATIVE);
}

}
<|endoftext|>


<commit_before><commit_msg>[BackgroundSync] Use appopriate type parameters for WebCallbacks (1/4)<commit_after><|endoftext|>


<commit_before>/*
 * BLINKERCOUGH: NSA Playset implant for IR bridging of airgap
 *
 * Copyright (C) 2015  Hacker, J.R. <r00tkillah@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "mac.h"
#include "util.h"
#include <Arduino.h>

BlinkerMac mac;
MemberFunctionCallable<BlinkerMac> MACRelayCB(&mac, &BlinkerMac::relayCallback);

BlinkerMac::BlinkerMac() : serial(SoftwareSerial(IR_RX_PIN, IR_TX_PIN, false))
{
}

void BlinkerMac::begin()
{
    serial.begin(IR_BAUD);
    reset();
    buf = FrameFactory.alloc();
    eventManager.addListener(BlinkerMac::PacketNeedsRelayEvent,
                             &MACRelayCB);
}

void BlinkerMac::reset()
{
    rx_blink = false;
    packet_in_progress = false;
    buf_pos = 0;
    prefix_state = 0;
    reset_codec_state();
}

void BlinkerMac::write_prefix()
{
    for (uint8_t i = 0; i < preamble_count; i++) {
        (*this)(preamble_byte);
    }
    for (uint8_t i = 0; i < sizeof(packet_prefix); i++) {
        (*this)(packet_prefix[i]);
    }
}

bool BlinkerMac::prefix_hit(uint8_t input)
{
    if (prefix_state == 0) {
        if (input == packet_prefix[0]) {
            prefix_state = 1;
        }
    } else if (prefix_state == 1) {
        if (input == packet_prefix[1]) {
            prefix_state = 2;
        } else {
            prefix_state = 0;
        }
    } else if (prefix_state == 2) {
        if (input == packet_prefix[2]) {
            prefix_state = 3;
        } else {
            prefix_state = 0;
        }
    } else if (prefix_state == 3) {
            prefix_state = 0;
        if (input == packet_prefix[3]) {
            return true;
        }
    }
    return false;
}

bool BlinkerMac::blink()
{
    rx_blink = rx_blink ? false : true;
    return rx_blink;
}

bool BlinkerMac::stalled()
{
    const unsigned long now = millis();

    if (now - last_rx_time > 250) {
        return true;
    }
    last_rx_time = now;
    return false;
}

//expectation here is that hton is done
//and crc is calculated
void BlinkerMac::send_frame(IRFrame &frame)
{
    debug("Sending packet");

    write_prefix();
    for (uint16_t i = 0; i < sizeof(IRFrame); i++) {
        encode_byte(frame.blob()[i], *this);
    }
    serial.flush();

    // while this is happening, you'll get crap that is your own packet.
    // clear out any remaining input
    while(serial.available()) {
        (void)serial.read();
        delay(1);
    }
}

void BlinkerMac::recv(const uint8_t c)
{
    digitalWrite(13, blink());

    // if you haven't gotten a byte in a while, then what you have
    // is probably garbage.
    if (packet_in_progress && stalled()) {
        debug("aborting rcv");
        IRFrame::hexdump(buf);
        reset();
        return;
    }
    if (!packet_in_progress) {
        packet_in_progress = prefix_hit(c);
        last_rx_time = millis();
        return; //the next byte should be the first byte of a packet
    }

    debugstart("%d", buf_pos);
    debugcont(" ");
    //geting a packet
    uint8_t input;
    if (decode_byte(c, input)) {
        buf->blob()[buf_pos] = input;
        buf_pos++;
    } else {
        return; // was a stuffed byte
    }

    if (buf_pos >= sizeof(IRFrame)) {
        //whole packet recieved!
        buf_pos = 0;
        packet_in_progress = false;

        if (buf->valid()) {
            buf->ntoh();

            if (buf->destination != address) {
                if (buf->hops < MAX_HOPS) {
                    auto newbuf = FrameFactory.alloc();
                    IRFrame::copy(newbuf, buf);
                    eventManager.queueEvent(PacketNeedsRelayEvent, (int)newbuf);
                    debugend();
                    reset();
                    return;
                } else {
                    debugcont("too many hops.. eating");
                    debugend();
                    reset();
                    return;
                }
            }

            auto newbuf = FrameFactory.alloc();
            IRFrame::copy(newbuf, buf);
            eventManager.queueEvent(ValidFrameRecievedEvent, (int)newbuf);
            debugend();
            reset();
            return;
        } else {
            auto newbuf = FrameFactory.alloc();
            IRFrame::copy(newbuf, buf);
            eventManager.queueEvent(InvalidFrameRecievedEvent, (int)newbuf);
            debugend();
            reset();
        }
    }
    return;
}

void BlinkerMac::relayCallback(int event, int param)
{
    //niave approach.. just send it back out this is kind of wrong we
    //should wait a random time before retransmit and as we get
    //packets, we should cancel retransmit if we saw a neighbor do it
    //first.  but when we see that neighbor do it, we schedule a new
    //one to retransmit.

    IRFrame *buf = (IRFrame*)param;
    debug("Packet from 0x%04x to 0x%04x hop %d",
          buf->source, buf->destination,
          buf->hops);

    buf->hops++;
    buf->hton();
    buf->calculate_crc();
    debug("Retransmitting packet...");
    send_frame(*buf);
    debug("done");
    reset();

    FrameFactory.free(buf);
}

/*
 * Editor modelines  -  https://www.wireshark.org/tools/modelines.html
 *
 * Local variables:
 * mode: c++
 * c-basic-offset: 4
 * tab-width: 8
 * indent-tabs-mode: nil
 * End:
 *
 * vi: set shiftwidth=4 tabstop=8 expandtab:
 * :indentSize=4:tabSize=8:noTabs=true:
 */
<commit_msg>don't relay your own packets<commit_after>/*
 * BLINKERCOUGH: NSA Playset implant for IR bridging of airgap
 *
 * Copyright (C) 2015  Hacker, J.R. <r00tkillah@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "mac.h"
#include "util.h"
#include <Arduino.h>

BlinkerMac mac;
MemberFunctionCallable<BlinkerMac> MACRelayCB(&mac, &BlinkerMac::relayCallback);

BlinkerMac::BlinkerMac() : serial(SoftwareSerial(IR_RX_PIN, IR_TX_PIN, false))
{
}

void BlinkerMac::begin()
{
    serial.begin(IR_BAUD);
    reset();
    buf = FrameFactory.alloc();
    eventManager.addListener(BlinkerMac::PacketNeedsRelayEvent,
                             &MACRelayCB);
}

void BlinkerMac::reset()
{
    rx_blink = false;
    packet_in_progress = false;
    buf_pos = 0;
    prefix_state = 0;
    reset_codec_state();
}

void BlinkerMac::write_prefix()
{
    for (uint8_t i = 0; i < preamble_count; i++) {
        (*this)(preamble_byte);
    }
    for (uint8_t i = 0; i < sizeof(packet_prefix); i++) {
        (*this)(packet_prefix[i]);
    }
}

bool BlinkerMac::prefix_hit(uint8_t input)
{
    if (prefix_state == 0) {
        if (input == packet_prefix[0]) {
            prefix_state = 1;
        }
    } else if (prefix_state == 1) {
        if (input == packet_prefix[1]) {
            prefix_state = 2;
        } else {
            prefix_state = 0;
        }
    } else if (prefix_state == 2) {
        if (input == packet_prefix[2]) {
            prefix_state = 3;
        } else {
            prefix_state = 0;
        }
    } else if (prefix_state == 3) {
            prefix_state = 0;
        if (input == packet_prefix[3]) {
            return true;
        }
    }
    return false;
}

bool BlinkerMac::blink()
{
    rx_blink = rx_blink ? false : true;
    return rx_blink;
}

bool BlinkerMac::stalled()
{
    const unsigned long now = millis();

    if (now - last_rx_time > 250) {
        return true;
    }
    last_rx_time = now;
    return false;
}

//expectation here is that hton is done
//and crc is calculated
void BlinkerMac::send_frame(IRFrame &frame)
{
    debug("Sending packet");

    write_prefix();
    for (uint16_t i = 0; i < sizeof(IRFrame); i++) {
        encode_byte(frame.blob()[i], *this);
    }
    serial.flush();

    // while this is happening, you'll get crap that is your own packet.
    // clear out any remaining input
    while(serial.available()) {
        (void)serial.read();
        delay(1);
    }
}

void BlinkerMac::recv(const uint8_t c)
{
    digitalWrite(13, blink());

    // if you haven't gotten a byte in a while, then what you have
    // is probably garbage.
    if (packet_in_progress && stalled()) {
        debug("aborting rcv");
        IRFrame::hexdump(buf);
        reset();
        return;
    }
    if (!packet_in_progress) {
        packet_in_progress = prefix_hit(c);
        last_rx_time = millis();
        return; //the next byte should be the first byte of a packet
    }

    debugstart("%d", buf_pos);
    debugcont(" ");
    //geting a packet
    uint8_t input;
    if (decode_byte(c, input)) {
        buf->blob()[buf_pos] = input;
        buf_pos++;
    } else {
        return; // was a stuffed byte
    }

    if (buf_pos >= sizeof(IRFrame)) {
        //whole packet recieved!
        buf_pos = 0;
        packet_in_progress = false;

        if (buf->valid()) {
            buf->ntoh();

            if (buf->source == address) {
                // don't relay our own packets
                debugend();
                reset();
                return;
            }

            if (buf->destination != address) {
                if (buf->hops < MAX_HOPS) {
                    auto newbuf = FrameFactory.alloc();
                    IRFrame::copy(newbuf, buf);
                    eventManager.queueEvent(PacketNeedsRelayEvent, (int)newbuf);
                    debugend();
                    reset();
                    return;
                } else {
                    debugcont("too many hops.. eating");
                    debugend();
                    reset();
                    return;
                }
            }

            auto newbuf = FrameFactory.alloc();
            IRFrame::copy(newbuf, buf);
            eventManager.queueEvent(ValidFrameRecievedEvent, (int)newbuf);
            debugend();
            reset();
            return;
        } else {
            auto newbuf = FrameFactory.alloc();
            IRFrame::copy(newbuf, buf);
            eventManager.queueEvent(InvalidFrameRecievedEvent, (int)newbuf);
            debugend();
            reset();
        }
    }
    return;
}

void BlinkerMac::relayCallback(int event, int param)
{
    //niave approach.. just send it back out this is kind of wrong we
    //should wait a random time before retransmit and as we get
    //packets, we should cancel retransmit if we saw a neighbor do it
    //first.  but when we see that neighbor do it, we schedule a new
    //one to retransmit.

    IRFrame *buf = (IRFrame*)param;
    debug("Packet from 0x%04x to 0x%04x hop %d",
          buf->source, buf->destination,
          buf->hops);

    buf->hops++;
    buf->hton();
    buf->calculate_crc();
    debug("Retransmitting packet...");
    send_frame(*buf);
    debug("done");
    reset();

    FrameFactory.free(buf);
}

/*
 * Editor modelines  -  https://www.wireshark.org/tools/modelines.html
 *
 * Local variables:
 * mode: c++
 * c-basic-offset: 4
 * tab-width: 8
 * indent-tabs-mode: nil
 * End:
 *
 * vi: set shiftwidth=4 tabstop=8 expandtab:
 * :indentSize=4:tabSize=8:noTabs=true:
 */
<|endoftext|>


<commit_before>/*
For more information, please see: http://software.sci.utah.edu

The MIT License

Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.

License for the specific language governing rights and limitations under
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/

#include <Interface/Modules/Forward/BuildBEMatrixDialog.h>
#include <Core/Algorithms/Legacy/Forward/BuildBEMatrixAlgo.h>

using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Algorithms::Forward;

namespace TableColumns
{
  const int FieldName = 0;
  const int FieldType = 1;
  const int BoundaryCondition = 2;
  const int InsideConductivity = 3;
  const int OutsideConductivity = 4;
};

BuildBEMatrixDialog::BuildBEMatrixDialog(const std::string& name, ModuleStateHandle state,
  QWidget* parent /* = 0 */)
  : ModuleDialogGeneric(state, parent)
{
  setupUi(this);
  setWindowTitle(QString::fromStdString(name));
  fixSize();

  tableWidget->resizeColumnsToContents();

  connect(tableWidget, SIGNAL(cellChanged(int,int)), this, SLOT(pushTable(int,int)));
}

void BuildBEMatrixDialog::updateFromPortChange(int numPorts)
{
  //std::cout << "updateFromPortChange " << numPorts << std::endl;
  auto oldRowCount = tableWidget->rowCount();
  tableWidget->setRowCount(numPorts - 1);
  tableWidget->blockSignals(true);
  for (int i = oldRowCount; i < tableWidget->rowCount(); ++i)
  {
    using namespace TableColumns;
    tableWidget->setItem(i, FieldName, new QTableWidgetItem("field" + QString::number(i)));
    tableWidget->setItem(i, FieldType, new QTableWidgetItem("[populated on execute]"));
    tableWidget->setCellWidget(i, BoundaryCondition, makeComboBoxItem(i));
    tableWidget->setCellWidget(i, InsideConductivity, makeDoubleEntryItem(i, InsideConductivity));
    tableWidget->setCellWidget(i, OutsideConductivity, makeDoubleEntryItem(i, OutsideConductivity));

    // type is readonly
    auto type = tableWidget->item(i, FieldType);
    type->setFlags(type->flags() & ~Qt::ItemIsEditable);
  }
  pull();
  tableWidget->resizeColumnsToContents();
  tableWidget->blockSignals(false);
}

QComboBox* BuildBEMatrixDialog::makeComboBoxItem(int i) const
{
  QStringList bcList;
  bcList << "Measurement (Neumann)" << "Source (Dirichlet)";
  QComboBox* bcBox = new QComboBox();
  bcBox->addItems(bcList);
  bcBox->setCurrentIndex(i == 0 ? 0 : 1);
  connect(bcBox, SIGNAL(currentIndexChanged(int)), this, SLOT(pushBoundaryConditions()));
  return bcBox;
}

QDoubleSpinBox* BuildBEMatrixDialog::makeDoubleEntryItem(int row, int col) const
{
  auto spin = new QDoubleSpinBox();
  spin->setValue((row + col + 1) % 2);
  const char* slot = col == TableColumns::InsideConductivity ? SLOT(pushInsides()) : SLOT(pushOutsides());
  connect(spin, SIGNAL(valueChanged(double)), this, slot);
  return spin;
}

void BuildBEMatrixDialog::pushTable(int row, int col)
{
  using namespace TableColumns;
  if (FieldName == col)
    pushNames();
  else if (BoundaryCondition == col)
    pushBoundaryConditions();
  else if (InsideConductivity == col)
    pushInsides();
  else if (OutsideConductivity == col)
    pushOutsides();
}

void BuildBEMatrixDialog::pushNames()
{
  using namespace TableColumns;
  if (!pulling_)
  {
    VariableList names;
    for (int i = 0; i < tableWidget->rowCount(); ++i)
    {
      auto item = tableWidget->item(i, FieldName);
      names.push_back(makeVariable("", item->text().toStdString()));
    }
    state_->setValue(Parameters::FieldNameList, names);
  }
}

void BuildBEMatrixDialog::pushBoundaryConditions()
{
  using namespace TableColumns;
  if (!pulling_)
  {
    VariableList names;
    for (int i = 0; i < tableWidget->rowCount(); ++i)
    {
      auto box = qobject_cast<QComboBox*>(tableWidget->cellWidget(i, BoundaryCondition));
      names.push_back(makeVariable("", box->currentText().toStdString()));
    }
    state_->setValue(Parameters::BoundaryConditionList, names);
  }
}

void BuildBEMatrixDialog::pushInsides()
{
  using namespace TableColumns;
  if (!pulling_)
  {
    VariableList names;
    for (int i = 0; i < tableWidget->rowCount(); ++i)
    {
      auto box = qobject_cast<QDoubleSpinBox*>(tableWidget->cellWidget(i, InsideConductivity));
      names.push_back(makeVariable("", box->value()));
    }
    state_->setValue(Parameters::InsideConductivityList, names);
  }
}

void BuildBEMatrixDialog::pushOutsides()
{
  using namespace TableColumns;
  if (!pulling_)
  {
    VariableList names;
    for (int i = 0; i < tableWidget->rowCount(); ++i)
    {
      auto box = qobject_cast<QDoubleSpinBox*>(tableWidget->cellWidget(i, OutsideConductivity));
      names.push_back(makeVariable("", box->value()));
    }
    state_->setValue(Parameters::OutsideConductivityList, names);
  }
}

void BuildBEMatrixDialog::pull()
{
  //std::cout << "BE pull" << std::endl;
  pullNames();
  pullFieldTypes();
  pullBoundaryConditions();
  pullInsides();
  pullOutsides();
}

void BuildBEMatrixDialog::pullNames()
{
  using namespace TableColumns;
  Pulling p(this);
  auto nameList = state_->getValue(Parameters::FieldNameList).toVector();
  const int rows = std::min(static_cast<int>(nameList.size()), tableWidget->rowCount());
  for (int row = 0; row < rows; ++row)
  {
    auto item = tableWidget->item(row, FieldName);
    item->setText(QString::fromStdString(nameList[row].toString()));
  }
}

void BuildBEMatrixDialog::pullFieldTypes()
{
  using namespace TableColumns;
  Pulling p(this);
  auto typeList = optional_any_cast_or_default<FieldTypeListType>(state_->getTransientValue(Parameters::FieldTypeList));
  const int rows = std::min(static_cast<int>(typeList.size()), tableWidget->rowCount());
  for (int row = 0; row < rows; ++row)
  {
    auto item = tableWidget->item(row, FieldName);
    item->setText(QString::fromStdString(typeList[row]));
  }
}

void BuildBEMatrixDialog::pullBoundaryConditions()
{
  using namespace TableColumns;
  Pulling p(this);
  auto bdyList = state_->getValue(Parameters::BoundaryConditionList).toVector();
  const int rows = std::min(static_cast<int>(bdyList.size()), tableWidget->rowCount());
  for (int row = 0; row < rows; ++row)
  {
    auto box = qobject_cast<QComboBox*>(tableWidget->cellWidget(row, BoundaryCondition));
    auto str = QString::fromStdString(bdyList[row].toString());
    box->setCurrentIndex(box->findText(str));
  }
}

void BuildBEMatrixDialog::pullInsides()
{
  using namespace TableColumns;
  Pulling p(this);
  auto condList = state_->getValue(Parameters::InsideConductivityList).toVector();
  const int rows = std::min(static_cast<int>(condList.size()), tableWidget->rowCount());
  for (int row = 0; row < rows; ++row)
  {
    auto box = qobject_cast<QDoubleSpinBox*>(tableWidget->cellWidget(row, InsideConductivity));
    box->setValue(condList[row].toDouble());
  }
}

void BuildBEMatrixDialog::pullOutsides()
{
  using namespace TableColumns;
  Pulling p(this);
  auto condList = state_->getValue(Parameters::OutsideConductivityList).toVector();
  const int rows = std::min(static_cast<int>(condList.size()), tableWidget->rowCount());
  for (int row = 0; row < rows; ++row)
  {
    auto box = qobject_cast<QDoubleSpinBox*>(tableWidget->cellWidget(row, OutsideConductivity));
    box->setValue(condList[row].toDouble());
  }
}
<commit_msg>Wrong column<commit_after>/*
For more information, please see: http://software.sci.utah.edu

The MIT License

Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.

License for the specific language governing rights and limitations under
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/

#include <Interface/Modules/Forward/BuildBEMatrixDialog.h>
#include <Core/Algorithms/Legacy/Forward/BuildBEMatrixAlgo.h>

using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Algorithms::Forward;

namespace TableColumns
{
  const int FieldName = 0;
  const int FieldType = 1;
  const int BoundaryCondition = 2;
  const int InsideConductivity = 3;
  const int OutsideConductivity = 4;
};

BuildBEMatrixDialog::BuildBEMatrixDialog(const std::string& name, ModuleStateHandle state,
  QWidget* parent /* = 0 */)
  : ModuleDialogGeneric(state, parent)
{
  setupUi(this);
  setWindowTitle(QString::fromStdString(name));
  fixSize();

  tableWidget->resizeColumnsToContents();

  connect(tableWidget, SIGNAL(cellChanged(int,int)), this, SLOT(pushTable(int,int)));
}

void BuildBEMatrixDialog::updateFromPortChange(int numPorts)
{
  //std::cout << "updateFromPortChange " << numPorts << std::endl;
  auto oldRowCount = tableWidget->rowCount();
  tableWidget->setRowCount(numPorts - 1);
  tableWidget->blockSignals(true);
  for (int i = oldRowCount; i < tableWidget->rowCount(); ++i)
  {
    using namespace TableColumns;
    tableWidget->setItem(i, FieldName, new QTableWidgetItem("field" + QString::number(i)));
    tableWidget->setItem(i, FieldType, new QTableWidgetItem("[populated on execute]"));
    tableWidget->setCellWidget(i, BoundaryCondition, makeComboBoxItem(i));
    tableWidget->setCellWidget(i, InsideConductivity, makeDoubleEntryItem(i, InsideConductivity));
    tableWidget->setCellWidget(i, OutsideConductivity, makeDoubleEntryItem(i, OutsideConductivity));

    // type is readonly
    auto type = tableWidget->item(i, FieldType);
    type->setFlags(type->flags() & ~Qt::ItemIsEditable);
  }
  pull();
  tableWidget->resizeColumnsToContents();
  tableWidget->blockSignals(false);
}

QComboBox* BuildBEMatrixDialog::makeComboBoxItem(int i) const
{
  QStringList bcList;
  bcList << "Measurement (Neumann)" << "Source (Dirichlet)";
  QComboBox* bcBox = new QComboBox();
  bcBox->addItems(bcList);
  bcBox->setCurrentIndex(i == 0 ? 0 : 1);
  connect(bcBox, SIGNAL(currentIndexChanged(int)), this, SLOT(pushBoundaryConditions()));
  return bcBox;
}

QDoubleSpinBox* BuildBEMatrixDialog::makeDoubleEntryItem(int row, int col) const
{
  auto spin = new QDoubleSpinBox();
  spin->setValue((row + col + 1) % 2);
  const char* slot = col == TableColumns::InsideConductivity ? SLOT(pushInsides()) : SLOT(pushOutsides());
  connect(spin, SIGNAL(valueChanged(double)), this, slot);
  return spin;
}

void BuildBEMatrixDialog::pushTable(int row, int col)
{
  using namespace TableColumns;
  if (FieldName == col)
    pushNames();
  else if (BoundaryCondition == col)
    pushBoundaryConditions();
  else if (InsideConductivity == col)
    pushInsides();
  else if (OutsideConductivity == col)
    pushOutsides();
}

void BuildBEMatrixDialog::pushNames()
{
  using namespace TableColumns;
  if (!pulling_)
  {
    VariableList names;
    for (int i = 0; i < tableWidget->rowCount(); ++i)
    {
      auto item = tableWidget->item(i, FieldName);
      names.push_back(makeVariable("", item->text().toStdString()));
    }
    state_->setValue(Parameters::FieldNameList, names);
  }
}

void BuildBEMatrixDialog::pushBoundaryConditions()
{
  using namespace TableColumns;
  if (!pulling_)
  {
    VariableList names;
    for (int i = 0; i < tableWidget->rowCount(); ++i)
    {
      auto box = qobject_cast<QComboBox*>(tableWidget->cellWidget(i, BoundaryCondition));
      names.push_back(makeVariable("", box->currentText().toStdString()));
    }
    state_->setValue(Parameters::BoundaryConditionList, names);
  }
}

void BuildBEMatrixDialog::pushInsides()
{
  using namespace TableColumns;
  if (!pulling_)
  {
    VariableList names;
    for (int i = 0; i < tableWidget->rowCount(); ++i)
    {
      auto box = qobject_cast<QDoubleSpinBox*>(tableWidget->cellWidget(i, InsideConductivity));
      names.push_back(makeVariable("", box->value()));
    }
    state_->setValue(Parameters::InsideConductivityList, names);
  }
}

void BuildBEMatrixDialog::pushOutsides()
{
  using namespace TableColumns;
  if (!pulling_)
  {
    VariableList names;
    for (int i = 0; i < tableWidget->rowCount(); ++i)
    {
      auto box = qobject_cast<QDoubleSpinBox*>(tableWidget->cellWidget(i, OutsideConductivity));
      names.push_back(makeVariable("", box->value()));
    }
    state_->setValue(Parameters::OutsideConductivityList, names);
  }
}

void BuildBEMatrixDialog::pull()
{
  //std::cout << "BE pull" << std::endl;
  pullNames();
  pullFieldTypes();
  pullBoundaryConditions();
  pullInsides();
  pullOutsides();
}

void BuildBEMatrixDialog::pullNames()
{
  using namespace TableColumns;
  Pulling p(this);
  auto nameList = state_->getValue(Parameters::FieldNameList).toVector();
  const int rows = std::min(static_cast<int>(nameList.size()), tableWidget->rowCount());
  for (int row = 0; row < rows; ++row)
  {
    auto item = tableWidget->item(row, FieldName);
    item->setText(QString::fromStdString(nameList[row].toString()));
  }
}

void BuildBEMatrixDialog::pullFieldTypes()
{
  using namespace TableColumns;
  Pulling p(this);
  auto typeList = optional_any_cast_or_default<FieldTypeListType>(state_->getTransientValue(Parameters::FieldTypeList));
  const int rows = std::min(static_cast<int>(typeList.size()), tableWidget->rowCount());
  for (int row = 0; row < rows; ++row)
  {
    auto item = tableWidget->item(row, FieldType);
    item->setText(QString::fromStdString(typeList[row]));
  }
}

void BuildBEMatrixDialog::pullBoundaryConditions()
{
  using namespace TableColumns;
  Pulling p(this);
  auto bdyList = state_->getValue(Parameters::BoundaryConditionList).toVector();
  const int rows = std::min(static_cast<int>(bdyList.size()), tableWidget->rowCount());
  for (int row = 0; row < rows; ++row)
  {
    auto box = qobject_cast<QComboBox*>(tableWidget->cellWidget(row, BoundaryCondition));
    auto str = QString::fromStdString(bdyList[row].toString());
    box->setCurrentIndex(box->findText(str));
  }
}

void BuildBEMatrixDialog::pullInsides()
{
  using namespace TableColumns;
  Pulling p(this);
  auto condList = state_->getValue(Parameters::InsideConductivityList).toVector();
  const int rows = std::min(static_cast<int>(condList.size()), tableWidget->rowCount());
  for (int row = 0; row < rows; ++row)
  {
    auto box = qobject_cast<QDoubleSpinBox*>(tableWidget->cellWidget(row, InsideConductivity));
    box->setValue(condList[row].toDouble());
  }
}

void BuildBEMatrixDialog::pullOutsides()
{
  using namespace TableColumns;
  Pulling p(this);
  auto condList = state_->getValue(Parameters::OutsideConductivityList).toVector();
  const int rows = std::min(static_cast<int>(condList.size()), tableWidget->rowCount());
  for (int row = 0; row < rows; ++row)
  {
    auto box = qobject_cast<QDoubleSpinBox*>(tableWidget->cellWidget(row, OutsideConductivity));
    box->setValue(condList[row].toDouble());
  }
}
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2020 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include "OSPRayCamera.h"
#include <Interface/Modules/Render/ES/RendererInterfaceCollaborators.h>

#include <glm/gtc/type_ptr.hpp>

using namespace SCIRun::Render;
using namespace SCIRun::Core::Geometry;

OSPRayCamera::OSPRayCamera()
{
  camera_ = ospNewCamera("perspective");
}

OSPRayCamera::~OSPRayCamera()
{
  ospRelease(camera_);
}

OSPCamera OSPRayCamera::getOSPCamera()
{
  glm::vec3 dir = target_ - pos_;
  float dist = glm::length(dir);
  dir = dir/dist;

  ospSetParam(camera_, "position",  OSP_VEC3F, glm::value_ptr(pos_));
  ospSetParam(camera_, "direction", OSP_VEC3F, glm::value_ptr(dir));
  ospSetParam(camera_, "up",        OSP_VEC3F, glm::value_ptr(up_));
  ospSetParam(camera_, "aspect",    OSP_FLOAT, &aspect_);
  ospSetParam(camera_, "fovy",      OSP_FLOAT, &fovy_);
  ospSetParam(camera_, "apertureRadius", OSP_FLOAT, &aperture_);
  ospSetParam(camera_, "focusDistance",  OSP_FLOAT, &dist);
  ospCommit(camera_);

  return camera_;
}

void OSPRayCamera::mousePress(float x, float y, MouseButton btn)
{
  switch(btn)
  {
    case MouseButton::LEFT:
    case MouseButton::RIGHT:
      lookat_.doReferenceDown(glm::vec2(x, -y));
    break;

    default:break;
  }
}

void OSPRayCamera::mouseMove(float x, float y, MouseButton btn)
{
  switch (btn)
  {
  case MouseButton::LEFT:
    lookat_.doRotation(glm::vec2(x, -y));
    pos_ = lookat_.getPos();
    up_ = lookat_.getUp();
    break;

  case MouseButton::RIGHT:
    lookat_.doPan(glm::vec2(x, -y));
    pos_ = lookat_.getPos();
    target_ = lookat_.getTarget();
    break;

  default:
    break;
  }
}

void OSPRayCamera::mouseRelease()
{

}

void OSPRayCamera::mouseWheel(int delta)
{
  lookat_.doZoom(-delta/100.0f);
  pos_ = lookat_.getPos();
}

float OSPRayCamera::toRadians(float v)
{
  const static float HALF_TURN_DEGREES = 180;
  const static float TO_RADIAN_OPERATOR = glm::pi<float>() / HALF_TURN_DEGREES;
  return TO_RADIAN_OPERATOR * v;
}

void OSPRayCamera::autoView()
{
  if(!sceneBBox_.valid()) return;

  // Convert core geom bbox to AABB.
  Core::Geometry::Point bboxMin = sceneBBox_.get_min();
  Core::Geometry::Point bboxMax = sceneBBox_.get_max();
  glm::vec3 min(bboxMin.x(), bboxMin.y(), bboxMin.z());
  glm::vec3 max(bboxMax.x(), bboxMax.y(), bboxMax.z());

  spire::AABB aabb(min, max);

  // The arcball class expects fov in radians
  lookat_.autoview(aabb, toRadians(fovy_));
  pos_ = lookat_.getPos();
}

void OSPRayCamera::setSceneBoundingBox(const BBox& bbox)
{
  sceneBBox_ = bbox;
}
<commit_msg>Set target on autoview<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2020 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include "OSPRayCamera.h"
#include <Interface/Modules/Render/ES/RendererInterfaceCollaborators.h>

#include <glm/gtc/type_ptr.hpp>

using namespace SCIRun::Render;
using namespace SCIRun::Core::Geometry;

OSPRayCamera::OSPRayCamera()
{
  camera_ = ospNewCamera("perspective");
}

OSPRayCamera::~OSPRayCamera()
{
  ospRelease(camera_);
}

OSPCamera OSPRayCamera::getOSPCamera()
{
  glm::vec3 dir = target_ - pos_;
  float dist = glm::length(dir);
  dir = dir/dist;

  ospSetParam(camera_, "position",  OSP_VEC3F, glm::value_ptr(pos_));
  ospSetParam(camera_, "direction", OSP_VEC3F, glm::value_ptr(dir));
  ospSetParam(camera_, "up",        OSP_VEC3F, glm::value_ptr(up_));
  ospSetParam(camera_, "aspect",    OSP_FLOAT, &aspect_);
  ospSetParam(camera_, "fovy",      OSP_FLOAT, &fovy_);
  ospSetParam(camera_, "apertureRadius", OSP_FLOAT, &aperture_);
  ospSetParam(camera_, "focusDistance",  OSP_FLOAT, &dist);
  ospCommit(camera_);

  return camera_;
}

void OSPRayCamera::mousePress(float x, float y, MouseButton btn)
{
  switch(btn)
  {
    case MouseButton::LEFT:
    case MouseButton::RIGHT:
      lookat_.doReferenceDown(glm::vec2(x, -y));
    break;

    default:break;
  }
}

void OSPRayCamera::mouseMove(float x, float y, MouseButton btn)
{
  switch (btn)
  {
  case MouseButton::LEFT:
    lookat_.doRotation(glm::vec2(x, -y));
    pos_ = lookat_.getPos();
    up_ = lookat_.getUp();
    break;

  case MouseButton::RIGHT:
    lookat_.doPan(glm::vec2(x, -y));
    pos_ = lookat_.getPos();
    target_ = lookat_.getTarget();
    break;

  default:
    break;
  }
}

void OSPRayCamera::mouseRelease()
{

}

void OSPRayCamera::mouseWheel(int delta)
{
  lookat_.doZoom(-delta/100.0f);
  pos_ = lookat_.getPos();
}

float OSPRayCamera::toRadians(float v)
{
  const static float HALF_TURN_DEGREES = 180;
  const static float TO_RADIAN_OPERATOR = glm::pi<float>() / HALF_TURN_DEGREES;
  return TO_RADIAN_OPERATOR * v;
}

void OSPRayCamera::autoView()
{
  if(!sceneBBox_.valid()) return;

  // Convert core geom bbox to AABB.
  Core::Geometry::Point bboxMin = sceneBBox_.get_min();
  Core::Geometry::Point bboxMax = sceneBBox_.get_max();
  glm::vec3 min(bboxMin.x(), bboxMin.y(), bboxMin.z());
  glm::vec3 max(bboxMax.x(), bboxMax.y(), bboxMax.z());

  spire::AABB aabb(min, max);

  // The arcball class expects fov in radians
  lookat_.autoview(aabb, toRadians(fovy_));
  pos_ = lookat_.getPos();
  target_ = lookat_.getTarget();
}

void OSPRayCamera::setSceneBoundingBox(const BBox& bbox)
{
  sceneBBox_ = bbox;
}
<|endoftext|>


<commit_before>#include "gridModel.h"
#include "cellutils.h"
#include "gridCell.h"
#include "inexcitablecell.h"

using namespace std;
using namespace LongQt;

GridModel::GridModel(shared_ptr<GridProtocol> proto, QObject* parent)
    : QAbstractTableModel(parent) {
  if (proto) {
    this->proto = proto;
  } else {
    this->proto.reset(new GridProtocol());
  }
  this->grid = proto->gridCell()->getGrid();
  cellMap = CellUtils::cellMap;
  cellMap["Inexcitable Cell"] = []() { return make_shared<InexcitableCell>(); };
}
bool GridModel::setProtocol(shared_ptr<GridProtocol> proto) {
  this->proto = proto;
  this->grid = proto->gridCell()->getGrid();
  QAbstractItemModel::resetInternalData();
  return true;
}
int GridModel::rowCount(const QModelIndex&) const {
  return this->grid->rowCount();
}
int GridModel::columnCount(const QModelIndex&) const {
  return this->grid->columnCount();
}
QVariant GridModel::data(const QModelIndex& index, int role) const {
  switch (role) {
    case Qt::DisplayRole:
      return this->dataDisplay(index);
      break;
    case Qt::ToolTipRole:
      return this->dataToolTip(index);
      break;
    case Qt::StatusTipRole:
      return this->dataStatusTip(index);
      break;
    default:
      return QVariant();
  }
}
QVariant GridModel::dataDisplay(const QModelIndex& index) const {
  if (index.internalPointer() == 0) {
    shared_ptr<Node> n = (*this->grid)(index.row(), index.column());
    if (!n) {
      return QVariant();
    }
    return QString(n->cell->type());
  } else {
    pair<int, int> p = make_pair(index.parent().row(), index.parent().column());
    if (index.row() == 0) {
      if (index.column() == 0) {
        return this->proto->getStimNodes().count(p) > 0;
      } else if (index.column() == 1) {
        return this->proto->gridMeasureMgr().dataNodes().count(p) > 0;
      }
    } else if (index.row() == 1) {
      switch (index.column()) {
        case 0:  // top
          return grid->columns.at(p.second).B.at(p.first);
          break;
        case 1:  // right
          return grid->rows.at(p.first).B.at(p.second + 1);
          break;
        case 2:  // bottom
          return grid->columns.at(p.second).B.at(p.first + 1);
          break;
        case 3:  // left
          return grid->rows.at(p.first).B.at(p.second);
          break;
      }
    }
  }
  return QVariant();
}
QVariant GridModel::dataToolTip(const QModelIndex& index) const {
  return this->data(index);
}
QVariant GridModel::dataStatusTip(const QModelIndex& index) const {
  QString statusTip = "";
  statusTip +=
      "Top: " + QString::number(index.child(1, 0).data().toDouble()) + " ";
  statusTip +=
      "Right: " + QString::number(index.child(1, 1).data().toDouble()) + " ";
  statusTip +=
      "Bottom: " + QString::number(index.child(1, 2).data().toDouble()) + " ";
  statusTip +=
      "Left: " + QString::number(index.child(1, 3).data().toDouble()) + " ";

  return statusTip;
}
bool GridModel::setData(const QModelIndex& index, const QVariant& value, int) {
  bool success = false;
  if (index.internalPointer() == 0) {
    CellInfo info;
    info.row = index.row();
    info.col = index.column();
    try {
      info.cell = this->cellMap.at(value.toString().toStdString())();
      info.dx = proto->cell()->par("dx");
      info.dy = proto->cell()->par("dy");
      info.np = proto->cell()->par("np");
      if (info.cell->par("dtmin") < proto->cell()->par("dtmin")) {
        proto->cell()->setPar("dtmin", info.cell->par("dtmin"));
      }
      if (info.cell->par("dtmed") < proto->cell()->par("dtmed")) {
        proto->cell()->setPar("dtmed", info.cell->par("dtmed"));
      }
      if (info.cell->par("dtmax") < proto->cell()->par("dtmax")) {
        proto->cell()->setPar("dtmax", info.cell->par("dtmax"));
      }
      this->grid->setCellTypes(info);
      emit cellChanged(proto->cell());
      emit dataChanged(index, index);
    } catch (const std::out_of_range&) {
      Logger::getInstance()->write(
          "{} not a valid cell type or ({},{}) out of range",
          qUtf8Printable(value.toString()), info.col, info.row);
    }
    success = true;
  } else {
    pair<int, int> p = make_pair(index.parent().row(), index.parent().column());
    if (index.row() == 0) {
      if (index.column() == 0) {
        if (value.toBool()) {
          this->proto->getStimNodes().insert(p);
        } else {
          this->proto->getStimNodes().erase(p);
        }
        success = true;
      } else if (index.column() == 1) {
        if (value.toBool()) {
          auto nodes = this->proto->gridMeasureMgr().dataNodes();
          nodes.insert(p);
          this->proto->gridMeasureMgr().dataNodes(nodes);
        } else {
          auto nodes = this->proto->gridMeasureMgr().dataNodes();
          nodes.erase(p);
          this->proto->gridMeasureMgr().dataNodes(nodes);
        }
        success = true;
      }
    } else if (index.row() == 1) {
      CellInfo u;
      u.row = index.parent().row();
      u.col = index.parent().column();
      u.dx = proto->cell()->par("dx");
      u.dy = proto->cell()->par("dy");
      u.np = proto->cell()->par("np");
      // this works because column is setup follow cellutils_side.h:Side
      double val = value.toDouble();
      if (this->percent) {
        val /= 100;
      }
      u.c[index.column()] = val;
      u.c_perc = this->percent;
      try {
        grid->setCellTypes(u);
        success = true;
      } catch (std::out_of_range) {
        Logger::getInstance()->write("({},{}) out of range", u.col, u.row);
        success = false;
      }
    }
    if (success) {
      emit dataChanged(index.parent(), index.parent());
    }
  }
  return success;
}
Qt::ItemFlags GridModel::flags(const QModelIndex& index) const {
  if (!index.isValid()) return Qt::ItemIsEnabled;

  return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
}
bool GridModel::insertRows(int row, int count, const QModelIndex& parent) {
  this->beginInsertRows(parent, row, row + count - 1);
  this->grid->addRows(static_cast<unsigned int>(count));
  this->endInsertRows();
  return true;
}
bool GridModel::removeRows(int row, int count, const QModelIndex& parent) {
  // imput must not be within grid size
  // sanitize inputs
  if (row < 0) {
    row = 0;
  }
  if (row > this->rowCount()) {
    row = this->rowCount() - 1;
  }
  int last = row + count - 1;
  if (last >= this->rowCount()) {
    last = this->rowCount() - 1;
  }
  this->beginRemoveRows(parent, row, last);
  this->grid->removeRows(static_cast<unsigned int>(count), row);
  this->endRemoveRows();
  return true;
}
bool GridModel::insertColumns(int column, int count,
                              const QModelIndex& parent) {
  this->beginInsertColumns(parent, column, column + count - 1);
  this->grid->addColumns(static_cast<unsigned int>(count));
  this->endInsertColumns();
  return true;
}
bool GridModel::removeColumns(int column, int count,
                              const QModelIndex& parent) {
  // imput must not be within grid size
  // sanitize inputs
  if (column < 0) {
    column = 0;
  }
  if (column > this->columnCount()) {
    column = this->columnCount() - 1;
  }
  int last = column + count - 1;
  if (last >= this->columnCount()) {
    last = this->columnCount() - 1;
  }
  this->beginRemoveColumns(parent, column, last);
  this->grid->removeColumns(static_cast<unsigned int>(count), column);
  this->endRemoveColumns();
  return true;
}
QModelIndex GridModel::index(int row, int column,
                             const QModelIndex& parent) const {
  if (!parent.isValid()) {
    return QAbstractTableModel::index(row, column, parent);
  }
  auto pos = new QPair<int, int>(parent.row(), parent.column());
  connect(this, &QObject::destroyed, [pos]() { delete pos; });
  return QAbstractTableModel::createIndex(row, column, pos);
}
QModelIndex GridModel::parent(const QModelIndex& index) const {
  QPair<int, int>* p = 0;
  if ((p = static_cast<QPair<int, int>*>(index.internalPointer()))) {
    return this->index(p->first, p->second, QModelIndex());
  }
  return QModelIndex();
}

QVariant GridModel::headerData(int section, Qt::Orientation o, int role) const {
  if (role == Qt::DisplayRole) {
    return section;
  }
  return QAbstractTableModel::headerData(section, o, role);
}

void GridModel::reloadModel() {
  this->beginResetModel();
  this->endResetModel();
}

void GridModel::clear() {
  this->grid->reset();
  this->beginResetModel();
  this->endResetModel();
}

bool GridModel::getPercent() { return this->percent; }

void GridModel::setPercent(bool percent) { this->percent = percent; }
<commit_msg>moved dx, dy, np from gridcell to grid<commit_after>#include "gridModel.h"
#include "cellutils.h"
#include "gridCell.h"
#include "inexcitablecell.h"

using namespace std;
using namespace LongQt;

GridModel::GridModel(shared_ptr<GridProtocol> proto, QObject* parent)
    : QAbstractTableModel(parent) {
  if (proto) {
    this->proto = proto;
  } else {
    this->proto.reset(new GridProtocol());
  }
  this->grid = proto->gridCell()->getGrid();
  cellMap = CellUtils::cellMap;
  cellMap["Inexcitable Cell"] = []() { return make_shared<InexcitableCell>(); };
}
bool GridModel::setProtocol(shared_ptr<GridProtocol> proto) {
  this->proto = proto;
  this->grid = proto->gridCell()->getGrid();
  QAbstractItemModel::resetInternalData();
  return true;
}
int GridModel::rowCount(const QModelIndex&) const {
  return this->grid->rowCount();
}
int GridModel::columnCount(const QModelIndex&) const {
  return this->grid->columnCount();
}
QVariant GridModel::data(const QModelIndex& index, int role) const {
  switch (role) {
    case Qt::DisplayRole:
      return this->dataDisplay(index);
      break;
    case Qt::ToolTipRole:
      return this->dataToolTip(index);
      break;
    case Qt::StatusTipRole:
      return this->dataStatusTip(index);
      break;
    default:
      return QVariant();
  }
}
QVariant GridModel::dataDisplay(const QModelIndex& index) const {
  if (index.internalPointer() == 0) {
    shared_ptr<Node> n = (*this->grid)(index.row(), index.column());
    if (!n) {
      return QVariant();
    }
    return QString(n->cell->type());
  } else {
    pair<int, int> p = make_pair(index.parent().row(), index.parent().column());
    if (index.row() == 0) {
      if (index.column() == 0) {
        return this->proto->getStimNodes().count(p) > 0;
      } else if (index.column() == 1) {
        return this->proto->gridMeasureMgr().dataNodes().count(p) > 0;
      }
    } else if (index.row() == 1) {
      switch (index.column()) {
        case 0:  // top
          return grid->columns.at(p.second).B.at(p.first);
          break;
        case 1:  // right
          return grid->rows.at(p.first).B.at(p.second + 1);
          break;
        case 2:  // bottom
          return grid->columns.at(p.second).B.at(p.first + 1);
          break;
        case 3:  // left
          return grid->rows.at(p.first).B.at(p.second);
          break;
      }
    }
  }
  return QVariant();
}
QVariant GridModel::dataToolTip(const QModelIndex& index) const {
  return this->data(index);
}
QVariant GridModel::dataStatusTip(const QModelIndex& index) const {
  QString statusTip = "";
  statusTip +=
      "Top: " + QString::number(index.child(1, 0).data().toDouble()) + " ";
  statusTip +=
      "Right: " + QString::number(index.child(1, 1).data().toDouble()) + " ";
  statusTip +=
      "Bottom: " + QString::number(index.child(1, 2).data().toDouble()) + " ";
  statusTip +=
      "Left: " + QString::number(index.child(1, 3).data().toDouble()) + " ";

  return statusTip;
}
bool GridModel::setData(const QModelIndex& index, const QVariant& value, int) {
  bool success = false;
  if (index.internalPointer() == 0) {
    CellInfo info;
    info.row = index.row();
    info.col = index.column();
    try {
      info.cell = this->cellMap.at(value.toString().toStdString())();
      if (info.cell->par("dtmin") < proto->cell()->par("dtmin")) {
        proto->cell()->setPar("dtmin", info.cell->par("dtmin"));
      }
      if (info.cell->par("dtmed") < proto->cell()->par("dtmed")) {
        proto->cell()->setPar("dtmed", info.cell->par("dtmed"));
      }
      if (info.cell->par("dtmax") < proto->cell()->par("dtmax")) {
        proto->cell()->setPar("dtmax", info.cell->par("dtmax"));
      }
      this->grid->setCellTypes(info);
      emit cellChanged(proto->cell());
      emit dataChanged(index, index);
    } catch (const std::out_of_range&) {
      Logger::getInstance()->write(
          "{} not a valid cell type or ({},{}) out of range",
          qUtf8Printable(value.toString()), info.col, info.row);
    }
    success = true;
  } else {
    pair<int, int> p = make_pair(index.parent().row(), index.parent().column());
    if (index.row() == 0) {
      if (index.column() == 0) {
        if (value.toBool()) {
          this->proto->getStimNodes().insert(p);
        } else {
          this->proto->getStimNodes().erase(p);
        }
        success = true;
      } else if (index.column() == 1) {
        if (value.toBool()) {
          auto nodes = this->proto->gridMeasureMgr().dataNodes();
          nodes.insert(p);
          this->proto->gridMeasureMgr().dataNodes(nodes);
        } else {
          auto nodes = this->proto->gridMeasureMgr().dataNodes();
          nodes.erase(p);
          this->proto->gridMeasureMgr().dataNodes(nodes);
        }
        success = true;
      }
    } else if (index.row() == 1) {
      CellInfo u;
      u.row = index.parent().row();
      u.col = index.parent().column();
      // this works because column is setup follow cellutils_side.h:Side
      double val = value.toDouble();
      if (this->percent) {
        val /= 100;
      }
      u.c[index.column()] = val;
      u.c_perc = this->percent;
      try {
        grid->setCellTypes(u);
        success = true;
      } catch (std::out_of_range) {
        Logger::getInstance()->write("({},{}) out of range", u.col, u.row);
        success = false;
      }
    }
    if (success) {
      emit dataChanged(index.parent(), index.parent());
    }
  }
  return success;
}
Qt::ItemFlags GridModel::flags(const QModelIndex& index) const {
  if (!index.isValid()) return Qt::ItemIsEnabled;

  return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
}
bool GridModel::insertRows(int row, int count, const QModelIndex& parent) {
  this->beginInsertRows(parent, row, row + count - 1);
  this->grid->addRows(static_cast<unsigned int>(count));
  this->endInsertRows();
  return true;
}
bool GridModel::removeRows(int row, int count, const QModelIndex& parent) {
  // imput must not be within grid size
  // sanitize inputs
  if (row < 0) {
    row = 0;
  }
  if (row > this->rowCount()) {
    row = this->rowCount() - 1;
  }
  int last = row + count - 1;
  if (last >= this->rowCount()) {
    last = this->rowCount() - 1;
  }
  this->beginRemoveRows(parent, row, last);
  this->grid->removeRows(static_cast<unsigned int>(count), row);
  this->endRemoveRows();
  return true;
}
bool GridModel::insertColumns(int column, int count,
                              const QModelIndex& parent) {
  this->beginInsertColumns(parent, column, column + count - 1);
  this->grid->addColumns(static_cast<unsigned int>(count));
  this->endInsertColumns();
  return true;
}
bool GridModel::removeColumns(int column, int count,
                              const QModelIndex& parent) {
  // imput must not be within grid size
  // sanitize inputs
  if (column < 0) {
    column = 0;
  }
  if (column > this->columnCount()) {
    column = this->columnCount() - 1;
  }
  int last = column + count - 1;
  if (last >= this->columnCount()) {
    last = this->columnCount() - 1;
  }
  this->beginRemoveColumns(parent, column, last);
  this->grid->removeColumns(static_cast<unsigned int>(count), column);
  this->endRemoveColumns();
  return true;
}
QModelIndex GridModel::index(int row, int column,
                             const QModelIndex& parent) const {
  if (!parent.isValid()) {
    return QAbstractTableModel::index(row, column, parent);
  }
  auto pos = new QPair<int, int>(parent.row(), parent.column());
  connect(this, &QObject::destroyed, [pos]() { delete pos; });
  return QAbstractTableModel::createIndex(row, column, pos);
}
QModelIndex GridModel::parent(const QModelIndex& index) const {
  QPair<int, int>* p = 0;
  if ((p = static_cast<QPair<int, int>*>(index.internalPointer()))) {
    return this->index(p->first, p->second, QModelIndex());
  }
  return QModelIndex();
}

QVariant GridModel::headerData(int section, Qt::Orientation o, int role) const {
  if (role == Qt::DisplayRole) {
    return section;
  }
  return QAbstractTableModel::headerData(section, o, role);
}

void GridModel::reloadModel() {
  this->beginResetModel();
  this->endResetModel();
}

void GridModel::clear() {
  this->grid->reset();
  this->beginResetModel();
  this->endResetModel();
}

bool GridModel::getPercent() { return this->percent; }

void GridModel::setPercent(bool percent) { this->percent = percent; }
<|endoftext|>


<commit_before>#include <iostream>
#include <cstdio>
#include <cstdlib>

#include <getopt.h>

#include <ft2build.h>
#include FT_FREETYPE_H

int main(int argc, char **argv) {

    int c;

    char *text_file_name;
    char *font_file_name;

    while (1) {
        static struct option long_options[] = { { "font", required_argument,
                NULL, 'f' }, { "text", required_argument, NULL, 't' }, { 0, 0,
                0, 0 } };

        int option_index = 0;

        c = getopt_long(argc, argv, "f:t:", long_options, &option_index);

        if (c == -1) {
            break;
        }

        switch (c) {
        case 0:
            break;

        case 't':
            text_file_name = optarg;
            break;

        case 'f':
            font_file_name = optarg;
            break;

        case '?':
            /* getopt_long already printed an error message. */
            break;

        default:
            return 1;
        }
    }

    return 0;
}

<commit_msg>can't read debian latex arphic font files??<commit_after>#include <iostream>
#include <cstdio>
#include <cstdlib>

#include <getopt.h>

#include <ft2build.h>
#include FT_FREETYPE_H

int main(int argc, char **argv) {

    char *text_file_name;
    char *font_file_name;

    int c;

    while (1) {
        static struct option long_options[] = { { "font", required_argument,
                NULL, 'f' }, { "text", required_argument, NULL, 't' }, { NULL,
                0, NULL, 0 } };

        int option_index = 0;

        c = getopt_long(argc, argv, "f:t:", long_options, &option_index);

        if (c == -1) {
            break;
        }

        switch (c) {
        case 0:
            break;

        case 't':
            text_file_name = optarg;
            break;

        case 'f':
            font_file_name = optarg;
            break;

        case '?':
            /* getopt_long already printed an error message. */
            break;

        default:
            return 1;
        }
    }

    FT_Library library;
    FT_Face face;

    int error;

    error = FT_Init_FreeType(&library);
    if (error) {
        std::cerr << "font library init failed at " << __FILE__ << " "
                << __LINE__ << std::endl;
        return 1;
    }

    error = FT_New_Face(library, font_file_name, 0, &face);
    if (error == FT_Err_Unknown_File_Format) {
        std::cerr << "unknown font file format" << std::endl;
    } else if (error) {
        std::cerr << "error reading font file" << std::endl;
    }

    return 0;
}

<|endoftext|>


<commit_before>#include "newCore.h"
#include <stdlib.h>

using namespace std;
int ask =1;
int answer=0;
void NewCore::init(){

	mngrSub = handle.subscribe<std_msgs::String>("/tawi/core/launch", 10, &NewCore::launchCallback, this);
	mngrPub = handle.advertise<std_msgs::String>("/tawi/core/launch", 100);

	mathSub = handle.subscribe<std_msgs::String>("/display", 10, &NewCore::mathCallback, this);
	serSub = handle.subscribe<std_msgs::String>("/tawi/arduino/serial", 100,&NewCore::serialCallback,this);
	mathPub = handle.advertise<std_msgs::String>("/questions", 100);

	ballPub = handle.advertise<std_msgs::Int16>("/tawi/core/ballcount", 100);
	nmbrPub = handle.advertise<std_msgs::Int16>("/tawi/core/number", 100);
}

void NewCore::launchCallback(const std_msgs::String::ConstPtr &msg){
	if("donelaunching" == msg->data){
		stopLaunch();
	}

	if("doneconveying" == msg->data){
		stopConvey();
	}
}

void NewCore::stopLaunch(){
	ballCount = 0;
}

void NewCore::stopConvey(){
	//Waittime currently hardcoded in converyorDriver.cpp
	//This method is currently not used
}

void NewCore::startLaunch(){
	std_msgs::String launchmsg;
	launchmsg.data = "startlaunch";
	mngrPub.publish(launchmsg);
}

void NewCore::startConvey(){
	std_msgs::String conveymsg;
	conveymsg.data = "startconveyor";
	mngrPub.publish(conveymsg);
}

void NewCore::spin(){
	ros::Rate rate(10);

	while(ros::ok()){

		if (ask){
			askMath();}
		ros::spinOnce();
		rate.sleep();
	}
}

void NewCore::acceptBall(){
	ROS_INFO("Ball accepted. Publishing to LaunchManager");
	ballCount++;
	std_msgs::Int16 balls;
	balls.data = ballCount;
	ballPub.publish(balls);
}

void NewCore::writeSerial(string shit){
	ROS_INFO("NewCore: Writing on serial through system call:%s", shit.c_str());
	std::stringstream sysCall;
        sysCall<<"/home/ubuntu/robotica-minor-5/com/arduino-serial/arduino-serial --port=/dev/ttyACM0 --send=\""<<shit<<"\"";
	string temp= sysCall.str();
	ROS_INFO("NewCOre: syscall: %s", temp.c_str());
	system(temp.c_str());

}

void NewCore::deleteBall(const int ballnumber){ //written by bob, muchos bugs
	std_msgs::Int16 number;
	number.data = ballnumber;
	nmbrPub.publish(number);
}
int getAnsweri(int firstnumber, int operation , int secondnumber){
  switch(operation){
    case 'D':
      answer = firstnumber + secondnumber;
      break;
    case 'E':
      answer = firstnumber - secondnumber;
      break;
    case 'F':
      answer = firstnumber * secondnumber;
      break;
  }
  return answer;
}
int getAnswer(string s){
	return getAnsweri(s[1]-48,s[2]-48,s[3]-48);
}

void NewCore::mathCallback(const std_msgs::String::ConstPtr& msg){
	ROS_INFO("ask= %d",ask);
	answer=getAnswer(msg->data);
	if(ask>0){
		ROS_INFO("NewCore: mathCallback: 	newSum: %s",msg->data.c_str());
		ask=0;
		writeSerial(msg->data);
	}
}

int stringToAscii(string s){
	int sum = 0;
  	for (unsigned int i = 0; i < 1; i++) {
    	sum += s[i];
  	}
  	return sum;
}

void NewCore::serialCallback(const std_msgs::String::ConstPtr& msg){
	ROS_INFO("msg-data is %d. Looking for %d", stringToAscii(msg->data), stringToAscii("c"));
	if(msg->data.find('c') != std::string::npos){
		acceptBall();
		NewCore::startConvey();
		ask=1;
	}
	else{
		if('n' == msg->data[0]){

			ask=1;
			NewCore::deleteBall(answer);
		}
		ROS_INFO("NewCore: SerialCallback: message was not c");
	}
}

void NewCore::askMath(){
	ROS_INFO("asking for something");
	std_msgs::String question;
	if (rand() %2){
		question.data = "1digitAddition";
	}
	else{
		question.data = "1digitSubstraction";
	}
	mathPub.publish(question);
}

int main(int argc, char **argv){

	ros::init(argc, argv, "newCore");
	NewCore nc;
	nc.init();

	nc.spin();
}
<commit_msg>better remove<commit_after>#include "newCore.h"
#include <stdlib.h>

using namespace std;
int ask =1;
int answer=0;
void NewCore::init(){

	mngrSub = handle.subscribe<std_msgs::String>("/tawi/core/launch", 10, &NewCore::launchCallback, this);
	mngrPub = handle.advertise<std_msgs::String>("/tawi/core/launch", 100);

	mathSub = handle.subscribe<std_msgs::String>("/display", 10, &NewCore::mathCallback, this);
	serSub = handle.subscribe<std_msgs::String>("/tawi/arduino/serial", 100,&NewCore::serialCallback,this);
	mathPub = handle.advertise<std_msgs::String>("/questions", 100);

	ballPub = handle.advertise<std_msgs::Int16>("/tawi/core/ballcount", 100);
	nmbrPub = handle.advertise<std_msgs::Int16>("/tawi/core/number", 100);
}

void NewCore::launchCallback(const std_msgs::String::ConstPtr &msg){
	if("donelaunching" == msg->data){
		stopLaunch();
	}

	if("doneconveying" == msg->data){
		stopConvey();
	}
}

void NewCore::stopLaunch(){
	ballCount = 0;
}

void NewCore::stopConvey(){
	//Waittime currently hardcoded in converyorDriver.cpp
	//This method is currently not used
}

void NewCore::startLaunch(){
	std_msgs::String launchmsg;
	launchmsg.data = "startlaunch";
	mngrPub.publish(launchmsg);
}

void NewCore::startConvey(){
	std_msgs::String conveymsg;
	conveymsg.data = "startconveyor";
	mngrPub.publish(conveymsg);
}

void NewCore::spin(){
	ros::Rate rate(10);

	while(ros::ok()){

		if (ask){
			askMath();}
		ros::spinOnce();
		rate.sleep();
	}
}

void NewCore::acceptBall(){
	ROS_INFO("Ball accepted. Publishing to LaunchManager");
	ballCount++;
	std_msgs::Int16 balls;
	balls.data = ballCount;
	ballPub.publish(balls);
}

void NewCore::writeSerial(string shit){
	ROS_INFO("NewCore: Writing on serial through system call:%s", shit.c_str());
	std::stringstream sysCall;
        sysCall<<"/home/ubuntu/robotica-minor-5/com/arduino-serial/arduino-serial --port=/dev/ttyACM0 --send=\""<<shit<<"\"";
	string temp= sysCall.str();
	ROS_INFO("NewCOre: syscall: %s", temp.c_str());
	system(temp.c_str());

}

void NewCore::deleteBall(const int ballnumber){ //written by bob, muchos bugs
	std_msgs::Int16 number;
	number.data = ballnumber;
	nmbrPub.publish(number);
}
int getAnsweri(int firstnumber, int operation , int secondnumber){
  switch(operation){
    case 'D':
      answer = firstnumber + secondnumber;
      break;
    case 'E':
      answer = firstnumber - secondnumber;
      break;
    case 'F':
      answer = firstnumber * secondnumber;
      break;
  }
  return answer;
}
int getAnswer(string s){
	return getAnsweri(s[1]-48,s[2]-48,s[3]-48);
}

void NewCore::mathCallback(const std_msgs::String::ConstPtr& msg){
	ROS_INFO("ask= %d",ask);
	answer=getAnswer(msg->data);
	if(ask>0){
		ROS_INFO("NewCore: mathCallback: 	newSum: %s",msg->data.c_str());
		ask=0;
		writeSerial(msg->data);
	}
}

int stringToAscii(string s){
	int sum = 0;
  	for (unsigned int i = 0; i < 1; i++) {
    	sum += s[i];
  	}
  	return sum;
}

void NewCore::serialCallback(const std_msgs::String::ConstPtr& msg){
	ROS_INFO("msg-data is %d. Looking for %d", stringToAscii(msg->data), stringToAscii("c"));
	if(msg->data.find('c') != std::string::npos){
		acceptBall();
		NewCore::startConvey();
		ask=1;
		deleteBall(answer);
	}
	else{
		if('n' == msg->data[0]){

			ask=1;
			NewCore::deleteBall(answer);
		}
		ROS_INFO("NewCore: SerialCallback: message was not c");
	}
}

void NewCore::askMath(){
	ROS_INFO("asking for something");
	std_msgs::String question;
	if (rand() %2){
		question.data = "1digitAddition";
	}
	else{
		question.data = "1digitSubstraction";
	}
	mathPub.publish(question);
}

int main(int argc, char **argv){

	ros::init(argc, argv, "newCore");
	NewCore nc;
	nc.init();

	nc.spin();
}
<|endoftext|>