Exemple #1
0
	void print()   {
		seq.print();
	}
bool
nsScreen::MozLockOrientation(const Sequence<nsString>& aOrientations,
                             ErrorResult& aRv)
{
  ScreenOrientation orientation = eScreenOrientation_None;

  for (uint32_t i = 0; i < aOrientations.Length(); ++i) {
    const nsString& item = aOrientations[i];

    if (item.EqualsLiteral("portrait")) {
      orientation |= eScreenOrientation_PortraitPrimary |
                     eScreenOrientation_PortraitSecondary;
    } else if (item.EqualsLiteral("portrait-primary")) {
      orientation |= eScreenOrientation_PortraitPrimary;
    } else if (item.EqualsLiteral("portrait-secondary")) {
      orientation |= eScreenOrientation_PortraitSecondary;
    } else if (item.EqualsLiteral("landscape")) {
      orientation |= eScreenOrientation_LandscapePrimary |
                     eScreenOrientation_LandscapeSecondary;
    } else if (item.EqualsLiteral("landscape-primary")) {
      orientation |= eScreenOrientation_LandscapePrimary;
    } else if (item.EqualsLiteral("landscape-secondary")) {
      orientation |= eScreenOrientation_LandscapeSecondary;
    } else {
      // If we don't recognize the token, we should just return 'false'
      // without throwing.
      return false;
    }
  }

  switch (GetLockOrientationPermission()) {
    case LOCK_DENIED:
      return false;
    case LOCK_ALLOWED:
      return hal::LockScreenOrientation(orientation);
    case FULLSCREEN_LOCK_ALLOWED: {
      // We need to register a listener so we learn when we leave full-screen
      // and when we will have to unlock the screen.
      // This needs to be done before LockScreenOrientation call to make sure
      // the locking can be unlocked.
      nsCOMPtr<EventTarget> target = do_QueryInterface(GetOwner()->GetDoc());
      if (!target) {
        return false;
      }

      if (!hal::LockScreenOrientation(orientation)) {
        return false;
      }

      // We are fullscreen and lock has been accepted.
      if (!mEventListener) {
        mEventListener = new FullScreenEventListener();
      }

      aRv = target->AddSystemEventListener(NS_LITERAL_STRING("mozfullscreenchange"),
                                           mEventListener, /* useCapture = */ true);
      return true;
    }
  }

  // This is only for compilers that don't understand that the previous switch
  // will always return.
  MOZ_CRASH("unexpected lock orientation permission value");
}
Exemple #3
0
TEST(Sequence, DefaultConstructor)
{
	Sequence<int> seq;
	ASSERT_TRUE(seq.size() == 0);
}
Exemple #4
0
already_AddRefed<WebSocket>
WebSocket::Constructor(const GlobalObject& aGlobal,
                       const nsAString& aUrl,
                       const Sequence<nsString>& aProtocols,
                       ErrorResult& aRv)
{
  if (!PrefEnabled()) {
    aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
    return nullptr;
  }

  nsCOMPtr<nsIScriptObjectPrincipal> scriptPrincipal =
    do_QueryInterface(aGlobal.GetAsSupports());
  if (!scriptPrincipal) {
    aRv.Throw(NS_ERROR_FAILURE);
    return nullptr;
  }

  nsCOMPtr<nsIPrincipal> principal = scriptPrincipal->GetPrincipal();
  if (!principal) {
    aRv.Throw(NS_ERROR_FAILURE);
    return nullptr;
  }

  nsCOMPtr<nsIScriptGlobalObject> sgo = do_QueryInterface(aGlobal.GetAsSupports());
  if (!sgo) {
    aRv.Throw(NS_ERROR_FAILURE);
    return nullptr;
  }

  nsCOMPtr<nsPIDOMWindow> ownerWindow = do_QueryInterface(aGlobal.GetAsSupports());
  if (!ownerWindow) {
    aRv.Throw(NS_ERROR_FAILURE);
    return nullptr;
  }

  nsTArray<nsString> protocolArray;

  for (uint32_t index = 0, len = aProtocols.Length(); index < len; ++index) {

    const nsString& protocolElement = aProtocols[index];

    if (protocolElement.IsEmpty()) {
      aRv.Throw(NS_ERROR_DOM_SYNTAX_ERR);
      return nullptr;
    }
    if (protocolArray.Contains(protocolElement)) {
      aRv.Throw(NS_ERROR_DOM_SYNTAX_ERR);
      return nullptr;
    }
    if (protocolElement.FindChar(',') != -1)  /* interferes w/list */ {
      aRv.Throw(NS_ERROR_DOM_SYNTAX_ERR);
      return nullptr;
    }

    protocolArray.AppendElement(protocolElement);
  }

  nsRefPtr<WebSocket> webSocket = new WebSocket(ownerWindow);
  nsresult rv = webSocket->Init(aGlobal.GetContext(), principal,
                                aUrl, protocolArray);
  if (NS_FAILED(rv)) {
    aRv.Throw(rv);
    return nullptr;
  }

  return webSocket.forget();
}
static void test_list_ops_non_unique_seq()
{
  typedef typename Sequence::iterator iterator;

  Sequence ss;
  for(int i=0;i<10;++i){
    ss.push_back(i);
    ss.push_back(i);
    ss.push_front(i);
    ss.push_front(i);
  } /* 9988776655443322110000112233445566778899 */

  ss.unique();
  CHECK_EQUAL(
    ss,
    (9)(8)(7)(6)(5)(4)(3)(2)(1)(0)
    (1)(2)(3)(4)(5)(6)(7)(8)(9));

  iterator it=ss.begin();
  for(int j=0;j<9;++j,++it){} /* it points to o */

  Sequence ss2;
  ss2.splice(ss2.end(),ss,ss.begin(),it);
  ss2.reverse();
  ss.merge(ss2);
  CHECK_EQUAL(
    ss,
    (0)(1)(1)(2)(2)(3)(3)(4)(4)(5)(5)
    (6)(6)(7)(7)(8)(8)(9)(9));

  ss.unique(same_integral_div<3>());
  CHECK_EQUAL(ss,(0)(3)(6)(9));

  ss.unique(same_integral_div<1>());
  CHECK_EQUAL(ss,(0)(3)(6)(9));

  /* testcases for bugs reported at
   * http://lists.boost.org/boost-users/2006/09/22604.php
   */
  {
    Sequence ss_,ss2_;
    ss_.push_back(0);
    ss2_.push_back(0);
    ss_.splice(ss_.end(),ss2_,ss2_.begin());
    CHECK_EQUAL(ss_,(0)(0));
    BOOST_TEST(ss2_.empty());

    ss_.clear();
    ss2_.clear();
    ss_.push_back(0);
    ss2_.push_back(0);
    ss_.splice(ss_.end(),ss2_,ss2_.begin(),ss2_.end());
    CHECK_EQUAL(ss_,(0)(0));
    BOOST_TEST(ss2_.empty());

    ss_.clear();
    ss2_.clear();
    ss_.push_back(0);
    ss2_.push_back(0);
    ss_.merge(ss2_);
    CHECK_EQUAL(ss_,(0)(0));
    BOOST_TEST(ss2_.empty());

    typedef typename Sequence::value_type value_type;
    ss_.clear();
    ss2_.clear();
    ss_.push_back(0);
    ss2_.push_back(0);
    ss_.merge(ss2_,std::less<value_type>());
    CHECK_EQUAL(ss_,(0)(0));
    BOOST_TEST(ss2_.empty());
  }
}
Exemple #6
0
RecipeReader::RecipeReader(std::string filename)
{

  XQilla xqilla;

  try{ 
 
   AutoDelete<XQQuery> qinit(xqilla.parse(X("data(/cooker/init)")));
   AutoDelete<DynamicContext> context (qinit->createDynamicContext());
    Sequence seq = context->resolveDocument(X(filename.c_str()));
    if(!seq.isEmpty() && seq.first()->isNode()) {
      context->setContextItem(seq.first());
      context->setContextPosition(1);
      context->setContextSize(1);
    }
 
    Result rinit=qinit->execute(context);

    InitXML=UTF8(rinit->next(context)->asString(context));

    AutoDelete<XQQuery> qsrctree(xqilla.parse(X("data(/cooker/source)")));
    Result rsrctree=qsrctree->execute(context);
    srctree=UTF8(rsrctree->next(context)->asString(context));

    AutoDelete<XQQuery> qdsttree(xqilla.parse(X("data(/cooker/destination)")));
    Result rdsttree=qdsttree->execute(context);
    dsttree=UTF8(rdsttree->next(context)->asString(context));

    AutoDelete<XQQuery> qplugs(xqilla.parse(X("/cooker/plugins/plugin")));
    Result rplugs=qplugs->execute(context);

    AutoDelete<XQQuery> qplname(xqilla.parse(X("data(./name)")));
    AutoDelete<XQQuery> qplfile(xqilla.parse(X("data(./file)")));
    AutoDelete<DynamicContext> context2 (qplname->createDynamicContext());
    
    while(Node::Ptr item=rplugs->next(context))
      {

	context2->setContextItem(item);
    	context2->setContextPosition(1);
    	context2->setContextSize(1);
	
    	Result rname=qplname->execute(context2);
    	Result rfile=qplfile->execute(context2);
	plugins[UTF8(rname->next(context2)->asString(context2))]=UTF8(rfile->next(context2)->asString(context2));
       }

    AutoDelete<XQQuery> qdefineHistograms(xqilla.parse(X("/cooker/defineHistograms/*")));
    Result rdefineHistograms=qdefineHistograms->execute(context);
    while(Node::Ptr item=rdefineHistograms->next(context))
      {
	defineHistograms.push_back(class_method(UTF8(item->dmNodeName(context)->getName()), UTF8(item->dmStringValue(context))));
      }

    AutoDelete<XQQuery> qstartup(xqilla.parse(X("/cooker/startup/*")));
    Result rstartup=qstartup->execute(context);
    while(Node::Ptr item=rstartup->next(context))
      {
	startup.push_back(class_method(UTF8(item->dmNodeName(context)->getName()), UTF8(item->dmStringValue(context))));
      }

    AutoDelete<XQQuery> qexecute(xqilla.parse(X("/cooker/execute/*")));
    Result rexecute=qexecute->execute(context);
    while(Node::Ptr item=rexecute->next(context))
      {
	commands.push_back(class_method(UTF8(item->dmNodeName(context)->getName()), UTF8(item->dmStringValue(context))));
      }
    AutoDelete<XQQuery> qfinalize(xqilla.parse(X("/cooker/finalize/*")));
    Result rfinalize=qfinalize->execute(context);
    while(Node::Ptr item=rfinalize->next(context))
      {
	finalize.push_back(class_method(UTF8(item->dmNodeName(context)->getName()), UTF8(item->dmStringValue(context))));
      }

  }
  catch(   XQException E)
    {
      std::cerr<<"Parsing of recipe XML failed, error type:"<<UTF8(E.getType())<<" Error:"<<UTF8(E.getError())<<std::endl;
    } 
  
  
}
Exemple #7
0
bool parse_query(std::string& query,
                 Sequence<bool,Allocator>& selected_column_list,
                 bool& count_mode,
                 dsv_filter& filter)
{
   std::deque<std::string> sub_query;
   strtk::parse(query,"|",sub_query);

   strtk::remove_empty_strings(sub_query);

   if (2 == sub_query.size())
   {
      if (0 == strtk::ifind("select",sub_query[0]))
      {
         std::fill_n(selected_column_list.begin(),selected_column_list.size(),false);

         std::deque<std::string> selected_cols;

         strtk::parse(sub_query[0],", ",selected_cols);
         bool col_found = false;

         for (std::size_t i = 1; i < selected_cols.size(); ++i)
         {
            if (selected_cols[i].empty())
               continue;

            col_found = false;

            for (std::size_t c = 0; c < filter.column_count(); ++c)
            {
               if (strtk::imatch(selected_cols[i],filter.column(c).name))
               {
                  selected_column_list[c] = true;
                  col_found = true;

                  break;
               }
            }

            if (!col_found)
            {
               std::cout << "Error - Invalid column: [" << selected_cols[i] << "]" << std::endl;
               return false;
            }
         }

         query = sub_query[1];
      }
      else if (0 == strtk::ifind("count",sub_query[0]))
      {
         count_mode = true;
         query = sub_query[1];
      }
      else
         return false;
   }
   else if (1 != sub_query.size())
      return false;
   else
      query = sub_query[0];

   return true;
}
Exemple #8
0
 static Iterator
 end  (Sequence       &seq) { return seq.end(); }
static void local_test_rearrange()
{
  typedef typename Sequence::iterator   iterator;
  typedef typename Sequence::value_type value_type;

  Sequence sc;
  sc.push_back(0);
  sc.push_back(1);
  sc.push_back(2);
  sc.push_back(3);
  sc.push_back(4);
  sc.push_back(5);

  iterator it;

  it=sc.begin();
  std::advance(it,3);
  sc.relocate(sc.begin(),it);
  CHECK_EQUAL(sc,(3)(0)(1)(2)(4)(5));
  BOOST_TEST(it==sc.begin());

  sc.relocate(it,it);
  CHECK_EQUAL(sc,(3)(0)(1)(2)(4)(5));

  std::advance(it,3);
  sc.relocate(sc.end(),it,sc.end());
  CHECK_EQUAL(sc,(3)(0)(1)(2)(4)(5));

  sc.relocate(sc.begin(),it,it);
  CHECK_EQUAL(sc,(3)(0)(1)(2)(4)(5));

  iterator it2;

  it2=sc.begin();
  ++it2;
  sc.relocate(it2,it,sc.end());
  CHECK_EQUAL(sc,(3)(2)(4)(5)(0)(1));
  BOOST_TEST(std::distance(it,it2)==3);

  sc.relocate(boost::prior(sc.end()),it,it2);
  CHECK_EQUAL(sc,(3)(0)(2)(4)(5)(1));

  std::vector<boost::reference_wrapper<const value_type> > v;
  for(iterator it3=sc.begin();it3!=sc.end();++it3){
    v.push_back(boost::cref(*it3));
  }

  sc.rearrange(v.begin());
  BOOST_TEST(std::equal(sc.begin(),sc.end(),v.begin()));

  std::reverse(v.begin(),v.end());
  sc.rearrange(v.begin());
  BOOST_TEST(std::equal(sc.begin(),sc.end(),v.begin()));

  std::sort(v.begin(),v.end());
  sc.rearrange(v.begin());
  BOOST_TEST(std::equal(sc.begin(),sc.end(),v.begin()));

  std::reverse(v.begin(),v.begin()+v.size()/2);
  sc.rearrange(v.begin());
  BOOST_TEST(std::equal(sc.begin(),sc.end(),v.begin()));
}
Exemple #10
0
 static Iterator
 begin(Sequence       &seq) { return seq.begin(); }
Exemple #11
0
 static ConstIterator
 end  (Sequence const &seq) { return seq.end(); }  
Exemple #12
0
 static ConstIterator
 begin(Sequence const &seq) { return seq.begin(); }
int ChimeraPintailCommand::driver(linePair* filePos, string outputFName, string filename, string accnos){
	try {
		ofstream out;
		m->openOutputFile(outputFName, out);
		
		ofstream out2;
		m->openOutputFile(accnos, out2);
		
		ifstream inFASTA;
		m->openInputFile(filename, inFASTA);

		inFASTA.seekg(filePos->start);

		bool done = false;
		int count = 0;
	
		while (!done) {
				
			if (m->control_pressed) {	return 1;	}
		
			Sequence* candidateSeq = new Sequence(inFASTA);  m->gobble(inFASTA);
				
			if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
				
				if (candidateSeq->getAligned().length() != templateSeqsLength)  {  //chimeracheck does not require seqs to be aligned
					m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
				}else{
					//find chimeras
					chimera->getChimeras(candidateSeq);
					
					if (m->control_pressed) {	delete candidateSeq; return 1;	}
		
					//print results
					chimera->print(out, out2);
				}
				count++;
			}
			delete candidateSeq;
			
			#if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
				unsigned long long pos = inFASTA.tellg();
				if ((pos == -1) || (pos >= filePos->end)) { break; }
			#else
				if (inFASTA.eof()) { break; }
			#endif
			
			//report progress
			if((count) % 100 == 0){	m->mothurOutJustToScreen("Processing sequence: " + toString(count) + "\n"); 		}
		}
		//report progress
		if((count) % 100 != 0){	m->mothurOutJustToScreen("Processing sequence: " + toString(count) + "\n"); 		}
		
		out.close();
		out2.close();
		inFASTA.close();
				
		return count;
	}
	catch(exception& e) {
		m->errorOut(e, "ChimeraPintailCommand", "driver");
		exit(1);
	}
}
Exemple #14
0
/********************************************************************/
TrimOligos::~TrimOligos() {}
//*******************************************************************/
int TrimOligos::stripBarcode(Sequence& seq, QualityScores& qual, int& group){
	try {
		
		string rawSequence = seq.getUnaligned();
		int success = bdiffs + 1;	//guilty until proven innocent
		
		//can you find the barcode
		for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
			string oligo = it->first;
			if(rawSequence.length() < oligo.length()){	//let's just assume that the barcodes are the same length
				success = bdiffs + 10;					//if the sequence is shorter than the barcode then bail out
				break;	
			}
			
			if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
				group = it->second;
				seq.setUnaligned(rawSequence.substr(oligo.length()));
				
				if(qual.getName() != ""){
					qual.trimQScores(oligo.length(), -1);
				}
				
				success = 0;
				break;
			}
		}
		
		//if you found the barcode or if you don't want to allow for diffs
		if ((bdiffs == 0) || (success == 0)) { return success;  }
		
		else { //try aligning and see if you can find it
			
			int maxLength = 0;
			
			Alignment* alignment;
			if (barcodes.size() > 0) {
				map<string,int>::iterator it=barcodes.begin();
				
				for(it;it!=barcodes.end();it++){
					if(it->first.length() > maxLength){
						maxLength = it->first.length();
					}
				}
				alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+bdiffs+1));  
				
			}else{ alignment = NULL; } 
			
			//can you find the barcode
			int minDiff = 1e6;
			int minCount = 1;
			int minGroup = -1;
			int minPos = 0;
			
			for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
				string oligo = it->first;
				//				int length = oligo.length();
				
				if(rawSequence.length() < maxLength){	//let's just assume that the barcodes are the same length
					success = bdiffs + 10;
					break;
				}
				
				//use needleman to align first barcode.length()+numdiffs of sequence to each barcode
				alignment->align(oligo, rawSequence.substr(0,oligo.length()+bdiffs));
				oligo = alignment->getSeqAAln();
				string temp = alignment->getSeqBAln();
				
				int alnLength = oligo.length();
				
				for(int i=oligo.length()-1;i>=0;i--){
					if(oligo[i] != '-'){	alnLength = i+1;	break;	}
				}
				oligo = oligo.substr(0,alnLength);
				temp = temp.substr(0,alnLength);
				
				int numDiff = countDiffs(oligo, temp);
				
				if(numDiff < minDiff){
					minDiff = numDiff;
					minCount = 1;
					minGroup = it->second;
					minPos = 0;
					for(int i=0;i<alnLength;i++){
						if(temp[i] != '-'){
							minPos++;
						}
					}
				}
				else if(numDiff == minDiff){
					minCount++;
				}
				
			}
			
			if(minDiff > bdiffs)	{	success = minDiff;		}	//no good matches
			else if(minCount > 1)	{	success = bdiffs + 100;	}	//can't tell the difference between multiple barcodes
			else{													//use the best match
				group = minGroup;
				seq.setUnaligned(rawSequence.substr(minPos));
				
				if(qual.getName() != ""){
					qual.trimQScores(minPos, -1);
				}
				success = minDiff;
			}
			
			if (alignment != NULL) {  delete alignment;  }
			
		}
		
		return success;
		
	}
	catch(exception& e) {
		m->errorOut(e, "TrimOligos", "stripBarcode");
		exit(1);
	}
	
}
//*******************************************************************/
int TrimOligos::stripBarcode(Sequence& seq, int& group){
	try {
		
		string rawSequence = seq.getUnaligned();
		int success = bdiffs + 1;	//guilty until proven innocent
		
		//can you find the barcode
		for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
			string oligo = it->first;
			if(rawSequence.length() < oligo.length()){	//let's just assume that the barcodes are the same length
				success = bdiffs + 10;					//if the sequence is shorter than the barcode then bail out
				break;	
			}
			
			if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
				group = it->second;
				seq.setUnaligned(rawSequence.substr(oligo.length()));
				
				success = 0;
				break;
			}
		}
		
		//if you found the barcode or if you don't want to allow for diffs
		if ((bdiffs == 0) || (success == 0)) { return success;  }
		
		else { //try aligning and see if you can find it
			
			int maxLength = 0;
			
			Alignment* alignment;
			if (barcodes.size() > 0) {
				map<string,int>::iterator it=barcodes.begin();
				
				for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
					if(it->first.length() > maxLength){
						maxLength = it->first.length();
					}
				}
				alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+bdiffs+1));  
				
			}else{ alignment = NULL; } 
			
			//can you find the barcode
			int minDiff = 1e6;
			int minCount = 1;
			int minGroup = -1;
			int minPos = 0;
			
			for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
				string oligo = it->first;
				//				int length = oligo.length();
				
				if(rawSequence.length() < maxLength){	//let's just assume that the barcodes are the same length
					success = bdiffs + 10;
					break;
				}
				
				//use needleman to align first barcode.length()+numdiffs of sequence to each barcode
				alignment->align(oligo, rawSequence.substr(0,oligo.length()+bdiffs));
				oligo = alignment->getSeqAAln();
				string temp = alignment->getSeqBAln();
				
				int alnLength = oligo.length();
				
				for(int i=oligo.length()-1;i>=0;i--){
					if(oligo[i] != '-'){	alnLength = i+1;	break;	}
				}
				oligo = oligo.substr(0,alnLength);
				temp = temp.substr(0,alnLength);
				
				int numDiff = countDiffs(oligo, temp);
				
				if(numDiff < minDiff){
					minDiff = numDiff;
					minCount = 1;
					minGroup = it->second;
					minPos = 0;
					for(int i=0;i<alnLength;i++){
						if(temp[i] != '-'){
							minPos++;
						}
					}
				}
				else if(numDiff == minDiff){
					minCount++;
				}
				
			}
			
			if(minDiff > bdiffs)	{	success = minDiff;		}	//no good matches
			else if(minCount > 1)	{	success = bdiffs + 100;	}	//can't tell the difference between multiple barcodes
			else{													//use the best match
				group = minGroup;
				seq.setUnaligned(rawSequence.substr(minPos));
				success = minDiff;
			}
			
			if (alignment != NULL) {  delete alignment;  }
			
		}
		
		return success;
		
	}
	catch(exception& e) {
		m->errorOut(e, "TrimOligos", "stripBarcode");
		exit(1);
	}
	
}
//********************************************************************/
int TrimOligos::stripForward(Sequence& seq, int& group){
	try {
		
		string rawSequence = seq.getUnaligned();
		int success = pdiffs + 1;	//guilty until proven innocent
		
		//can you find the primer
		for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
			string oligo = it->first;
			if(rawSequence.length() < oligo.length()){	//let's just assume that the primers are the same length
				success = pdiffs + 10;					//if the sequence is shorter than the barcode then bail out
				break;	
			}
			
			if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
				group = it->second;
				seq.setUnaligned(rawSequence.substr(oligo.length()));
				success = 0;
				break;
			}
		}
		
		//if you found the barcode or if you don't want to allow for diffs
		if ((pdiffs == 0) || (success == 0)) {	return success;  }
		
		else { //try aligning and see if you can find it
			
			int maxLength = 0;
			
			Alignment* alignment;
			if (primers.size() > 0) {
				map<string,int>::iterator it=primers.begin();
				
				for(it;it!=primers.end();it++){
					if(it->first.length() > maxLength){
						maxLength = it->first.length();
					}
				}
				alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+pdiffs+1));  
				
			}else{ alignment = NULL; } 
			
			//can you find the barcode
			int minDiff = 1e6;
			int minCount = 1;
			int minGroup = -1;
			int minPos = 0;
			
			for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
				string oligo = it->first;
				//				int length = oligo.length();
				
				if(rawSequence.length() < maxLength){	
					success = pdiffs + 100;
					break;
				}
				
				//use needleman to align first barcode.length()+numdiffs of sequence to each barcode
				alignment->align(oligo, rawSequence.substr(0,oligo.length()+pdiffs));
				oligo = alignment->getSeqAAln();
				string temp = alignment->getSeqBAln();
				
				int alnLength = oligo.length();
				
				for(int i=oligo.length()-1;i>=0;i--){
					if(oligo[i] != '-'){	alnLength = i+1;	break;	}
				}
				oligo = oligo.substr(0,alnLength);
				temp = temp.substr(0,alnLength);
				
				int numDiff = countDiffs(oligo, temp);
				
				if(numDiff < minDiff){
					minDiff = numDiff;
					minCount = 1;
					minGroup = it->second;
					minPos = 0;
					for(int i=0;i<alnLength;i++){
						if(temp[i] != '-'){
							minPos++;
						}
					}
				}
				else if(numDiff == minDiff){
					minCount++;
				}
				
			}
			
			if(minDiff > pdiffs)	{	success = minDiff;		}	//no good matches
			else if(minCount > 1)	{	success = pdiffs + 10;	}	//can't tell the difference between multiple primers
			else{													//use the best match
				group = minGroup;
				seq.setUnaligned(rawSequence.substr(minPos));
				success = minDiff;
			}
			
			if (alignment != NULL) {  delete alignment;  }
			
		}
		
		return success;
		
	}
	catch(exception& e) {
		m->errorOut(e, "TrimOligos", "stripForward");
		exit(1);
	}
}
//*******************************************************************/
int TrimOligos::stripForward(Sequence& seq, QualityScores& qual, int& group){
	try {
		string rawSequence = seq.getUnaligned();
		int success = pdiffs + 1;	//guilty until proven innocent
		
		//can you find the primer
		for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
			string oligo = it->first;
			if(rawSequence.length() < oligo.length()){	//let's just assume that the primers are the same length
				success = pdiffs + 10;					//if the sequence is shorter than the barcode then bail out
				break;	
			}
			
			if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
				group = it->second;
				seq.setUnaligned(rawSequence.substr(oligo.length()));
				if(qual.getName() != ""){
					qual.trimQScores(oligo.length(), -1);
				}
				success = 0;
				break;
			}
		}
		
		//if you found the barcode or if you don't want to allow for diffs
		if ((pdiffs == 0) || (success == 0)) { return success;  }
		
		else { //try aligning and see if you can find it
			
			int maxLength = 0;
			
			Alignment* alignment;
			if (primers.size() > 0) {
				map<string,int>::iterator it=primers.begin();
				
				for(it;it!=primers.end();it++){
					if(it->first.length() > maxLength){
						maxLength = it->first.length();
					}
				}
				alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+pdiffs+1));  
				
			}else{ alignment = NULL; } 
			
			//can you find the barcode
			int minDiff = 1e6;
			int minCount = 1;
			int minGroup = -1;
			int minPos = 0;
			
			for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
				string oligo = it->first;
				//				int length = oligo.length();
				
				if(rawSequence.length() < maxLength){	
					success = pdiffs + 100;
					break;
				}
				
				//use needleman to align first barcode.length()+numdiffs of sequence to each barcode
				alignment->align(oligo, rawSequence.substr(0,oligo.length()+pdiffs));
				oligo = alignment->getSeqAAln();
				string temp = alignment->getSeqBAln();
				
				int alnLength = oligo.length();
				
				for(int i=oligo.length()-1;i>=0;i--){
					if(oligo[i] != '-'){	alnLength = i+1;	break;	}
				}
				oligo = oligo.substr(0,alnLength);
				temp = temp.substr(0,alnLength);
				
				int numDiff = countDiffs(oligo, temp);
				
				if(numDiff < minDiff){
					minDiff = numDiff;
					minCount = 1;
					minGroup = it->second;
					minPos = 0;
					for(int i=0;i<alnLength;i++){
						if(temp[i] != '-'){
							minPos++;
						}
					}
				}
				else if(numDiff == minDiff){
					minCount++;
				}
				
			}
			
			if(minDiff > pdiffs)	{	success = minDiff;		}	//no good matches
			else if(minCount > 1)	{	success = pdiffs + 10;	}	//can't tell the difference between multiple primers
			else{													//use the best match
				group = minGroup;
				seq.setUnaligned(rawSequence.substr(minPos));
				if(qual.getName() != ""){
					qual.trimQScores(minPos, -1);
				}
				success = minDiff;
			}
			
			if (alignment != NULL) {  delete alignment;  }
			
		}
		
		return success;
		
	}
	catch(exception& e) {
		m->errorOut(e, "TrimOligos", "stripForward");
		exit(1);
	}
}
Exemple #15
0
NthOrdRateMatrix *NmerRateMatrix::nextHigherOrder()
{
  // Misc initialization
  const int n=order+1; // my n, not M's!
  const int Nm=n+1;    // M's n
  NmerRateMatrix *M=new NmerRateMatrix(Nm);
  Sequence from, to, fromSuffix, toSuffix, fromPrefix, toPrefix;
  int numNmersInM=M->numNmers;
  M->eqFreqsFromMarginals(eqSingle);
  *(M->lowerOrderModel)=*this;
  M->parms.setAllTo(-1);

  // Compute averages of parameter values for each nmer in the lower-order
  // model, for use in initializing higher-order parameters having no direct
  // analog in the lower-order model
  Array1D<double> aveParms(numNmers);
  for(int i=0 ; i<numNmers ; ++i) {
    from.fromInt(i,n,alphabetMap);
    double sum=0;
    int sampleSize=0;
    for(int j=0 ; j<numNmers ; ++j) {
      to.fromInt(j,n,alphabetMap);
      Sequence fromTo=from+to;
      if(parmIndices.isDefined(fromTo)) {
	sum+=parms[parmIndices[fromTo]];
	++sampleSize;
      }
    }
    aveParms[i]=1-sum; //  sum/sampleSize;
  }

  NmerRateMatrix *zerothM=this;
  if(order>0) zerothM=(NmerRateMatrix*)getLowerOrderModel(0);
  //if(!zerothM) throw "zerothM is null";
  int numAlpha=alphabetMap.getDomain()->size();
  Array1D<double> zerothParm(numAlpha);
  zerothParm.setAllTo(NEGATIVE_INFINITY);
  Sequence seq;
  seq.resize(2);
  for(Symbol s=0 ; s<numAlpha ; ++s) {
    if(alphabetMap(s)==INVALID_SYMBOL) continue;
    zerothParm[s]=1;
    for(Symbol z=0 ; z<numAlpha ; ++z) {
      if(z==s || alphabetMap(z)==INVALID_SYMBOL) continue;
      seq[0]=s; seq[1]=z;
      zerothParm[s]-=zerothM->parms[zerothM->parmIndices[seq]];
    }
  }

  // Now iterate over all nmer pairs in the higher-order model and
  // initialize parameters from lower-order analogs (or from aveParms[])
  for(int i=0 ; i<numNmersInM ; ++i) {
    from.fromInt(i,Nm,alphabetMap);
    from.getSubsequence(1,n,fromSuffix);
    int suffixInt=fromSuffix.asInt(alphabetMap);
    for(int j=i+1 ; j<numNmersInM ; ++j) {
      to.fromInt(j,Nm,alphabetMap);
      if(countDifferences(from,to)!=1) continue;
      Sequence nmerPair=from+to;
      int higherParmIndex=M->parmIndices[nmerPair];
      if(from[0]==to[0]) {
	// The difference is in the suffix, so just copy the parameter
	// from the lower-order model
	to.getSubsequence(1,n,toSuffix);
	nmerPair=fromSuffix+toSuffix;
	int lowerParmIndex=parmIndices[nmerPair];
	M->parms[higherParmIndex]=
	  parms[lowerParmIndex] *
	  zerothParm[from[0]];
      }
      /*else {
	// The difference is in the first position, so copy the parameter
	// from the lower-order model for the prefixes (not suffixes)
	from.getSubsequence(0,n,fromPrefix);
	to.getSubsequence(0,n,toPrefix);
	nmerPair=fromPrefix+toPrefix;
	int lowerParmIndex=parmIndices[nmerPair];
	M->parms[higherParmIndex]=parms[lowerParmIndex]
	  ;//*zerothParm[from[Nm-1]];
	  }*/
      else {
	// The difference is in the leftmost base, so just initialize
	// the new parameter to an average of the parameters for the
	// row of the suffix in the lower-order model
	seq[0]=from[0]; seq[1]=to[0];
	M->parms[higherParmIndex]=
	  aveParms[suffixInt] *
	  zerothM->parms[zerothM->parmIndices[seq]];
      }
    }
  }

  return M;
}
 void const_constraints(const Sequence& c) {
   const_reference r = c.front();
   ignore_unused_variable_warning(r);
 }
std::map<size_t, size_t> SiteContainerTools::translateAlignment(const Sequence& seq1, const Sequence& seq2)
throw (AlphabetMismatchException, Exception)
{
  if (seq1.getAlphabet()->getAlphabetType() != seq2.getAlphabet()->getAlphabetType())
    throw AlphabetMismatchException("SiteContainerTools::translateAlignment", seq1.getAlphabet(), seq2.getAlphabet());
  map<size_t, size_t> tln;
  if (seq1.size() == 0)
    return tln;
  unsigned int count1 = 0;
  unsigned int count2 = 0;
  if (seq2.size() == 0)
    throw Exception("SiteContainerTools::translateAlignment. Sequences do not match at position " + TextTools::toString(count1 + 1) + " and " + TextTools::toString(count2 + 1) + ".");
  int state1 = seq1[count1];
  int state2 = seq2[count2];
  bool end = false;
  while (!end)
  {
    while (state1 == -1)
    {
      count1++;
      if (count1 < seq1.size())
        state1 = seq1[count1];
      else
        break;
    }
    while (state2 == -1)
    {
      count2++;
      if (count2 < seq2.size())
        state2 = seq2[count2];
      else
        break;
    }
    if (state1 != state2)
      throw Exception("SiteContainerTools::translateAlignment. Sequences do not match at position " + TextTools::toString(count1 + 1) + " and " + TextTools::toString(count2 + 1) + ".");
    tln[count1 + 1] = count2 + 1; // Count start at 1
    if (count1 == seq1.size() - 1)
      end = true;
    else
    {
      if (count2 == seq2.size() - 1)
      {
        state1 = seq1[++count1];
        while (state1 == -1)
        {
          count1++;
          if (count1 < seq1.size())
            state1 = seq1[count1];
          else
            break;
        }
        if (state1 == -1)
          end = true;
        else
          throw Exception("SiteContainerTools::translateAlignment. Sequences do not match at position " + TextTools::toString(count1 + 1) + " and " + TextTools::toString(count2 + 1) + ".");
      }
      else
      {
        state1 = seq1[++count1];
        state2 = seq2[++count2];
      }
    }
  }
  return tln;
}
void
GetDirectoryListingTaskChild::HandlerCallback()
{
  mFileSystem->AssertIsOnOwningThread();

  if (mFileSystem->IsShutdown()) {
    mPromise = nullptr;
    return;
  }

  if (HasError()) {
    mPromise->MaybeReject(mErrorValue);
    mPromise = nullptr;
    return;
  }

  size_t count = mTargetData.Length();

  nsAutoString directoryPath;
  ErrorResult error;
  mDirectory->GetPath(directoryPath, error);
  if (NS_WARN_IF(error.Failed())) {
    mPromise->MaybeReject(error.StealNSResult());
    mPromise = nullptr;
    return;
  }

  Sequence<OwningFileOrDirectory> listing;

  if (!listing.SetLength(count, mozilla::fallible_t())) {
    mPromise->MaybeReject(NS_ERROR_OUT_OF_MEMORY);
    mPromise = nullptr;
    return;
  }

  for (unsigned i = 0; i < count; i++) {
    nsCOMPtr<nsIFile> path;
    NS_ConvertUTF16toUTF8 fullPath(mTargetData[i].mPath);
    nsresult rv = NS_NewNativeLocalFile(fullPath, true, getter_AddRefs(path));
    if (NS_WARN_IF(NS_FAILED(rv))) {
      mPromise->MaybeReject(rv);
      mPromise = nullptr;
      return;
    }

#ifdef DEBUG
    nsCOMPtr<nsIFile> rootPath;
    rv = NS_NewLocalFile(mFileSystem->LocalOrDeviceStorageRootPath(), false,
                         getter_AddRefs(rootPath));
    if (NS_WARN_IF(NS_FAILED(rv))) {
      mPromise->MaybeReject(rv);
      mPromise = nullptr;
      return;
    }

    MOZ_ASSERT(FileSystemUtils::IsDescendantPath(rootPath, path));
#endif

    if (mTargetData[i].mType == Directory::FileOrDirectoryPath::eDirectoryPath) {
      RefPtr<Directory> directory =
        Directory::Create(mFileSystem->GetParentObject(), path, mFileSystem);
      MOZ_ASSERT(directory);

      // Propogate mFilter onto sub-Directory object:
      directory->SetContentFilters(mFilters);
      listing[i].SetAsDirectory() = directory;
    } else {
      MOZ_ASSERT(mTargetData[i].mType == Directory::FileOrDirectoryPath::eFilePath);

      RefPtr<File> file =
        File::CreateFromFile(mFileSystem->GetParentObject(), path);
      MOZ_ASSERT(file);

      nsAutoString filePath;
      filePath.Assign(directoryPath);

      // This is specific for unix root filesystem.
      if (!directoryPath.EqualsLiteral(FILESYSTEM_DOM_PATH_SEPARATOR_LITERAL)) {
        filePath.AppendLiteral(FILESYSTEM_DOM_PATH_SEPARATOR_LITERAL);
      }

      nsAutoString name;
      file->GetName(name);
      filePath.Append(name);
      file->SetPath(filePath);

      listing[i].SetAsFile() = file;
    }
  }

  mPromise->MaybeResolve(listing);
  mPromise = nullptr;
}
Exemple #19
0
 SceneManager() {
   // Pull Path指定しないと仮想関数のアドレスを取ろうとする->err
   sequence.changeAction(&SceneManager::title);
 }
Exemple #20
0
int main(int argc, char * argv[]) {
    
    log_call(argc, argv);
    
    bool outfileset = false;
    bool sfileset = false;
    bool cfileset = false;
    bool nfileset = false;
    bool verbose = false;
    char * outf = NULL;
    char * seqf = NULL;
    string cnamef = "";
    string nnamef = "";
    while (1) {
        int oi = -1;
        int c = getopt_long(argc, argv, "s:c:n:o:vhV", long_options, &oi);
        if (c == -1) {
            break;
        }
        switch(c) {
            case 's':
                sfileset = true;
                seqf = strdup(optarg);
                check_file_exists(seqf);
                break;
            case 'c':
                cfileset = true;
                cnamef = strdup(optarg);
                check_file_exists(cnamef.c_str());
                break;
            case 'n':
                nfileset = true;
                nnamef = strdup(optarg);
                check_file_exists(nnamef.c_str());
                break;
            case 'o':
                outfileset = true;
                outf = strdup(optarg);
                break;
            case 'v':
                verbose = true;
                break;
            case 'h':
                print_help();
                exit(0);
            case 'V':
                cout << versionline << endl;
                exit(0);
            default:
                print_error(argv[0], (char)c);
                exit(0);
        }
    }
    
    if (sfileset && outfileset) {
        check_inout_streams_identical(seqf, outf);
    }
    
    istream * pios = NULL;
    ostream * poos = NULL;
    ifstream * fstr = NULL;
    ofstream * ofstr = NULL;
    
    if (!nfileset | !cfileset) {
        cout << "Must supply both name files (-c for current, -n for new)." << endl;
        exit(0);
    }
    
    if (sfileset == true) {
        fstr = new ifstream(seqf);
        pios = fstr;
    } else {
        pios = &cin;
        if (check_for_input_to_stream() == false) {
            print_help();
            exit(1);
        }
    }
    if (outfileset == true) {
        ofstr = new ofstream(outf);
        poos = ofstr;
    } else {
        poos = &cout;
    }
    
    Relabel rl (cnamef, nnamef, verbose);
    
    set <string> orig = rl.get_names_to_replace();
    
    Sequence seq;
    string retstring;
    
    int ft = test_seq_filetype_stream(*pios, retstring);
    
    bool success = false;
    
    while (read_next_seq_from_stream(*pios, ft, retstring, seq)) {
        string terp = seq.get_id();
        success = rl.relabel_sequence(seq);
        if (success) {
            orig.erase(terp);
        }
        (*poos) << ">" << seq.get_id() << endl;
        (*poos) << seq.get_sequence() << endl;
    }
// have to deal with last sequence outside while loop. fix this.
    if (ft == 2) {
        string terp = seq.get_id();
        success = rl.relabel_sequence(seq);
        if (success) {
            orig.erase(terp);
        }
        (*poos) << ">" << seq.get_id() << endl;
        (*poos) << seq.get_sequence() << endl;
    }
    
    if (orig.size() > 0) {
        if (verbose) {
            cerr << "The following names to match were not found in the alignment:" << endl;
            for (auto elem : orig) {
                cerr << elem << endl;
            }
        }
    }
    
    if (sfileset) {
        fstr->close();
        delete pios;
    }
    if (outfileset) {
        ofstr->close();
        delete poos;
    }
    return EXIT_SUCCESS;
}
Exemple #21
0
void RDD9Track::AddHeaderMetadata(HeaderMetadata *header_metadata, MaterialPackage *material_package,
                                  SourcePackage *file_source_package)
{
    mxfUL data_def_ul;
    BMX_CHECK(mxf_get_ddef_label(mDataDef, &data_def_ul));

    int64_t material_track_duration = -1; // unknown - could be updated if not writing in a single pass
    int64_t source_track_duration   = -1; // unknown - could be updated if not writing in a single pass
    int64_t source_track_origin     = 0;  // could be updated if not writing in a single pass


    // Preface - ContentStorage - MaterialPackage - Timeline Track
    Track *track = new Track(header_metadata);
    material_package->appendTracks(track);

    track->setTrackName(get_track_name(mDataDef, mOutputTrackNumber));
    track->setTrackID(mTrackId);
    // TODO: not sure whether setting TrackNumber in the MaterialPackage is a good idea for this MXF flavour
    //       track->setTrackNumber(mOutputTrackNumber);
    track->setTrackNumber(0);
    track->setEditRate(mEditRate);
    track->setOrigin(0);

    // Preface - ContentStorage - MaterialPackage - Timeline Track - Sequence
    Sequence *sequence = new Sequence(header_metadata);
    track->setSequence(sequence);
    sequence->setDataDefinition(data_def_ul);
    sequence->setDuration(material_track_duration);

    // Preface - ContentStorage - MaterialPackage - Timeline Track - Sequence - SourceClip
    SourceClip *source_clip = new SourceClip(header_metadata);
    sequence->appendStructuralComponents(source_clip);
    source_clip->setDataDefinition(data_def_ul);
    source_clip->setDuration(material_track_duration);
    source_clip->setStartPosition(0);
    source_clip->setSourcePackageID(file_source_package->getPackageUID());
    source_clip->setSourceTrackID(mTrackId);


    // Preface - ContentStorage - SourcePackage - Timeline Track
    track = new Track(header_metadata);
    file_source_package->appendTracks(track);
    track->setTrackName(get_track_name(mDataDef, mOutputTrackNumber));
    track->setTrackID(mTrackId);
    track->setTrackNumber(mTrackNumber);
    track->setEditRate(mEditRate);
    track->setOrigin(source_track_origin);

    // Preface - ContentStorage - SourcePackage - Timeline Track - Sequence
    sequence = new Sequence(header_metadata);
    track->setSequence(sequence);
    sequence->setDataDefinition(data_def_ul);
    sequence->setDuration(source_track_duration);

    // Preface - ContentStorage - SourcePackage - Timeline Track - Sequence - SourceClip
    source_clip = new SourceClip(header_metadata);
    sequence->appendStructuralComponents(source_clip);
    source_clip->setDataDefinition(data_def_ul);
    source_clip->setDuration(source_track_duration);
    source_clip->setStartPosition(0);
    source_clip->setSourceTrackID(0);
    source_clip->setSourcePackageID(g_Null_UMID);

    // Preface - ContentStorage - SourcePackage - FileDescriptor
    FileDescriptor *descriptor = mDescriptorHelper->CreateFileDescriptor(header_metadata);
    BMX_ASSERT(file_source_package->haveDescriptor());
    MultipleDescriptor *mult_descriptor = dynamic_cast<MultipleDescriptor*>(file_source_package->getDescriptor());
    BMX_ASSERT(mult_descriptor);
    mult_descriptor->appendSubDescriptorUIDs(descriptor);
    descriptor->setLinkedTrackID(mTrackId);
}
	bool operator<(const Sequence& other ) const
	{
		return getAbsoluteStandardPattern() < other.getAbsoluteStandardPattern();
	}
Exemple #23
0
/* Resolve ambiguous region using multiple alignment of all paths in
 * `solutions'.
 */
static ContigPath alignMulti(const Graph& g,
		const vector<Path>& solutions, ofstream& out)
{
	// Find the size of the smallest path.
	const Path& firstSol = solutions.front();
	size_t min_len = firstSol.size();
	for (vector<Path>::const_iterator it = solutions.begin() + 1;
			it != solutions.end(); ++it)
		min_len = min(min_len, it->size());

	// Find the longest prefix.
	Path vppath;
	size_t longestPrefix;
	bool commonPrefix = true;
	for (longestPrefix = 0;
			longestPrefix < min_len; longestPrefix++) {
		const ContigNode& common_path_node = firstSol[longestPrefix];
		for (vector<Path>::const_iterator solIter = solutions.begin();
				solIter != solutions.end(); ++solIter) {
			const ContigNode& pathnode = (*solIter)[longestPrefix];
			if (pathnode != common_path_node) {
				// Found the longest prefix.
				commonPrefix = false;
				break;
			}
		}
		if (!commonPrefix)
			break;
		vppath.push_back(common_path_node);
	}

	// Find the longest suffix.
	Path vspath;
	size_t longestSuffix;
	bool commonSuffix = true;
	for (longestSuffix = 0;	longestSuffix < min_len-longestPrefix;
			longestSuffix++) {
		const ContigNode& common_path_node
			= firstSol[firstSol.size()-longestSuffix-1];
		for (vector<Path>::const_iterator solIter = solutions.begin();
				solIter != solutions.end(); ++solIter) {
			const ContigNode& pathnode
				= (*solIter)[solIter->size()-longestSuffix-1];
			if (pathnode != common_path_node) {
				// Found the longest suffix.
				commonSuffix = false;
				break;
			}
		}
		if (!commonSuffix)
			break;
		vspath.push_back(common_path_node);
	}
	reverse(vspath.begin(), vspath.end());

	if (opt::verbose > 1 && vppath.size() + vspath.size() > 2)
		cerr << vppath << " * " << vspath << '\n';

	// Get sequence of ambiguous region in paths
	assert(longestPrefix > 0 && longestSuffix > 0);
	vector<Sequence> amb_seqs;
	unsigned coverage = 0;
	for (vector<Path>::const_iterator solIter = solutions.begin();
			solIter != solutions.end(); solIter++) {
		assert(longestPrefix + longestSuffix <= solIter->size());
		Path path(solIter->begin() + longestPrefix,
				solIter->end() - longestSuffix);
		if (!path.empty()) {
			amb_seqs.push_back(mergePath(g, path));
			coverage += calculatePathProperties(g, path).coverage;
		} else {
			// The prefix and suffix paths overlap by k-1 bp.
			Sequence s = getSequence(solutions[0][longestPrefix-1]);
			amb_seqs.push_back(s.substr(s.length() - opt::k + 1));
		}
	}

	vector<unsigned> lengths(amb_seqs.size());
	transform(amb_seqs.begin(), amb_seqs.end(), lengths.begin(),
			mem_fun_ref(&string::length));
	unsigned minLength = *min_element(lengths.begin(), lengths.end());
	unsigned maxLength = *max_element(lengths.begin(), lengths.end());
	float lengthRatio = (float)minLength / maxLength;
	if (lengthRatio < opt::identity) {
		if (opt::verbose > 1)
			cerr << minLength << '\t' << maxLength
				<< '\t' << lengthRatio << "\t(different length)\n";
		return ContigPath();
	}

	string alignment;
	unsigned matches;
	Sequence consensus = dialign(amb_seqs, alignment, matches);
	if (opt::verbose > 2)
	   	cerr << alignment << consensus << '\n';
	float identity = (float)matches / consensus.size();
	if (opt::verbose > 1)
		cerr << identity
			<< (identity < opt::identity ? " (too low)\n" : "\n");
	if (identity < opt::identity)
		return ContigPath();

	if (identity == 1) {
		// A perfect match must be caused by two palindromes.
		ContigID palindrome0
			= solutions[0][longestPrefix].contigIndex();
		ContigID palindrome1
			= solutions[0].rbegin()[longestSuffix].contigIndex();
		if (opt::verbose > 1)
			cerr << "Palindrome: "
				<< get(g_contigNames, palindrome0) << '\n'
				<< "Palindrome: "
				<< get(g_contigNames, palindrome1) << '\n';
#ifndef NDEBUG
		string s0 = getSequence(ContigNode(palindrome0, false));
		string s1 = getSequence(ContigNode(palindrome1, false));
		assert(s0 == reverseComplement(s0));
		assert(s1 == reverseComplement(s1));
		for (vector<Path>::const_iterator it = solutions.begin();
				it != solutions.end(); ++it) {
			const ContigPath& path = *it;
			assert(path[longestPrefix].contigIndex() == palindrome0);
			assert(path.rbegin()[longestSuffix].contigIndex()
					== palindrome1);
			assert(path.size() == solutions[0].size());
		}
#endif
		return solutions[0];
	}

	ContigNode u = outputNewContig(g, solutions,
		longestPrefix, longestSuffix, consensus, coverage, out);
	ContigPath path(vppath);
	path.push_back(u);
	path.insert(path.end(), vspath.begin(), vspath.end());
	return path;
}
Exemple #24
0
void SequenceConcatenater::read_sequences (string & seqf) {
    filename_ = seqf;
    string retstring;
    istream * pios = new ifstream(filename_);
    ft_ = test_seq_filetype_stream(*pios, retstring);
    Sequence seq;
    int counter = 0;
    int length = 0;
    
    // phylip (1) NEXUS (0)
    if (ft_ == 1 || ft_ == 0) {
        if (ft_ == 1) {
            vector <string> fileDim = tokenize(retstring);
            num_taxa_ = stoi(fileDim[0]);
            num_char_ = stoi(fileDim[1]);
        } else {
            get_nexus_dimensions_file(seqf, num_taxa_, num_char_, interleave_);
        }
        if (!interleave_) {
            while (read_next_seq_from_stream(*pios, ft_, retstring, seq)) {
                length = (int)seq.get_sequence().size();
                if (length != num_char_) {
                    cout << "Sequence '" << seq.get_id() << "' has " << length << " characters, but the file '"
                        << filename_ << "' specified " << num_char_ << " characters. Exiting." << endl;
                    delete pios;
                    exit(1);
                }
                if (toupcase_) {
                    seq.set_sequence(seq.seq_to_upper());
                }
                seqs_.push_back(seq);
                counter++;
            }
            if (counter != num_taxa_) {
                cout << "Read " << counter << " taxa, but the file '" << filename_ << "' specified "
                    << num_taxa_ << " taxa. Exiting." << endl;
                delete pios;
                exit(1);
            }
        } else {
            seqs_ = read_interleaved_nexus_file(seqf, num_taxa_, num_char_);
            if (toupcase_) {
                for (int i = 0; i < num_taxa_; i++) {
                    seqs_[i].set_sequence(seqs_[i].seq_to_upper());
                }
            }
        }
        
    } else if (ft_ == 2) { // fasta
        bool first = true;
        while (read_next_seq_from_stream(*pios, ft_, retstring, seq)) {
            int curr = (int)seq.get_sequence().size();
            if (!first) {
                if (curr != length) {
                    cout << "Error: current sequence has " << curr << " characters, but previous sequence had "
                        << length << " characters. Exiting." << endl;
                    delete pios;
                    exit(1);
                }
            } else {
                length = curr;
                first = false;
            }
            if (toupcase_) {
                seq.set_sequence(seq.seq_to_upper());
            }
            seqs_.push_back(seq);
            counter++;
        }
        // fasta has a trailing one
        if (toupcase_) {
            seq.set_sequence(seq.seq_to_upper());
        }
        seqs_.push_back(seq);
        counter++;
        num_taxa_ = counter;
        num_char_ = length;
    } else {
        cout << "I don't know what that alignment file format is! Exiting." << endl;
        exit(0);
    }
    num_partitions_ = 1;
    partition_sizes_.push_back(num_char_);
    delete pios;
}
void
nsBrowserElement::SendTouchEvent(const nsAString& aType,
                                 const Sequence<uint32_t>& aIdentifiers,
                                 const Sequence<int32_t>& aXs,
                                 const Sequence<int32_t>& aYs,
                                 const Sequence<uint32_t>& aRxs,
                                 const Sequence<uint32_t>& aRys,
                                 const Sequence<float>& aRotationAngles,
                                 const Sequence<float>& aForces,
                                 uint32_t aCount,
                                 uint32_t aModifiers,
                                 ErrorResult& aRv)
{
  NS_ENSURE_TRUE_VOID(IsBrowserElementOrThrow(aRv));

  if (aIdentifiers.Length() != aCount ||
      aXs.Length() != aCount ||
      aYs.Length() != aCount ||
      aRxs.Length() != aCount ||
      aRys.Length() != aCount ||
      aRotationAngles.Length() != aCount ||
      aForces.Length() != aCount) {
    aRv.Throw(NS_ERROR_DOM_INVALID_ACCESS_ERR);
    return;
  }

  nsresult rv = mBrowserElementAPI->SendTouchEvent(aType,
                                                   aIdentifiers.Elements(),
                                                   aXs.Elements(),
                                                   aYs.Elements(),
                                                   aRxs.Elements(),
                                                   aRys.Elements(),
                                                   aRotationAngles.Elements(),
                                                   aForces.Elements(),
                                                   aCount,
                                                   aModifiers);

  if (NS_WARN_IF(NS_FAILED(rv))) {
    aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
  }
}
Exemple #26
0
void GlueCommander::output(string seq)
{
	Sequence s (Data::ASCII);
	s.getData().setRef ((char*)seq.c_str(), seq.size());
	out->insert(s);
}
Exemple #27
0
TEST(Sequence, InitializerListConstructor)
{
	Sequence<int> seq {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
	ASSERT_TRUE(seq.size() == 10);
}
Exemple #28
0
void NmerRateMatrix::setNmerEqFreq(const Sequence &nmer,double nmerFreq)
{
  int index=nmer.asInt(alphabetMap);
  eq[index]=nmerFreq;
}
inline size_t EditDistance(const Sequence& s1, const Sequence& s2) {
	return edit_distance(s1.str(), s2.str());
}
Exemple #30
0
	bool isEmpty() {
		return seq.isEmpty();
	}