Beispiel #1
0
int main()
{
    // FRAGMENT(example)
    // The horizontal and vertical sequence (database and query).
    seqan::CharString seqH = "The quick BROWN fox jumped again!";
    seqan::CharString seqV =     "thick BROWN boxes of brownies!";
                                     //  ^^^
    // Create seed and print the seeed sequence.
    seqan::Seed<seqan::Simple> seed(11, 7, 14, 10);

    // Perform match extension.
    seqan::Score<int, seqan::Simple> scoringScheme(1, -1, -1);
    extendSeed(seed, seqH, seqV, seqan::EXTEND_BOTH, scoringScheme, 3,
               seqan::UnGappedXDrop());

    // Perform a banded alignment.
    seqan::Align<seqan::CharString> align;
    resize(rows(align), 2);
    assignSource(row(align, 0), infix(seqH, beginPositionH(seed),
                                      endPositionH(seed)));
    assignSource(row(align, 1), infix(seqV, beginPositionV(seed),
                                      endPositionV(seed)));

    // TODO(holtgrew): Use seed diagonals as bands.
    globalAlignment(align, scoringScheme);
    std::cerr << "Resulting alignment\n" << align << "\n";

    // FRAGMENT(footer)
    return 0;
}
Beispiel #2
0
void SimpleTableDump::dumpHeader(std::string name, std::shared_ptr<AbstractTable> table) {
  std::stringstream header;
  std::vector<std::string> names, types;
  std::vector<uint32_t> parts;

  // Get names and types
  for(size_t i=0; i < table->columnCount(); ++i) {
    names.push_back(table->nameOfColumn(i));
    types.push_back(data_type_to_string(table->typeOfColumn(i)));
  }

  // This calculation will break if the width of the value_id changes
  // or someone forgets to simply update the width accordingly in the
  // constructor of the table
  for(size_t i=0; i < table->partitionCount(); ++i) {
    parts.push_back(table->partitionWidth(i));
  }
    
  // Dump and join
  header << std::accumulate(names.begin(), names.end(), std::string(), infix(" | ")) << "\n";
  header << std::accumulate(types.begin(), types.end(), std::string(), infix(" | ")) << "\n";
  std::vector<std::string> allParts;
  for(size_t i=0; i < parts.size(); ++i) {
    auto p = parts[i];
    auto tmp = std::vector<std::string>(p, std::to_string(i) + "_R");
    allParts.insert(allParts.end(), tmp.begin(), tmp.end());
  }
  header << std::accumulate(allParts.begin(), allParts.end(), std::string(), infix(" | ")) << "\n";
  header << "===";

  std::string fullPath = _baseDirectory + "/" + name + "/header.dat";
  std::ofstream data (fullPath, std::ios::out | std::ios::binary);
  data << header.str();
  data.close();
}
Beispiel #3
0
void ProjectSplicedRoi::updateRanges(seqan::GffRecord const & record)
{
    // Get group name (possibly comma separated list).
    seqan::CharString groupNames;
    for (unsigned i = 0; i < length(record.tagNames); ++i)
        if (record.tagNames[i] == groupBy)
            groupNames = record.tagValues[i];
    if (empty(groupNames))
        return;  // Record has no group names.

    // Parse out the group names.
    unsigned beginPos = 0;
    unsigned endPos = 0;
    for (; endPos <= length(groupNames); ++endPos)
    {
        if (endPos == length(groupNames) && beginPos < endPos)  // Ignore empty keys.
        {
            _updateRanges(record, infix(groupNames, beginPos, endPos));
        }
        else if (groupNames[endPos] == ',')
        {
            if (beginPos < endPos)  // Ignore empty keys.
                _updateRanges(record, infix(groupNames, beginPos, endPos));
            beginPos = endPos + 1;
        }
    }
}
Beispiel #4
0
void infix(treeNode *root)
{
    if(root)
    {
	infix(root->lTree);
	printf("%d\t",root -> data);
	infix(root ->rTree);
    }
}
Beispiel #5
0
void infix(tree* root)
{
    if(root)
    {
	infix(root->left);
	printf("%d\t",root -> data);
	infix(root ->right);
    }
}
void infix(Pointer<T> pointer)
{
    if(pointer)
    {
        if(! is_leaf(pointer))  std::cout << "(";
        infix(pointer->left_);
        std::cout << pointer->val_;
        infix(pointer->right_);
        if(! is_leaf(pointer))  std::cout << ")";
    }
}
//fills contingency tables with online pattern matching and kmerToID- method (see above)
void  countFinds (Contingency & allContigs, seqan::StringSet<seqan::DnaString> kmers, Transcriptome transcripts){
    timeval online;
    gettimeofday(&online, NULL);
    double startOnline= (online.tv_sec *1000000) + online.tv_usec;
    // Database are the mRNAs from Transcriptome;
    
    // Define the Aho-Corasick pattern over the kmers
    seqan::Pattern<seqan::StringSet<seqan::DnaString>, seqan::AhoCorasick> pattern(kmers);
    // Search for the kmers database sequence by database sequence.
    //search kmers in down-/upregulated genes
    unsigned id;
    std::cout <<"processing mRNAs"<<'\n';
    for (unsigned i = 0; i < length(transcripts.mRNAset); i++){
        //std::cout <<"processing mRNA number"<<'\t'<< i<<'\n';
        seqan::Finder<seqan::DnaString> finder(transcripts.mRNAset[i]);  // new finder for each seq
        while(find(finder, pattern)){
            
            //assign the hit to the correct kmer sequence by converting the pattern sequence into an ID
            id= kmerToID(infix(finder));
            
            if(transcripts.isReg[i]){
                allContigs.idDN[id].push_back(i);
            }
            else {
                allContigs.idNoDN[id].push_back(i);
            }
        }
    }
    gettimeofday(&online, NULL);
    double endOnline= (online.tv_sec *1000000) + online.tv_usec;
    std::cout << length(kmers) << " kmers checked in " << (endOnline-startOnline)/1000000  << " seconds with Aho-Corasick pattern matching" << '\n';
}
Beispiel #8
0
// Simulate single-end sequencing from a fragment.
void SequencingSimulator::simulateSingleEnd(TRead & seq, TQualities & quals, SequencingSimulationInfo & info,
                                            TFragment const & frag,
                                            MethylationLevels const * levels)
{
    bool isForward;
    if (seqOptions->strands == SequencingOptions::BOTH)
        isForward = (pickRandomNumber(rng, seqan::Pdf<seqan::Uniform<int> >(0, 1)) == 1);
    else
        isForward = (seqOptions->strands == SequencingOptions::FORWARD);

    if (!seqOptions->bsSeqOptions.bsSimEnabled)
    {
        _simulateSingleEnd(seq, quals, info, frag, isForward);
    }
    else
    {
        SEQAN_ASSERT(levels);
        bool bsForward = isForward;
        // Re-pick strandedness of the BS-treated fragment.
        if (seqOptions->bsSeqOptions.bsProtocol != BSSeqOptions::DIRECTIONAL)
            bsForward = (pickRandomNumber(methRng, seqan::Pdf<seqan::Uniform<int> >(0, 1)) == 1);
        _simulateBSTreatment(methFrag, frag, *levels, !bsForward);
        _simulateSingleEnd(seq, quals, info, infix(methFrag, 0, length(methFrag)), isForward);
    }
}
Beispiel #9
0
std::string* allt(int* idel, std::string ideligen) {
  if (*idel > 3 || ideligen == "ifall")
    return new std::string("igen");
  int identifiering = *idel + 1;
  std::string igenom("ihopkoppling");
  int ihop = aning(&identifiering, igenom);
  std::string* ikapp = new std::string("ilning");
  int* illa = ann(identifiering, ikapp);
  std::string* ilska = new std::string("implementering");
  int* imperfekt = advent(identifiering, ilska);
  std::string* inalles = new std::string("inblick");
  int* inblandning = aftonsol(identifiering, inalles);
  std::string* inbromsning = new std::string("indelning");
  std::string indatagenerering = alltigenom(identifiering, inbromsning);
  std::string indentering("indikering");
  int indexering = aldrig(&identifiering, indentering);
  std::string infix("informationsbit");
  std::string* inflygning = alm(&identifiering, infix);
  std::string ing("ingendera");
  int ingalunda = andel(&identifiering, ing);
  std::string* ingenstans = new std::string("ingetdera");
  int* ingenting = allmoge(identifiering, ingenstans);
  std::string* ingnidning = new std::string("initialisering");
  return ingnidning;
} // allt
seqan::String<int> computeScore(TText const & text, TPattern const & pattern)
{
    seqan::String<int> score;
    seqan::resize(score, seqan::length(text), 0);
    for (unsigned i = 0; i < seqan::length(text) - seqan::length(pattern) + 1; ++i)
        score[i] = computeLocalScore(infix(text, i, i + seqan::length(pattern)), pattern);
    return score;
}
Beispiel #11
0
int main(){
	Integer ans;
	char arr[128];
	scanf("%[^\n]", arr);   /* expression */
	ans = infix(arr);
	printf("Answer: ");
	PrintInteger(ans);
	return 0;
}
Beispiel #12
0
void main()
{
	clrscr();

	printf("\n Enter PostFix Expression :");
	flushall();
	gets(expr);

	strcpy(str,infix());
	printf("\n %s",str);
getch();
}
Beispiel #13
0
struct expr *infix(struct expr *left, char *expect)
{
  exprlist_t args;
  int toktype = tok->type;
  char *ident;
  switch (toktype)
  {
    case PLUS: case MINUS: case STAR: case SLASH: case OR: case XOR:
    case LT: case LE: case GT: case GE: case NEQ: case EQ: case AND:
      return binopexpr(left, toktype, expression(lbp(toktype)));
    case LPAREN:
      if (left->exprtype != identtype)
        syntaxerror("calling non-callable expression");
      args = empty_exprlist();
      if (lookahead[0]->type != COMMA && lookahead[0]->type != RPAREN)
        list_push_back(args, expression(0));
      while (lookahead[0]->type == COMMA)
      {
        eat(COMMA);
        list_push_back(args, expression(0));
      }
      eat(RPAREN);
      ident = strdup(left->val.ident);
      left->type = NULL; // To prevent segfaults when freeing the expr
      free_expression(left);
      return funcallexpr(ident, args);
    case LSQBRACKET:
      args = empty_exprlist();
      list_push_back(args, expression(0));
      while (lookahead[0]->type == COMMA)
      {
        eat(COMMA);
        list_push_back(args, expression(0));
      }
      eat(RSQBRACKET);
      return arrayexpr(left, args);
    case DOT:
      eat(IDENTIFIER);
      char *ident = strdup(tok->val);
      return record_access(left, ident);
    case DEREF:
      return make_deref(left);
    default:
      syntaxerror("expected %s, not %s", expect, tok->val);
      next();
      switch (tok->type)
      {
        case ENDOFFILE: return expr_from_val(0);
        default: return infix(left, "expression");
      }
  }
}
Beispiel #14
0
struct expr *expression(int rbp)
{
  next();
  struct expr *left = prefix("expression");
  struct pos pos;
  left->pos = *tok->pos;
  while (rbp < lbp(lookahead[0]->type))
  {
    next();
    pos = left->pos;
    left = infix(left, "expression");
    left->pos.line = pos.line;
    left->pos.charstart = pos.charstart;
    left->pos.len = tok->pos->charstart + tok->pos->len - pos.charstart;
  }
  return left;
}
Beispiel #15
0
/*
 * debug function, used only for view query
 * which will be executed in non-leaf pages in index
 */
Datum
tsquerytree(PG_FUNCTION_ARGS)
{
	QUERYTYPE  *query = (QUERYTYPE *) DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0)));
	INFIX		nrm;
	text	   *res;
	ITEM	   *q;
	int4		len;


	if (query->size == 0)
	{
		res = (text *) palloc(VARHDRSZ);
		VARATT_SIZEP(res) = VARHDRSZ;
		PG_RETURN_POINTER(res);
	}

	q = clean_NOT_v2(GETQUERY(query), &len);

	if (!q)
	{
		res = (text *) palloc(1 + VARHDRSZ);
		VARATT_SIZEP(res) = 1 + VARHDRSZ;
		*((char *) VARDATA(res)) = 'T';
	}
	else
	{
		nrm.curpol = q;
		nrm.buflen = 32;
		nrm.cur = nrm.buf = (char *) palloc(sizeof(char) * nrm.buflen);
		*(nrm.cur) = '\0';
		nrm.op = GETOPERAND(query);
		infix(&nrm, true);

		res = (text *) palloc(nrm.cur - nrm.buf + VARHDRSZ);
		VARATT_SIZEP(res) = nrm.cur - nrm.buf + VARHDRSZ;
		strncpy(VARDATA(res), nrm.buf, nrm.cur - nrm.buf);
		pfree(q);
	}

	PG_FREE_IF_COPY(query, 0);

	PG_RETURN_POINTER(res);
}
Beispiel #16
0
int main()
{
  int totalNodesInTree , inFixArr[20] , preFixArr[20] ;
  tree *root = NULL;
  tree* pred = NULL;
  int sum;
  
  printf("\nEnter length of arr : ");
  scanf("%d",&totalNodesInTree);


  printf("\nEnter values of nodes in preorder\n");
  scanArr(preFixArr,totalNodesInTree);
  printArr(preFixArr,totalNodesInTree);


  printf("\nEnter values of nodes in inorder\n");
  scanArr(inFixArr,totalNodesInTree);
  printArr(inFixArr,totalNodesInTree);


  printf("\n\nPost Fix Order as shown :\n");
  root = toPostFix(inFixArr,preFixArr,0,totalNodesInTree-1,0);
  printf("\n");
  printf("after creating tree :- \n");
  printf("\nPrefix Notation\n");
  prefix(root);
  printf("\nInfix Notation\n");
  infix(root);
  printf("\nPostfix Notation\n");
  postfix(root);
  printf("\n");

  if(isBst(root, &pred)){
    printf("Its BST \n");
  }
  else{
    printf("Its not BST\n");
  }
  printf("Final root pred => %d\n",pred -> data);
  return 0;
}
Beispiel #17
0
int main()
{
    int totalNodesInTree, inFixArr[15],preFixArr[15],nodeToBeDeleted;
  treeNode *root = NULL;
  
  printf("\nEnter length of arr : ");
  scanf("%d",&totalNodesInTree);


  printf("\nEnter values of nodes in preorder\n");
  scanArr(preFixArr,totalNodesInTree);
  printArr(preFixArr,totalNodesInTree);


  printf("\nEnter values of nodes in inorder\n");
  scanArr(inFixArr,totalNodesInTree);
  printArr(inFixArr,totalNodesInTree);


  printf("\n\nPost Fix Order as shown :\n");
  root = toPostFix(inFixArr,preFixArr,0,totalNodesInTree-1,0);
  printf("\n");
  printf("after creating tree :- \n");
  printf("\nPrefix Notation\n");
  prefix(root);
  printf("\nInfix Notation\n");
  infix(root);
  printf("\nPostfix Notation\n");
  postfix(root);
  printf("\n");

/*  printf("Enter node to be deleted :- ");
  scanf("%d",&nodeToBeDeleted);
  root = deleteFromBst(root,nodeToBeDeleted);
*/
  ClearTree(&root);
  printf("After dispose :%d\n",root->data);
  postfix(root);
  printf("\n");

  return 0;
}
Beispiel #18
0
Datum
bqarr_out(PG_FUNCTION_ARGS)
{
	QUERYTYPE  *query = (QUERYTYPE *) PG_DETOAST_DATUM(PG_GETARG_POINTER(0));
	INFIX		nrm;

	if (query->size == 0)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("empty query")));

	nrm.curpol = GETQUERY(query) + query->size - 1;
	nrm.buflen = 32;
	nrm.cur = nrm.buf = (char *) palloc(sizeof(char) * nrm.buflen);
	*(nrm.cur) = '\0';
	infix(&nrm, true);

	PG_FREE_IF_COPY(query, 0);
	PG_RETURN_POINTER(nrm.buf);
}
Beispiel #19
0
Datum
querytree(PG_FUNCTION_ARGS)
{
	QUERYTYPE  *query = (QUERYTYPE *) PG_GETARG_QUERYTYPE_P_COPY(0);
	INFIX		nrm;
	text	   *res;
	ITEM	   *q;
	int4		len;

	if (query->size == 0)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("empty query")));

	q = (ITEM *) palloc(sizeof(ITEM) * query->size);
	memcpy((void *) q, GETQUERY(query), sizeof(ITEM) * query->size);
	len = shorterquery(q, query->size);
	PG_FREE_IF_COPY(query, 0);

	if (len == 0)
	{
		res = (text *) palloc(1 + VARHDRSZ);
		SET_VARSIZE(res, 1 + VARHDRSZ);
		*((char *) VARDATA(res)) = 'T';
	}
	else
	{
		nrm.curpol = q + len - 1;
		nrm.buflen = 32;
		nrm.cur = nrm.buf = (char *) palloc(sizeof(char) * nrm.buflen);
		*(nrm.cur) = '\0';
		infix(&nrm, true);

		res = (text *) palloc(nrm.cur - nrm.buf + VARHDRSZ);
		SET_VARSIZE(res, nrm.cur - nrm.buf + VARHDRSZ);
		memcpy(VARDATA(res), nrm.buf, nrm.cur - nrm.buf);
	}
	pfree(q);

	PG_RETURN_POINTER(res);
}
Beispiel #20
0
int main()
{
  int hight,totalNodesInTree, inFixArr[15],preFixArr[15],nodeToBeDeleted;
  treeNode *root = NULL;
  
  printf("\nEnter length of arr : ");
  scanf("%d",&totalNodesInTree);


  printf("\nEnter values of nodes in preorder\n");
  scanArr(preFixArr,totalNodesInTree);
  printArr(preFixArr,totalNodesInTree);


  printf("\nEnter values of nodes in inorder\n");
  scanArr(inFixArr,totalNodesInTree);
  printArr(inFixArr,totalNodesInTree);


  printf("\n\nPost Fix Order as shown :\n");
  root = toPostFix(inFixArr,preFixArr,0,totalNodesInTree-1,0);
  printf("\n");
  printf("after creating tree :- \n");
  printf("\nPrefix Notation\n");
  prefix(root);
  printf("\nInfix Notation\n");
  infix(root);
  printf("\nPostfix Notation\n");
  postfix(root);
  printf("\n");

//  printf("Enter node to be deleted :- ");
  //scanf("%d",&nodeToBeDeleted);
  //root = deleteFromBst(root,nodeToBeDeleted);

  hight = hightOfBtree(root);
  printf("Hight of Tree is :- %d\n",hight);

  return 0;
}
Beispiel #21
0
void LLVM_Generator::visit (ast::Function_Declaration::Ptr   node) {
    auto& declarator = node->function_declarator();

    // step 1
    apply_indent_();
    out_ << "declare ";

    // step 2: function return type
    out_ << type(node->type());

    // step 3: function name
    out_ << " @" << declarator->name();

    // step 4: function argument list
    out_ << "(";
    infix(out_, ", ", declarator->argument_list(),
        [] (parser::Symbol::Ptr symbol) { return type(symbol->type()); });
    out_ << ")";

    // step 5
    out_ << std::endl;
}
Beispiel #22
0
Datum
ltxtq_out(PG_FUNCTION_ARGS)
{
	ltxtquery  *query = PG_GETARG_LTXTQUERY(0);
	INFIX		nrm;

	if (query->size == 0)
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
				 errmsg("syntax error"),
				 errdetail("Empty query.")));

	nrm.curpol = GETQUERY(query);
	nrm.buflen = 32;
	nrm.cur = nrm.buf = (char *) palloc(sizeof(char) * nrm.buflen);
	*(nrm.cur) = '\0';
	nrm.op = GETOPERAND(query);
	infix(&nrm, true);

	PG_FREE_IF_COPY(query, 0);
	PG_RETURN_POINTER(nrm.buf);
}
Beispiel #23
0
void LLVM_Generator::visit (ast::Function_Call::Ptr          node) {
    std::string register_ref = "%tmp." + to_string(register_reference_.size());
    register_reference_[node] = register_ref;

    auto& function  = node->function();
    auto& arguments = node->argument_list();

    // Step 1: Prepare arguments
    for (auto& argument : node->argument_list()) {
        argument->emit_code(*this);
    }

    // // Step 2: call the function
    // apply_indent_();
    // out_ << register_ref << " = call " << type(function->type()) << " (";
    // infix(out_, ", ", function->argument_list(),
    //     [] (parser::Symbol::Ptr symbol) { return type(symbol->type()); });

    // out_ << ")* @" << function->name() << "(";
    // infix(out_, ", ", arguments,
    //     [&] (ast::Expression::Ptr expr) {
    //         std::string tmp = type(expr->type()) + " " + register_reference_[expr];
    //         return tmp;// register_reference_[expr];
    // });

    // Step 2: call the function
    apply_indent_();
    out_ << register_ref << " = call " << type(function->type());

    out_ << " @" << function->name() << "(";
    infix(out_, ", ", arguments,
        [&] (ast::Expression::Ptr expr) {
            std::string tmp = type(expr->type()) + " " + register_reference_[expr];
            return tmp;// register_reference_[expr];
        });

    out_ << ')' << std::endl;
}
Beispiel #24
0
Datum
tsquery_out(PG_FUNCTION_ARGS)
{
	QUERYTYPE  *query = (QUERYTYPE *) DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0)));
	INFIX		nrm;

	if (query->size == 0)
	{
		char	   *b = palloc(1);

		*b = '\0';
		PG_RETURN_POINTER(b);
	}
	nrm.curpol = GETQUERY(query);
	nrm.buflen = 32;
	nrm.cur = nrm.buf = (char *) palloc(sizeof(char) * nrm.buflen);
	*(nrm.cur) = '\0';
	nrm.op = GETOPERAND(query);
	infix(&nrm, true);

	PG_FREE_IF_COPY(query, 0);
	PG_RETURN_POINTER(nrm.buf);
}
Beispiel #25
0
Datum
querytree(PG_FUNCTION_ARGS)
{
	QUERYTYPE  *query = (QUERYTYPE *) PG_DETOAST_DATUM(PG_GETARG_POINTER(0));
	INFIX		nrm;
	text	   *res;
	ITEM	   *q;
	int4		len;

	if (query->size == 0)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("empty query")));

	q = (ITEM *) palloc(sizeof(ITEM) * query->size);
	memcpy((void *) q, GETQUERY(query), sizeof(ITEM) * query->size);
	len = shorterquery(q, query->size);
	PG_FREE_IF_COPY(query, 0);

	if (len == 0)
	{
		res = cstring_to_text("T");
	}
	else
	{
		nrm.curpol = q + len - 1;
		nrm.buflen = 32;
		nrm.cur = nrm.buf = (char *) palloc(sizeof(char) * nrm.buflen);
		*(nrm.cur) = '\0';
		infix(&nrm, true);
		res = cstring_to_text_with_len(nrm.buf, nrm.cur - nrm.buf);
	}
	pfree(q);

	PG_RETURN_TEXT_P(res);
}
Beispiel #26
0
int main(int argc, char ** argv)
{
    double startTime = 0;

    // Parse command line.
    SakOptions options;
    seqan::ArgumentParser::ParseResult res = parseArgs(options, argc, argv);
    if (res != seqan::ArgumentParser::PARSE_OK)
        return res == seqan::ArgumentParser::PARSE_ERROR;  // 1 on errors, 0 otherwise

    // -----------------------------------------------------------------------
    // Show options.
    // -----------------------------------------------------------------------
    if (options.verbosity >= 2)
    {
        std::cerr << "____OPTIONS___________________________________________________________________\n"
                  << "\n"
                  << "VERBOSITY    " << options.verbosity << "\n"
                  << "IN           " << options.inFastxPath << "\n"
                  << "OUT          " << options.outPath << "\n"
                  << "INFIX BEGIN  " << options.seqInfixBegin << "\n"
                  << "INFIX END    " << options.seqInfixEnd << "\n"
                  << "MAX LEN      " << options.maxLength << "\n"
                  << "READ PATTERN " << options.readPattern << "\n"
                  << "REVCOMP      " << yesNo(options.reverseComplement) << "\n"
                  << "SEQUENCES\n";
        for (unsigned i = 0; i < length(options.seqIndices); ++i)
            std::cerr << "  SEQ  " << options.seqIndices[i] << "\n";
        for (unsigned i = 0; i < length(options.seqIndexRanges); ++i)
            std::cerr << "  SEQS " << options.seqIndexRanges[i].i1 << "-" << options.seqIndexRanges[i].i2 << "\n";
    }

    // -----------------------------------------------------------------------
    // Open Files.
    // -----------------------------------------------------------------------
    seqan::SeqFileIn inFile;
    seqan::SeqFileOut outFile;

    bool openRes = false;
    if (!empty(options.inFastxPath))
        openRes = open(inFile, toCString(options.inFastxPath));
    else
        openRes = open(inFile, std::cin);
    if (!openRes)
    {
        std::cerr << "ERROR: Problem opening input file.\n";
        return 1;
    }

    if (!empty(options.outPath))
        openRes = open(outFile, toCString(options.outPath));
    else
        openRes = open(outFile, std::cout, seqan::Fastq());
    if (!openRes)
    {
        std::cerr << "ERROR: Problem opening output file.\n";
        return 1;
    }

    // Compute index of last sequence to write if any.
    uint64_t endIdx = seqan::maxValue<uint64_t>();
    for (unsigned i = 0; i < length(options.seqIndices); ++i)
        if (endIdx == seqan::maxValue<uint64_t>() || endIdx > options.seqIndices[i] + 1)
            endIdx = options.seqIndices[i] + 1;
    for (unsigned i = 0; i < length(options.seqIndexRanges); ++i)
        if (endIdx == seqan::maxValue<uint64_t>() || endIdx > options.seqIndexRanges[i].i2)
            endIdx = options.seqIndexRanges[i].i2;
    if (options.verbosity >= 2)
        std::cerr << "Sequence end idx: " << endIdx << "\n";

    // -----------------------------------------------------------------------
    // Read and Write Filtered.
    // -----------------------------------------------------------------------
    startTime = seqan::sysTime();

    unsigned idx = 0;
    uint64_t charsWritten = 0;
    seqan::CharString id;
    seqan::CharString seq;
    seqan::CharString quals;
    while (!atEnd(inFile) && charsWritten < options.maxLength && idx < endIdx)
    {
        try
        {
            readRecord(id, seq, quals, inFile);
        }
        catch (seqan::ParseError const & e)
        {
            std::cerr << "ERROR: Problem reading file: " << e.what() << "\n";
            return 1;
        }

        // Check whether to write out sequence.
        bool writeOut = false;
        if (empty(options.seqIndices) && empty(options.seqIndexRanges))
            writeOut = true;
        // One of options.seqIndices.
        if (!writeOut)
        {
            for (unsigned i = 0; i < length(options.seqIndices); ++i)
            {
                if (options.seqIndices[i] == idx)
                {
                    writeOut = true;
                    break;
                }
            }
        }
        // One of options.seqIndexRanges.
        if (!writeOut)
        {
            for (unsigned i = 0; i < length(options.seqIndexRanges); ++i)
            {
                if (idx >= options.seqIndexRanges[i].i1 && idx < options.seqIndexRanges[i].i2)
                {
                    writeOut = true;
                    break;
                }
            }
        }
        // Name pattern matches.
        if (!writeOut && !empty(options.readPattern))
        {
            unsigned l = length(options.readPattern);
            if (l > length(id))
                l = length(id);
            if (prefix(id, l) == prefix(options.readPattern, l))
                writeOut = true;
        }

        // Write out if we want this.
        if (writeOut)
        {
            // Get begin and end index of infix to write out.
            uint64_t infixBegin = 0;
            if (options.seqInfixBegin != seqan::maxValue<uint64_t>())
                infixBegin = options.seqInfixBegin;
            if (infixBegin > length(seq))
                infixBegin = length(seq);
            uint64_t infixEnd = length(seq);
            if (options.seqInfixEnd < length(seq))
                infixEnd = options.seqInfixEnd;
            if (infixEnd < infixBegin)
                infixEnd = infixBegin;
            if (options.verbosity >= 3)
                std::cerr << "INFIX\tbegin:" << infixBegin << "\tend:" << infixEnd << "\n";

            if (options.reverseComplement)
            {
                seqan::Dna5String seqCopy = seq;
                reverseComplement(seqCopy);
                reverse(quals);
                infixEnd = length(seq) - infixEnd;
                infixBegin = length(seq) - infixBegin;
                std::swap(infixEnd, infixBegin);

                writeRecord(outFile, id, infix(seqCopy, infixBegin, infixEnd), infix(quals, infixBegin, infixEnd));
            }
            else
                writeRecord(outFile, id, infix(seq, infixBegin, infixEnd), infix(quals, infixBegin, infixEnd));
        }

        // Advance counter idx.
        idx += 1;
    }

    if (options.verbosity >= 2)
        std::cerr << "Took " << (seqan::sysTime() - startTime) << " s\n";

    return 0;
}
Beispiel #27
0
static void
infix(INFIX *in, bool first)
{
	if (in->curpol->type == VAL)
	{
		RESIZEBUF(in, 11);
		sprintf(in->cur, "%d", in->curpol->val);
		in->cur = strchr(in->cur, '\0');
		in->curpol--;
	}
	else if (in->curpol->val == (int4) '!')
	{
		bool		isopr = false;

		RESIZEBUF(in, 1);
		*(in->cur) = '!';
		in->cur++;
		*(in->cur) = '\0';
		in->curpol--;
		if (in->curpol->type == OPR)
		{
			isopr = true;
			RESIZEBUF(in, 2);
			sprintf(in->cur, "( ");
			in->cur = strchr(in->cur, '\0');
		}
		infix(in, isopr);
		if (isopr)
		{
			RESIZEBUF(in, 2);
			sprintf(in->cur, " )");
			in->cur = strchr(in->cur, '\0');
		}
	}
	else
	{
		int4		op = in->curpol->val;
		INFIX		nrm;

		in->curpol--;
		if (op == (int4) '|' && !first)
		{
			RESIZEBUF(in, 2);
			sprintf(in->cur, "( ");
			in->cur = strchr(in->cur, '\0');
		}

		nrm.curpol = in->curpol;
		nrm.buflen = 16;
		nrm.cur = nrm.buf = (char *) palloc(sizeof(char) * nrm.buflen);

		/* get right operand */
		infix(&nrm, false);

		/* get & print left operand */
		in->curpol = nrm.curpol;
		infix(in, false);

		/* print operator & right operand */
		RESIZEBUF(in, 3 + (nrm.cur - nrm.buf));
		sprintf(in->cur, " %c %s", op, nrm.buf);
		in->cur = strchr(in->cur, '\0');
		pfree(nrm.buf);

		if (op == (int4) '|' && !first)
		{
			RESIZEBUF(in, 2);
			sprintf(in->cur, " )");
			in->cur = strchr(in->cur, '\0');
		}
	}
}
 void infix_print()  const { infix(root_);   }
Beispiel #29
0
namespace cat
{

    //////////////////////////////////////////////////////////////////////////////////
    //
    // identity function
    //

    struct Identity
    {
        using function_type = placeholders::_a(placeholders::_a);

        template <typename T>
        constexpr auto
        operator()(T &&x) const noexcept
        {
            return std::forward<T>(x);
        }
    };

    constexpr Identity identity = {};


    //////////////////////////////////////////////////////////////////////////////////
    //
    // make_function
    //

    template<typename F>
    auto constexpr make_function(F &&f)
    {
        return std::function<typename function_type<F>::type>(std::forward<F>(f));
    }


    //////////////////////////////////////////////////////////////////////////////////
    //
    // first, second, elem<> on pair/tuple...:
    //

    struct First_
    {
        using function_type = placeholders::_a(std::pair<placeholders::_a, placeholders::_b>);

        template <typename P>
        constexpr decltype(auto)
        operator()(P && p) const noexcept
        {
            return std::get<0>(std::forward<P>(p));
        }

    } constexpr first = First_{};


    struct Second_
    {
        using function_type = placeholders::_b(std::pair<placeholders::_a, placeholders::_b>);

        template <typename P>
        constexpr decltype(auto)
        operator()(P &&p) const noexcept
        {
            return std::get<1>(std::forward<P>(p));
        }

    } constexpr second = Second_{};


    template <size_t N>
    struct Elem_
    {
        using function_type = placeholders::unspec(std::tuple<placeholders::unspec>);

        template <typename Tuple>
        constexpr decltype(auto)
        operator()(Tuple && t) const noexcept
        {
            return std::get<N>(std::forward<Tuple>(t));
        }
    };


#if defined(__clang__)

    template <size_t N>
    constexpr auto elem = Elem_<N>{};

#endif

    //////////////////////////////////////////////////////////////////////////////////
    //
    // Callable_ with partial application support
    //

    namespace details
    {
        //
        // Argument decay on the basis of the target signature.
        //

        template <typename F, size_t Idx, typename T>
        struct currying_decay
        {
            using Tp = arg_type_at_t<Idx, F>;

            using type = typename std::conditional<
                            std::is_lvalue_reference<Tp>::value,
                            T, std::decay_t<T> >::type;
        };

        template <typename F, size_t Idx, typename T>
        using currying_decay_t = typename currying_decay<F, Idx, T>::type;
    }


    template <typename F, typename ...Ts>
    struct Callable_
    {
        using function_type =
            typename meta::partial_function_type<
                typename function_type<F>::type, sizeof...(Ts)>::type;

        template <typename ...Xs>
        constexpr explicit Callable_(F fun, std::tuple<Xs...> args = std::tuple<Xs...>{})
        : fun_(std::move(fun))
        , args_(std::move(args))
        { }

        template <typename ...Xs>
        auto operator()(Xs && ... xs) const
        {
            constexpr size_t N = function_arity<F>::value - sizeof...(Ts);
            static_assert(N >= sizeof...(Xs), "Too many argument!");
            return eval_(std::integral_constant<size_t, N - sizeof...(Xs)>(), std::make_index_sequence<sizeof...(Xs)>(), std::forward<Xs>(xs)...);
        }

        template <typename ...Xs>
        auto apply(Xs && ... xs) const
        {
            constexpr size_t N = function_arity<F>::value - sizeof...(Ts);
            static_assert(N >= sizeof...(Xs), "Too many argument!");
            return apply_(std::integral_constant<size_t, N - sizeof...(Xs)>(), std::make_index_sequence<sizeof...(Xs)>(), std::forward<Xs>(xs)...);
        }

    private:
        template <size_t ...N, typename ...Xs>
        auto eval_(std::integral_constant<size_t, 0>, std::index_sequence<N...>, Xs &&...xs) const
        {
            return tuple_apply(fun_, std::tuple_cat(args_, std::forward_as_tuple(std::forward<Xs>(xs)...)));
        }

        template <size_t I, size_t ...N, typename ...Xs>
        auto eval_(std::integral_constant<size_t, I>, std::index_sequence<N...>, Xs &&...xs) const
        {
            return Callable_<F, Ts..., details::currying_decay_t<function_type, N, Xs>...>(
                        fun_, std::tuple_cat(args_, std::forward_as_tuple(std::forward<Xs>(xs)...)));
        }

        template <size_t I, size_t ...N, typename ...Xs>
        auto apply_(std::integral_constant<size_t, I>, std::index_sequence<N...>, Xs &&...xs) const
        {
            return Callable_<F, Ts..., details::currying_decay_t<function_type, N, Xs>...>(
                        fun_, std::tuple_cat(args_, std::forward_as_tuple(std::forward<Xs>(xs)...)));
        }

        F fun_;
        std::tuple<Ts...> args_;
    };


    template<typename F>
    constexpr auto curry(F && f)
    {
        return Callable_<std::decay_t<F>>(std::forward<F>(f));
    }
    template<typename F, typename ...Ts>
    constexpr auto curry(F && f, Ts&& ...xs)
    {
        return curry(std::forward<F>(f)).apply(std::forward<Ts>(xs)...);
    }


    //////////////////////////////////////////////////////////////////////////////////
    //
    // Generic callable (for generic lambdas and polymorphic C++ callable objects)
    //

    template <typename Fun, typename F>
    struct Callable_as_
    {
        using function_type = Fun;

        constexpr Callable_as_()
        : fun_{}
        { }

        constexpr Callable_as_(F f)
        : fun_(std::move(f))
        { }

        template <typename ...Ts>
        constexpr decltype(auto)
        operator()(Ts&& ... xs) const
        {
            return fun_(std::forward<Ts>(xs)...);
        }

        F fun_;
    };

    template <typename Fun, typename F>
    constexpr auto curry_as(F && f)
    {
        return curry(Callable_as_<Fun, std::decay_t<F>>(std::forward<F>(f)));
    };
    template <typename Fun, typename F, typename ...Ts>
    constexpr auto curry_as(F && f, Ts && ... xs)
    {
        return curry_as<Fun>(std::forward<F>(f)).apply(std::forward<Ts>(xs)...);
    };


    //////////////////////////////////////////////////////////////////////////////////
    //
    // Compose_: functional composition of callable types
    //

    template <typename F, typename G, typename = void>  struct Compose_;

    template <typename F, typename G>
    struct Compose_<F, G, std::enable_if_t<function_arity<G>::value != 0>>
    {
       using function_type = meta::compose_function_type_t<
                                function_type_t<F>,
                                function_type_t<G>>;

        constexpr Compose_(F f, G g)
        : f_(std::move(f))
        , g_(std::move(g))
        { }

        template <typename T, typename ...Ts>
        constexpr decltype(auto)
        operator()(T &&x, Ts && ...xs) const
        {
            return f_( g_(std::forward<T>(x)), std::forward<Ts>(xs)...);
        }

        F f_;
        G g_;
    };

    template <typename F, typename G>
    struct Compose_<F, G, std::enable_if_t<function_arity<G>::value == 0>>
    {
        using function_type = meta::compose_function_type_t<
                                function_type_t<F>,
                                function_type_t<G>>;

        constexpr Compose_(F f, G g)
        : f_(std::move(f))
        , g_(std::move(g))
        { }

        template <typename ...Ts>
        constexpr decltype(auto)
        operator()(Ts && ...xs) const
        {
            return f_( g_(), std::forward<Ts>(xs)...);
        }

        F f_;
        G g_;
    };

    template <typename F, typename G>
    constexpr auto compose(F && f, G && g)
    {
        static_assert(is_callable<F>::value && is_callable<G>::value,
                      "compose: F and G must be callable types");

        return Compose_<std::decay_t<F>,std::decay_t<G>>{ std::forward<F>(f), std::forward<G>(g) };
    }

    template <typename F, typename G,
              std::enable_if_t<is_callable<F>::value && is_callable<G>::value> * = nullptr>
    constexpr auto operator^(F && f, G && g)
    {
        return compose(std::forward<F>(f), std::forward<G>(g));
    }

    //////////////////////////////////////////////////////////////////////////////////
    //
    // flip:
    //

    template <typename F>
    struct Flip_
    {
        using function_type = meta::flip_function_type_t<function_type_t<F>>;

        constexpr Flip_(F fun)
        : fun_(std::move(fun))
        { }

        template <typename T1, typename T2, typename ...Ts>
        constexpr decltype(auto)
        operator()(T1 && x1, T2 && x2, Ts && ...xs) const
        {
            return fun_(std::forward<T2>(x2),
                        std::forward<T1>(x1),
                        std::forward<Ts>(xs)...);
        }

    private:
        F fun_;
    };

    template <typename F>
    constexpr auto flip(F && fun_)
    {
        return Flip_<std::decay_t<F>>{ std::forward<F>(fun_) };
    };


    //////////////////////////////////////////////////////////////////////////////////
    //
    // on (infix version):
    //

    template <typename F, typename G>
    struct On_
    {
        using function_type = meta::on_function_type_t<function_type_t<F>,
                                                 function_type_t<G>>;

        constexpr On_(F f, G g)
        : f_(std::move(f))
        , g_(std::move(g))
        { }

        template <typename T1, typename T2, typename ...Ts>
        constexpr decltype(auto)
        operator()(T1 && x1, T2 && x2, Ts && ...xs) const
        {
            return f_(g_(std::forward<T1>(x1)),
                      g_(std::forward<T2>(x2)), std::forward<Ts>(xs)...);
        }

    private:
        F f_;
        G g_;
    };

    struct on_
    {
        template <typename F, typename G>
        constexpr auto
        operator()(F f_, G g_) const
        {
            return On_<F,G>{ std::move(f_), std::move(g_) };
        };
    };

    constexpr auto on = infix(on_{});

    //////////////////////////////////////////////////////////////////////////////////
    //
    // constant
    //

    template <typename T>
    struct Constant_
    {
        using function_type = T(placeholders::unspec);

        template <typename Tp>
        constexpr T operator()(Tp const &) const
        {
            return value_;
        }

        T value_;
    };

    template <typename T>
    constexpr auto constant(T && value)
    {
        return Constant_<std::decay_t<T>>{ std::forward<T>(value) };
    }

} // namespace cat
Beispiel #30
0
/*
 * recursive walk on tree and print it in
 * infix (human-readable) view
 */
static void
infix(INFIX * in, bool first)
{
	if (in->curpol->type == VAL)
	{
		char	   *op = in->op + in->curpol->distance;

		RESIZEBUF(in, in->curpol->length * 2 + 2 + 5);
		*(in->cur) = '\'';
		in->cur++;
		while (*op)
		{
			if (*op == '\'')
			{
				*(in->cur) = '\\';
				in->cur++;
			}
			*(in->cur) = *op;
			op++;
			in->cur++;
		}
		*(in->cur) = '\'';
		in->cur++;
		if (in->curpol->weight)
		{
			*(in->cur) = ':';
			in->cur++;
			if (in->curpol->weight & (1 << 3))
			{
				*(in->cur) = 'A';
				in->cur++;
			}
			if (in->curpol->weight & (1 << 2))
			{
				*(in->cur) = 'B';
				in->cur++;
			}
			if (in->curpol->weight & (1 << 1))
			{
				*(in->cur) = 'C';
				in->cur++;
			}
			if (in->curpol->weight & 1)
			{
				*(in->cur) = 'D';
				in->cur++;
			}
		}
		*(in->cur) = '\0';
		in->curpol++;
	}
	else if (in->curpol->val == (int4) '!')
	{
		bool		isopr = false;

		RESIZEBUF(in, 1);
		*(in->cur) = '!';
		in->cur++;
		*(in->cur) = '\0';
		in->curpol++;
		if (in->curpol->type == OPR)
		{
			isopr = true;
			RESIZEBUF(in, 2);
			sprintf(in->cur, "( ");
			in->cur = strchr(in->cur, '\0');
		}
		infix(in, isopr);
		if (isopr)
		{
			RESIZEBUF(in, 2);
			sprintf(in->cur, " )");
			in->cur = strchr(in->cur, '\0');
		}
	}
	else
	{
		int4		op = in->curpol->val;
		INFIX		nrm;

		in->curpol++;
		if (op == (int4) '|' && !first)
		{
			RESIZEBUF(in, 2);
			sprintf(in->cur, "( ");
			in->cur = strchr(in->cur, '\0');
		}

		nrm.curpol = in->curpol;
		nrm.op = in->op;
		nrm.buflen = 16;
		nrm.cur = nrm.buf = (char *) palloc(sizeof(char) * nrm.buflen);

		/* get right operand */
		infix(&nrm, false);

		/* get & print left operand */
		in->curpol = nrm.curpol;
		infix(in, false);

		/* print operator & right operand */
		RESIZEBUF(in, 3 + (nrm.cur - nrm.buf));
		sprintf(in->cur, " %c %s", op, nrm.buf);
		in->cur = strchr(in->cur, '\0');
		pfree(nrm.buf);

		if (op == (int4) '|' && !first)
		{
			RESIZEBUF(in, 2);
			sprintf(in->cur, " )");
			in->cur = strchr(in->cur, '\0');
		}
	}
}