Exemplo n.º 1
0
HRESULT TaudioFilterChannelSwap::process(TfilterQueue::iterator it, TsampleFormat &fmt, void *samples, size_t numsamples, const TfilterSettingsAudio *cfg0)
{
    const TchannelSwapSettings *cfg = (const TchannelSwapSettings*)cfg0;

    if (!cfg->equal(oldcfg) || oldfmt != fmt || old_nchannels != fmt.nchannels) {
        makeMap(fmt, cfg);
    }

    fmt.channelmask = newchannelmask;
    switch (fmt.sf) {
        case TsampleFormat::SF_PCM16:
            swapChannels((int16_t*)samples, numsamples);
            break;
        case TsampleFormat::SF_PCM24:
            swapChannels((int24_t*)samples, numsamples);
            break;
        case TsampleFormat::SF_PCM32:
            swapChannels((int32_t*)samples, numsamples);
            break;
        case TsampleFormat::SF_FLOAT32:
            swapChannels((float*)samples, numsamples);
            break;
    }
    return parent->deliverSamples(++it, fmt, samples, numsamples);
}
Exemplo n.º 2
0
void doPeakList(char KNMap[], cosmo_hm *cmhm, peak_param *peak, error **err)
{
  map_t *kMap = initialize_map_t(peak->resol[0], peak->resol[1], peak->theta_pix, err); forwardError(*err, __LINE__,);
  
  if (KNMap == NULL) {
    //-- Carry out KMap from fast simulation
    sampler_arr *sampArr = initialize_sampler_arr(peak->N_z_halo, peak->nbMassBins);
    setMassSamplers(cmhm, peak, sampArr, err);                                                        forwardError(*err, __LINE__,);
    halo_map *hMap       = initialize_halo_map(peak->resol[0], peak->resol[1], peak->theta_pix, err); forwardError(*err, __LINE__,);
    gal_map *gMap        = initialize_gal_map(peak->resol[0], peak->resol[1], peak->theta_pix, err);  forwardError(*err, __LINE__,);
    makeGalaxies(cmhm, peak, gMap, err);                                                              forwardError(*err, __LINE__,);
    map_t *nMap          = initialize_map_t(peak->resol[0], peak->resol[1], peak->theta_pix, err);    forwardError(*err, __LINE__,);
    FFT_t *transformer   = initialize_FFT_t(peak->FFTSize, peak->FFTSize);
    fillGaussianKernel(transformer, peak->s);
    
    makeFastSimul(cmhm, peak, sampArr, hMap, err);     forwardError(*err, __LINE__,);
    lensingForMap(cmhm, peak, hMap, gMap, err);        forwardError(*err, __LINE__,);
    makeMap(peak, gMap, kMap, nMap, transformer, err); forwardError(*err, __LINE__,);
    
    outputFastSimul("haloList", cmhm, peak, hMap);
    outputGalaxies("galList", cmhm, peak, gMap);
    outputMap("KNMap", cmhm, peak, kMap);
    outputMap("NMap", cmhm, peak, nMap);
    
    free_sampler_arr(sampArr);
    free_halo_map(hMap);
    free_gal_map(gMap);
    free_map_t(nMap);
    free_FFT_t(transformer);
  }
Exemplo n.º 3
0
Path PathFinder::findPath(const Coord& start, const Coord& end)
{
  Coord mapEnd;
  if ( makeMap( start, DistanceTo(end), ReachedPos(end), &mapEnd ) )
  {
    return getPath(start, end);
  }
  return Path();
}
Exemplo n.º 4
0
Path PathFinder::findPath(const Coord& start, Item item, const CoordSet& doNotUse, Coord* end)
{
  assert(end);
  if ( makeMap(start, Zero(), ReachedItem(item, m_field, doNotUse), end) )
  {
    return getPath(start, *end);
  }
  return Path();
}
Exemplo n.º 5
0
void peakListFromMassFct(cosmo_hm *cmhm, peak_param *peak, sampler_arr *sampArr, halo_map *hMap, gal_map *gMap, 
			 map_t *kMap, map_t *nMap, FFT_t *transformer, double_arr *peakList, error **err)
{
  makeFastSimul(cmhm, peak, sampArr, hMap, err);     forwardError(*err, __LINE__,);
  lensingForMap(cmhm, peak, hMap, gMap, err);        forwardError(*err, __LINE__,);
  makeMap(peak, gMap, kMap, nMap, transformer, err); forwardError(*err, __LINE__,);
  selectPeaks(peak, kMap, peakList, err);            forwardError(*err, __LINE__,);
  return;
}
Exemplo n.º 6
0
bool TaudioFilterChannelSwap::getOutputFmt(TsampleFormat &fmt, const TfilterSettingsAudio *cfg0)
{
    if (super::getOutputFmt(fmt, cfg0)) {
        makeMap(fmt, (const TchannelSwapSettings*)cfg0);
        fmt.channelmask = newchannelmask;
        return true;
    } else {
        return false;
    }
}
Exemplo n.º 7
0
void DecoratorDescriptors_t::addDescriptor(DecoratorDescriptor *descriptor)
{
    assert(descriptor != nullptr);
    makeMap();
    if(!std::get<1>(map->insert(std::pair<std::wstring, DecoratorDescriptorPointer>(descriptor->name, descriptor))))
    {
        UNREACHABLE();
    }
    descriptor->index = list->size();
    list->push_back(sortedList->emplace(descriptor->priority, descriptor));
}
Exemplo n.º 8
0
/*   ---------------  close the next balise  --------------------------*/
int  SparseXML::closeBalise()
{
//cout<<"closeBalise"<<endl;
if(_current_position>=_xml_string->length())
      return(EndXMLFile);
// find the open chevron
while(_xml_string->at(_current_position)!='<')
          {
            _current_position++;
            if(_current_position>=_xml_string->length())  return(EndXMLFile);
           }
// we have to check that we  deal with a close balise
if(_xml_string->at(_current_position+1)!='/')
          {// it is not  a close balise
            _current_position--; //reposition of the pointer
            return(NoCloseBalise); // we can not open more balise
          } 
// ok, we are sure to deal with a close balise, find the element
_level--;
_element.clear();
_current_position+=2; // skip the </           
// skip the spaces
while (_xml_string->at(_current_position)==' ')
           {
            _current_position++;
            if(_current_position>=_xml_string->length())
                      {cout<<" error  function closeBalise "<<"  in "<<__FILE__<< " line "<<__LINE__<<endl;
                        return(BadBaliseFormat);}    
            }
// we get the element name            
while(_xml_string->at(_current_position)!=' ' &&
          _xml_string->at(_current_position)!='>')
            {
              _element+=_xml_string->at(_current_position);
              _current_position++;
              if(_current_position>=_xml_string->length())
                      {cout<<" error  function closeBalise "<<"  in "<<__FILE__<< " line "<<__LINE__<<endl;
                        return(BadBaliseFormat);}
// new position after the close chevron >                        
            }            
  while(_xml_string->at(_current_position)!='>')
            {
            _current_position++;
            if(_current_position>=_xml_string->length())
                      {cout<<" error  function closeBalise "<<"  in "<<__FILE__<< " line "<<__LINE__<<endl;
                        return(BadBaliseFormat);}    
            }
_current_position++;   
// clean the map
string  attribute_string;
attribute_string.clear();
makeMap(attribute_string);  
return(OkCloseBalise);    
}  
Exemplo n.º 9
0
void DecorationTest::testCreate()
{
    // just test that creating the Decoration doesn't crash
    MockBridge bridge;
    const QString bridgeKey = QStringLiteral("bridge");
    MockDecoration deco1(nullptr, QVariantList({
#ifdef _MSC_VER
                                                makeMap(bridgeKey, QVariant::fromValue(5)),
#else
                                                QVariantMap({ {bridgeKey, QVariant::fromValue(5)} }),
#endif
                                                QVariant::fromValue(bridgeKey),
                                                QVariantMap(),
#ifdef _MSC_VER
                                                makeMap(bridgeKey, QVariant::fromValue(&bridge)),
#else
                                                QVariantMap({ {bridgeKey, QVariant::fromValue(&bridge)} })
#endif
                                               }));
    QVERIFY(!deco1.client().isNull());
}
Exemplo n.º 10
0
GPIOInterface::GPIOInterface():
    m_mmap_fd(-1),
    m_gpio1_base(),
    m_gpio2_base(),
    m_gpio3_base(),
    m_gpio4_base(),
    m_gpio5_base(),
    m_gpio6_base()
{

    m_mmap_fd = open("/dev/mem", O_RDWR | O_SYNC);
    if(m_mmap_fd<0)
    {
        perror("open(\"/dev/mem\")");
        exit(EXIT_FAILURE);
    }

    //      virtual adr   physical adr
    makeMap(m_gpio1_base, ADR_GPIO1_BASE);
    makeMap(m_gpio2_base, ADR_GPIO2_BASE);
    makeMap(m_gpio3_base, ADR_GPIO3_BASE);
    makeMap(m_gpio4_base, ADR_GPIO4_BASE);
    makeMap(m_gpio5_base, ADR_GPIO5_BASE);
    makeMap(m_gpio6_base, ADR_GPIO6_BASE);
}
Exemplo n.º 11
0
s_map	*init_map(char **argv)
{
  s_map	*map;

  if (argv[1])
    map = makeMap(argv[1]);
  else
    {
      printf("Usage : ./epikong file_map\n");
      exit(-1);
    }
  return map;
}
Exemplo n.º 12
0
int main(int argc, char* argv[])
{
	
	  if (argc > 1)
		{
			std::string arg1(argv[1]);
			std::cout << "Yes.\n";
			makeMap(arg1);
		}
		else
		{
			std::cout << "No.\n";
		}
		return 0;
}
Exemplo n.º 13
0
void ModeLaplace1DQ1::preProcess() {

  // Create the distribution of equations across processors
  makeMap();

  // Count the number of elements touched by this processor
  bool *isTouched = new bool[nX];
  int i;
  for (i=0; i<nX; ++i)
    isTouched[i] = false;

  int numEle = countElements(isTouched);

  // Create the mesh
  int *elemTopo = new int[dofEle*numEle];
  makeMyElementsTopology(elemTopo, isTouched);

  delete[] isTouched;

  // Get the number of nonzeros per row
  int localSize = Map->NumMyElements();
  int *numNz = new int[localSize];
  int *connectivity = new int[localSize*maxConnect];
  makeMyConnectivity(elemTopo, numEle, connectivity, numNz);

  // Make the stiffness matrix
  makeStiffness(elemTopo, numEle, connectivity, numNz);

  // Assemble the mass matrix
  makeMass(elemTopo, numEle, connectivity, numNz);

  // Free some memory
  delete[] elemTopo;
  delete[] numNz;
  delete[] connectivity;

  // Get the geometrical coordinates of the managed nodes
  double hx = Lx/nX;
  x = new double[localSize];

  int globalSize = Map->NumGlobalElements();
  for (i=0; i<globalSize; ++i) {
    if (Map->LID(i) > -1) {
      x[Map->LID(i)] = (i+1)*hx;
    }
  }

}
Exemplo n.º 14
0
Path PathFinder::findPath(const Coord& start, const std::vector<Item>& items, const CoordSet& doNotUse, Coord* end)
{
  if ( !items.empty() )
  {
    assert(end);
    if ( items.size() == 1 )
    {
      return findPath( start, items.front(), doNotUse, end );
    }
    if ( makeMap(start, Zero(), ReachedAnyItemOf(items, m_field, doNotUse), end) )
    {
      return getPath(start, *end);
    }
  }
  return Path();
}
Exemplo n.º 15
0
void SparseXML::readXML(const char * filename,string &xml)
{
_current_position=0; // initialize the position 
_data_position=0;   
_data_length=0;
_level=0;
_empty_element=true;
_element.clear();  // clean the element string
//
size_t filesize;
ifstream f(filename);
if(!f.is_open())
            {
             cout<<" error opening file:"<<filename<<"  in "<<__FILE__<< " line "<<__LINE__<<endl; 
             cout<<" file does not exist"<<endl;
             exit(0);
            }
filesize=f.tellg();
 _xml_string= &xml;
(*_xml_string).reserve(filesize);
f.seekg(0);
while (!f.eof())// read the file
      {
      (*_xml_string) += f.get(); 
      }
f.close();        
// first find the prologue       
    string begin_string_prologue="<?xml",end_string_prologue="?>";
    size_t begin_position_prologue=_xml_string->find(begin_string_prologue);
  if(begin_position_prologue==string::npos)
            {cout<<" error prologue begin format:"<<"  in "<<__FILE__<< " line "<<__LINE__<<endl; exit(1);}  
    size_t end_position_prologue=_xml_string->find(end_string_prologue);
   if(end_position_prologue==string::npos)
            {cout<<" error prologue end format:"<<"  in "<<__FILE__<< " line "<<__LINE__<<endl; exit(1);}   
   string prologue;
   begin_position_prologue+=5;// eliminate <?xml
   prologue.append((*_xml_string),begin_position_prologue,end_position_prologue-begin_position_prologue);
   end_position_prologue+=2; // eliminate  ?>
  // store the  attribute in the map.
   makeMap(prologue);
   // now we have to check if the is one root and  extract  
   _xml_string->erase(0,end_position_prologue);
   (*_xml_string)+='\0';
   // and we remove the comment balise
   removeComment();
   //cout<< "after the prologue"<<(*_xml_string) <<endl;
}
Exemplo n.º 16
0
void APalette::createEmptyMapAndHistogram()
{
  resetHistogram();
  for(unsigned int t=0;t<getNumColors();t++) score[t]=getNumColors();
  if(map) {
#ifdef DEBUG_VERBOSE
    dBug<<"Already a map!!!\n";
#endif // DEBUG_VERBOSE
    free(map);
  }
  map=(int *)malloc(sizeof(int)*numColors);
  if(!map) {
#ifdef DEBUG_VERBOSE
    dBug<<"Couldn't alloc map array!\n";
#endif // DEBUG_VERBOSE
    return;
  }
  histComputed=true;
  makeMap();
}
Exemplo n.º 17
0
/**
 * Load covariate from @param fn, using specified @param covNameToUse, for
 * given
 * @param includedSample
 * covariate will be stored in @param covariate, and column names will be
 * stored
 * in @colNames
 * if covariate file missed some samples, those sample names will be stored in
 * @sampleToDrop
 * NOTE: for missing values in a covariate, it will drop this covariate out of
 * the following anaylysis
 * @return number of samples have covariates.
 * Example:
 * includedSample = [A, B, C] and in covaraite file we have [B, C, C, D]
 * then output covariate have 3 rows corresponding to [A, B, C]
 * row C filled by the last C in covariate file
 * sample D will be in sampleToDrop
 */
int _loadCovariate(const std::string& fn,
                   const std::vector<std::string>& includedSample,
                   const std::vector<std::string>& covNameToUse,
                   DataLoader::HandleMissingCov handleMissingCov,
                   SimpleMatrix* covariate, std::vector<std::string>* colNames,
                   std::set<std::string>* sampleToDrop) {
  // load covariate
  SimpleMatrix mat;
  int ret = extractCovariate(fn, includedSample, covNameToUse, handleMissingCov,
                             &mat, sampleToDrop);
  if (ret < 0) {
    return -1;
  }

  // create covariate sample index
  // const int nr = mat.nrow();
  const int nc = mat.ncol();

  std::map<std::string, int> covIndex;
  makeMap(mat.getRowName(), &covIndex);
  int idx = 0;
  for (size_t i = 0; i < includedSample.size(); ++i) {
    if (covIndex.find(includedSample[i]) == covIndex.end()) {
      sampleToDrop->insert(includedSample[i]);
      continue;
    }
    const int match = covIndex[includedSample[i]];
    covariate->resize(idx + 1, nc);
    for (int j = 0; j < mat.ncol(); ++j) {
      (*covariate)[idx][j] = mat[match][j];
      // skip row label, as MathMatrix class does not have row label
    }
    ++idx;
  }
  // set col label
  for (int i = 0; i < mat.ncol(); ++i) {
    // (*covariate).SetColumnLabel(i, mat.getColName()[i].c_str());
    (*covariate).setColName(i, mat.getColName()[i]);
  }
  return 0;
}  // end _loadCovariate
Exemplo n.º 18
0
Monster::Monster(SceneNode* node, Entity* entity, Maze* maze, MonsterManager* monsterMgr)
	:
	mMonsterManager(monsterMgr),
	mSpeedPre(1),
	mSpeedTemp(1),
	mSpeedCurrent(1),
	/*mPos(Ogre::Vector3(BEGIN_POS_X, 10, BEGIN_POS_Y)),*/
	mBlood(0),
	mMaxBlood(0),
	mFace(Ogre::Vector3(0, 0, 0)),
	mRadius(1),
	mType(),
	//mHarmList(),
	mIsDead(false),
	mBeginPosIndex(-1),
	mNextPosIndex(0),
	mDistance(-0.1f),
	mBulletHarmTime(0),
	mBulletHarmValue(0),
	mTerrainHarmvalue(0),
	mHealthHUD(0),
	mIsGetUFO(false),
	mNode(node),
	mEntity(entity),
	mMaze(maze),
	mFrozenPs(0), mBurnPs(0)
{
	mCheckMethod = new CheckMethod();
	mMonsterState = new MonsterState();

	//mNode->setOrientation(0, 0, 1, 0);
	makeMap(mMaze->getMazeInfo());
	int i = rand() % startPos.size();
	fromPos = startPos[i];
	findPath(fromPos);
	this->transPos();

}
Exemplo n.º 19
0
/**
 * Extract covaraite from file @param fn.
 * Only samples included in @param includedSample will be processed
 * If some samples appear more than once, only the first appearance will be
 * readed
 * Only covaraites provided in @param covNameToUse will be included
 * Missing values will be imputed to the mean columnwise.
 * Result will be put to @param mat (sample by covariate) and @param
 * sampleToDrop
 * @return number of sample loaded (>=0); or a minus number meaning error
 * @param sampleToDrop: store samples that are not found in covariate.
 */
int extractCovariate(const std::string& fn,
                     const std::vector<std::string>& sampleToInclude,
                     const std::vector<std::string>& covNameToUse,
                     DataLoader::HandleMissingCov handleMissingCov,
                     SimpleMatrix* mat, std::set<std::string>* sampleToDrop) {
  std::set<std::string> includeSampleSet;
  makeSet(sampleToInclude, &includeSampleSet);
  if (includeSampleSet.size() != sampleToInclude.size()) {
    logger->warn(
        "Some samples have appeared more than once, and we record covariate "
        "for its first appearance");
  }
  std::vector<std::string> noPhenotypeSample;

  std::map<std::string, int>
      processed;  // record how many times a sample is processed
  std::set<std::pair<int, int> >
      missing;  // record which number is covaraite is missing.
  int missingCovariateWarning =
      0;  // record how many times a missing warning is geneated.
  bool missingValueInLine;  // record whether there is missing value in the
                            // line
  int missingLines = 0;     // record how many lines has missing values
  std::vector<int> columnToExtract;
  std::vector<std::string> extractColumnName;
  std::vector<std::string> fd;
  LineReader lr(fn);
  int lineNo = 0;
  int fieldLen = 0;
  while (lr.readLineBySep(&fd, "\t ")) {
    ++lineNo;
    if (lineNo == 1) {  // header line
      fieldLen = fd.size();
      if (fieldLen < 2) {
        logger->error(
            "Insufficient column number (<2) in the first line of covariate "
            "file!");
        return -1;
      };
      if (tolower(fd[0]) != "fid" || tolower(fd[1]) != "iid") {
        logger->error("Covariate file header should begin with \"FID IID\"!");
        return -1;
      }
      std::map<std::string, int> headerMap;
      makeMap(fd, &headerMap);
      if (fd.size() != headerMap.size()) {
        logger->error("Covariate file have duplicated header!");
        return -1;
      }
      // specify which covariates to extract
      if (covNameToUse.size()) {
        for (size_t i = 0; i < covNameToUse.size(); ++i) {
          if (headerMap.count(covNameToUse[i]) == 0) {
            logger->error(
                "The covariate [ %s ] you specified cannot be found from "
                "covariate file!",
                covNameToUse[i].c_str());
            continue;
          }
          columnToExtract.push_back(headerMap[covNameToUse[i]]);
          extractColumnName.push_back(covNameToUse[i]);
        }
      } else {
        for (size_t i = 2; i < fd.size(); ++i) {
          columnToExtract.push_back(headerMap[fd[i]]);
          extractColumnName.push_back(fd[i]);
        }
      }
    } else {  // body lines
      if (fd.empty() ||
          (fd[0].empty() && fd.size() == 1)) {  // skip empty lines
        continue;
      }
      if ((int)fd.size() != fieldLen) {
        logger->error(
            "Inconsistent column number in covariate file line [ %d ] - skip "
            "this file!",
            lineNo);
        return -1;
      }
      if (includeSampleSet.find(fd[1]) ==
          includeSampleSet.end()) {  // does not have phenotype
        noPhenotypeSample.push_back(fd[1]);
        continue;
      };
      processed[fd[1]]++;
      if (processed[fd[1]] > 1) {
        logger->info("Duplicate sample [ %s ] in covariate file, skipping",
                     fd[1].c_str());
        continue;
      };
      int idx = (*mat).nrow();
      (*mat).resize(idx + 1, columnToExtract.size());
      (*mat).setRowName(idx, fd[1]);

      missingValueInLine = false;
      for (int i = 0; i < (int)columnToExtract.size(); ++i) {
        double d;
        if (str2double(fd[columnToExtract[i]], &d)) {
          (*mat)[idx][i] = d;
        } else {  // found missing
          missingValueInLine = true;
          ++missingCovariateWarning;
          if (missingCovariateWarning <= 10) {
            if (handleMissingCov == DataLoader::COVARIATE_IMPUTE) {
              logger->warn(
                  "Covariate file line [ %d ] has non-numerical value [ %s "
                  "], "
                  "we will impute to its mean",
                  lineNo, fd[columnToExtract[i]].c_str());
            } else if (handleMissingCov == DataLoader::COVARIATE_DROP) {
              logger->warn(
                  "Covariate file line [ %d ] has non-numerical value [ %s "
                  "], "
                  "we will skip this sample",
                  lineNo, fd[columnToExtract[i]].c_str());
            }
          }
          (*mat)[idx][i] = 0.0;  // will later be updated
          missing.insert(std::make_pair(idx, i));
        };
      }
      if (!missing.empty() && handleMissingCov == DataLoader::COVARIATE_DROP) {
        // drop row and row name
        (*mat).deleteRow((*mat).nrow() - 1);
        missing.clear();
      }
      missingLines += missingValueInLine ? 1 : 0;
    }
  }
  if (missingCovariateWarning > 10) {
    if (handleMissingCov == DataLoader::COVARIATE_IMPUTE) {
      logger->warn(
          "Total [ %d ] lines in covariate file contain non-numerical "
          "values, "
          "we will impute these to their mean",
          missingLines);
    } else if (handleMissingCov == DataLoader::COVARIATE_DROP) {
      logger->warn(
          "Total [ %d ] lines in covariate file contain non-numerical "
          "values, "
          "we will skip these lines",
          missingLines);
    }
  }

  // output samples in covaraite but without phenotype
  for (size_t i = 0; i < noPhenotypeSample.size(); ++i) {
    if (i == 0)
      logger->warn(
          "Total [ %zu ] samples are skipped from covariate file due to "
          "missing phenotype",
          noPhenotypeSample.size());
    if (i > 10) {
      logger->warn(
          "Skip outputting additional [ %d ] samples from covariate file "
          "with "
          "missing phenotypes",
          ((int)noPhenotypeSample.size() - 10));
      break;
    }
    logger->warn(
        "Skip sample [ %s ] from covariate file due to missing phenotype",
        (noPhenotypeSample)[i].c_str());
  }

  // set up labels
  for (size_t i = 0; i < extractColumnName.size(); ++i) {
    mat->setColName(i, extractColumnName[i]);
  }
  for (size_t i = 0; i < sampleToInclude.size(); i++) {
    if (processed.find(sampleToInclude[i]) == processed.end()) {
      logger->warn("Covariate file does not contain sample [ %s ]",
                   sampleToInclude[i].c_str());
      sampleToDrop->insert(sampleToInclude[i]);
    };
  }

  if (handleMissingCov == DataLoader::COVARIATE_DROP) {
    assert(missing.empty());
    return (*mat).nrow();
  }
  // impute missing covariates to mean by column
  for (int col = 0; col < mat->ncol(); ++col) {
    double sum = 0;
    int nonZero = 0;
    for (int row = 0; row < (*mat).nrow(); ++row) {
      if (missing.count(std::make_pair(row, col))) continue;  // missing
      sum += (*mat)[row][col];
      ++nonZero;
    }
    if (nonZero == 0) {  // all column are missing, drop column
      logger->info(
          "Covariate [ %s ] is missing for all samples. Exclude please "
          "before "
          "continue!",
          mat->getColName()[col].c_str());
      return -1;
    }
    // some elements are missing
    double mean = sum / nonZero;
    for (int row = 0; row < (*mat).nrow(); ++row) {
      if (missing.count(std::make_pair(row, col))) {
        (*mat)[row][col] = mean;
      }
    }
  }
  return (*mat).nrow();
}  // end extractCovariate
Exemplo n.º 20
0
/* -----------    open the next Balise ---------------------*/
int  SparseXML::openBalise()
{
// note that all the comment balise have been removed of the string xml  
//cout<<"openBalise"<<endl;
if(_current_position>=_xml_string->length())
      return(EndXMLFile);
// find the open chevron
while(_xml_string->at(_current_position)!='<')
          {
            _current_position++;
            if(_current_position>=_xml_string->length()) return EndXMLFile;
           }
// we have to check that we do not deal with a close balise
if(_xml_string->at(_current_position+1)=='/')
          {// it is a close balise
            _current_position--; //reposition of the pointer
            return(NoOpenBalise); // we can not open more balise
          } 
// ok it is an open balise
_level++;
_element.clear();
_current_position++; // skip the open chevron           
// skip the spaces
while (_xml_string->at(_current_position)==' ')
           {
            _current_position++;
            if(_current_position>=_xml_string->length())
                      {cout<<" error  function openBalise "<<"  in "<<__FILE__<< " line "<<__LINE__<<endl;
                        return(BadBaliseFormat);}    
            }
//  _current_position is on the element 
while(_xml_string->at(_current_position)!=' ' &&
          _xml_string->at(_current_position)!='/'&& 
          _xml_string->at(_current_position)!='>')
            {
              _element+=_xml_string->at(_current_position);
              _current_position++;
              if(_current_position>=_xml_string->length())
                      {cout<<" error  function openBalise "<<"  in "<<__FILE__<< " line "<<__LINE__<<endl;
                        return(BadBaliseFormat);}    
            }
// extract attribute line if any
string  attribute_string;
string end1=">";
string end2="/>";
size_t end_position_attribute1,end_position_attribute2;
attribute_string.clear();

end_position_attribute1=_xml_string->find(end1,_current_position);
end_position_attribute2=_xml_string->find(end2,_current_position);
if(end_position_attribute1==string::npos) // check that we close the chevron
              {cout<<" bad format for open balise  "<<"  in "<<__FILE__<< " line "<<__LINE__<<endl;
                return(BadBaliseFormat);} 
if(end_position_attribute2<end_position_attribute1)   //\we have an empty element
      {
       // cout<<"it is an empty balise"<<endl;
       _empty_element=true; // it is an empty element
       attribute_string.append((*_xml_string),_current_position,end_position_attribute2-_current_position);
       _data_length=0;// no data
      _current_position= end_position_attribute2+2;// jump />
      }
else // there is possible data
      {
       // cout<<"balise with possible data"<<endl;
       _empty_element=false; 
        //cout<<"my position:"<<_xml_string->at(_current_position-2)<<_xml_string->at(_current_position-1)<<endl;       
        attribute_string.append((*_xml_string),_current_position,end_position_attribute1-_current_position);
        //cout<<"the attribute_string "<<attribute_string<<endl;
        _current_position= end_position_attribute1+1;// jump >
      }
makeMap(attribute_string);        
return(OkOpenBalise);     
}
Exemplo n.º 21
0
void APalette::finishHistogram()
{
  //if(error()) return;
  if(!score) {
#ifdef DEBUG_VERBOSE
    dBug<<"Don't have a score!\n";
#endif // DEBUG_VERBOSE
    return;
  }
#ifdef DEBUG_VERBOSE
  dBug<<"Finishing up Histogram...\n";
#endif // DEBUG_VERBOSE
  int *a=(int *)malloc(sizeof(int)*numColors);
  if(!a) {
#ifdef DEBUG_VERBOSE
    dBug<<"Couldn't alloc temp score array!\n";
#endif // DEBUG_VERBOSE
    return;
  }
  for(unsigned int t=0;t<numColors;t++) a[t]=0;
#ifdef DEBUG_VERBOSE
  dBug<<"Removing duplicate colors...\n";
#endif // DEBUG_VERBOSE
  if(!bitsHint) bitsHint=significantBits/3;
  // We only handle up to 24 bit color for now (not 32 or 48, etc)
  if(bitsHint>8) bitsHint=8;
  mapSigBits=bitsHint*3;
  unsigned int shift=8-bitsHint,mask=0xff;
  for(unsigned int qq=0;qq<shift;qq++) mask-=(1<<qq);
#ifdef DEBUG_VERBOSE
  dBug<<"(Mask is "<<mask<<", and shift is "<<shift<<")\n";
#endif // DEBUG_VERBOSE
  int tr,tg,tb,xr,xg,xb;
  for(unsigned int ds=0;ds<numColors;ds++) {
    tr=(r[ds]&mask)>>shift;  tg=(g[ds]&mask)>>shift;  tb=(b[ds]&mask)>>shift;
    for(unsigned int xs=0;xs<numColors;xs++) {
      // Same for these...
      xr=(r[xs]&mask)>>shift;  xg=(g[xs]&mask)>>shift;  xb=(b[xs]&mask)>>shift;
      if((ds!=xs)&&score[ds]&&score[xs]&&(tr==xr)&&(tg==xg)&&(tb==xb)) {
        score[ds]+=score[xs];  score[xs]=0;
      }
      if(isHBrite()) {
        tr/=2;  tg/=2;  tb/=2;
        if((ds!=xs)&&score[ds]&&score[xs]&&(tr==xr)&&(tg==xg)&&(tb==xb)) {
          score[ds]+=score[xs];  score[xs]=0;
        }
      }
    }
  }
#ifdef DEBUG_VERBOSE
  dBug<<"Pixels: ";
  for(unsigned int ps=0;ps<numColors;ps++) dBug<<score[ps]<<" ";
  dBug<<"\n";
#endif // DEBUG_VERBOSE
  long best;
  int p;
#ifdef DEBUG_VERBOSE
  dBug<<"Pass: "******" ";
#endif // DEBUG_VERBOSE
    best=0;  p=-1;
    for(unsigned int s=0;s<numColors;s++) {
      if((best<=score[s])&&(!a[s])) { best=score[s];  p=s; }
    }
    if(p!=-1) a[p]=cur;
#ifdef DEBUG_VERBOSE
    else dBug<<"No best on this pass!\n";
#endif // DEBUG_VERBOSE
  }
#ifdef DEBUG_VERBOSE
  dBug<<"\n";
  dBug<<"Scores: ";
#endif // DEBUG_VERBOSE
  for(unsigned int s=0;s<numColors;s++)  {
    score[s]=a[s];
#ifdef DEBUG_VERBOSE
    dBug<<score[s]<<" ";
#endif // DEBUG_VERBOSE
  }
#ifdef DEBUG_VERBOSE
  dBug<<"\n";
#endif // DEBUG_VERBOSE
  free(a);
  if(map) {
#ifdef DEBUG_VERBOSE
    dBug<<"Already a map!!!\n";
#endif // DEBUG_VERBOSE
  }
  map=(int *)malloc(sizeof(int)*numColors);
  if(!map) {
#ifdef DEBUG_VERBOSE
    dBug<<"Couldn't alloc map array!\n";
#endif // DEBUG_VERBOSE
    return;
  }
  histComputed=true;
  makeMap();
}
Exemplo n.º 22
0
MvScene::MvScene(QObject *parent) : QGraphicsScene(parent)
{
        makeMap();
	setBackgroundBrush(QBrush(QColor(255,255,255), QPixmap("bg.jpg")));
}
Exemplo n.º 23
0
/** 找开文件
@param   pszFileName:文件名
@param   
@return  
*/
bool CCsvReader::Open(const char* pszFileName, bool bEncrypt)
{
	if(pszFileName == NULL)
	{
		return false;
	}

	m_curStrName = pszFileName;

	// 取得文件系统
	FileSystem * pFileSystem = getFileSystem();
	if(pFileSystem == NULL)
	{
		return false;
	}

	// 读取文件
	Stream * pStream = pFileSystem->open(pszFileName);
	if(pStream == NULL)
	{
		return false;
	}

	// 解密文件
	char * pFileBuffer = NULL;
	MemoryStream memorystream;
	if(bEncrypt)
	{
		int nFileLength = pStream->getLength();
		pFileBuffer = new char [nFileLength + 1];
		if(!pStream->read(pFileBuffer, nFileLength))
		{
			return false;
		}
		pStream->close();
		pStream->release();

		if(!makeMap((uchar *)pFileBuffer, nFileLength, 'LAND'))
		{
			return false;
		}

		memorystream.attach((uchar *)pFileBuffer, nFileLength);
		pStream = &memorystream;
	}
	
	// 解析
	if(!_Open(pStream))
	{
		if(pFileBuffer != NULL)
		{
			delete [] pFileBuffer;
			pFileBuffer = NULL;
		}
		
		// 关闭文件
		pStream->close();
		pStream->release();
		return false;
	}
	// 关闭文件
	pStream->close();
	
	pStream->release();
	if(pFileBuffer != NULL)
	{
		delete [] pFileBuffer;
		pFileBuffer = NULL;
	}
	return true;
}
Exemplo n.º 24
0
/**
 * Load kinship file and store the kinship matrix internally
 */
int KinshipHolder::loadK() {
  // check kinship file existance
  if (!fileExists(this->fileName)) {
    logger->warn("Cannot open kinship file [ %s ]", this->fileName.c_str());
    return -1;
  }

  const std::vector<std::string>& names = *this->pSample;
  if (this->fileName == "IDENTITY" || this->fileName == "UNRELATED") {
    this->matK->mat.resize(names.size(), names.size());
    this->matK->mat.setZero();
    this->matK->mat.diagonal().setOnes();
    this->matK->mat.diagonal() *= 0.5;
    return 0;
  }

  LineReader lr(this->fileName);
  int lineNo = 0;
  int fieldLen = 0;
  std::vector<std::string> fd;
  std::vector<int> columnToExtract;
  std::vector<std::string> header;  // kinship header line
  Eigen::MatrixXf& mat = this->matK->mat;
  std::map<std::string, int> nameMap;
  makeMap(names, &nameMap);

  while (lr.readLineBySep(&fd, "\t ")) {
    ++lineNo;
    if (lineNo == 1) {  // check header
      header = fd;
      fieldLen = fd.size();
      if (fieldLen < 2) {
        logger->error(
            "Insufficient column number (<2) in the first line of kinsihp "
            "file!");
        return -1;
      };
      if (tolower(fd[0]) != "fid" || tolower(fd[1]) != "iid") {
        logger->error("Kinship file header should begin with \"FID IID\"!");
        return -1;
      }
      std::map<std::string, int> headerMap;
      makeMap(fd, &headerMap);
      if (fd.size() != headerMap.size()) {
        logger->error("Kinship file have duplicated header!");
        return -1;
      }
      for (size_t i = 0; i < names.size(); ++i) {
        if (headerMap.count(names[i]) == 0) {
          logger->error("Cannot find sample [ %s ] from the kinship file!",
                        names[i].c_str());
          return -1;
        }
        columnToExtract.push_back(headerMap[names[i]]);
      }
      mat.resize(columnToExtract.size(), columnToExtract.size());
      continue;
    }
    // body lines
    if ((int)fd.size() != fieldLen) {
      logger->error(
          "Inconsistent column number [ %zu ] (used to be [ %d ]) in kinship "
          "file line [ %d ] - skip this file!",
          fd.size(), fieldLen, lineNo);
      // todo: this error may be false alarm - as the last line may be empty
      continue;
      // exit(1);
    }
    if (fd[1] != header[lineNo]) {  // PID in line i (1-based) should matched
                                    // the (i+1) (1-based) column in the header
      logger->error(
          "Inconsistent IID names in kinship file line [ %d ], file corrupted!",
          lineNo);
      return -1;
    }
    int row;
    if (nameMap.find(fd[1]) == nameMap.end()) {
      continue;
    }
    row = nameMap[fd[1]];
    for (size_t i = 0; i < columnToExtract.size(); ++i) {
      double d;
      if (str2double(fd[columnToExtract[i]], &d)) {
        mat(row, i) = d;
      } else {
        // unable to read, then set it to zero
        mat(row, i) = 0.0;
      }
    }
  }
#ifdef DEBUG
  std::string tmp = fn;
  tmp += ".tmp";
  std::ofstream ofs(tmp.c_str(), std::ofstream::out);
  ofs << mat;
  ofs.close();
#endif

  // fprintf(stderr, "Kinship matrix [ %d x %d ] loaded", (int)mat.rows(),
  // (int)mat.cols());
  this->loaded = true;
  return 0;
}
Exemplo n.º 25
0
// Main Function
void _main(void)
{	
	// declare variables
	char keys[8]; getKeyMasks(keys);
	BITS bit= {0,0,0,0,0,0,0,0};
	char arrow_key=0;
	POSITION thingPOS= {0,0};
	POSITION mapPOS= {0,0};
	// main menu
	title();
	
	// prepare for GRAYSCALE AND ROWREAD
	interrupt1 = GetIntVec(AUTO_INT_1);
	SetIntVec(AUTO_INT_1,DUMMY_HANDLER);
	
	while (1) {
		
		// initialize
		bit.one=0;
		thingPOS= (POSITION){0,0};
		
		// a blank slate
		ClrScr();
		
		//setup game, draw screen, etc
		draw(thing,thingPOS,mapPOS);
		makeMap(mapPOS);
		while (!button(ARROW_ROW,keys[UP]));
		
		while(!button(TI89_ESCROW,TI89_ESCKEY) && !bit.one) {
			// the game loop
			arrow_key=_rowread(ARROW_ROW);
			bit=(BITS){0,0,0,0,0,0,0,0};
			
			//get input
			if (arrow_key) {
				if (arrow_key & keys[UP]) bit.yup=1;
				if (arrow_key & keys[RIGHT]) bit.xright=1;
				if (arrow_key & keys[DOWN]) bit.ydown=1;
				if (arrow_key & keys[LEFT]) bit.xleft=1;
			}
			
			// test gunner is within dimension
			if (dim(thingPOS,bit)) {
				bit.draw=1;
				thingPOS.x+=bit.xright+(-bit.xleft);
				thingPOS.y+=bit.yup+(-bit.ydown);
			}
			
			if (bit.draw) {
			mapPOS.x=thingPOS.x-10;
			mapPOS.y=thingPOS.y-5;
			if (mapPOS.x<0) mapPOS.x=0;
			else if (mapPOS.x>11) mapPOS.x=11;
			if (mapPOS.y<0) mapPOS.y=0;
			else if (mapPOS.y>20) mapPOS.y=20;
			}
			
			// if movement=true, draw new position
			if (bit.draw) {
				ClrScr();
				makeMap(mapPOS);
				draw(thing,thingPOS,mapPOS);
			}
			
			//delay
			delay(6);
		} 
		if (!bit.one) {
			SetIntVec(AUTO_INT_1,interrupt1);
			return;
		}	  														//while !quit and !done
	} 																														//infinite loop
}
Exemplo n.º 26
0
int KinshipHolder::loadDecomposed() {
  LineReader lr(this->eigenFileName);
  int lineNo = 0;
  int fieldLen = 0;
  std::vector<std::string> fd;
  std::vector<int> columnToExtract;
  std::vector<std::string> header;  // header line of the kinship eigen file
  Eigen::MatrixXf& matK = this->matK->mat;
  Eigen::MatrixXf& matS = this->matS->mat;
  Eigen::MatrixXf& matU = this->matU->mat;
  const std::vector<std::string>& names = *this->pSample;
  const int NumSample = (int)names.size();
  std::map<std::string, int> nameMap;
  makeMap(names, &nameMap);
  std::map<std::string, int> headerMap;

  while (lr.readLineBySep(&fd, "\t ")) {
    ++lineNo;
    if (lineNo == 1) {  // check header
      header = fd;
      fieldLen = fd.size();
      if (fieldLen < 3) {  // at least three columns: IID, Lambda, U1
        logger->error(
            "Insufficient column number (<3) in the first line of kinsihp "
            "file!");
        return -1;
      };
      for (size_t i = 0; i != fd.size(); ++i) {
        fd[i] = tolower(fd[i]);
      }
      makeMap(fd, &headerMap);
      if (fd.size() != headerMap.size()) {
        logger->error("Kinship file have duplicated headers!");
        return -1;
      }

      // check IID, Lambda, U1, U2, ... U(N) where (N) is the sample size
      if (headerMap.count("iid") == 0) {
        logger->error("Missing 'IID' column!");
        return -1;
      }
      columnToExtract.push_back(headerMap["iid"]);

      if (headerMap.count("lambda") == 0) {
        logger->error("Missing 'Lambda' column!");
        return -1;
      }
      columnToExtract.push_back(headerMap["lambda"]);

      std::string s;
      for (int i = 0; i < NumSample; ++i) {
        s = "u";
        s += toString(i + 1);
        if (headerMap.count(s) == 0) {
          logger->error("Missing '%s' column!", s.c_str());
          return -1;
        }
        columnToExtract.push_back(headerMap[s]);
      }
      s = "u";
      s += toString(NumSample + 1);
      if (headerMap.count(s) != 0) {
        logger->error("Unexpected column '%s'!", s.c_str());
        return -1;
      }

      matS.resize(NumSample, 1);
      matU.resize(NumSample, NumSample);
      continue;
    }
    // body lines
    if ((int)fd.size() != fieldLen) {
      logger->error(
          "Inconsistent column number [ %zu ] (used to be [ %d ])in kinship "
          "file line [ %d ] - skip this file!",
          fd.size(), fieldLen, lineNo);
      return -1;
    }

    const int iidColumn = columnToExtract[0];
    const std::string& iid = fd[iidColumn];
    if (nameMap.count(iid) == 0) {
      logger->error("Unexpected sample [ %s ]!", iid.c_str());
      return -1;
    }
    const int row = nameMap[iid];

    const int lambdaColumn = columnToExtract[1];
    double temp = 0.0;
    if (!str2double(fd[lambdaColumn], &temp)) {
      logger->warn("Invalid numeric value [ %s ] treated as zero!",
                   fd[lambdaColumn].c_str());
    }
    matS(lineNo - 2, 0) = temp;

    for (int i = 0; i < NumSample; ++i) {
      int uColumn = columnToExtract[i + 2];
      if (!str2double(fd[uColumn], &temp)) {
        logger->warn("Invalid numeric value [ %s ] treated as zero!",
                     fd[lambdaColumn].c_str());
      }
      matU(row, i) = temp;
    }
  }

  // verify eigen decomposition results make senses
  // check largest eigen vector and eigen value
  Eigen::MatrixXf v1 = matK * matU.col(0);
  Eigen::MatrixXf v2 = matS(0, 0) * matU.col(0);
  if (matS(0, 0) > 0.5 && v1.col(0).norm() > .5 && v2.col(0).norm() > 0.5 &&
      corr(v1, v2) < 0.8) {
    logger->warn("Cannot verify spectral decompose results!");
    return -1;
  }

  // check the min(10, NumSample) random eigen vector and eigen value
  int randomCol = 10;
  if (randomCol > NumSample - 1) {
    randomCol = NumSample - 1;
  }
  v1 = matK * matU.col(randomCol);
  v2 = matS(randomCol, 0) * matU.col(randomCol);
  if (matS(randomCol, 0) > 0.5 && v1.col(0).norm() > 0.5 &&
      v2.col(0).norm() > 0.5 && corr(v1, v2) < 0.8) {
    logger->warn("Cannot verify spectral decompose results!");
    return -1;
  }

#ifdef DEBUG
  std::string tmp = fn;
  tmp += ".tmp";
  std::ofstream ofs(tmp.c_str(), std::ofstream::out);
  ofs << mat;
  ofs.close();
#endif

  // fprintf(stderr, "Kinship matrix [ %d x %d ] loaded", (int)mat.rows(),
  // (int)mat.cols());

  if (this->matK) {
    delete this->matK;
    this->matK = NULL;
  }

  return 0;
}
Exemplo n.º 27
0
// #    #  ######  #    # #     #  #    #  #    #   #####  ######  #####
// ##   #  #       #    # #     #  #    #  ##   #     #    #       #    #
// # #  #  #####   #    # #######  #    #  # #  #     #    #####   #    #
// #  # #  #       # ## # #     #  #    #  #  # #     #    #       #####
// #   ##  #       ##  ## #     #  #    #  #   ##     #    #       #   #
// #    #  ######  #    # #     #   ####   #    #     #    ######  #    #
//SPLIT STRING PLAY INTO 2D array with 7 chars. 
HunterView newHunterView( char *pastPlays, playerMessage messages[] ) {
    HunterView hunterView = malloc( sizeof( *hunterView ) );
    hunterView->score = GAME_START_SCORE;
    
    int i;
    int counter;
    
    counter = 0;
    hunterView->totalTurns = (strlen(pastPlays)+1)/(PLAYLEN+1);


    // Initialise the 2D array of strings
    // http://stackoverflow.com/a/14583642
    // Initialise an array of pointers for the  amount of total turns
    hunterView->seperatedPP = malloc (hunterView->totalTurns * sizeof(char*));
    assert(hunterView->seperatedPP != NULL);
    
    // Intialise a string for every turn
    for(i = 0; i < hunterView->totalTurns; i++) {
        hunterView->seperatedPP[i] = malloc(sizeof(char));
        assert(hunterView->seperatedPP[i] != NULL);
    }

    for(i=0; i<hunterView->totalTurns; i++){

        int j;
        for(j=0; j<PLAYLEN; j++){
            
            hunterView->seperatedPP[i][j] = pastPlays[counter];
            counter++;
        }
        //hunterView->seperatedPP[i][PLAYLEN] = '\0';
        counter++;
    }
    
    for (i=0; i<hunterView->totalTurns; i++) {
        printf ("[%d]*%s*\n", i, hunterView->seperatedPP[i]);
    }


    // intialise all values to 0 (false)
    for (i = 0; i < NUM_PLAYERS; i++) {
        // MALLOC FOR PLAYERSTRUCT
        hunterView->playerStruct[i] = malloc(sizeof(struct _playerStruct));
        
        hunterView->died[i] = FALSE;

        hunterView->playerStruct[i]->health = calculateHealth(hunterView, i);
        // initialise died to 0
        hunterView->playerStruct[i]->numDied = 0;
        
    }
    
    // store latest score into struct
    hunterView->score = calculateScore(hunterView);
       

        makeMap(hunterView);

        
       
    
    return hunterView;
}