Example #1
0
 int top() {
     if(v.empty()) return -1;
     return v.back();
 }
Example #2
0
void traverseAstree(astree* root) {
    if( flag == 0 ) {
        symbol_stack.push_back(nullptr);
        flag++;
    }
    for (size_t a = 0; a < root->children.size(); ++a) {
        int sym = root->children[a]->symbol;
        astree* curr = root->children[a];
        switch(sym) {
        case TOK_VARDECL:
        case '=':
            travVardecl(curr);
            break;
        case TOK_IF:
        case TOK_WHILE:
            validCompare(curr);
            symbol_stack.push_back(nullptr);
            blockcount++;
            traverseAstree(curr->children[1]);
            blockcount--;
            symbol_stack.pop_back();
            break;
        case TOK_IFELSE:
            validCompare(curr);
            for(size_t i = 0; i<curr->children.size(); i++) {
                symbol_stack.push_back(nullptr);
                blockcount++;
                traverseAstree(curr->children[i]);
                blockcount--;
                symbol_stack.pop_back();
            }
            break;
        case TOK_FUNCTION:
        {
            root->children[a]->children[1]->block = blockcount+1;
            symbol* newFunc = create_symbol(root->children[a]);
            blockcount++;
            newFunc->attributes.set(ATTR_function);
            switch(curr->children[0]->symbol) {
            case TOK_INT:
                newFunc->attributes.set(ATTR_int);
                break;
            case TOK_STRING:
                newFunc->attributes.set(ATTR_string);
                break;
            case TOK_CHAR:
                newFunc->attributes.set(ATTR_char);
                break;
            case TOK_BOOL:
                newFunc->attributes.set(ATTR_bool);
                break;
            case TOK_TYPEID:
                newFunc->attributes.set(ATTR_struct);
                newFunc->attributes.set(ATTR_typeid);
                newFunc->type_id =*root->children[a]->children[0]->lexinfo;
                break;
            }
            newFunc->parameters = new vector<symbol*>;
            for(size_t i = 0; i<curr->children[1]->children.size(); i++) {
                astree* param_node = curr->children[1]->children[i];
                symbol* param = create_symbol(param_node->children[0]);
                param->attributes.set(ATTR_variable);
                param->attributes.set(ATTR_lval);
                param->attributes.set(ATTR_param);
                int paramSym = param_node->symbol;
                switch(paramSym) {
                case TOK_INT:
                    param->attributes.set(ATTR_int);
                    break;
                case TOK_CHAR:
                    param->attributes.set(ATTR_char);
                    break;
                case TOK_STRING:
                    param->attributes.set(ATTR_string);
                    break;
                case TOK_BOOL:
                    param->attributes.set(ATTR_bool);
                    break;
                }
                newFunc->parameters->push_back(param);
            }
            if(symbol_stack.back() == nullptr || symbol_stack.empty()) {
                symbol_table* tab = new symbol_table();
                tab->insert(symbol_entry(curr->children[0]->children[0]->
                                         lexinfo,newFunc));
                symbol_stack.pop_back();
                symbol_stack.push_back(tab);
            } else {
                symbol_stack.back()->insert(symbol_entry(curr->children[0]->
                                            children[0]->lexinfo,newFunc));
            }
            dumpToFile(file_sym, newFunc, curr->children[0]->children[0]);
            symbol_stack.push_back(nullptr);
            if (curr->children[1]->children.size() != 0) {
                dumpParams(newFunc, curr->children[1]);
            }
            int funcSym;
            switch (curr->children[0]->symbol) {
            case TOK_INT:
                funcSym = TOK_INTCON;
                break;
            case TOK_CHAR:
                funcSym = TOK_CHARCON;
                break;
            case TOK_STRING:
                funcSym = TOK_STRINGCON;
                break;
            case TOK_BOOL:
                funcSym = TOK_BOOL;
                break;
            }
            traverseFunc(curr->children[2], funcSym);
            blockcount--;
            symbol_stack.pop_back();
            break;
        }
        case TOK_STRUCT:
        {
            astree *temp = root->children[a];
            symbol *newSym = create_symbol(temp->children[0]);
            newSym->attributes.set(ATTR_struct);
            newSym->attributes.set(ATTR_typeid);
            newSym->type_id = *temp->children[0]->lexinfo;
            dumpToFile(file_sym,newSym,temp->children[0]);
            if(symbol_stack.back() == nullptr || symbol_stack.empty()) {
                symbol_table* tab = new symbol_table();
                tab->insert(symbol_entry(temp->children[0]->lexinfo,newSym));
                symbol_stack.push_back(tab);
            } else {
                symbol_stack.back()->insert(symbol_entry(temp->children[0]->
                                            lexinfo,newSym));
            }
            newSym->fields = new symbol_table();
            for(size_t i = 1; i<temp->children.size(); i++) {
                symbol *tempSym = create_symbol(temp->children[i]->
                                                children[0]);
                tempSym->attributes.set(ATTR_field);
                switch(temp->children[i]->symbol) {
                case TOK_INT:
                    tempSym->attributes.set(ATTR_int);
                    break;
                case TOK_CHAR:
                    tempSym->attributes.set(ATTR_char);
                    break;
                case TOK_BOOL:
                    tempSym->attributes.set(ATTR_bool);
                    break;
                case TOK_STRING:
                    tempSym->attributes.set(ATTR_string);
                    break;
                case TOK_TYPEID:
                    tempSym->attributes.set(ATTR_typeid);
                    tempSym->attributes.set(ATTR_struct);
                    break;
                }
                newSym->fields->insert(symbol_entry(temp->children[i]->
                                                    children[0]->lexinfo,tempSym));
            }
            dumpFields(newSym,temp);
            break;
        }
        case TOK_CALL:
            checkCall(curr);
            break;
        case TOK_PROTOTYPE:
        {
            symbol* newFunc = create_symbol(root->children[a]);
            blockcount++;
            newFunc->attributes.set(ATTR_function);
            switch(curr->children[0]->symbol) {
            case TOK_INT:
                newFunc->attributes.set(ATTR_int);
                break;
            case TOK_STRING:
                newFunc->attributes.set(ATTR_string);
                break;
            case TOK_CHAR:
                newFunc->attributes.set(ATTR_char);
                break;
            case TOK_BOOL:
                newFunc->attributes.set(ATTR_bool);
                break;
            case TOK_TYPEID:
                newFunc->attributes.set(ATTR_struct);
                newFunc->attributes.set(ATTR_typeid);
                newFunc->type_id =*root->children[a]->children[0]->lexinfo;
                break;
            }
            newFunc->parameters = new vector<symbol*>;
            for(size_t i = 0; i<curr->children[1]->children.size(); i++) {
                astree* param_node = curr->children[1]->children[i];
                symbol* param = create_symbol(param_node->children[0]);
                param->attributes.set(ATTR_variable);
                param->attributes.set(ATTR_lval);
                param->attributes.set(ATTR_param);
                int paramSym = param_node->symbol;
                switch(paramSym) {
                case TOK_INT:
                    param->attributes.set(ATTR_int);
                    break;
                case TOK_CHAR:
                    param->attributes.set(ATTR_char);
                    break;
                case TOK_STRING:
                    param->attributes.set(ATTR_string);
                    break;
                case TOK_BOOL:
                    param->attributes.set(ATTR_bool);
                    break;
                }
                newFunc->parameters->push_back(param);
            }
            if(symbol_stack.back() == nullptr || symbol_stack.empty()) {
                symbol_table* tab = new symbol_table();
                tab->insert(symbol_entry(curr->children[0]->children[0]->
                                         lexinfo,newFunc));
                symbol_stack.pop_back();
                symbol_stack.push_back(tab);
            } else {
                symbol_stack.back()->insert(symbol_entry(curr->children[0]->
                                            children[0]->lexinfo,newFunc));
            }
            dumpToFile(file_sym, newFunc, curr->children[0]->children[0]);
            symbol_stack.push_back(nullptr);
            if (curr->children[1]->children.size() != 0) {
                dumpParams(newFunc, curr->children[1]);
            }
            int funcSym;
            switch (curr->children[0]->symbol) {
            case TOK_INT:
                funcSym = TOK_INTCON;
                break;
            case TOK_CHAR:
                funcSym = TOK_CHARCON;
                break;
            case TOK_STRING:
                funcSym = TOK_STRINGCON;
                break;
            case TOK_BOOL:
                funcSym = TOK_BOOL;
                break;
            }
            blockcount--;
            break;
        }
        }
    }
}
box refine_CE_with_nlopt_core(box counterexample, vector<Enode*> const & opt_ctrs, vector<Enode*> const & side_ctrs) {
    // Plug-in `a` into the constraint and optimize `b` in the counterexample `M` by solving:
    //
    //    ∃ y_opt ∈ I_y. ∀ y ∈ I_y. f(a, y_opt) >= f(a, y) — (2)
    //
    // using local optimizer (i.e. nlopt).
    // Let `M’ = (a, b_opt)` be a model for (2).

    DREAL_LOG_DEBUG << "================================" << endl;
    DREAL_LOG_DEBUG << "  Before Refinement              " << endl;
    DREAL_LOG_DEBUG << "================================" << endl;
    DREAL_LOG_DEBUG << counterexample << endl;
    DREAL_LOG_DEBUG << "================================" << endl;
    static bool initialized = false;
    static vector<double> lb, ub, init;
    init.clear();
    for (Enode * e : counterexample.get_vars()) {
        if (e->isForallVar()) {
            if (!initialized) {
                lb.push_back(e->getDomainLowerBound());
                ub.push_back(e->getDomainUpperBound());
            }
            init.push_back(counterexample[e].mid());
            DREAL_LOG_DEBUG << lb.back() << " <= " << init.back() << " <= " << ub.back() << endl;
        }
    }
    auto const n = init.size();
    static nlopt::opt opt(nlopt::LD_SLSQP, n);
    if (!initialized) {
        opt.set_lower_bounds(lb);
        opt.set_upper_bounds(ub);
        // set tollerance
        // TODO(soonhok): set precision
        // opt.set_xtol_rel(0.0001);
        opt.set_xtol_abs(0.001);
        opt.set_maxtime(0.01);
        initialized = true;
    }

    opt.remove_equality_constraints();
    opt.remove_inequality_constraints();

    // set objective function
    vector<tuple<Enode *, box const &, bool> *> extra_vec;
    Enode * e = opt_ctrs[0];
    bool polarity = false;
    while (e->isNot()) {
        e = e->get1st();
        polarity = !polarity;
    }
    auto extra = new tuple<Enode *, box const &, bool>(e, counterexample, polarity);
    extra_vec.push_back(extra);
    opt.set_min_objective(nlopt_obj, extra);
    opt.add_inequality_constraint(nlopt_side_condition, extra);
    DREAL_LOG_DEBUG << "objective function is added: " << e << endl;

    // set side conditions
    for (Enode * e : side_ctrs) {
        bool polarity = false;
        while (e->isNot()) {
            e = e->get1st();
            polarity = !polarity;
        }
        auto extra = new tuple<Enode *, box const &, bool>(e, counterexample, polarity);
        extra_vec.push_back(extra);
        DREAL_LOG_DEBUG << "refine_counterexample_with_nlopt: Side condition is added: " << e << endl;
        if (e->isEq()) {
            opt.add_equality_constraint(nlopt_side_condition, extra);
        } else if (e->isLt() || e->isLeq() || e->isGt() || e->isGeq()) {
            opt.add_inequality_constraint(nlopt_side_condition, extra);
        }
    }
    try {
        vector<double> output = opt.optimize(init);
        unsigned i = 0;
        for (Enode * e : counterexample.get_vars()) {
            if (e->isForallVar()) {
                counterexample[e] = output[i];
                i++;
            }
        }
    } catch (nlopt::roundoff_limited & e) {
    } catch (std::runtime_error & e) {
        DREAL_LOG_DEBUG << e.what() << endl;
    }

    for (auto extra : extra_vec) {
        delete extra;
    }
    DREAL_LOG_DEBUG << "================================" << endl;
    DREAL_LOG_DEBUG << "  After Refinement              " << endl;
    DREAL_LOG_DEBUG << "================================" << endl;
    DREAL_LOG_DEBUG << counterexample << endl;
    DREAL_LOG_DEBUG << "================================" << endl;
    return counterexample;
}
int main(int argc, char *argv[]) {

	time(&startTime);	

	/******************************************************************************
	 *                 === PARSE THE COMMAND LINE OPTIONS ===
	 ******************************************************************************/
	Options defaults;
  
  	Options opt = parseOptions(argc, argv, defaults);
  	if (opt.errorFlag) {
  		cerr << endl;
  		cerr << "The program terminated with errors:" << endl;
  		cerr << endl;
  		cerr << opt.errorMessages << endl;
  		cerr << endl;
  		cerr << opt.OPerrors << endl;
  
  		usage();
  		exit(1);
  	}	

	ofstream fout;
	fout.open((opt.proteinId + ".out" ).c_str());

	if(!fout.is_open()) {
		cerr << "Unable to open " << opt.proteinId << endl;
		exit(0);
	}

	System sys;
	if(!sys.readPdb(opt.pdbFile)) {
		cerr << "Unable to read from " << opt.pdbFile << endl;
		exit(0);
	}

	// Read topology file to get Charge for each atom
	CharmmTopologyReader topRead(opt.topFile);
	if(!topRead.read()) {
		cerr << "Unable to read topology file " << opt.topFile << endl;
		exit(0);
	}

	setCharge(sys,topRead);
/*
	CharmmSystemBuilder CSB(sys,opt.topFile,opt.parFile,opt.solvFile);
	CSB.setSolvent("CHEX");
	CSB.setBuildNonBondedInteractions(false);

	if(!CSB.buildSystemFromPDB(opt.pdbFile)) {
		cerr << "Unable to build system from " << opt.pdbFile << endl;
		exit(0);
	}

	sys.buildAllAtoms();
*/
	// Add hydrogen bond term
	HydrogenBondBuilder hb(sys, opt.hBondFile);
	if(!hb.buildInteractions(10)) {
		cerr << "Unable to build hbond interactions for " << opt.pdbFile << endl;
		exit(0);
	}
	// print format for the logfile
	/*
	tmsegment A,1 233 238
	tmsegment B,2 233 238
	tmsegment C,3 233 238

	sequence 1 GKDIAFIVHGYGGLVFMDLLVRR
	sequence 2 GRDIGFIVHGYGGLVFMDLLVRR
	sequence 3 GRDITFIYHGYGGLVFMDLLVRR

	interfacial 1 00000110110010011001001
	interfacial 2 00100110110010011001001
	interfacial 3 01000110110010011001001

	allhbonds B,235,HA2:A,234,O=2.84814;B,238,HA1:A,234,O=3.40832;A,235,HA2:B,234,O=2.84814A,238,HA1:B,234,O=3.40832;B,235,HA2:A,234,O=2.84814;B,238,HA1:A,234,O=3.40832;A,235,HA2:B,234,O=2.84814A,238,HA1:B,234,O=3.40832;B,235,HA2:A,234,O=2.84814;B,238,HA1:A,234,O=3.40832;A,235,HA2:B,234,O=2.84814A,238,HA1:B,234,O=3.40832

	hbonds 1 2 B,235,HA2:A,234,O=2.84814;B,238,HA1:A,234,O=3.40832;A,235,HA2:B,234,O=2.84814A,238,HA1:B,234,O=3.40832
	hbonds 1 3 B,235,HA2:A,234,O=2.84814;B,238,HA1:A,234,O=3.40832;A,235,HA2:B,234,O=2.84814A,238,HA1:B,234,O=3.40832
	hbonds 2 3 B,235,HA2:A,234,O=2.84814;B,238,HA1:A,234,O=3.40832;A,235,HA2:B,234,O=2.84814A,238,HA1:B,234,O=3.40832
	*/

	// create segments;
	for(int i = 0; i < opt.segment.size(); i++) {
		vector<string> toks = MslTools::tokenize(opt.segment[i]);
		segments.push_back(new Segment(sys,toks[0],toks[1],MslTools::toInt(toks[2]),MslTools::toInt(toks[3])));
		fout << "tmsegment " << toks[0] << "," << toks[1] << " " << toks[2] << " " << toks[3] << " " << segments.back()->getSequence() << endl;
		mappedSegments[toks[0] + "," + toks[1]] = segments.back();
	}

	EnergySet* Eset = sys.getEnergySet();
	vector<Hbond*> interhelicalHbonds;
	getInterHelicalHbonds(Eset,interhelicalHbonds);

	//fout << "allhbonds "; 
	//for(int i = 0; i < interhelicalHbonds.size(); i++) {
	//	fout << interhelicalHbonds[i]->getFormattedLine() << ";";
	//}
	//fout << endl;

	// map hbonds based on the helices
	map<string,vector<Hbond*> > hbondsMapped;
	for(int i = 0; i < interhelicalHbonds.size(); i++) {
		string seg1 =  interhelicalHbonds[i]->getDonor()->getChainId() + "," + interhelicalHbonds[i]->getDonorTmId() ;
		string seg2 = interhelicalHbonds[i]->getAcceptor()->getChainId() + "," + interhelicalHbonds[i]->getAcceptorTmId();
		if(hbondsMapped.find(seg1 + " " + seg2) != hbondsMapped.end()) {
			hbondsMapped[seg1 + " " + seg2].push_back(interhelicalHbonds[i]);
		} else if (hbondsMapped.find(seg2 + " " + seg1) != hbondsMapped.end()) {
			hbondsMapped[seg2 + " " + seg1].push_back(interhelicalHbonds[i]);
		} else {
			hbondsMapped[seg1 + " " + seg2].push_back(interhelicalHbonds[i]);
		}
		//cout << "HERE " << seg1 << " " << seg2 << endl;
	}


	stringstream ss;

	ss << "bg_color white" << endl;
	ss << "load " << opt.pdbFile << endl;
	ss << "rotate X,90,all, 0" << endl;
	ss << "show cartoon" << endl;



	int interfaceNum = 0;
	int hbondNum = 0;
	for(map<string,vector<Hbond*> >::iterator it = hbondsMapped.begin(); it != hbondsMapped.end(); it++) {
		//if(it->second.size() < 4) {
		//	continue;
		//}
		ss << getHbondPseLine(hbondNum,it->second );
		interfaceNum++;

		// find interface
		vector<string> toks = MslTools::tokenize(it->first);
		Segment* seg1 = NULL;
		Segment* seg2 = NULL;
		if(mappedSegments.find(toks[0]) != mappedSegments.end()) {
			seg1 = mappedSegments[toks[0]];
		} else {
			cerr << "ERROR cant find segment " << opt.pdbFile << " " << toks[0] << endl;
		}

		if(mappedSegments.find(toks[1]) != mappedSegments.end()) {
			seg2 = mappedSegments[toks[1]];
		} else {
			cerr << "ERROR cant find segment " << opt.pdbFile << " " << toks[1] << endl;
		}

		AtomPointerVector& seg1Atoms = seg1->getAtoms();
		AtomPointerVector& seg2Atoms = seg2->getAtoms();

		map<string,unsigned int> interface = interfaceResidueCheck(seg1Atoms,seg2Atoms); 
		map<string,string> perChainInterface;
		
		for(map<string,unsigned int>::iterator it1 = interface.begin(); it1 != interface.end(); it1++) {
			// split A,23,GLY A,24,GLY and map [A] = 23+24
			vector<string> toks = MslTools::tokenize(it1->first,","); 
			if(perChainInterface.find(toks[0]) == perChainInterface.end()) {
				perChainInterface[toks[0]] = toks[1];
			} else {
				perChainInterface[toks[0]] += "+" + toks[1];
			}
		}

		string interfaceId = "TM_" + seg1->getChain() + "_" + seg1->getTmId() + "_" + seg2->getChain() + "_" + seg2->getTmId() ;
		
		ss << "select " << interfaceId << " , "; 

		for(map<string,string>::iterator it1 = perChainInterface.begin(); it1 != perChainInterface.end(); it1++) {
			if(it1 == perChainInterface.begin()) {
				ss << " chain " << it1->first << " and resi " << it1->second ; 
			} else {
				ss << " or chain " << it1->first << " and resi " << it1->second ; 
			}
		}

		ss << endl;
		ss << "show stick, " << interfaceId << endl;
		
		fout << "hbonds " << it->first << "  ";
		for(vector<Hbond*>::iterator it1 = it->second.begin(); it1 != it->second.end(); it1++) {
			Atom* donor = (*it1)->getDonor();
			Atom* acceptor = (*it1)->getAcceptor();
			double distance = (*it1)->getDistance();
			char tmp[10000];
			sprintf(tmp,"%s:%s=%4.3f;",donor->getAtomOfIdentityId().c_str(),acceptor->getAtomOfIdentityId().c_str(),distance);
			fout << tmp;
		}
		fout << endl;
	}

	ss << "zoom all,3" << endl;
	ss << "set label_color, black" << endl;
	ss << "save " << opt.proteinId << ".pse" << endl;

	if(interfaceNum > 0) {
		ofstream pout;
		pout.open((opt.proteinId + ".inp").c_str());
		if(!pout.is_open()) {
			cerr << "Unable to open " << opt.proteinId << ".inp" << endl;
			exit(0);
		}

		pout << ss.str() ;

		string cmd = "pymol -cqd \"@" + opt.proteinId + ".inp\"";
		system(cmd.c_str());
	}

	time(&endTime);
	diffTime = difftime (endTime, startTime);

	fout << endl << "Total Time: " << setiosflags(ios::fixed) << setprecision(0) << diffTime << " seconds" << endl;
}
Example #5
0
void insertArr(astree* node, astree* node1) {
    if(typechkArr(node, node1)) {
        int arrSym = node->symbol;
        switch (arrSym) {
        case TOK_INT:
        {
            symbol *newSym = create_symbol(node->children[1]);

            newSym->attributes.set(ATTR_int);
            newSym->attributes.set(ATTR_array);
            newSym->attributes.set(ATTR_lval);
            newSym->attributes.set(ATTR_variable);
            if(symbol_stack.back() == nullptr || symbol_stack.empty()) {
                symbol_table* tab = new symbol_table();
                tab->insert(symbol_entry(node->children[1]
                                         ->lexinfo,newSym));
                symbol_stack.pop_back();
                symbol_stack.push_back(tab);
            } else {
                symbol_stack.back()->insert(symbol_entry(node->children[1]->
                                            lexinfo,newSym));
            }
            dumpToFile(file_sym, newSym, node->children[1]);
            break;
        }
        case TOK_CHAR:
        {
            symbol *newSym = create_symbol(node->children[1]);
            newSym->attributes.set(ATTR_char);
            newSym->attributes.set(ATTR_array);
            newSym->attributes.set(ATTR_lval);
            newSym->attributes.set(ATTR_variable);
            if(symbol_stack.back() == nullptr || symbol_stack.empty()) {
                symbol_table* tab = new symbol_table();
                tab->insert(symbol_entry(node->children[1]
                                         ->lexinfo,newSym));
                symbol_stack.pop_back();
                symbol_stack.push_back(tab);
            } else {
                symbol_stack.back()->insert(symbol_entry(node->children[1]->
                                            lexinfo,newSym));
            }
            dumpToFile(file_sym, newSym, node->children[1]);
            break;
        }

        case TOK_BOOL:
        {
            symbol *newSym = create_symbol(node->children[1]);
            newSym->attributes.set(ATTR_bool);
            newSym->attributes.set(ATTR_lval);
            newSym->attributes.set(ATTR_array);
            newSym->attributes.set(ATTR_variable);
            if(symbol_stack.back() == nullptr || symbol_stack.empty()) {
                symbol_table* tab = new symbol_table();
                tab->insert(symbol_entry(node->children[1]
                                         ->lexinfo,newSym));
                symbol_stack.pop_back();
                symbol_stack.push_back(tab);
            } else {
                symbol_stack.back()->insert(symbol_entry(node->children[1]->
                                            lexinfo,newSym));
            }
            dumpToFile(file_sym, newSym, node->children[1]);
            break;
        }
        case TOK_STRING:
        {
            symbol *newSym = create_symbol(node->children[1]);
            newSym->attributes.set(ATTR_string);
            newSym->attributes.set(ATTR_lval);
            newSym->attributes.set(ATTR_array);
            newSym->attributes.set(ATTR_variable);
            if(symbol_stack.back() == nullptr || symbol_stack.empty()) {
                symbol_table* tab = new symbol_table();
                tab->insert(symbol_entry(node->children[1]->
                                         lexinfo,newSym));
                symbol_stack.pop_back();
                symbol_stack.push_back(tab);
            } else {
                symbol_stack.back()->insert(symbol_entry(node->children[1]->
                                            lexinfo,newSym));
            }
            dumpToFile(file_sym, newSym, node->children[1]);
        }
        }
    }
}
Example #6
0
//================================================= the Euler tour ========================================
// function: a simple and subtle parser; linear time Euler tour to get all the necessary lists for LCA
// the description for the E L r and R:
// E: not initialized; put all the labels
// L: not initialized; put the levels of all nodes; so using the stack to help
// r: not initialized; put the tMRCA value of the internal nodes
// R: initialized; use the names of the nodes to index the positions of these nodes' positions in E
// input: the tree (Nexus/Newick)
// output: the updated E, L, r and R
void LCA_list_construction(char * tree)
{
	//R.assign(SAMPLE, 0);
	// the following stack and l2 are all local things, which will later be dropped
	vector<int> stack;  // used to store all the internal nodes temporarily
	int parent = 0;  // record the in-time present internal node in the stack

	vector<double> l2;  // store the MRCA of corresponding nodes; initialized as None

	int i = 0;
	while(tree[i] != '(')i++;

	while(tree[i] != ';')
	{
		if(tree[i] == ' ' || tree[i] == ';')
		{
			i++;
			// do nothing here!!
			continue;
		}

		if(tree[i] == ',')
		{
			i++;
			E.push_back(stack.back());
			L.push_back(stack.size()-1);
			continue;
		}

		if(tree[i] == '(')
		{
			i++;
			stack.push_back(parent);
			E.push_back(stack.back());
			L.push_back(stack.size()-1);
			r.push_back(0);
			parent++;
			l2.push_back(0);
			continue;
		}

		if(tree[i] >= 48 && tree[i] <= 57)
		{
			char node[5];
			int j = 0;
			while(tree[i] != '.')
			{
				node[j++] = tree[i++];
			}
			node[j] = '\0';
			long int node_value = string_long(node);
			while(tree[i++] != ':');
			char tmrca[20];  // I give this double type number 20 effective digits; it is just kidding of course
			j = 0;
			while(tree[i] != ',' && tree[i] != ')' && tree[i] != '\0')
			{
				tmrca[j++] = tree[i];
				i++;
			}
			tmrca[j] = '\0';
			double tmrca_value = string_double(tmrca);

			E.push_back(node_value);
			L.push_back(stack.size());
			R[node_value-1] = E.size() - 1;

			if(l2.back() == 0)  // this is the left sub-tree
			{
				l2.back() = tmrca_value;
			}
			continue;
		}

		if(tree[i] == ')')  // there may be a ":" following the ")"
		{
			if(tree[i+1] != ';')
			{
				// two possibilities: left leaf and right leaf
				i+=2;
				char tmrca[20];  // I give this double type number 20 effective digits
				int j = 0;
				while(tree[i] != ',' && tree[i] != ')' && tree[i] != '\0')
				{
					tmrca[j++] = tree[i];
					i++;
				}
				tmrca[j] = '\0';
				double tP = string_double(tmrca);

				E.push_back(stack.back());
				L.push_back(stack.size()-1);
				r[E.back()] = l2.back();
				stack.pop_back();

				double temp = l2.back();
				l2.pop_back();
				if(l2.back() == 0)  // back from the left sub-tree
				{
					temp += tP;
					l2.back() = temp;
				}
			}
			else
			{
				i++;
				E.push_back(stack.back());
				L.push_back(stack.size()-1);
				r[E.back()] = l2.back();
				stack.pop_back();
				l2.pop_back();
			}
			continue;
		}
	}
	return;
}
Example #7
0
void lexer_badtoken (char* lexeme) {
   errprintf ("%:%s: %d: invalid token (%s)\n",
              included_filenames.back().c_str(),
              scan_linenr, lexeme);
}
Example #8
0
  virtual void Handle_Keypress(unsigned char key,int x,int y)
  {
    switch(key) {
    case 'h':
      printf("Help:\n");
      printf("[space]: next link\n");
      printf("z: previous link\n");
      printf("+: increase joint value by 0.1\n");
      printf("-: decrease joint value by 0.1\n");
      printf("d: in pose-by-IK mode, delete constraint\n");
      printf("c: in pose-by-IK mode, constrain current rotations\n");
      printf("p: print the current configuration\n");
      break;
    case ' ':
      cur_link++;
      if(cur_link >= (int)robot->links.size()) cur_link=0;
      UpdateCurLinkGUI();
      UpdateLinkValueGUI();
      break;
    case 'z':
      cur_link--;
      if(cur_link < 0) cur_link = robot->links.size()-1;
      UpdateCurLinkGUI();
      UpdateLinkValueGUI();
      break;
    case '+':
    case '=':
      {
	Real val = robot->q(cur_link)+0.1;
	robot->q(cur_link) = Clamp(val,robot->qMin(cur_link),robot->qMin(cur_link));
	UpdateConfig();
	UpdateLinkValueGUI();
      }
      break;
    case '-':
    case '_':
      {
	Real val = robot->q(cur_link)-0.1;
	robot->q(cur_link) = Clamp(val,robot->qMin(cur_link),robot->qMin(cur_link));
	UpdateConfig();
	UpdateLinkValueGUI();
      }
      break;
    case 'c':
      if(true || pose_ik) {
	if(hoverLink < 0) {
	  printf("Before constraining a link you need to hover over it\n");
	}
	else {
	  for(size_t i=0;i<poseGoals.size();i++)
	    if(poseGoals[i].link == hoverLink) {
	      poseGoals.erase(poseGoals.begin()+i);
	      poseWidgets.erase(poseWidgets.begin()+i);
	      break;
	    }
	  printf("Fixing link %s\n",robot->LinkName(hoverLink).c_str());
	  poseGoals.resize(poseGoals.size()+1);
	  poseGoals.back().link = hoverLink;
	  poseGoals.back().localPosition = robot->links[hoverLink].com;
	  poseGoals.back().SetFixedPosition(robot->links[hoverLink].T_World*robot->links[hoverLink].com);
	  poseGoals.back().SetFixedRotation(robot->links[hoverLink].T_World.R);
	  poseWidgets.resize(poseWidgets.size()+1);
	  poseWidgets.back().T.R = robot->links[hoverLink].T_World.R;
	  poseWidgets.back().T.t = poseGoals.back().endPosition;
	}
      }
      break;
    case 'd':
      if(hoverWidget != -1) {
	printf("Deleting IK goal on link %s\n",robot->LinkName(poseGoals[hoverWidget].link).c_str());
	poseGoals.erase(poseGoals.begin()+hoverWidget);
	poseWidgets.erase(poseWidgets.begin()+hoverWidget);
	hoverWidget = -1;
      }
      else {
	for(size_t i=0;i<poseGoals.size();i++)
	  if(poseGoals[i].link == hoverLink) {
	    printf("Deleting IK goal on link %s\n",robot->LinkName(hoverLink).c_str());
	    poseGoals.erase(poseGoals.begin()+i);
	    poseWidgets.erase(poseWidgets.begin()+i);
	    break;
	  }
      }
      break;
    case 'p':
      cout<<robot->q<<endl;
      break;
    }
    Refresh();
  }
Example #9
0
File: main.cpp Project: HuiD/ece590
void gameLoopCleanUp() {
    delete background;
    while(!colList.empty()) {
        CollisionPair * tmp = colList.back();
        colList.pop_back();
        delete tmp;
    }
    cout<<"collist"<<colList.size()<<endl;
    for(map<int, Hero* >::iterator it=heroGroup.begin(); it!=heroGroup.end(); ++it) {
        delete it->second;
        heroGroup.erase(it);
    }
    //                        while (!heroGroup.empty()){
    //                            Hero * tmp = heroGroup[0];
    //                            heroGroup.erase(0);
    //                            delete tmp;
    //                        }
    cout<<"hero"<<heroGroup.size()<<endl;

    while(!blocks.empty()) {
        Block * tmp = blocks.back();
        blocks.pop_back();
        delete tmp;
    }
    cout<<"block"<<blocks.size()<<endl;

    while(!explosionGroup.empty()) {
        Explosion * tmp = explosionGroup.back();
        explosionGroup.pop_back();
        delete tmp;
    }
    cout<<"exp"<<explosionGroup.size()<<endl;

    //                        while(!enemyGroup.empty()){
    //                            Enemy * tmp = enemyGroup.back();
    //                            enemyGroup.pop_back();
    //                            delete tmp;
    //                        }
    //                        cout<<"enemy"<<enemyGroup.size()<<endl;

    while(!bombGroup.empty()) {
        Bomb * tmp = bombGroup.back();
        bombGroup.pop_back();
        delete tmp;
    }
    cout<<"bomb"<<bombGroup.size()<<endl;

    while(!upgradeGroup.empty()) {
        Upgrade * tmp = upgradeGroup.back();
        upgradeGroup.pop_back();
        delete tmp;
    }
    cout<<"up"<<upgradeGroup.size()<<endl;

    TTF_CloseFont(text_font);
    delete tcpclient;
    delete udpclient;
    delete remoteip;
    Mix_HaltMusic();
    Mix_FreeMusic(mainMusic);
    delete winScreen;
    delete loseScreen;
}
Example #10
0
 int getMin() {
     return min.back();
 }
 void restore(vector<int>& path) {
     while(!path.empty()) {
         restore(path.back());
         path.pop_back();
     } 
 }
Example #12
0
 int top() {
     return val.back();
 }
Example #13
0
 int64 pop() {
     int64 largest = v.back();
     v.pop_back();
     return largest;
 }
Example #14
0
 int getMin() {
     if( minPos.empty() ) return -1;
     return v[ minPos.back() ];
 }
Example #15
0
File: c.cpp Project: Igorjan94/CF
void print(vector<vector<Type> >& a){if(a.size())(a.size()==1)?print(a[0]):writeln2(a[0]);for(int i=1;i<a.size()-1;++i)writeln2(a[i]);if(a.size()>=2)print_no_space(a.back());}
Example #16
0
// Based on a paper by Samuel R. Buss and Jin-Su Kim // TODO: Cite the paper properly
rk_result_t Robot::selectivelyDampedLeastSquaresIK_chain(const vector<size_t> &jointIndices, VectorXd &jointValues,
                                              const Isometry3d &target, const Isometry3d &finalTF)
{
    return RK_SOLVER_NOT_READY;
    // FIXME: Make this work


    // Arbitrary constant for maximum angle change in one step
    gammaMax = M_PI/4; // TODO: Put this in the constructor so the user can change it at a whim


    vector<Linkage::Joint*> joints;
    joints.resize(jointIndices.size());
    // FIXME: Add in safety checks
    for(int i=0; i<joints.size(); i++)
        joints[i] = joints_[jointIndices[i]];

    // ~~ Declarations ~~
    MatrixXd J;
    JacobiSVD<MatrixXd> svd;
    Isometry3d pose;
    AngleAxisd aagoal;
    AngleAxisd aastate;
    Vector6d goal;
    Vector6d state;
    Vector6d err;
    Vector6d alpha;
    Vector6d N;
    Vector6d M;
    Vector6d gamma;
    VectorXd delta(jointValues.size());
    VectorXd tempPhi(jointValues.size());
    // ~~~~~~~~~~~~~~~~~~

//    cout << "\n\n" << endl;

    tolerance = 1*M_PI/180; // TODO: Put this in the constructor so the user can set it arbitrarily
    maxIterations = 1000; // TODO: Put this in the constructor so the user can set it arbitrarily

    size_t iterations = 0;
    do {

        values(jointIndices, jointValues);

        jacobian(J, joints, joints.back()->respectToRobot().translation()+finalTF.translation(), this);

        svd.compute(J, ComputeFullU | ComputeThinV);

    //    cout <<  "\n\n" << svd.matrixU() << "\n\n\n" << svd.singularValues().transpose() << "\n\n\n" << svd.matrixV() << endl;

    //    for(int i=0; i<svd.matrixU().cols(); i++)
    //        cout << "u" << i << " : " << svd.matrixU().col(i).transpose() << endl;


    //    std::cout << "Joint name: " << joint(jointIndices.back()).name()
    //              << "\t Number: " << jointIndices.back() << std::endl;
        pose = joint(jointIndices.back()).respectToRobot()*finalTF;

    //    std::cout << "Pose: " << std::endl;
    //    std::cout << pose.matrix() << std::endl;

    //    AngleAxisd aagoal(target.rotation());
        aagoal = target.rotation();
        goal << target.translation(), aagoal.axis()*aagoal.angle();

        aastate = pose.rotation();
        state << pose.translation(), aastate.axis()*aastate.angle();

        err = goal-state;

    //    std::cout << "state: " << state.transpose() << std::endl;
    //    std::cout << "err: " << err.transpose() << std::endl;

        for(int i=0; i<6; i++)
            alpha[i] = svd.matrixU().col(i).dot(err);

    //    std::cout << "Alpha: " << alpha.transpose() << std::endl;

        for(int i=0; i<6; i++)
        {
            N[i] = svd.matrixU().block(0,i,3,1).norm();
            N[i] += svd.matrixU().block(3,i,3,1).norm();
        }

    //    std::cout << "N: " << N.transpose() << std::endl;

        double tempMik = 0;
        for(int i=0; i<svd.matrixV().cols(); i++)
        {
            M[i] = 0;
            for(int k=0; k<svd.matrixU().cols(); k++)
            {
                tempMik = 0;
                for(int j=0; j<svd.matrixV().cols(); j++)
                    tempMik += fabs(svd.matrixV()(j,i))*J(k,j);
                M[i] += 1/svd.singularValues()[i]*tempMik;
            }
        }

    //    std::cout << "M: " << M.transpose() << std::endl;

        for(int i=0; i<svd.matrixV().cols(); i++)
            gamma[i] = minimum(1, N[i]/M[i])*gammaMax;

    //    std::cout << "Gamma: " << gamma.transpose() << std::endl;

        delta.setZero();
        for(int i=0; i<svd.matrixV().cols(); i++)
        {
    //        std::cout << "1/sigma: " << 1/svd.singularValues()[i] << std::endl;
            tempPhi = 1/svd.singularValues()[i]*alpha[i]*svd.matrixV().col(i);
    //        std::cout << "Phi: " << tempPhi.transpose() << std::endl;
            clampMaxAbs(tempPhi, gamma[i]);
            delta += tempPhi;
    //        std::cout << "delta " << i << ": " << delta.transpose() << std::endl;
        }

        clampMaxAbs(delta, gammaMax);

        jointValues += delta;

        std::cout << iterations << " | Norm:" << delta.norm() << "\tdelta: "
                  << delta.transpose() << "\tJoints:" << jointValues.transpose() << std::endl;

        iterations++;
    } while(delta.norm() > tolerance && iterations < maxIterations);
}
Example #17
0
File: c.cpp Project: Igorjan94/CF
void print_no_space(vector<vector<Type> >&a){for(int i=0;i<a.size()-1;++i)writeln(a[i]);if(a.size())print_no_space(a.back());}
Example #18
0
rk_result_t Robot::pseudoinverseIK_chain(const vector<size_t> &jointIndices, VectorXd &jointValues,
                                  const Isometry3d &target, const Isometry3d &finalTF)
{
    return RK_SOLVER_NOT_READY;
    // FIXME: Make this solver work


    vector<Linkage::Joint*> joints;
    joints.resize(jointIndices.size());
    // FIXME: Add in safety checks
    for(int i=0; i<joints.size(); i++)
        joints[i] = joints_[jointIndices[i]];

    // ~~ Declarations ~~
    MatrixXd J;
    MatrixXd Jinv;
    Isometry3d pose;
    AngleAxisd aagoal;
    AngleAxisd aastate;
    Vector6d goal;
    Vector6d state;
    Vector6d err;
    VectorXd delta(jointValues.size());

    MatrixXd Jsub;
    aagoal = target.rotation();
    goal << target.translation(), aagoal.axis()*aagoal.angle();

    tolerance = 1*M_PI/180; // TODO: Put this in the constructor so the user can set it arbitrarily
    maxIterations = 100; // TODO: Put this in the constructor so the user can set it arbitrarily
    errorClamp = 0.25; // TODO: Put this in the constructor
    deltaClamp = M_PI/4; // TODO: Put this in the constructor

    size_t iterations = 0;
    do {

        values(jointIndices, jointValues);

        jacobian(J, joints, joints.back()->respectToRobot().translation()+finalTF.translation(), this);
        Jsub = J.block(0,0,3,jointValues.size());

        pinv(Jsub, Jinv);

        pose = joint(jointIndices.back()).respectToRobot()*finalTF;
        aastate = pose.rotation();
        state << pose.translation(), aastate.axis()*aastate.angle();

        err = goal-state;
        for(int i=3; i<6; i++)
            err[i] *= 0;
        err.normalize();

        Vector3d e = (target.translation() - pose.translation()).normalized()*0.005;

//        delta = Jinv*err*0.1;
//        clampMag(delta, deltaClamp);
        VectorXd d = Jinv*e;

//        jointValues += delta;
        jointValues += d;
        std::cout << iterations << " | Norm:" << delta.norm()
//                  << "\tdelta: " << delta.transpose() << "\tJoints:" << jointValues.transpose() << std::endl;
                  << " | " << (target.translation() - pose.translation()).norm()
                  << "\tErr: " << (goal-state).transpose() << std::endl;


        iterations++;
    } while(delta.norm() > tolerance && iterations < maxIterations);

}
Example #19
0
void yyerror (const char* message) {
   assert (not included_filenames.empty());
   errprintf ("%:%s: %d: %s\n",
              included_filenames.back().c_str(),
              scan_linenr, message);
}
Example #20
0
rk_result_t Robot::jacobianTransposeIK_chain(const vector<size_t> &jointIndices, VectorXd &jointValues, const Isometry3d &target, const Isometry3d &finalTF)
{
    return RK_SOLVER_NOT_READY;
    // FIXME: Make this solver work


    vector<Linkage::Joint*> joints;
    joints.resize(jointIndices.size());
    // FIXME: Add in safety checks
    for(int i=0; i<joints.size(); i++)
        joints[i] = joints_[jointIndices[i]];

    // ~~ Declarations ~~
    MatrixXd J;
    MatrixXd Jinv;
    Isometry3d pose;
    AngleAxisd aagoal;
    AngleAxisd aastate;
    Vector6d state;
    Vector6d err;
    VectorXd delta(jointValues.size());
    Vector6d gamma;
    double alpha;

    aagoal = target.rotation();

    double Tscale = 3; // TODO: Put these as a class member in the constructor
    double Rscale = 0;

    tolerance = 1*M_PI/180; // TODO: Put this in the constructor so the user can set it arbitrarily
    maxIterations = 100; // TODO: Put this in the constructor so the user can set it arbitrarily

    size_t iterations = 0;
    do {
        values(jointIndices, jointValues);

        jacobian(J, joints, joints.back()->respectToRobot().translation()+finalTF.translation(), this);

        pose = joint(jointIndices.back()).respectToRobot()*finalTF;
        aastate = pose.rotation();
        state << pose.translation(), aastate.axis()*aastate.angle();

        err << (target.translation()-pose.translation()).normalized()*Tscale,
               (aagoal.angle()*aagoal.axis()-aastate.angle()*aastate.axis()).normalized()*Rscale;

        gamma = J*J.transpose()*err;
        alpha = err.dot(gamma)/gamma.norm();

        delta = alpha*J.transpose()*err;

        jointValues += delta;
        iterations++;

        std::cout << iterations << " | Norm:" << delta.norm()
//                  << "\tdelta: " << delta.transpose() << "\tJoints:" << jointValues.transpose() << std::endl;
                  << " | " << (target.translation() - pose.translation()).norm()
                  << "\tErr: " << (target.translation()-pose.translation()).transpose() << std::endl;

    } while(err.norm() > tolerance && iterations < maxIterations);

}
Example #21
0
int main(int argc, char** argv){
	string fileName="";
	int camIndex=-1;
    char flag;
    char options[]="hp:m:c::";
	char inputMedia=Unknown;
    CvCapture* capture=NULL;
	IplImage* original=NULL;
	IplImage* frame=NULL;


    while((flag=getopt(argc, argv, options)) != -1){
		switch(flag){
			case 'h':
				printUsage(argv[0]);
				exit(EXIT_SUCCESS);
			case 'c':
				if(optarg == 0){
					if(optind < argc){
						camIndex=atoi(argv[optind]);
					}
				}
				else{
					camIndex=atoi(optarg);
				}
				inputMedia=Camera;
				break;
			case 'p':
				fileName=optarg;
				inputMedia=Photo;
				break;
			case 'm':
				fileName=optarg;
				inputMedia=Video;
				break;
			default:
				printUsage(argv[0]);
				exit(-1);
		}
    }

    if(inputMedia==Video){
		capture = cvCaptureFromAVI(fileName.c_str());
		if(!capture){
			cerr<<"Error: Could not open video "<<fileName<<endl;
			exit(-1);
		}
		cout<<"Reading video "<<fileName<<endl;
		frame=getFrame(capture);
    }

	if(inputMedia==Photo){
		original=cvLoadImage(fileName.c_str());
		if(original == NULL){
			cout<<"Error: Could not load photo "<<fileName<<endl;
			exit(-1);
		}

		cout<<"Input image depth="<<original->depth<<endl;

		int width = original->width;
		int height = original->height;
		if(original->width > 512 || original->height > 512){
			width = width/2;
			height = height/2;
			frame = cvCreateImage( cvSize(width, height), original->depth, original->nChannels );
			cvResize(original, frame);
		}
		else{
			frame=cvCreateImage( cvGetSize(original), original->depth, original->nChannels );
			cvCopy(original, frame);
		}
		cout<<"Loaded photo "<<fileName<<endl;
	}

    if(inputMedia==Camera){
		capture = cvCaptureFromCAM(camIndex);
		if(!capture){
			cerr<<"Error: Could not open camera "<<camIndex<<endl;
			exit(-1);
		}
		cout<<"Reading from camera "<<camIndex<<endl;
		frame=getFrame(capture);
    }

	if(inputMedia==Unknown){
		cout<<"Option error!"<<endl;
		printUsage(argv[0]);
		exit(-1);
	}


	IplImage* greyImg=NULL;
	IplImage* edgeImg=NULL;
	IplImage* input = frame;
	IplImage* colorSpace =NULL;

	if(frame->width > 512 || frame->height > 512){
		int width = frame->width/2;
		int height = frame->height/2;
		colorSpace=cvCreateImage(cvSize(width, height), frame->depth, frame->nChannels);
		cvResize(frame, colorSpace);
	}
	else{
		colorSpace=cvCreateImage(cvGetSize(frame), frame->depth, frame->nChannels);
	}

	cvNamedWindow("Input", CV_WINDOW_AUTOSIZE);
	cvNamedWindow("ColorSpace", CV_WINDOW_AUTOSIZE);
	cvNamedWindow("Grey", CV_WINDOW_AUTOSIZE);
	cvNamedWindow("Lines", CV_WINDOW_AUTOSIZE);
	//cvNamedWindow("Controls", 0);

	cvSetMouseCallback("Input", mouseHandler, (void*)colorSpace);
	cvSetMouseCallback("ColorSpace", mouseHandler, (void*)colorSpace);

	int colorIndex=2;
	int colorChannel=0;
	int lineThresh=20;
	int minLength=30;
	int maxGap=10;
	int cannyThresh1=10;
	int cannyThresh2=200;
	int cannyAperture=1;


	cvCreateTrackbar("Color Space", "Input", &colorIndex, 3, forceUpdate);
	cvCreateTrackbar("Color Channel", "Input", &colorChannel, 3, forceUpdate);
	cvCreateTrackbar("Canny Aperture", "Input", &cannyAperture, 3, forceUpdate);
	cvCreateTrackbar("Canny Threshold1", "Input", &cannyThresh1, 300, forceUpdate);
	cvCreateTrackbar("Canny Threshold2", "Input", &cannyThresh2, 300, forceUpdate);
	cvCreateTrackbar("Line Threshold", "Input", &lineThresh, 300, forceUpdate);
	cvCreateTrackbar("Minimum Line Length", "Input", &minLength, 300, forceUpdate);
	cvCreateTrackbar("Maximum Segment Gap", "Input", &maxGap, 300, forceUpdate);

	//cvResizeWindow("Controls", 400, 300);

	bool isPaused=false;
	bool stepMode=false;
	char keyVal='p';
	float milSecs=0;
	uint32_t frameCount=0;

	while(keyVal!='q'){
		if(keyVal=='o'){	//Output data
			saveData=true;
		}
		if(keyVal=='r'){	//RESET
			while(!seedPoints.empty()){
				delete seedPoints.back();
				seedPoints.pop_back();
			}
			updateNeeded=true;
		}
		if(keyVal=='s'){
			cout<<"Enter, step mode"<<endl;
			cout<<"\tn - Next frame"<<endl;
			cout<<"\tq - Quit"<<endl;
			cout<<"\ts - Exit step mode"<<endl;
			stepMode=true;
		}
		if(keyVal=='j'){
			int jump=frameCount;
			cout<<"Enter, jump mode @ frame="<<frameCount<<endl;
			cout<<"\tWhat frame to jump to? ";
			cin>>jump;

			while(frameCount < jump){
				frameCount++;
				/*if(input!=frame && input!=NULL){
					cvReleaseImage(&input);
					input=NULL;
					cout<<"Release"<<endl;
				}*/

				frame=getFrame(capture);
				if(frame==NULL){
					cout<<"At end of stream, read "<<frameCount<<" frames"<<endl;
					exit(1);
				}

				if(frameCount%10==0){
					int width = frame->width;
					int height = frame->height;
					//input = frame;
					/*if(width > 512 || height > 512){
						width = width/2;
						height = height/2;
						if(input==frame || input==NULL){
							cout<<"Alloc"<<endl;
							input = cvCreateImage( cvSize(width, height), frame->depth, frame->nChannels );
						}
						cvResize(frame, input);
					}
					cvShowImage("Input", input);*/
					cvWaitKey(10);
				}
				//cvWaitKey(2);
				cout<<"frame="<<frameCount<<endl;
			}

			cout<<"Jump complete!"<<endl;
		}

		if(stepMode){
			while(1){
				keyVal=cvWaitKey(50);
				if(keyVal=='s'){		//Stop step mode
					stepMode=false;
					keyVal=0;
					cout<<"Exit, step mode"<<endl;
					break;
				}
				else if(keyVal=='q'){	//Exit program
					stepMode=false;
					cout<<"Exit program"<<endl;
					break;
				}
				else if(keyVal=='n'){	//Next frame
					cout<<"Step, frame="<<frameCount<<endl;
					getNewFrame=true;
					break;
				}
			}
		}

		if(updateNeeded || !isPaused || getNewFrame){
			if(inputMedia != Photo){
				if(!isPaused || getNewFrame){
					frameCount++;

					if(input!=frame && input!=NULL){
						cvReleaseImage(&input);
						input=NULL;
					}
					frame=getFrame(capture);
					if(frame==NULL){
						cout<<"At end of stream, read "<<frameCount<<" frames"<<endl;
						break;
						//exit(1);
					}
					getNewFrame=false;
				}
				int width = frame->width;
				int height = frame->height;

				if(frame->width > 512 || frame->height > 512){
					width = width/2;
					height = height/2;
					if(input==frame || input==NULL){
						//cvReleaseImage(&input);
						input = cvCreateImage( cvSize(width, height), frame->depth, frame->nChannels );
					}
					cvResize(frame, input);
				}
				else{
					input=frame;
				}
			}
			else{
				int width = original->width;
				int height = original->height;
				if(original->width > 512 || original->height > 512){
					width = width/2;
					height = height/2;
					//input = cvCreateImage( cvSize(width, height), orginal->depth, orginal->nChannels );
					cvResize(original, input);
				}
				else{
					cvCopy(original, input);
				}
			}

			if(frameCount < STARTUP_DELAY){
				cout<<"Starting up"<< STARTUP_DELAY-frameCount <<endl;
				frameCount++;
			}
			else{
				//Time how long it takes to process
				timeval timeTemp;
				timeval timeDelta;
				gettimeofday(&timeTemp, NULL);

				/********* PROCESS IMAGE *******/


				if(greyImg==NULL){
					greyImg=cvCreateImage( cvGetSize(input), IPL_DEPTH_8U, 1 );
				}
				if(edgeImg==NULL){
					edgeImg=cvCreateImage( cvGetSize(input), IPL_DEPTH_8U, 1 );
				}


				if(colorIndex==1){	//Normalized RGB
					for(int row=0; row<input->height; row++){
						for(int col=0; col<input->width; col++){
							float red=(uint8_t)GetPixelPtrD8(input, row, col, 0);
							float green=(uint8_t)GetPixelPtrD8(input, row, col, 1);
							float blue=(uint8_t)GetPixelPtrD8(input, row, col, 2);

							float sum=red+green+blue;

							float r=red/sum;
							float g=green/sum;
							float b=blue/sum;

							GetPixelPtrD8(colorSpace, row, col, 0) = (uint8_t) (r * 255);
							GetPixelPtrD8(colorSpace, row, col, 1) = (uint8_t) (g * 255);
							GetPixelPtrD8(colorSpace, row, col, 2) = (uint8_t) (b * 255);

						}
					}
				}
				else if(colorIndex==2){	//HSV
					cvCvtColor(input, colorSpace, CV_RGB2HSV);
				}
				else if(colorIndex==3){	//HLS
					cvCvtColor(input, colorSpace, CV_RGB2HLS);
				}
				else{
					cvCopy(input, colorSpace);
				}

				if(colorChannel>=3){
					cvCvtColor(colorSpace, greyImg, CV_RGB2GRAY);
				}
				else{
					//Copy target color channel into buffer
					IplImage* channels[3]={NULL, NULL, NULL};
					channels[colorChannel]=greyImg;

					cvSplit(colorSpace, channels[0], channels[1], channels[2], NULL);
				}

				CvMemStorage* storage = cvCreateMemStorage(0);
				CvSeq* lines = 0;


				cvCanny( greyImg, edgeImg, cannyThresh1, cannyThresh2, (2*cannyAperture)+1 );

				clearHist(targetHist);
				clearHist(rejectedHist);
				clearHist(acceptedHist);


				lines = cvHoughLines2( edgeImg,
									   storage,
									   CV_HOUGH_PROBABILISTIC,
									   1,
									   CV_PI/180,
									   lineThresh+1,
									   minLength,
									   maxGap );

                                //Delete old points
                                while(!seedPoints.empty()){
                                        delete seedPoints.back();
                                        seedPoints.pop_back();
                                }

                                for(int row=colorSpace->height/2; row<colorSpace->height; row+=10){
                                        for(int col=0; col < colorSpace->width; col+=10){
                                                CvPoint* pt=new CvPoint;
                                                pt->x=col;
                                                pt->y=row;
                                                seedPoints.push_back(pt);
                                        }
                                }

                                PixelStats stats;
                                calcStats(colorSpace, seedPoints, &stats);
                                vector<CvPoint*>::iterator iter=seedPoints.begin();
                                while(iter!=seedPoints.end()){
                                        CvPoint* pt=*iter;
                                        double chan0Delta=fabs(((uint8_t)GetPixelPtrD8(colorSpace, pt->y, pt->x, 0)) - stats.avgVal.val[0]);
                                        double chan1Delta=fabs(((uint8_t)GetPixelPtrD8(colorSpace, pt->y, pt->x, 1)) - stats.avgVal.val[1]);
                                        double chan2Delta=fabs(((uint8_t)GetPixelPtrD8(colorSpace, pt->y, pt->x, 2)) - stats.avgVal.val[2]);
                                        if(chan0Delta > stats.stdDev.val[0]*1 /*||
                                                chan1Delta > stats.stdDev.val[1]*1.5 ||
                                                chan2Delta > stats.stdDev.val[2]*1.5*/){
                                                delete (*iter);
                                                iter=seedPoints.erase(iter);
                                                continue;
                                        }
                                        iter++;
                                }

                                //PixelStats stats;
				calcStats(colorSpace, seedPoints, &stats);

				int removed=0;
				int total=lines->total;

				totalChecked+=total;

				for(int i=0; i<lines->total; i++){
					CvPoint* line = (CvPoint*)cvGetSeqElem(lines,i);

					float slope=(float)(line[0].y - line[1].y)/(float)(line[0].x - line[1].x);

					/*if(line[0].y < 50 || line[1].y<50){
						removed++;
						continue;
					}

					if(fabsf(slope-1) < 0.1){
						removed++;
						continue;
					}*/

					CvLineIterator iterator;
					int count=cvInitLineIterator( colorSpace, line[0], line[1], &iterator, 8, 0 );

					CvScalar avgVal=cvScalarAll(0);
					CvScalar delta=cvScalarAll(0);
					CvScalar variance=cvScalarAll(0);
					CvScalar stdDev=cvScalarAll(0);

					clearHist(tempHist);

					for(int p=0; p<count; p++){	//Loop over pixels in line
						tempHist[iterator.ptr[0]][0]++;
						tempHist[iterator.ptr[1]][1]++;
						tempHist[iterator.ptr[2]][2]++;

						avgVal.val[0]+=iterator.ptr[0];
						avgVal.val[1]+=iterator.ptr[1];
						avgVal.val[2]+=iterator.ptr[2];
						CV_NEXT_LINE_POINT(iterator);
					}

					avgVal.val[0]=avgVal.val[0]/count;
					avgVal.val[1]=avgVal.val[1]/count;
					avgVal.val[2]=avgVal.val[2]/count;

					count=cvInitLineIterator( colorSpace, line[0], line[1], &iterator, 8, 0 );

					for(int p=0; p<count; p++){	//Loop over pixels in line
						variance.val[0]+=(iterator.ptr[0]-avgVal.val[0])*(iterator.ptr[0]-avgVal.val[0]);
						variance.val[1]+=(iterator.ptr[1]-avgVal.val[1])*(iterator.ptr[1]-avgVal.val[1]);
						variance.val[2]+=(iterator.ptr[2]-avgVal.val[2])*(iterator.ptr[2]-avgVal.val[2]);
						CV_NEXT_LINE_POINT(iterator);
					}

					variance.val[0]/=count;
					variance.val[1]/=count;
					variance.val[2]/=count;

					delta.val[0]=fabs(avgVal.val[0]-stats.avgVal.val[0]);
					delta.val[1]=fabs(avgVal.val[1]-stats.avgVal.val[1]);
					delta.val[2]=fabs(avgVal.val[2]-stats.avgVal.val[2]);

					stdDev.val[0]=sqrt(variance.val[0]);
					stdDev.val[1]=sqrt(variance.val[1]);
					stdDev.val[2]=sqrt(variance.val[2]);

					//cout<<"line m="<<slope<<" stdDev="<<cvScalarToString(stdDev, 3)<<", avg="<<cvScalarToString(avgVal, 3);


					if(delta.val[0] < 10*stats.stdDev.val[0] &&
					   delta.val[1] < 2*stats.stdDev.val[1] &&
					   delta.val[2] < 4*stats.stdDev.val[2]){

						cout<<" REMOVED deltaAvg="<<cvScalarToString(delta,3)<<" stdDev="<<cvScalarToString(stdDev,3)<<endl;

						removed++;
						cvLine( input, line[0], line[1], CV_RGB(255,0,0), 1);
						stageRemoved[0]++;

						addHist(tempHist, rejectedHist, rejectedHist);
						continue;
					}

					//Dark grass Checking for HSV
					if(avgVal.val[0] > stats.avgVal.val[0]){
						cout<<" REMOVED chan0 AVG deltaAvg="<<cvScalarToString(delta,3)<<" stdDev="<<cvScalarToString(stdDev,3)<<endl;
						removed++;
						cvLine( input, line[0], line[1], CV_RGB(255,255,0), 1);
						stageRemoved[1]++;
						addHist(tempHist, rejectedHist, rejectedHist);
						continue;
					}
					else if(avgVal.val[1] > stats.avgVal.val[1]){
						cout<<" REMOVED chan1 AVG deltaAvg="<<cvScalarToString(delta,3)<<" stdDev="<<cvScalarToString(stdDev,3)<<endl;
						removed++;
						cvLine( input, line[0], line[1], CV_RGB(0,127,127), 1);
						stageRemoved[2]++;
						addHist(tempHist, rejectedHist, rejectedHist);
						continue;
					}
					else if(avgVal.val[2] > 200){
						//cout<<" REMOVED chan2 AVG deltaAvg="<<cvScalarToString(delta,3)<<" stdDev="<<cvScalarToString(stdDev,3)<<endl;
						//removed++;
						//cvLine( input, line[0], line[1], CV_RGB(255,157,0), 1);
						//continue;
					}

					if(15*stats.stdDev.val[0] < stdDev.val[0]){
						cout<<" REMOVED hue deltaAvg="<<cvScalarToString(delta,3)<<" stdDev="<<cvScalarToString(stdDev,3)<<endl;
						removed++;
						cvLine( input, line[0], line[1], CV_RGB(255,83,83), 1);
						stageRemoved[3]++;
						addHist(tempHist, rejectedHist, rejectedHist);
						continue;
					}

					cout<<"Keeping deltaAvg="<<cvScalarToString(delta,3)<<" stdDev="<<cvScalarToString(stdDev,3)<<endl;
					cvLine( input, line[0], line[1], CV_RGB(0, 255, 0), 1);
					addHist(tempHist, acceptedHist, acceptedHist);
				}

				if(saveData==true){
					dataFile1.open("targetHist.dat", ios_base::trunc);
					dataFile2.open("acceptedHist.dat", ios_base::trunc);
					dataFile3.open("rejectedHist.dat", ios_base::trunc);

					cout<<"Writing Data to file..."<<endl;

					for(int j=0; j<256; j++){
						dataFile1<<targetHist[j][0]<<" "<<targetHist[j][1]<<" "<<targetHist[j][2]<<endl;
						dataFile2<<acceptedHist[j][0]<<" "<<acceptedHist[j][1]<<" "<<acceptedHist[j][2]<<endl;
						dataFile3<<rejectedHist[j][0]<<" "<<rejectedHist[j][1]<<" "<<rejectedHist[j][2]<<endl;
					}

					cout<<"Writing complete"<<endl;

					dataFile1.close();
					dataFile2.close();
					dataFile3.close();

					saveData=false;
					isPaused=true;
				}

				totalAccepted+=total-removed;

				cvReleaseMemStorage(&storage);

				/********* END PROCESSING *******/

				gettimeofday(&timeDelta, NULL);
				timeDelta.tv_sec-=timeTemp.tv_sec;
				timeDelta.tv_usec-=timeTemp.tv_usec;
				milSecs=((float)timeDelta.tv_sec)*1000 + ((float)timeDelta.tv_usec)/1000;

				for(int i=0; i<seedPoints.size(); i++){
						CvPoint* pt=seedPoints.at(i);
						cvCircle(input, *pt, 2, cvScalar(0,0,255), 1);
				}

				cout<<"\tAvg="<<cvScalarToString(stats.avgVal,3)<<endl;
				cout<<"\tVariance="<<cvScalarToString(stats.variance,3)<<endl;
				cout<<"\tStdDev="<<cvScalarToString(stats.stdDev,3)<<endl;
				cout<<"Found "<<total<<" lines and removed "<<removed<<" lines";
				cout<<" - Processed frame in "<<milSecs<<"ms."<<endl;
			}

			cvShowImage("Input", input);
			cvShowImage("ColorSpace", colorSpace);
			cvShowImage("Grey", greyImg);
			cvShowImage("Lines", edgeImg);
			updateNeeded=false;
		}

		if(keyVal=='p'){
			isPaused=!isPaused;
			if(isPaused){
				cout<<"Paused @ frame="<<frameCount<<endl;
			}
			else{
				cout<<"Unpaused"<<endl;
			}
		}
		if(keyVal=='q'){
			break;
		}
		keyVal=cvWaitKey(10);
	}
Example #22
0
rk_result_t Robot::dampedLeastSquaresIK_chain(const vector<size_t> &jointIndices, VectorXd &jointValues, const Isometry3d &target, const Isometry3d &finalTF)
{


    vector<Linkage::Joint*> joints;
    joints.resize(jointIndices.size());
    // FIXME: Add in safety checks
    for(int i=0; i<joints.size(); i++)
        joints[i] = joints_[jointIndices[i]];

    // ~~ Declarations ~~
    MatrixXd J;
    MatrixXd Jinv;
    Isometry3d pose;
    AngleAxisd aagoal(target.rotation());
    AngleAxisd aastate;
    Vector3d Terr;
    Vector3d Rerr;
    Vector6d err;
    VectorXd delta(jointValues.size());
    VectorXd f(jointValues.size());


    tolerance = 0.001;
    maxIterations = 50; // TODO: Put this in the constructor so the user can set it arbitrarily
    damp = 0.05;

    values(jointIndices, jointValues);

    pose = joint(jointIndices.back()).respectToRobot()*finalTF;
    aastate = pose.rotation();

    Terr = target.translation()-pose.translation();
    Rerr = aagoal.angle()*aagoal.axis()-aastate.angle()*aastate.axis();
    err << Terr, Rerr;

    size_t iterations = 0;
    do {

        jacobian(J, joints, joints.back()->respectToRobot().translation()+finalTF.translation(), this);

        f = (J*J.transpose() + damp*damp*Matrix6d::Identity()).colPivHouseholderQr().solve(err);
        delta = J.transpose()*f;

        jointValues += delta;

        values(jointIndices, jointValues);

        pose = joint(jointIndices.back()).respectToRobot()*finalTF;
        aastate = pose.rotation();

        Terr = target.translation()-pose.translation();
        Rerr = aagoal.angle()*aagoal.axis()-aastate.angle()*aastate.axis();
        err << Terr, Rerr;

        iterations++;


    } while(err.norm() > tolerance && iterations < maxIterations);

}
/**
 * Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
 */
bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
{
    // Templates
    static multimap<txnouttype, CScript> mTemplates;
    if (mTemplates.empty())
    {
        // Standard tx, sender provides pubkey, receiver adds signature
        mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));

        // Transactcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
        mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));

        // Sender provides N pubkeys, receivers provides M signatures
        mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));

        // Empty, provably prunable, data-carrying output
        if (GetBoolArg("-datacarrier", true))
            mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN << OP_SMALLDATA));
        mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN));
    }

    // Shortcut for pay-to-script-hash, which are more constrained than the other types:
    // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
    if (scriptPubKey.IsPayToScriptHash())
    {
        typeRet = TX_SCRIPTHASH;
        vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
        vSolutionsRet.push_back(hashBytes);
        return true;
    }

    // Scan templates
    const CScript& script1 = scriptPubKey;
    BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
    {
        const CScript& script2 = tplate.second;
        vSolutionsRet.clear();

        opcodetype opcode1, opcode2;
        vector<unsigned char> vch1, vch2;

        // Compare
        CScript::const_iterator pc1 = script1.begin();
        CScript::const_iterator pc2 = script2.begin();
        while (true)
        {
            if (pc1 == script1.end() && pc2 == script2.end())
            {
                // Found a match
                typeRet = tplate.first;
                if (typeRet == TX_MULTISIG)
                {
                    // Additional checks for TX_MULTISIG:
                    unsigned char m = vSolutionsRet.front()[0];
                    unsigned char n = vSolutionsRet.back()[0];
                    if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
                        return false;
                }
                return true;
            }
            if (!script1.GetOp(pc1, opcode1, vch1))
                break;
            if (!script2.GetOp(pc2, opcode2, vch2))
                break;

            // Template matching opcodes:
            if (opcode2 == OP_PUBKEYS)
            {
                while (vch1.size() >= 33 && vch1.size() <= 65)
                {
                    vSolutionsRet.push_back(vch1);
                    if (!script1.GetOp(pc1, opcode1, vch1))
                        break;
                }
                if (!script2.GetOp(pc2, opcode2, vch2))
                    break;
                // Normal situation is to fall through
                // to other if/else statements
            }

            if (opcode2 == OP_PUBKEY)
            {
                if (vch1.size() < 33 || vch1.size() > 65)
                    break;
                vSolutionsRet.push_back(vch1);
            }
            else if (opcode2 == OP_PUBKEYHASH)
            {
                if (vch1.size() != sizeof(uint160))
                    break;
                vSolutionsRet.push_back(vch1);
            }
            else if (opcode2 == OP_SMALLINTEGER)
            {   // Single-byte small integer pushed onto vSolutions
                if (opcode1 == OP_0 ||
                    (opcode1 >= OP_1 && opcode1 <= OP_16))
                {
                    char n = (char)CScript::DecodeOP_N(opcode1);
                    vSolutionsRet.push_back(valtype(1, n));
                }
                else
                    break;
            }
            else if (opcode2 == OP_SMALLDATA)
            {
                // small pushdata, <= nMaxDatacarrierBytes
                if (vch1.size() > nMaxDatacarrierBytes)
                    break;
            }
            else if (opcode1 != opcode2 || vch1 != vch2)
            {
                // Others must match exactly
                break;
            }
        }
    }

    vSolutionsRet.clear();
    typeRet = TX_NONSTANDARD;
    return false;
}
Example #24
0
State PenteLinearAI::toStateOld() {
    /* X variables:
       0: doubles (ours)
       1: triples (ours)
       2: quads (ours)
       3: pentes (ours) // useful when looking at potential moves
       4: possible captures (ours)
       5: Resulting captures from the last move (ours).
       6: Resulting 3x blocks (ours)
       7: Resulting 4x blocks (ours)
       8: Resulting 5x blocks (ours)
       9: Proximity(ours, 2)
       
       10: doubles (theirs)
       11: triples (theirs)
       12: quads (theirs)
       13: pentes (theirs) // useful when looking at potential moves
       14: possible captures (theirs)
       15: resulting captures from the last move (theirs)
       16: Resulting 3x blocks (ours)
       17: Resulting 4x blocks (ours)
       18: Resulting 5x blocks (ours)
       19: Proximity(theirs, 2)

       
    */

    // Construct and return the state of the game.
    State s(20);

    int ours, theirs;

    if (playerNumber("COMPUTER") == 0) {
        ours = WHITE;
        theirs = BLACK;
    } else {
        ours = BLACK;
        theirs = WHITE;
    }
            

    /*    if(playerNumber("COMPUTER")==0) {
     */
       
    // Figure for our pieces...
    getCertain(s[0], s[1], s[2], s[3], ours);
    s[4] = getPossibleCaptures(ours);
    s[5] = (gametrace.empty()) ? 0 : 
        chkCapture( gametrace.back()->r, gametrace.back()->c,
                    ours );

    chkBlocks(s[6], s[7], s[8], ours);

    s[9] = getProximity(ours, 2);
    
    // Figure for their pieces.
    getCertain(s[10], s[11], s[12], s[13], theirs);
    s[14] = getPossibleCaptures(theirs);
    s[15] = (gametrace.empty()) ? 0 :
        chkCapture( gametrace.back()->r, gametrace.back()->c,
                    theirs );

    chkBlocks(s[16], s[17], s[18], theirs);

    s[19] = getProximity(theirs, 2);

    /*
      } else if(playerNumber("COMPUTER")==1) {
      // Figure for black pieces...
      getCertain(s[0], s[1], s[2], s[3], BLACK);
      s[4] = getPossibleCaptures(BLACK);
      s[5] = (gametrace.empty()) ? 0 : 
      chkCapture( gametrace.back()->r, gametrace.back()->c,
      gametrace.back()->color );
      // Figure for white pieces.
      getCertain(s[6], s[7], s[8], s[9], WHITE);
      s[10] = getPossibleCaptures(WHITE);
      s[11] = gametrace.empty() ? 0 :
      chkCapture( gametrace.back()->r, gametrace.back()->c,
      gametrace.back()->color );
      } 
        
      //s[8] = (playerColor("COMPUTER"));
      */
    return s;
}
Example #25
0
void travVardecl(astree* root) {
    astree* node = root->children[0];
    astree* node1 = root->children[1];
    root->block = blockcount;
    int sym = node->symbol;
    int otherSym = getReturnType(node1);
    switch(sym) {
    case TOK_INT:
        checkDecl(node);
        if(otherSym==TOK_INTCON || otherSym==TOK_NULL) {
            symbol *newSym = create_symbol(node->children[0]);
            newSym->attributes.set(ATTR_int);
            newSym->attributes.set(ATTR_lval);
            newSym->attributes.set(ATTR_variable);
            if(symbol_stack.back() == nullptr || symbol_stack.empty()) {
                symbol_table* tab = new symbol_table();
                tab->insert(symbol_entry(node->children[0]->lexinfo,newSym));
                symbol_stack.pop_back();
                symbol_stack.push_back(tab);
            } else {
                symbol_stack.back()->insert(symbol_entry(node->children[0]->
                                            lexinfo,newSym));
            }
            dumpToFile(file_sym, newSym, node->children[0]);
        } else if(otherSym == TOK_NEWARRAY) {
            insertArr(node, node1);
        }
        break;

    case TOK_CHAR:
        checkDecl(node);
        if(otherSym==TOK_CHARCON || otherSym==TOK_NULL) {
            symbol *newSym = create_symbol(node->children[0]);
            newSym->attributes.set(ATTR_char);
            newSym->attributes.set(ATTR_lval);
            newSym->attributes.set(ATTR_variable);
            if(symbol_stack.back() == nullptr || symbol_stack.empty()) {
                symbol_table* tab = new symbol_table();
                tab->insert(symbol_entry(node->children[0]->lexinfo,newSym));
                symbol_stack.pop_back();
                symbol_stack.push_back(tab);
            } else {
                symbol_stack.back()->insert(symbol_entry(node->children[0]->
                                            lexinfo,newSym));
            }
            dumpToFile(file_sym, newSym, node->children[0]);
        } else if(otherSym == TOK_NEWARRAY) {
            insertArr(node, node1);
        }
        break;

    case TOK_BOOL:
        checkDecl(node);
        if(otherSym==TOK_TRUE ||
                otherSym==TOK_FALSE || otherSym==TOK_NULL) {
            symbol *newSym = create_symbol(node->children[0]);
            newSym->attributes.set(ATTR_bool);
            newSym->attributes.set(ATTR_lval);
            newSym->attributes.set(ATTR_variable);
            if(symbol_stack.back() == nullptr || symbol_stack.empty()) {
                symbol_table* tab = new symbol_table();
                tab->insert(symbol_entry(node->children[0]->lexinfo,newSym));
                symbol_stack.pop_back();
                symbol_stack.push_back(tab);
            } else {
                symbol_stack.back()->insert(symbol_entry(node->children[0]->
                                            lexinfo,newSym));
            }
            dumpToFile(file_sym, newSym, node->children[0]);
        } else if (otherSym == TOK_NEWARRAY) {
            insertArr(node, node1);
        }
        break;
    case TOK_STRING:
        checkDecl(node);
        if(otherSym == TOK_NEWSTRING) {
            if(node1->children[0]->symbol == TOK_INTCON ||
                    otherSym==TOK_NULL) {
                symbol *newSym = create_symbol(node->children[0]);
                newSym->attributes.set(ATTR_string);
                newSym->attributes.set(ATTR_lval);
                newSym->attributes.set(ATTR_variable);
                if(symbol_stack.back() == nullptr || symbol_stack.empty()) {
                    symbol_table* tab = new symbol_table();
                    tab->insert(symbol_entry(node->children[0]
                                             ->lexinfo,newSym));
                    symbol_stack.pop_back();
                    symbol_stack.push_back(tab);
                } else {
                    symbol_stack.back()->insert(symbol_entry(node->children[0]->
                                                lexinfo,newSym));
                }
                dumpToFile(file_sym, newSym, node->children[0]);
            } else {
                errprintf("%zu.%zu.%zu String size allocator not of "
                          "type int.\n",
                          node1->children[1]->filenr, node1->children[1]->linenr,
                          node1->children[1]->offset);
            }
        } else if (otherSym == TOK_STRINGCON || otherSym==TOK_NULL) {
            if(otherSym!=TOK_NULL)
                strvec.push_back(node1->lexinfo);
            symbol *newSym = create_symbol(node->children[0]);
            newSym->attributes.set(ATTR_string);
            newSym->attributes.set(ATTR_lval);
            newSym->attributes.set(ATTR_variable);
            if(symbol_stack.back() == nullptr || symbol_stack.empty()) {
                symbol_table* tab = new symbol_table();
                tab->insert(symbol_entry(node->children[0]->lexinfo,newSym));
                symbol_stack.pop_back();
                symbol_stack.push_back(tab);
            } else {
                symbol_stack.back()->insert(symbol_entry(node->children[0]->
                                            lexinfo,newSym));
            }

            dumpToFile(file_sym, newSym, node->children[0]);
        } else if(otherSym == TOK_NEWARRAY) {
            insertArr(node, node1);
        }
        break;
    case TOK_TYPEID:
        if(otherSym == TOK_TYPEID || otherSym==TOK_NULL
                || otherSym == TOK_STRUCT) {
            if(node1->symbol != TOK_CALL) {
                string leftStr = *node->lexinfo;
                string rightStr = *node1->children[0]->lexinfo;
                if(leftStr != rightStr) {
                    errprintf("%zu.%zu.%zu Type mismatch between constructor "
                              "and declaration.\n",
                              node1->children[1]->filenr, node1->children[1]->linenr,
                              node1->children[1]->offset);
                }
            } else {
                if(lookup(node1->children[0]->lexinfo)) {
                    symbol* funcSym = lookupSym(node1->children[0]->lexinfo);
                    string leftStr = *node->lexinfo;
                    string rightStr = funcSym->type_id;
                    if(leftStr != rightStr) {
                        errprintf("%zu.%zu.%zu Type mismatch between constructor "
                                  "and declaration.\n",
                                  node1->children[1]->filenr, node1->children[1]->linenr,
                                  node1->children[1]->offset);
                    }
                }
            }
            symbol *newSym = create_symbol(node->children[0]);
            newSym->attributes.set(ATTR_struct);
            newSym->attributes.set(ATTR_lval);
            newSym->attributes.set(ATTR_variable);
            newSym->type_id = *node->lexinfo;
            if(symbol_stack.back() == nullptr || symbol_stack.empty()) {
                symbol_table* tab = new symbol_table();
                tab->insert(symbol_entry(node->children[0]->lexinfo,newSym));
                symbol_stack.pop_back();
                symbol_stack.push_back(tab);
            } else {
                symbol_stack.back()->insert(symbol_entry(node->children[0]->
                                            lexinfo,newSym));
            }

            dumpToFile(file_sym, newSym, node->children[0]);
        } else {
            errprintf("%zu.%zu.%zu Variable not allocated correctly.\n",
                      node1->children[1]->filenr, node1->children[1]->linenr,
                      node1->children[1]->offset);
        }
        break;
    case TOK_IDENT:
        if(lookup(node->lexinfo)) {
            symbol* newSym = lookupSym(node->lexinfo);
            int type = getIdentReturn(newSym);
            if(type==TOK_STRUCT&&otherSym==TOK_TYPEID) {
                if(newSym->type_id!=*node1->children[0]->lexinfo) {
                    errprintf("%zu.%zu.%zu Variable being reassigned wrong "
                              "type",node->filenr,node->linenr,node->offset);
                }
            }
        } else {
            errprintf("%zu.%zu.%zu"
                      " Variable being referenced is undefined\n",node->filenr,
                      node->linenr,node->offset);
        }
    }
}
Example #26
0
 int lastRow() {
     return gametrace.back()->r;
 }
 int getType() {
   return !data.empty() && tool::isNum(data.back());
 }
Example #28
0
 int lastCol() {
     return gametrace.back()->c;
 }
Example #29
0
 void regulation(void) {
     while(value.back() == 0 && value.size() > 1)
         value.pop_back();
     if(value.size() == 1 && value[0] == 0)
         negative = false;
 }
Example #30
0
 void push(int x) {
     v.push_back(x);
     if( minPos.empty() || v[ minPos.back() ] >= x ) {
         minPos.push_back( v.size() - 1 );
     }
 }