예제 #1
0
static inline bool IsAtomLine(ArgList& lineIn) {
  for (int i = 0; i < lineIn.Nargs(); i++) {
    std::string item = lineIn.GetStringNext();
    if (i == 0 || i >= 5) {
      try {
        convertToInteger( item );
      }
      catch (std::runtime_error e) {
        return false;
      }
    } else if (i >= 2 && i < 5) {
      try {
        convertToDouble( item );
      }
      catch (std::runtime_error e) {
        return false;
      }
    }
  }
  return true;
}
예제 #2
0
/**
 * @brief OptionDefinition::convertValue
 * @param stringValue
 * @return
 */
QVariant OptionDefinition::convertValue(const QString &stringValue) const
{
    QVariant value(QVariant::Invalid);
    switch (d->m_dataType) {
    case QVariant::Bool:
        value.setValue(convertToBool(stringValue));
        break;
    case QVariant::Date:
        value.setValue(convertToDate(stringValue));
        break;
    case QVariant::DateTime:
        value.setValue(convertToDateTime(stringValue));
        break;
    case QVariant::Double:
        value.setValue(convertToDouble(stringValue));
        break;
    case QVariant::Int:
        value.setValue(convertToInt(stringValue));
        break;
    case QVariant::LongLong:
        value.setValue(convertToLongLong(stringValue));
        break;
    case QVariant::String:
        value.setValue(stringValue);
        break;
    case QVariant::Time:
        value.setValue(convertToTime(stringValue));
        break;
    case QVariant::UInt:
        value.setValue(convertToUInt(stringValue));
        break;
    case QVariant::ULongLong:
        value.setValue(convertToULongLong(stringValue));
        break;
    default:
        break;
    }

    return value;
}
예제 #3
0
bool TinkerFile::ID_Tinker(CpptrajFile& fileIn) {
  // NOTE: ASSUME FILE SET UP FOR READ
  if (fileIn.OpenFile()) return false;
  ArgList firstLine( fileIn.NextLine() );
  ArgList secondLine( fileIn.NextLine() );
  ArgList thirdLine( fileIn.NextLine() );
  fileIn.CloseFile();
  // First line should have <natom> <title> only
  int natom = 0;
  std::string title;
  if ( SetNatomAndTitle(firstLine, natom, title) != 0 )
    return false;
  //mprinterr("Past SetNatomAndTitle\n");
  if (secondLine.Nargs() == 6) {
    bool isBoxLine = true;
    for (int i = 0; i < 6; i++) {
      // It is a box line if all 6 tokens are doubles
      try {
        convertToDouble( secondLine.GetStringNext() );
      } 
      catch (std::runtime_error e) {
        if (i != 1) return false;
        // We found a non-double on the second character -- it could be an atom
        // name. Check that the rest of the line matches an atom record
        isBoxLine = false;
        break;
      }
    }
    // If we are here it is not a box line, so make sure 
    if (!isBoxLine) {
      return IsAtomLine(secondLine);
    } else { // our second line WAS a box, now check the 3rd line
      return IsAtomLine(thirdLine);
    }
  }
  // There is no box, check that the second line is an atom line
  return IsAtomLine(secondLine);
}
예제 #4
0
void PDI::gaussianConvolution(int sigma, cv::Mat &image, bool separated_kernel){
    // Get the image range (to re-convert)
    int min, max;
    getImageRange(image, min, max);
    // Create a copy of the values (as double)
    cv::Mat g = convertToDouble(image);
    // Image double of zeros
    cv::Mat f = cv::Mat::zeros(g.rows, g.cols, CV_64F);

    if(separated_kernel){ // Kernel separated routine
        // Generating Kernel
        double h0[6*sigma];
        double h1[6*sigma];
        gaussianArrays(sigma, h0, h1);

        f = convolutionSeparatedKernel(g, h0, 6*sigma, h1, 6*sigma);
    }

    else{ // Unique Kernel routine
        // Generating Kernel
        cv::Mat h = gaussianImage(sigma);
        cv::namedWindow("Kernel",CV_WINDOW_NORMAL);
        cv::imshow("Kernel", convertToInterger(h));

        f = convolution(g, h);
    }

    // Image double converted into integer
    normalizateMatrix(f, min, max);
    cv::Mat img = convertToInterger(f);

    cv::namedWindow("Initial Image");
    cv::imshow("Initial Image", image);
    cv::namedWindow("Final Image");
    cv::imshow("Final Image", img);
}
예제 #5
0
/** Given an ArgList containing name,[min,max,step,bins,col,N], set up a 
  * coordinate with that name and parameters min, max, step, bins.
  * If '*' or not specified, a default value will be set.
  * \return 1 if error occurs, 0 otherwise.
  */
int Analysis_Hist::setupDimension(ArgList &arglist, DataSet_1D const& dset, size_t& offset) {
  bool minArg = false;
  bool maxArg = false;
  bool stepArg = false;
  bool binsArg = false; 

  if (debug_>1)
    arglist.PrintList();

  // Set up dimension name
  // NOTE: arglist[0] should be same as dset name from CheckDimension 
  std::string const& dLabel = arglist[0];

  // Cycle through coordinate arguments. Any argument left blank will be 
  // assigned a default value later.
  double dMin = 0.0;
  double dMax = 0.0;
  double dStep = 0.0;
  int dBins = -1;
  for (int i = 1; i < arglist.Nargs(); i++) {
    if (debug_>1) mprintf("DEBUG: setupCoord: Token %i (%s)\n", i, arglist[i].c_str());
    // '*' means default explicitly requested
    if (arglist[i] == "*") continue;
    switch (i) {
      case 1 : dMin  = convertToDouble( arglist[i]); minArg = true; break;
      case 2 : dMax  = convertToDouble( arglist[i]); maxArg = true; break;
      case 3 : dStep = convertToDouble( arglist[i]); stepArg = true; break;
      case 4 : dBins = convertToInteger(arglist[i]); binsArg = true; break;
    }
  }

  // If no min arg and no default min arg, get min from dataset
  if (!minArg) {
    if (!minArgSet_) 
      dMin = dset.Min();
    else
      dMin = default_min_;
  }
  // If no max arg and no default max arg, get max from dataset
  if (!maxArg) {
    if (!maxArgSet_)
      dMax = dset.Max();
    else
      dMax = default_max_;
  }
  // If bins/step not specified, use default
  if (!binsArg)
    dBins = default_bins_;
  if (!stepArg)
    dStep = default_step_;

  // Calculate dimension from given args.
  HistBin dim;
  if (dim.CalcBinsOrStep( dMin, dMax, dStep, dBins, dLabel )) {
    mprinterr("Error: Could not set up histogram dimension '%s'\n", dLabel.c_str());
    return 1;
  }
  dim.PrintHistBin();
  dimensions_.push_back( dim );

  // Recalculate offsets for all dimensions starting at farthest coord. This
  // follows row major ordering.
  size_t last_offset = 1UL; // For checking overflow.
  offset = 1UL;
  binOffsets_.resize( dimensions_.size() );
  OffType::iterator bOff = binOffsets_.begin();
  for (HdimType::const_iterator rd = dimensions_.begin();
                                rd != dimensions_.end(); ++rd, ++bOff)
  {
    if (debug_>0) mprintf("\tHistogram: %s offset is %zu\n", rd->label(), offset);
    *bOff = (long int)offset;
    offset *= rd->Bins();
    // Check for overflow.
    if ( offset < last_offset ) {
      mprinterr("Error: Too many bins for histogram. Try reducing the number of bins and/or\n"
                "Error:   the number of dimensions.\n");
      return 1;
    }
    last_offset = offset;
  }
  // offset should now be equal to the total number of bins across all dimensions
  if (debug_>0) mprintf("\tHistogram: Total Bins = %zu\n",offset);

  return 0;
}
예제 #6
0
// Parm_CIF::ReadParm()
int Parm_CIF::ReadParm(FileName const& fname, Topology &TopIn) {
  CIFfile infile;
  CIFfile::DataBlock::data_it line;

  if (infile.Read( fname, debug_ )) return 1;
  CIFfile::DataBlock const& block = infile.GetDataBlock("_atom_site");
  if (block.empty()) {
    mprinterr("Error: CIF data block '_atom_site' not found.\n");
    return 1;
  }
  // Does this CIF contain multiple models?
  int Nmodels = 0;
  int model_col = block.ColumnIndex("pdbx_PDB_model_num");
  if (model_col != -1) {
    line = block.end();
    --line;
    Nmodels = convertToInteger( (*line)[model_col] );
    if (Nmodels > 1)
      mprintf("Warning: CIF '%s' contains %i models. Using first model for topology.\n", 
              fname.full(), Nmodels);
  }
  // Get essential columns
  int COL[NENTRY];
  for (int i = 0; i < (int)NENTRY; i++) {
    COL[i] = block.ColumnIndex(Entries[i]);
    if (COL[i] == -1) {
      mprinterr("Error: In CIF file '%s' could not find entry '%s' in block '%s'\n",
                fname.full(), Entries[i], block.Header().c_str());
      return 1;
    }
    if (debug_>0) mprintf("DEBUG: '%s' column = %i\n", Entries[i], COL[i]);
  }
  // Get optional columns
  int occ_col = block.ColumnIndex("occupancy");
  int bfac_col = block.ColumnIndex("B_iso_or_equiv");
  int icode_col = block.ColumnIndex("pdbx_PDB_ins_code");
  int altloc_col = block.ColumnIndex("label_alt_id");
  std::vector<AtomExtra> extra;

  // Loop over all atom sites
  int current_res = 0;
  double XYZ[3];
  double occupancy = 1.0;
  double bfactor = 0.0;
  char altloc = ' ';
  char icode;
  icode = ' ';
  Frame Coords;
  for (line = block.begin(); line != block.end(); ++line) {
    // If more than 1 model check if we are done.
    if (Nmodels > 1) {
      if ( convertToInteger( (*line)[model_col] ) > 1 )
        break;
    }
    if (occ_col != -1) occupancy = convertToDouble( (*line)[ occ_col ] );
    if (bfac_col != -1) bfactor = convertToDouble( (*line)[ bfac_col ] );
    if (altloc_col != -1) altloc = (*line)[ altloc_col ][0];
    // '.' altloc means blank?
    if (altloc == '.') altloc = ' ';
    extra.push_back( AtomExtra(occupancy, bfactor, altloc) );
    if (icode_col != -1) {
      icode = (*line)[ icode_col ][0];
      // '?' icode means blank
      if (icode == '?') icode = ' ';
    }
    XYZ[0] = convertToDouble( (*line)[ COL[X] ] );
    XYZ[1] = convertToDouble( (*line)[ COL[Y] ] );
    XYZ[2] = convertToDouble( (*line)[ COL[Z] ] );
    NameType currentResName( (*line)[ COL[RNAME] ] );
    // It seems that in some CIF files, there doesnt have to be a residue
    // number. Check if residue name has changed.
    if ( (*line)[ COL[RNUM] ][0] == '.' ) {
      Topology::res_iterator lastResidue = TopIn.ResEnd();
      --lastResidue;
      if ( currentResName != (*lastResidue).Name() )
        current_res = TopIn.Nres() + 1;
    } else
      current_res = convertToInteger( (*line)[ COL[RNUM] ] );
    TopIn.AddTopAtom( Atom((*line)[ COL[ANAME] ], "  "),
                      Residue(currentResName, current_res, icode,
                              (*line)[ COL[CHAINID] ][0]) );
    Coords.AddXYZ( XYZ );
  }
  if (TopIn.SetExtraAtomInfo( 0, extra )) return 1;
  // Search for bonds // FIXME nobondsearch?
  BondSearch( TopIn, Coords, Offset_, debug_ );
  // Get title. 
  CIFfile::DataBlock const& entryblock = infile.GetDataBlock("_entry");
  std::string ciftitle;
  if (!entryblock.empty())
    ciftitle = entryblock.Data("id");
  TopIn.SetParmName( ciftitle, infile.CIFname() );
  // Get unit cell parameters if present.
  CIFfile::DataBlock const& cellblock = infile.GetDataBlock("_cell");
  if (!cellblock.empty()) {
    double cif_box[6];
    cif_box[0] = convertToDouble( cellblock.Data("length_a") );
    cif_box[1] = convertToDouble( cellblock.Data("length_b") );
    cif_box[2] = convertToDouble( cellblock.Data("length_c") );
    cif_box[3] = convertToDouble( cellblock.Data("angle_alpha") );
    cif_box[4] = convertToDouble( cellblock.Data("angle_beta" ) );
    cif_box[5] = convertToDouble( cellblock.Data("angle_gamma") );
    mprintf("\tRead cell info from CIF: a=%g b=%g c=%g alpha=%g beta=%g gamma=%g\n",
              cif_box[0], cif_box[1], cif_box[2], cif_box[3], cif_box[4], cif_box[5]);
    TopIn.SetParmBox( Box(cif_box) ); 
  }
  
  return 0;
}
예제 #7
0
// DataIO_Mdout::ReadData()
int DataIO_Mdout::ReadData(FileName const& fname,
                            DataSetList& datasetlist, std::string const& dsname)
{
  mprintf("\tReading from mdout file: %s\n", fname.full());
  BufferedLine buffer;
  if (buffer.OpenFileRead( fname )) return 1;
  const char* ptr = buffer.Line();
  if (ptr == 0) {
    mprinterr("Error: Nothing in MDOUT file: %s\n", fname.full());
    return 1;
  }
  // ----- PARSE THE INPUT SECTION ----- 
  int imin = -1;           // imin for this file
  const char* Trigger = 0; // Trigger for storing energies, must be 8 chars long.
  int frame = 0;           // Frame counter for this file
  double dt = 1.0;         // Timestep for this file (MD)
  double t0 = 0.0;         // Initial time for this file (MD)
  int ntpr = 1;            // Value of ntpr
  int irest = 0;           // Value of irest
  while ( ptr != 0 && strncmp(ptr, "   2.  CONTROL  DATA", 20) != 0 )
    ptr = buffer.Line();
  if (ptr == 0) return EOF_ERROR();
  // Determine whether this is dynamics or minimization, get dt
  ptr = buffer.Line(); // Dashes 
  ptr = buffer.Line(); // Blank 
  ptr = buffer.Line(); // title line
  while ( strncmp(ptr, "   3.  ATOMIC", 13) != 0 ) 
  {
    ArgList mdin_args( ptr, " ,=" ); // Remove commas, equal signs
    // Scan for stuff we want
    //mprintf("DEBUG:\tInput[%i] %s", mdin_args.Nargs(), mdin_args.ArgLine());
    for (int col=0; col < mdin_args.Nargs(); col += 2) {
      int col1 = col + 1;
      if (mdin_args[col] == "imin") {
        imin = convertToInteger( mdin_args[ col1 ] );
        if (debug_ > 0) mprintf("\t\tMDIN: imin is %i\n", imin);
        // Set a trigger for printing. For imin5 this is the word minimization.
        // For imin0 or imin1 this is NSTEP.
        if      (imin==0) Trigger = " NSTEP =";
        else if (imin==1) Trigger = "   NSTEP";
        else if (imin==5) Trigger = "minimiza";
        // Since imin0 and imin1 first trigger has no data, set frame 1 lower.
        if (imin==1 || imin==0) frame = -1;
      } else if (mdin_args[col] == "dt") {
        dt = convertToDouble( mdin_args[ col1 ] );
        if (debug_ > 0) mprintf("\t\tMDIN: dt is %f\n", dt);
      } else if (mdin_args[col] == "t") {
        t0 = convertToDouble( mdin_args[ col1 ] );
        if (debug_ > 0) mprintf("\t\tMDIN: t is %f\n", t0);
      } else if (mdin_args[col] == "ntpr") {
        ntpr = convertToInteger( mdin_args[ col1 ] );
        if (debug_ > 0) mprintf("\t\tMDIN: ntpr is %i\n", ntpr);
      } else if (mdin_args[col] == "irest") {
        irest = convertToInteger( mdin_args[ col1 ] );
        if (debug_ > 0) mprintf("\t\tMDIN: irest is %i\n", irest);
      }
    }
    ptr = buffer.Line();
    if (ptr == 0) return EOF_ERROR();
  }
  if (Trigger == 0) {
    mprinterr("Error: Could not determine whether MDOUT is md, min, or post-process.\n");
    return 1;
  }
  // ----- PARSE THE ATOMIC ... SECTION -----
  while ( ptr != 0 && strncmp(ptr, "   4.  RESULTS", 14) != 0 )
  {
    ptr = buffer.Line();
    // If run is a restart, set the initial time value.
    if (irest == 1) {
      if (strncmp(ptr, " begin time", 11) == 0) {
        sscanf(ptr, " begin time read from input coords = %lf", &t0);
        if (debug_ > 0) mprintf("\t\tMD restart initial time= %f\n", t0);
      }
    }
  }
  if (ptr == 0) return EOF_ERROR();
  // ----- PARSE THE RESULTS SECTION -----
  bool finalE = false;
  int nstep;
  int minStep = 0; // For imin=1 only
  if (irest == 0)
    nstep = 0;
  else
    nstep = ntpr;
  double Energy[N_FIELDTYPES];
  std::fill( Energy, Energy+N_FIELDTYPES, 0.0 );
  std::vector<bool> EnergyExists(N_FIELDTYPES, false);
  DataSetList::Darray TimeVals;
  DataSetList::DataListType inputSets(N_FIELDTYPES, 0);
  Sarray Name(2);
  double time = 0.0;
  while (ptr != 0) {
    // Check for end of imin 0 or 1 run; do not record Average and Stdevs
    if ( (imin == 1 && (strncmp(ptr, "                    FINAL", 25) == 0 ||
                        strncmp(ptr, "   5.  TIMINGS",            14) == 0   )) ||
         (imin == 0 && strncmp(ptr, "      A V", 9) == 0))
      finalE = true;
    // Check for '| TI region  2' to prevent reading duplicate energies
    if ( strncmp(ptr, "| TI region  2", 14) == 0 ) {
      while (ptr != 0 && !(ptr[0] == ' ' && ptr[1] == '-'))
        ptr = buffer.Line();
      if (ptr == 0) return EOF_ERROR();
    }
    // Record set for energy post-processing
    if (imin == 5 && strncmp(ptr, "minimizing", 10) == 0)
      nstep = atoi( ptr + 22 );
    // MAIN OUTPUT ROUTINE
    // If the trigger has been reached print output.
    // For imin0 and imin1 the first trigger will have no data.
    // If the end of the file has been reached print then exit.
    if ( strncmp(ptr, Trigger, 8) == 0 || finalE ) {
      if (frame > -1) {
        // Store all energies present.
        for (int i = 0; i < (int)N_FIELDTYPES; i++) {
          if (EnergyExists[i]) {
            if (inputSets[i] == 0) {
              MetaData md( dsname, Enames[i] );
              md.SetLegend( dsname + "_" + Enames[i] );
              inputSets[i] = new DataSet_double();
              inputSets[i]->SetMeta( md );
            }
            // Since energy terms can appear and vanish over the course of the
            // mdout file, resize if necessary.
            if (frame > (int)inputSets[i]->Size())
              ((DataSet_double*)inputSets[i])->Resize( frame );
            ((DataSet_double*)inputSets[i])->AddElement( Energy[i] );
          }
        }
        TimeVals.push_back( time );
        nstep += ntpr;
      }
      frame++;
      if (finalE) break;
    }
    // Check for NSTEP in minimization or post-processing. Values will be
    // on the next line. NOTE: NSTEP means something different for imin=5.
    if ((imin == 1 || imin == 5) && strncmp(ptr, "   NSTEP", 8) == 0) {
      ptr = buffer.Line(); // Get next line
      //sscanf(ptr, " %6lf    %13lE  %13lE  %13lE", Energy+NSTEP, Energy+EPtot, Energy+RMS, Energy+GMAX);
      sscanf(ptr, " %i %lE %lE %lE", &minStep, Energy+EPtot, Energy+RMS, Energy+GMAX);
      EnergyExists[EPtot] = true;
      EnergyExists[RMS] = true;
      EnergyExists[GMAX] = true;
      ptr = buffer.Line();
    }
    // Tokenize line, scan through until '=' is reached; value after is target.
    int ntokens = buffer.TokenizeLine(" ");
    if (ntokens > 0) {
      int nidx = 0;
      Name[0].clear();
      Name[1].clear();
      for (int tidx = 0; tidx < ntokens; tidx++) {
        const char* tkn = buffer.NextToken();
        if (tkn[0] == '=') {
          FieldType Eindex = getEindex(Name);
          tkn = buffer.NextToken();
          ++tidx;
          if (tkn == 0)
            mprintf("Warning: No numerical value, line %i column %i. Skipping.\n",
                    buffer.LineNumber(), tidx+1);
          else if (tkn[0] == '*' || tkn[0] == 'N') // Assume if number begins with N it is NaN
            mprintf("Warning: Numerical overflow detected, line %i column %i. Skipping.\n",
                     buffer.LineNumber(), tidx+1);
          else {
            if (Eindex != N_FIELDTYPES) {
              Energy[Eindex] = atof( tkn );
              EnergyExists[Eindex] = true;
            }
          }
          nidx = 0;
          Name[0].clear();
          Name[1].clear();
        } else {
          if (nidx > 1) break; // Two tokens, no '=' found. Not an E line.
          Name[nidx++].assign( tkn );
        }
      }
    }
    // Set time
    switch (imin) {
      case 5: time = (double)nstep + t0; break;
      case 1: time = (double)minStep + t0; break;
      case 0: time = ((double)nstep * dt) + t0; break;
    }
    // Read in next line
    ptr = buffer.Line();
  }
  mprintf("\t%i frames\n", frame);
  buffer.CloseFile();
  std::string Xlabel;
  if      (imin == 5) Xlabel.assign("Set");
  else if (imin == 1) Xlabel.assign("Nstep");
  else                Xlabel.assign("Time"); // imin == 0
  if (datasetlist.AddOrAppendSets( Xlabel, TimeVals, inputSets )) return 1;
  return 0;
}
예제 #8
0
double moProperty::asDouble() {
	return convertToDouble(this->type, this->val);
}
예제 #9
0
void summariseEigensoft() {
    std::ifstream* eigenFile = new std::ifstream(opt::eigensoftFile.c_str());
    string fileRoot = stripExtension(opt::eigensoftFile);
    string FstResultsFileName = fileRoot + "_" + opt::runName + "_fst_matrix.forR";
    std::ofstream* pFst = new std::ofstream(FstResultsFileName.c_str());
    std::vector<std::vector<std::string> > fst_matrix;
    
    string line;
    getline(*eigenFile, line); // Get the first description line
    short type;
    if (line == "##") {
        type = 1;
    } else {
        type = 2;
    }
    std::cerr << "It is type: " << type << std::endl;
    if (type == 1) {
        getline(*eigenFile, line);
        std::vector<std::string> fields = split(line, '\t');
        std::vector<std::string> this_indiv_fst;
        std::vector<std::string> all_indiv;
        string this_indiv = fields[0];
        this_indiv_fst.push_back(fields[2]);
        while (getline(*eigenFile, line)) {
            fields = split(line, '\t');
            std::cerr << "Indiv: " << fields[0] << std::endl;
            if (this_indiv == fields[0]) {
                this_indiv_fst.push_back(fields[2]);
            } else {
                fst_matrix.push_back(this_indiv_fst);
                all_indiv.push_back(this_indiv);
                this_indiv = fields[0];
                this_indiv_fst.clear();
                this_indiv_fst.push_back(fields[2]);
            }
        }
        all_indiv.push_back(this_indiv);
        fst_matrix.push_back(this_indiv_fst);
        this_indiv_fst.clear(); this_indiv_fst.push_back("0"); all_indiv.push_back(fields[1]);
        fst_matrix.push_back(this_indiv_fst);
        
        for (std::vector<std::vector<std::string> >::size_type i = 0; i != fst_matrix.size(); i++) {
            std::reverse(fst_matrix[i].begin(), fst_matrix[i].end());
            fst_matrix[i].insert(fst_matrix[i].end(), "0");
            while (fst_matrix[i].size() != fst_matrix[0].size()) {
                fst_matrix[i].insert(fst_matrix[i].end(), "0");
            }
        }
        std::reverse(fst_matrix.begin(), fst_matrix.end());
        std::reverse(all_indiv.begin(), all_indiv.end());
        
        print_vector(all_indiv, *pFst);
        print_matrix(fst_matrix, *pFst);
    } else if (type == 2) {
        std::cerr << "type2" << std::endl;
        std::vector<std::string> fields = split(line, '\t');
        std::vector<std::string> all_indiv(fields.begin()+1,fields.end());
        getline(*eigenFile, line); getline(*eigenFile, line);
        std::vector<std::string> this_indiv_fst;
        while (getline(*eigenFile, line)) {
            fields = split(line, '\t');
            std::copy(fields.begin()+1,fields.end(),std::back_inserter(this_indiv_fst));
            for (std::vector<std::string>::size_type i = 0; i != this_indiv_fst.size(); i++) {
                double fst = convertToDouble(this_indiv_fst[i]) / 1000;
                this_indiv_fst[i] = numToString(fst);
            }
            fst_matrix.push_back(this_indiv_fst);
            this_indiv_fst.clear();
        }
        print_vector(all_indiv, *pFst);
        print_matrix(fst_matrix, *pFst);
    }
}
예제 #10
0
// Exec_DataSetCmd::Remove()
Exec::RetType Exec_DataSetCmd::Remove(CpptrajState& State, ArgList& argIn) {
  std::string status;
  // Get criterion type
  CriterionType criterion = UNKNOWN_C;
  for (int i = 1; i < (int)N_C; i++)
    if (argIn.hasKey( CriterionKeys[i] )) {
      criterion = (CriterionType)i;
      status.assign( CriterionKeys[i] );
      break;
    }
  if (criterion == UNKNOWN_C) {
    mprinterr("Error: No criterion specified for 'remove'.\n");
    return CpptrajState::ERR;
  }
  // Get select type
  SelectType select = UNKNOWN_S;
  std::string val1, val2;
  for (const SelectPairType* ptr = SelectKeys; ptr->key_ != 0; ptr++)
    if (argIn.Contains( ptr->key_ )) {
      select = ptr->type_;
      val1 = argIn.GetStringKey( ptr->key_ );
      status.append( " " + std::string(ptr->key_) + " " + val1 );
      // Get 'and' value for between/outside. TODO put nargs in SelectPairType?
      if (select == BETWEEN || select == OUTSIDE) {
        val2 = argIn.GetStringKey("and");
        if (val2.empty()) {
          mprinterr("Error: Missing 'and' value for selection '%s'\n", ptr->key_);
          return CpptrajState::ERR;
        }
        status.append(" and " + val2);
      }
      break;
    }
  if (select == UNKNOWN_S || val1.empty()) {
    mprinterr("Error: No selection specified for 'remove'.\n");
    return CpptrajState::ERR;
  }
  if ( (criterion == SMODE || criterion == STYPE) &&
       (select != EQUAL && select != NOT_EQUAL) )
  {
    mprinterr("Error: Specified select not valid for criterion '%s'\n", CriterionKeys[criterion]);
    return CpptrajState::ERR;
  }
  mprintf("\tRemoving data sets");
  std::string setSelectArg = argIn.GetStringNext();
  if (setSelectArg.empty())
    setSelectArg.assign("*");
  else
    mprintf(" within selection '%s'", setSelectArg.c_str());
  mprintf(" %s\n", status.c_str());
  DataSetList tempDSL = State.DSL().GetMultipleSets( setSelectArg );
  if (tempDSL.empty()) {
    mprinterr("Error: No data sets selected.\n");
    return CpptrajState::ERR;
  }
  // Remove sets
  unsigned int Nremoved = 0;
  if ( criterion == AVERAGE ) {
    if (!validDouble( val1 )) {
      mprinterr("Error: '%s' is not a valid number\n", val1.c_str());
      return CpptrajState::ERR;
    }
    double d_val1 = convertToDouble( val1 );
    double d_val2  = d_val1;
    if (!val2.empty()) {
      if (!validDouble( val2 )) {
        mprinterr("Error: '%s' is not a valid number\n", val2.c_str());
        return CpptrajState::ERR;
      }
      d_val2 = convertToDouble( val2 );
    }
    for (DataSetList::const_iterator ds = tempDSL.begin(); ds != tempDSL.end(); ++ds)
    {
      if ( (*ds)->Group() != DataSet::SCALAR_1D )
        mprintf("Warning: '%s' is not a valid data set for 'average' criterion.\n", (*ds)->legend());
      else {
        DataSet_1D const& ds1 = static_cast<DataSet_1D const&>( *(*ds) );
        double avg = ds1.Avg();
        bool remove = false;
        switch (select) {
          case EQUAL        : remove = (avg == d_val1); break;
          case NOT_EQUAL    : remove = (avg != d_val1); break;
          case LESS_THAN    : remove = (avg < d_val1); break;
          case GREATER_THAN : remove = (avg > d_val1); break;
          case BETWEEN      : remove = (avg > d_val1 && avg < d_val2); break;
          case OUTSIDE      : remove = (avg < d_val1 || avg > d_val2); break;
          case UNKNOWN_S:
          case N_S      : return CpptrajState::ERR; // Sanity check
        }
        if (remove) {
          mprintf("\t  Removing set '%s' (avg is %g)\n", (*ds)->legend(), avg);
          State.RemoveDataSet( *ds );
          ++Nremoved;
        }
      }
    }
  } else if ( criterion == SIZE ) {
    if (!validInteger( val1 )) {
      mprinterr("Error: '%s' is not a valid number\n", val1.c_str());
      return CpptrajState::ERR;
    }
    unsigned int i_val1 = (unsigned int)convertToInteger( val1 );
    unsigned int i_val2 = i_val1;
    if (!val2.empty()) {
      if (!validInteger( val2 )) {
        mprinterr("Error: '%s' is not a valid number\n", val2.c_str());
        return CpptrajState::ERR;
      }
      i_val2 = convertToInteger( val2 );
    }
    for (DataSetList::const_iterator ds = tempDSL.begin(); ds != tempDSL.end(); ++ds)
    {
      unsigned int size = (*ds)->Size();
      bool remove = false;
      switch ( select ) {
        case EQUAL        : remove = (size == i_val1); break;
        case NOT_EQUAL    : remove = (size != i_val1); break;
        case LESS_THAN    : remove = (size < i_val1); break;
        case GREATER_THAN : remove = (size > i_val1); break;
        case BETWEEN      : remove = (size > i_val1 && size < i_val2); break;
        case OUTSIDE      : remove = (size < i_val1 || size > i_val2); break;
        case UNKNOWN_S:
        case N_S      : return CpptrajState::ERR; // Sanity check
      }
      if (remove) {
        mprintf("\t  Removing set '%s' (size is %u)\n", (*ds)->legend(), size);
        State.RemoveDataSet( *ds );
        ++Nremoved;
      }
    }
  } else if ( criterion == SMODE ) {
    MetaData::scalarMode mode_val = MetaData::ModeFromKeyword( val1 );
    if (mode_val == MetaData::UNKNOWN_MODE) {
      mprinterr("Error: '%s' is not a valid mode.\n", val1.c_str());
      return CpptrajState::ERR;
    }
    for (DataSetList::const_iterator ds = tempDSL.begin(); ds != tempDSL.end(); ++ds)
    {
      bool remove = false;
      MetaData::scalarMode mode = (*ds)->Meta().ScalarMode();
      if      (select == EQUAL    ) remove = ( mode == mode_val );
      else if (select == NOT_EQUAL) remove = ( mode != mode_val );
      else return CpptrajState::ERR; // Sanity check
      if (remove) {
        mprintf("\t  Removing set '%s' (mode is '%s')\n", (*ds)->legend(), MetaData::ModeString(mode));
        State.RemoveDataSet( *ds );
        ++Nremoved;
      }
    }
  } else if ( criterion == STYPE ) {
    MetaData::scalarType type_val = MetaData::TypeFromKeyword( val1, MetaData::UNKNOWN_MODE );
    if (type_val == MetaData::UNDEFINED) {
      mprinterr("Error: '%s' is not a valid type.\n", val1.c_str());
      return CpptrajState::ERR;
    }
    for (DataSetList::const_iterator ds = tempDSL.begin(); ds != tempDSL.end(); ++ds)
    {
      bool remove = false;
      MetaData::scalarType type = (*ds)->Meta().ScalarType();
      if      (select == EQUAL    ) remove = ( type == type_val );
      else if (select == NOT_EQUAL) remove = ( type != type_val );
      else return CpptrajState::ERR; // Sanity check
      if (remove) {
        mprintf("\t  Removing set '%s' (typeis '%s')\n", (*ds)->legend(), MetaData::TypeString(type));
        State.RemoveDataSet( *ds );
        ++Nremoved;
      }
    }
  } else {
    mprinterr("Internal Error: Criterion not yet implemented.\n");
    return CpptrajState::ERR;
  }
  mprintf("\tRemoved %u of %zu sets.\n", Nremoved, tempDSL.size());
  return CpptrajState::OK;
}
예제 #11
0
void PDI::mosaicEcualization(cv::Mat &img, int pixels, bool interpolate){
    cv::Mat temp;
    imageRGB(img);
    // Slices (pixels * pixels)
    int hor = int(img.cols/pixels);
    int ver = int(img.rows/pixels);
    int rHor = int(img.cols%pixels);
    int rVer = int(img.rows%pixels);
    int x, y;

    for(int i=0; i<ver; i++){ // Moving in rows
        y = i*pixels;
        for(int j=0; j<hor; j++){
            x = j*pixels;
            temp = cv::Mat(img, cvRect(x, y, pixels, pixels));
            // Ecualizing subimage
            ecualizeImage(temp);
            if(rHor>0 && j==hor-1){
                temp = cv::Mat(img, cvRect(x+pixels, y, rHor, pixels));
                // Ecualizing subimage
                ecualizeImage(temp);
            }
        }
        if(rVer>0 && i==ver-1){
            for(int j=0; j<hor; j++){
                x = j*pixels;
                temp = cv::Mat(img, cvRect(x, y+pixels, pixels, rVer));
                // Ecualizing subimage
                ecualizeImage(temp);
                if(rHor>0 && j==hor-1){
                    temp = cv::Mat(img, cvRect(x+pixels, y+pixels, rHor, rVer));
                    // Ecualizing subimage
                    ecualizeImage(temp);
                }
            }
        }
    }

    if(interpolate){
        if(img.cols < 2*pixels || img.rows < 2*pixels ){
            std::cout << "ERROR: It's not possible to equalize, try again changing the dimensions of the sub-images." << std::endl;
            std::cout << "Image Dimensions: " << img.rows << ", " << img.cols << std::endl;
            std::cout << "Sub-image Dimensions: " << pixels << ", " << pixels << std::endl;
        }
        else{
            // Get the image range (to re-convert)
            int min, max;
            getImageRange(img, min, max);

            int subimg = 0;
            int f00, f01, f10, f11;

            cv::Mat im = convertToDouble(img);


            // img: imagen de entrada (en cuadritos)
            // pixels: dimensiones del cuadrito
            // hor: num de cuadros horizontales
            // ver: num de cuadros verticales
            // rHor: pixeles horizontales sobrantes
            // rVer: pixeles verticales sobrantes
            // y: fila inicial para la sub imagen
            // x: columna inicial para la sub imagen

            std::cout << "Image dims: " << img.rows << " x " << img.cols << std::endl;

            for(int v=0; v<ver; v++){ // Moving in rows (Vertical)
                y = v*pixels + pixels/2;
                for(int h=0; h<hor; h++){ // Moving in colums (Horizontal)
                    x = h*pixels + pixels/2;
                    std::cout << "(" << v << ", " << h << "): " << y << ", " << x << std::endl;
                    if( y+pixels < img.rows && x+pixels < img.cols ){
                        temp = cv::Mat(img, cvRect(x, y, pixels, pixels));
                        for(int i=0; i<temp.rows; i++){
                            for(int j=0; j<temp.cols; j++){
                                int s = j + 1;
                                int t = i + 1;
                                f00 = vHistograms[subimg].HistA[temp.at<uchar>(i, j)];
                                f01 = vHistograms[subimg+1].HistA[temp.at<uchar>(i, j)];
                                f10 = vHistograms[subimg+ver].HistA[temp.at<uchar>(i, j)];
                                f11 = vHistograms[subimg+ver+1].HistA[temp.at<uchar>(i, j)];
                                temp.at<uchar>(i,j) = (1-s) * (1-t) * f00 + s * (1-t) * f10
                                        + (1-s) * t+1 * f01 + s * t * f11;
                            }
                        }
                    }
                    subimg++;
                }
            }
/*




            for(int v=0; v<ver; v++){ // Moving in rows
                y = v*pixels;
                for(int h=0; h<hor; h++){
                    x = h*pixels;
                    // Ecualizing subimage
                    std::cout << subimg << std::endl;
                    Hists = vHistograms[subimg];
                    for(int s=0; s<pixels; s++){
                        for(int t=0; t<pixels; t++){
                            int ss = s + v * pixels;
                            int tt = t + h * pixels;
                            f00 = vHistograms[subimg].HistA[img.at<uchar>(s, t)];
                            f01 = vHistograms[subimg+1].HistA[img.at<uchar>(s, t)];
                            f10 = vHistograms[subimg+ver].HistA[img.at<uchar>(s, t)];
                            f11 = vHistograms[subimg+ver+1].HistA[img.at<uchar>(s, t)];                            // std::cout << "s: " << s << " ss: " << ss << " t: " << t << " tt: " << tt << " => ";
                            // std::cout << "f00(" << 0+v*pixels << ", " << 0+h*pixels << ") - "
                            //          << "f10(" << 0+v*pixels << ", " << pixels-1+h*pixels << ") - "
                            //          << "f01(" << pixels-1+v*pixels << ", " << 0+h*pixels << ") - "
                            //          << "f11(" << pixels-1+v*pixels << ", " << pixels-1+h*pixels << ")" << std::endl;

                            im.at<double>(ss,tt) = (1-s) * (1-t) * f00 + s * (1-t) * f10
                                                 + (1-s) * t+1 * f01 + s * t * f11;
                        }
                    }
                    subimg++;

                    if(rHor>0 && h==hor-1){
                        std::cout << subimg << std::endl;
                        Hists = vHistograms[subimg];
                        // Ecualizing subimage
                        subimg++;


                    }
                }

                if(rVer>0 && v==ver-1){
                    for(int h=0; h<hor; h++){
                        x = h*pixels;
                        std::cout << subimg << std::endl;
                        Hists = vHistograms[subimg];
                        // Ecualizing subimage
                        subimg++;

                        if(rHor>0 && h==hor-1){
                            std::cout << subimg << std::endl;
                            Hists = vHistograms[subimg];
                            // Ecualizing subimage
                            subimg++;

                        }

                    }
                }

            }
*/
            // Image double converted into integer
            // normalizateMatrix(im, min, max);
            // cv::Mat im2 = convertToInterger(im);
            // im2.copyTo(img);
        }
    }
}
예제 #12
0
파일: tdata.c 프로젝트: amic3r/Terra
double TDataToDouble(const TData *context)
{
	if (context) return convertToDouble(context->data, context->type);
	return 0;
}
// Action_MakeStructure::Init()
Action::RetType Action_MakeStructure::Init(ArgList& actionArgs, TopologyList* PFL, DataSetList* DSL, DataFileList* DFL, int debugIn)
{
  debug_ = debugIn;
  secstruct_.clear();
  // Get all arguments 
  std::string ss_expr = actionArgs.GetStringNext();
  while ( !ss_expr.empty() ) {
    ArgList ss_arg(ss_expr, ":");
    if (ss_arg.Nargs() < 2) {
      mprinterr("Error: Malformed SS arg.\n");
      Help();
      return Action::ERR;
    }
    // Type is 1st arg, range is 2nd arg.
    SecStructHolder ss_holder(ss_arg[1], FindSStype(ss_arg[0]));

    if (ss_arg.Nargs() == 2) {
    // Find SS type: <ss type>:<range>
      if (ss_holder.sstype_idx == SS_EMPTY) {
        mprinterr("Error: SS type %s not found.\n", ss_arg[0].c_str());
        return Action::ERR;
      } 
      ss_holder.dihSearch_.SearchFor(MetaData::PHI);
      ss_holder.dihSearch_.SearchFor(MetaData::PSI);
      secstruct_.push_back( ss_holder );

    } else if (ss_arg[0] == "ref") {
    // Use dihedrals from reference structure
      if (ss_arg.Nargs() < 3) {
        mprinterr("Error: Invalid 'ref' arg. Requires 'ref:<range>:<refname>[:<ref range>]'\n");
        return Action::ERR;
      }
      ss_arg.MarkArg(0);
      ss_arg.MarkArg(1);
      // Sanity check: Currently only unique args of this type are allowed
      if (ss_holder.sstype_idx != SS_EMPTY) {
        mprinterr("Error: Ref backbone types must be unique [%s]\n", ss_arg[0].c_str());
        return Action::ERR;
      }
      // Use backbone phi/psi from reference structure
      ss_holder.dihSearch_.SearchFor(MetaData::PHI);
      ss_holder.dihSearch_.SearchFor(MetaData::PSI);
      // Get reference structure
      DataSet_Coords_REF* REF = (DataSet_Coords_REF*)
                                DSL->FindSetOfType(ss_arg.GetStringNext(),
                                                   DataSet::REF_FRAME); // ss_arg[2]
      if (REF == 0) {
        mprinterr("Error: Could not get reference structure [%s]\n", ss_arg[2].c_str());
        return Action::ERR;
      }
      // Get reference residue range, or use resRange
      Range refRange(ss_arg.GetStringNext(), -1); // ss_arg[3]
      if (!refRange.Empty()) {
        if (ss_holder.resRange.Size() != refRange.Size()) {
          mprinterr("Error: Reference range [%s] must match residue range [%s]\n",
                    refRange.RangeArg(), ss_holder.resRange.RangeArg());
          return Action::ERR;
        }
      } else
        refRange = ss_holder.resRange;
      // Look for phi/psi only in reference
      DihedralSearch refSearch;
      refSearch.SearchFor(MetaData::PHI);
      refSearch.SearchFor(MetaData::PSI);
      if (refSearch.FindDihedrals( REF->Top(), refRange )) return Action::ERR;
      // For each found dihedral, set theta 
      for (DihedralSearch::mask_it dih = refSearch.begin(); dih != refSearch.end(); ++dih)
      {
        double torsion = Torsion( REF->RefFrame().XYZ(dih->A0()),
                                  REF->RefFrame().XYZ(dih->A1()),
                                  REF->RefFrame().XYZ(dih->A2()),
                                  REF->RefFrame().XYZ(dih->A3()) );
        ss_holder.thetas_.push_back( (float)torsion );
      }
      secstruct_.push_back( ss_holder );

    } else if (ss_arg.Nargs() == 4 && isalpha(ss_arg[2][0])) {
    // Single dihedral type: <name>:<range>:<dih type>:<angle>
      DihedralSearch::DihedralType dtype = DihedralSearch::GetType(ss_arg[2]);
      if (ss_holder.sstype_idx == SS_EMPTY) {
        // Type not yet defined. Create new type. 
        if (dtype == MetaData::UNDEFINED) {
          mprinterr("Error: Dihedral type %s not found.\n", ss_arg[2].c_str());
          return Action::ERR;
        }
        if (!validDouble(ss_arg[3])) {
          mprinterr("Error: 4th arg (angle) is not a valid number.\n");
          return Action::ERR;
        }
        SS.push_back( SS_TYPE(convertToDouble(ss_arg[3]), 0.0, 0.0, 0.0, 2, ss_arg[0]) );
        ss_holder.sstype_idx = (int)(SS.size() - 1);
      }
      ss_holder.dihSearch_.SearchFor( dtype ); 
      secstruct_.push_back( ss_holder );

    } else if (ss_arg.Nargs() == 7 || ss_arg.Nargs() == 8) {
    // Single custom dihedral type: <name>:<range>:<at0>:<at1>:<at2>:<at3>:<angle>[:<offset>]
      if (ss_holder.sstype_idx == SS_EMPTY) {
        // Type not yet defined. Create new type.
        if (!validDouble(ss_arg[6])) {
          mprinterr("Error: 7th arg (angle) is not a valid number.\n");
          return Action::ERR;
        }
        SS.push_back( SS_TYPE(convertToDouble(ss_arg[6]), 0.0, 0.0, 0.0, 2, ss_arg[0]) );
        ss_holder.sstype_idx = (int)(SS.size() - 1);
      }
      int offset = 0;
      if (ss_arg.Nargs() == 8) {
        if (!validInteger(ss_arg[7])) {
          mprinterr("Error: 8th arg (offset) is not a valid number.\n");
          return Action::ERR;
        }
        offset = convertToInteger(ss_arg[7]);
      }
      ss_holder.dihSearch_.SearchForNewType(offset,ss_arg[2],ss_arg[3],ss_arg[4],ss_arg[5],
                                            ss_arg[0]);
      secstruct_.push_back( ss_holder );

    } else if (ss_arg.Nargs() == 4 || ss_arg.Nargs() == 6) {
    // Custom SS/turn type: <name>:<range>:<phi1>:<psi1>[:<phi2>:<psi2>]
      if (ss_holder.sstype_idx == SS_EMPTY) {
        // Type not yet defined. Create new type.
        if (!validDouble(ss_arg[2]) || !validDouble(ss_arg[3])) {
          mprinterr("Error: 3rd or 4th arg (phi1/psi1) is not a valid number.\n");
          return Action::ERR;
        }
        double phi1 = convertToDouble(ss_arg[2]);
        double psi1 = convertToDouble(ss_arg[3]);
        int isTurn = 0;
        double phi2 = 0.0;
        double psi2 = 0.0;
        if (ss_arg.Nargs() == 6) {
          isTurn = 1;
          if (!validDouble(ss_arg[4]) || !validDouble(ss_arg[5])) {
            mprinterr("Error: 5th or 6th arg (phi2/psi2) is not a valid number.\n");
            return Action::ERR;
          }
          phi2 = convertToDouble(ss_arg[4]);
          psi2 = convertToDouble(ss_arg[5]);
        }
        SS.push_back(SS_TYPE(phi1, psi1, phi2, psi2, isTurn, ss_arg[0] ));
        ss_holder.sstype_idx = (int)(SS.size() - 1);
      }
      ss_holder.dihSearch_.SearchFor(MetaData::PHI);
      ss_holder.dihSearch_.SearchFor(MetaData::PSI);
      secstruct_.push_back( ss_holder );

    } else {
      mprinterr("Error: SS arg type [%s] not recognized.\n", ss_arg[0].c_str());
      return Action::ERR;
    }
    ss_expr = actionArgs.GetStringNext();
  } // End loop over args
  if (secstruct_.empty()) {
    mprinterr("Error: No SS types defined.\n");
    return Action::ERR;
  }
  mprintf("    MAKESTRUCTURE:\n");
  for (std::vector<SecStructHolder>::iterator ss = secstruct_.begin();
                                              ss != secstruct_.end(); ++ss)
  {
    if (ss->sstype_idx != SS_EMPTY) {
      const SS_TYPE& myType = SS[ss->sstype_idx];
      switch ( myType.isTurn ) {
        case 0:
          mprintf("\tSS type %s will be applied to residue(s) %s\n",
                 myType.type_arg.c_str(), ss->resRange.RangeArg());
          break;
        case 1:
          mprintf("\tTurn type %s will be applied to residue(s) %s\n",
                  myType.type_arg.c_str(), ss->resRange.RangeArg());
          break;
        case 2:
          mprintf("\tDihedral value of %.2f will be applied to %s dihedrals in residue(s) %s\n",
                  myType.phi, myType.type_arg.c_str(), ss->resRange.RangeArg());
      }
    } else 
      mprintf("\tBackbone angles from reference will be applied to residue(s) %s\n",
              ss->resRange.RangeArg());
  }
  return Action::OK;
}