int main(int argc, char **argv) { if (argc < 3) { fprintf(stderr, "**ERROR main(): please provide input library and verilog\n"); exit(0); } Library lib; LibraryParser libp(&lib); libp.read(argv[1]); cout << "parse lib done" <<endl; CircuitBuilder cb; cb.set(&lib); cb.set("CK"); // set flip flop functional pins cb.set("Q","QN","D","SI","SE","CK"); if (!cb.read(argv[2])) { fprintf(stderr, "**ERROR main(): verilog parser failed\n"); exit(0); } Circuit cir = cb.getCircuit(); cir.print(); return 0; }
void Spice::saveFile(string filename, Circuit& netList){ ofstream file; file.open(filename.c_str()); // Write if (!file) throw AstranError("Could not save file: " + filename); printHeader (file, "* ", ""); map<string, CellNetlst>::iterator cells_it; for ( cells_it = netList.getCellNetlsts()->begin(); cells_it != netList.getCellNetlsts()->end(); cells_it++ ){ file << ".SUBCKT " << cells_it->first; for ( vector<int>::iterator inouts_it=cells_it->second.getInouts().begin(); inouts_it != cells_it->second.getInouts().end(); inouts_it++ ) file << " " << cells_it->second.getNetName(*inouts_it); file << endl; for(map<string,Inst>::iterator tmp=cells_it->second.getInstances().begin(); tmp!=cells_it->second.getInstances().end(); ++tmp){ file << tmp->first << " "; for(vector<int>::iterator tmp2=tmp->second.ports.begin(); tmp2!=tmp->second.ports.end(); ++tmp2) file << cells_it->second.getNetName(*tmp2) << " "; file << tmp->second.subCircuit << endl; } for(int x=0; x<cells_it->second.size(); x++){ file << cells_it->second.getTrans(x).name << " " << cells_it->second.getNetName(cells_it->second.getTrans(x).drain) << " " << cells_it->second.getNetName(cells_it->second.getTrans(x).gate) << " " << cells_it->second.getNetName(cells_it->second.getTrans(x).source) << " "; if(cells_it->second.getTrans(x).type==PMOS) file << netList.getVddNet() << " PMOS"; else file << netList.getGndNet() << " NMOS"; file << " L=" << cells_it->second.getTrans(x).length << "U W=" << cells_it->second.getTrans(x).width << "U"<< endl; } file << ".ENDS " << cells_it->first << endl << endl; } }
int main() { // Create the top-level circuit Circuit topLevel; // In this example, we use this to store information about the components that // are in the circuit, rather than just the input and output components. // Create the components. topLevel.AddComponent("in1", new Button()); topLevel.AddComponent("in2", new Button()); topLevel.AddComponent("SR", new SRlatch()); topLevel.AddComponent("out1", new LED()); topLevel.AddComponent("out2", new LED()); // Link the components. topLevel.Connect("in1",0,"SR",0); topLevel.Connect("in2",0,"SR",1); topLevel.Connect("SR",0,"out1",0); topLevel.Connect("SR",1,"out2",0); // Specify the input and output components. topLevel.AddInput("in1"); topLevel.AddInput("in2"); topLevel.AddOutput("out1"); topLevel.AddOutput("out2"); // Evaluate the circuit. topLevel.Evaluate(); return 0; }
int main() { Circuit circuit; Lamp lamp; Fan fan; Button button; circuit.setSwitch(&button); circuit.append(&lamp); circuit.append(&fan); button.on(); button.off(); return 0; }
Diode::Diode(Circuit& cir, Node* n1, Node* n2, string name) : TwoEndedDevice(n1, n2, name) { cir.addDevice(this); n1->base.push_back(this); n2->head.push_back(this); }
Resistor::Resistor(Circuit& cir, double R, Node* n1, Node* n2, string name) : TwoEndedDevice(n1, n2, name), R(R) { cir.addDevice(this); n1->base.push_back(this); n2->head.push_back(this); }
int Compute(const Circuit& c, byte *out, int outcount, const byte *in, int incount, int limit = 100) { byte value[COUNT]; memset(value, 0, COUNT); int w = 0; for(int i = 0; i < incount; i++) for(int q = 0x80; q; q >>= 1) value[w++] = !!(q & in[i]); memset(out, 0, outcount); for(int ii = 0; ii < limit; ii++) { c.Evaluate(value); Buffer<byte> nout(outcount, 0); int r = w; for(int i = 0; i < outcount; i++) { nout[i] = 0; for(int q = 0x80; q; q >>= 1) if(value[r++]) nout[i] |= q; } if(memcmp(out, ~nout, outcount) == 0) return ii; memcpy(out, ~nout, outcount); } return limit; }
Inductor::Inductor(Circuit& cir, double H, Node* n1, Node* n2, string name) : TwoEndedDevice(n1, n2, name), H(H) { cir.addDevice(this); n1->base.push_back(this); n2->head.push_back(this); }
Capacitor::Capacitor(Circuit& cir, double C, Node* n1, Node* n2, string name) : TwoEndedDevice(n1, n2, name), C(C) { cir.addDevice(this); n1->base.push_back(this); n2->head.push_back(this); }
//Adds new random gate with a controlled bit, 0 1 or 2 controller bits, and inverted bool void Solver::addNewGates(int k) { for(int i=0;i<k;++i) { Circuit tempCircuit = circuits[i]; int nl = limits[rand()%limits.size()]; vector<int> c; int temp = rand()%3; for(int i=0;i<temp;++i) { c.push_back(limits[rand()%limits.size()]); } temp = rand()%2; Gate g(nl,c,temp); tempCircuit.addGate(g); circuits.push_back(tempCircuit); } }
ECDiode::ECDiode(Circuit& ownerCircuit) : Component(ownerCircuit) { m_diode = new Diode(); ElementMap *map = new ElementMap(m_diode); m_elementMapList.append(map); m_pinMap.insert("n1", new ECNode(ownerCircuit, map->pin(0))); m_pinMap.insert("p1", new ECNode(ownerCircuit, map->pin(1))); DiodeSettings ds; // it will have the default properties that we use Property * i_s = new Property("I_S", Variant::Type::Double); i_s->setCaption(tr("Saturation Current")); i_s->setUnit("A"); i_s->setMinValue(1e-20); i_s->setMaxValue(1e-0); i_s->setValue(ds.I_S); i_s->setAdvanced(true); addProperty(i_s); Property *n = new Property("N", Variant::Type::Double); n->setCaption(tr("Emission Coefficient")); n->setMinValue(1.0); n->setMaxValue(1e1); n->setValue(ds.N); n->setAdvanced(true); addProperty(n); Property *v_b = new Property("V_B", Variant::Type::Double); v_b->setCaption(tr("Breakdown Voltage")); v_b->setUnit("V"); v_b->setMinAbsValue(1e-5); v_b->setMaxValue(1e10); v_b->setValue(ds.V_B); v_b->setAdvanced(true); addProperty(v_b); // createProperty( "R", Variant::Type::Double ); // property("R")->setCaption( i18n("Series Resistance") ); // property("R")->setUnit( QChar(0x3a9) ); // property("R")->setMinValue(1e-5); // property("R")->setMaxValue(1e0); // property("R")->setValue( ds.R ); // property("R")->setAdvanced(true); ownerCircuit.addComponent(this); }
Capacitor::Capacitor(Circuit &ownerCircuit) : Component(ownerCircuit) { // model m_capacitance = new Capacitance(0.001, LINEAR_UPDATE_PERIOD); ElementMap *m_elemMap = new ElementMap(m_capacitance); m_elementMapList.append(m_elemMap); // pins m_pinMap.insert("n1", new ECNode(ownerCircuit, m_elemMap->pin(0))); m_pinMap.insert("p1", new ECNode(ownerCircuit, m_elemMap->pin(1))); Property *cap = new Property("Capacitance", Variant::Type::Double); cap->setCaption(tr("Capacitance")); cap->setUnit("F"); cap->setMinValue(1e-12); cap->setMaxValue(1e12); cap->setValue(1e-3); addProperty(cap); ownerCircuit.addComponent(this); }
void timeStep(Circuit &c){ double dt = c.dt; double iR = c.iR; double iC = c.iC; for(int i = 0; i < c.Vin.rows; i++){ for(int j = 0; j < c.Vin.cols; j++){ for(int index = 0; index < 3;index++){ double _Vout = c.Vout(i,j)[index]; double _dVout = c.dVout(i,j)[index]; double _ddVout = ((c.Vin(i,j)[index] -c.Vin_prev(i,j)[index]) -_dVout)*iR*iC; c.Vout(i,j)[index] = _Vout+_dVout*dt; c.dVout(i,j)[index] = _dVout+_ddVout*dt; c.qVout(i,j)[index] = _Vout; } } } }
//BEGIN class ADDAC ADDAC::ADDAC(Circuit& ownerCircuit) : Component(ownerCircuit) { m_numBits = 0; m_range = 0; Property *bits = new Property("numBits", Variant::Type::Int); bits->setCaption( tr("Number Bits") ); bits->setMinValue(2); bits->setMaxValue(max_ADDAC_bits); bits->setValue(2); addProperty(bits); Property *range = new Property("range", Variant::Type::Double); range->setCaption( tr("Input Range") ); range->setUnit("V"); range->setMinValue(-1e12); range->setMaxValue(1e12); range->setValue(5); addProperty(range); /* createProperty( "numBits", Variant::Type::Int ); property("numBits")->setCaption( i18n("Number Bits") ); property("numBits")->setMinValue(2); property("numBits")->setMaxValue(max_ADDAC_bits); property("numBits")->setValue(2); createProperty( "range", Variant::Type::Double ); property("range")->setCaption( i18n("Input Range") ); property("range")->setUnit("V"); property("range")->setMinValue(-1e12); property("range")->setMaxValue(1e12); property("range")->setValue(5); */ ownerCircuit.addComponent(this); }
bool operator()(Juggler &lhs, Juggler &rhs) const { return ComputeMatchscore(circuit_.skills(),lhs.skills()) > ComputeMatchscore(circuit_.skills(), rhs.skills()); }
int main(int argc, char **argv) { // default values unsigned int numBits = 0; string outFilename = ""; Circuit c; // parsing inputs if (argc < 2) { usage(argv[0]); } if (argv[1] == string("-h") || argv[1] == string("-help")) { usage(argv[0]); } for (int i = 1; i < argc; ++i) { if (argv[1] == string("-h") || argv[1] == string("-help")) { usage(argv[0]); } else if (argv[i] == string("-add")) { if (i+2 < argc) { numBits = static_cast<unsigned>(atoi(argv[++i])); outFilename = argv[++i]; if (!c.createADDModule("a", "b", "cin", "s", "cout", numBits)) { cout << "Adder module successfully created." << endl; // your code here c.setName("pyongjoo_adder"); c.setPIs("a", 0, numBits); c.setPIs("b", 0, numBits); c.setPI("cin"); c.setPOs("s", 0, numBits); c.setPO("cout"); c.writeBLIF(outFilename); } else cout << "Problem creating adder module." << endl; } else { cout << "option -add requires two arguments" << endl; usage(argv[0]); } } else if (argv[i] == string("-sub")) { if (i+2 < argc) { numBits = static_cast<unsigned>(atoi(argv[++i])); outFilename = argv[++i]; if (!c.createSUBModule("a", "b", "s", numBits)) { cout << "Subtractor module successfully created." << endl; // your code here c.setName("pyongjoo_subtractor"); c.setPIs("a", 0, numBits); c.setPIs("b", 0, numBits); c.setPOs("s", 0, numBits); c.writeBLIF(outFilename); } else cout << "Problem creating substractor module." << endl; } else { cout << "option -sub requires two arguments" << endl; usage(argv[0]); } } else if (argv[i] == string("-shift")) { if (i+3 < argc) { numBits = static_cast<unsigned>(atoi(argv[++i])); unsigned int numShift = static_cast<unsigned>(atoi(argv[++i])); outFilename = argv[++i]; if (!c.createSHIFTModule("orig", "out", numBits, numShift)) { cout << "Shifter module successfully created." << endl; c.setName("shifter"); c.setPIs("orig", 0, numBits); c.setPOs("out", 0, numBits+numShift); // c.print(); // optional c.writeBLIF(outFilename); } else cout << "Problem creating shifter module." << endl; } else { cout << "option -shift requires three arguments" << endl; usage(argv[0]); } } else if (argv[i] == string("-absmin5x3y")) { if (i+1 < argc) { outFilename = argv[++i]; if (!c.createABSMIN5X3YModule("x", "y", "z")) { cout << "abs(min(5x, 3y)) module successfully created." << endl; // your code here c.setName("pyongjoo_absmin5x3y"); c.setPIs("x", 0, 16); c.setPIs("y", 0, 16); c.setPOs("z", 0, 19); c.writeBLIF(outFilename); } else cout << "Problem creating abs(min(5x, 3y)) module." << endl; } else { cout << "option -absmin5x3y requires one argument" << endl; usage(argv[0]); } } else { cout << "unrecognized command" << argv[i] << endl; usage(argv[0]); } } return 0; }
void run() { input->poll_input(); if(circuit && !settings.pause) { circuit->run(2.5e-3 / Circuit::timescale); // Run 2.5 ms //circuit->run(100.0e-6 / Circuit::timescale); // Run 100 us uint64_t emu_time = circuit->global_time * 1000000.0 * Circuit::timescale; // Make sure real time is at least mostly caught up if(settings.throttle) while(circuit->rtc.get_usecs() + 50000 < emu_time); // If real time is too far ahead, adjust timer if(circuit->rtc.get_usecs() > emu_time + 100000) circuit->rtc += (circuit->rtc.get_usecs() - emu_time - 100000); if(real_time.get_usecs() > 1000000) { setStatusText({"FPS: ", circuit->video.frame_count}); circuit->video.frame_count = 0; real_time += 1000000; } //if(emu_time > 1.56e6) onClose(); } else { SDL_Delay(10); if(settings.pause && statusText() != "Paused") setStatusText("Paused"); else if(!settings.pause && statusText() != VERSION_STRING) setStatusText(VERSION_STRING); if(circuit == nullptr && (focused() || video_window.focused())) drawLogo(); } if(input_window.active_selector) { auto key_state = Keyboard::state(); for(unsigned i = 0; i < key_state.size(); i++) if(key_state[i]) input_window.active_selector->assign({KeyAssignment::KEYBOARD, i}); //Check Joystick Events SDL_Event event; while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_JOYBUTTONDOWN: input_window.active_selector->assign({KeyAssignment::JOYSTICK_BUTTON, event.jbutton.button, event.jbutton.which}); break; case SDL_JOYAXISMOTION: if(!input_window.active_selector->allow_joystick) break; if(abs(event.jaxis.value) > 8192) { unsigned axis = (event.jaxis.axis << 1) | (event.jaxis.value > 0); input_window.active_selector->assign({KeyAssignment::JOYSTICK_AXIS, axis, event.jaxis.which}); } default: break; } } } else // Handle user interface inputs { UserInterfaceState ui_state = UserInterfaceState::getCurrent(*this); // Don't update ui inputs while main window is in the background if(focused()) { if(ui_state.quit && !prev_ui_state.quit) { onClose(); } if(ui_state.pause && !prev_ui_state.pause) { settings.pause = !settings.pause; pause_item.setChecked(settings.pause); } if(ui_state.fullscreen && !prev_ui_state.fullscreen) { fullscreen_item.setChecked(!settings.fullscreen); fullscreen_item.onToggle(); } if(ui_state.throttle && !prev_ui_state.throttle) { throttle_item.setChecked(!settings.throttle); throttle_item.onToggle(); } } prev_ui_state = ui_state; } }
void Spice::readFile(string nome, Circuit& netlist, bool reading_cadence) { ifstream arq (nome.c_str()); string linha; if (!arq.is_open()) throw AstranError("Could not open Spice file: " + nome ); vector<string> palavras; string palavra; CellNetlst subcktCell,topCell; CellNetlst *currentCell=&topCell; topCell.setName(upcase(removeExt(getFileName(nome)))); string cellName; unsigned int lineNr=0; while (!arq.eof()){ lineNr++; getline(arq,linha); palavras.clear(); istrstream clin(linha.c_str()); while (clin>>palavra) palavras.push_back(upcase(palavra)); if (palavras.size() == 0 || palavras[0] == ".GLOBAL") continue; if (palavras[0] == "*INTERFACE"){ if(palavras.size() == 4 || palavras.size() == 6){ IOType type; direction orient; switch(palavras[2][palavras[2].size()-1]){ case 'N': orient=N; break; case 'S': orient=S; break; case 'E': orient=E; break; case 'W': orient=W; break; default: throw AstranError("Line" + intToStr(lineNr) + ": Interface orientation unknown."); } switch(palavras[3][0]){ case 'I': type=IOTYPE_INPUT; break; case 'O': type=IOTYPE_OUTPUT; break; default: throw AstranError("Line" + intToStr(lineNr) + ": Interface type unknown. Use INPUT or OUTPUT"); } topCell.insertInOut(palavras[1]); netlist.insertInterface(palavras[1], orient, type, 0, 0); } else throw AstranError("Line" + intToStr(lineNr) + ": Number of parameters for *interface is not correct"); continue; } if (reading_cadence && palavras[0] == "*" && palavras.size() == 5 && palavras[1] == "SUBCIRCUIT"){ currentCell->clear(); topCell.setName(palavras[4].substr(0,palavras[4].size()-1)); } if (palavras[0][0] == '*' || palavras[0][0] == 'C' || palavras[0][0] == '+' || palavras[0][0] == 'D' || (palavras[0][0]=='X' && reading_cadence)) // corrigir aqui para ler o '+' e ignorar os parâmetros desnecessários continue; if (palavras[0] == ".MODEL" || palavras[0] == ".END") break; if (palavras[0] == ".SUBCKT" && currentCell==&topCell && !reading_cadence){ // It's a new cell definition. . . subcktCell.clear(); currentCell=&subcktCell; cellName=palavras[1]; // compare if subcircuit name is the same as the top cell name if(cellName == topCell.getName()){ string topname = topCell.getName() + "-TOP"; topCell.setName(topname); } for (int p=2; p<palavras.size(); p++) currentCell->insertInOut(palavras[p]); } else if (palavras[0] == string(".INCLUDE")){ readFile(getPath(nome)+palavras[1],netlist,reading_cadence); // throw AstranError("Could not read included file in line: " + intToStr(lineNr)); } // declaring transistor in subcircuit read from Cadence else if (palavras[0][0] == 'M' && palavras.size()>=5){ // insert in and out pins if (reading_cadence){ for (int p=1; p<5; ++p){ if (!isNumber(palavras[p]) || palavras[p] == "0") currentCell->insertInOut(palavras[p]); } } // identify transistor type transType type; if(palavras[5]=="PMOS" || palavras[5]=="CMOSP" || palavras[5]=="MODP" || palavras[5]=="PMOS_VTL") type=PMOS; else if(palavras[5]=="NMOS" || palavras[5]=="CMOSN" || palavras[5]=="MODN" || palavras[5]=="NMOS_VTL") type=NMOS; else throw AstranError("Line" + intToStr(lineNr) + ": Parameter " + palavras[5] + " is incorrect. Use NMOS or PMOS"); // get parameters' values float length=0, width=0; for (int p=6; p<palavras.size(); p++){ int pos=palavras[p].find("="); string parm=palavras[p].substr(0,pos++); float tam=atof((palavras[p].substr(pos)).c_str())*getFactor(palavras[p][palavras[p].size()-1])*getFactor(palavras[p][palavras[p].size()-2]); if(parm=="L") length=tam; else if(parm=="W") width=tam; else if(parm!="AD" && parm!="PD" && parm!="AS" && parm!="PS" && parm!="NRD" && parm!="NRS" && parm!="M") throw AstranError("Line" + intToStr(lineNr) + ": Parameter " + parm + " not supported"); } // insert transistor in cell currentCell->insertTrans(palavras[0], palavras[1], palavras[2], palavras[3], type, length, width); } else if (palavras[0][0] == 'X' && !reading_cadence){ string instName=palavras[0]; vector<string> net_ids; int p; for (p=1; p<palavras.size()-1; p++) net_ids.push_back(palavras[p]); currentCell->insertInstance(instName, palavras[p], net_ids); } else if (currentCell==&subcktCell && palavras[0] == ".ENDS"){ currentCell->setName(cellName); netlist.insertCell(*currentCell); currentCell=&topCell; } else throw AstranError("Line" + intToStr(lineNr)); } if(topCell.getNets().size() != 0) netlist.insertCell(topCell); }
int main() { // Create the top-level circuit Circuit topLevel; // Create the components topLevel.AddComponent("D", new CircuitInput()); topLevel.AddComponent("CLK", new CircuitInput()); topLevel.AddComponent("Top", new SRlatch()); topLevel.AddComponent("Bottom", new SRlatch()); topLevel.AddComponent("Out", new SRlatch()); topLevel.AddComponent("clk_splitter", new Splitter(2)); topLevel.AddComponent("bottom_splitter", new Splitter(2)); topLevel.AddComponent("end", new Dead(1)); topLevel.AddComponent("orGate", new Or()); topLevel.AddComponent("Q", new LED()); topLevel.AddComponent("Qbar", new LED()); // Link the components. topLevel.Connect("D",0,"Top",1); // D -- Top::S topLevel.Connect("CLK",0,"clk_splitter",0); // CLK -- clk_splitter topLevel.Connect("clk_splitter",0,"orGate",0); // clk_splitter::0 -- orGate::0 topLevel.Connect("clk_splitter",1,"Bottom",0); // clk_splitter::1 -- Bottom::R topLevel.Connect("orGate",0,"Top",0); // orGate -- Top::R topLevel.Connect("Top",0,"Out",1); // Top::Q -- Out::S topLevel.Connect("Top",1,"Bottom",1); // Top::Qbar -- Bottom::S topLevel.Connect("Bottom",0,"bottom_splitter",0); // Bottom::Q -- bottom_splitter topLevel.Connect("Bottom",1,"end",0); // Bottom::Qbar -- x_x topLevel.Connect("bottom_splitter",0,"orGate",1); // bottom_splitter::0 -- orGate::1 topLevel.Connect("bottom_splitter",1,"Out",0); // bottom_splitter::1 -- Out::R topLevel.Connect("Out",0,"Q",0); // Out::0 -- Q topLevel.Connect("Out",1,"Qbar",0); // Out::1 -- Qbar // Specify the input and output components. topLevel.AddInput("D"); topLevel.AddInput("CLK"); topLevel.AddOutput("Q"); topLevel.AddOutput("Qbar"); // Start Evaluating the Circuit topLevel.Evaluate(); dynamic_cast<CircuitInput*>(topLevel.Lookup("CLK").body())->SetState(false); dynamic_cast<CircuitInput*>(topLevel.Lookup("D").body())->SetState(false); cout << "----------\n"; cout << "CLK: 0\n"; cout << "D: 0\n"; topLevel.Evaluate(); dynamic_cast<CircuitInput*>(topLevel.Lookup("CLK").body())->SetState(false); dynamic_cast<CircuitInput*>(topLevel.Lookup("D").body())->SetState(true); cout << "----------\n"; cout << "CLK: 0\n"; cout << "D: 1\n"; topLevel.Evaluate(); dynamic_cast<CircuitInput*>(topLevel.Lookup("CLK").body())->SetState(true); dynamic_cast<CircuitInput*>(topLevel.Lookup("D").body())->SetState(true); cout << "----------\n"; cout << "CLK: 1\n"; cout << "D: 1\n"; topLevel.Evaluate(); dynamic_cast<CircuitInput*>(topLevel.Lookup("CLK").body())->SetState(false); dynamic_cast<CircuitInput*>(topLevel.Lookup("D").body())->SetState(true); cout << "----------\n"; cout << "CLK: 0\n"; cout << "D: 1\n"; topLevel.Evaluate(); dynamic_cast<CircuitInput*>(topLevel.Lookup("CLK").body())->SetState(true); dynamic_cast<CircuitInput*>(topLevel.Lookup("D").body())->SetState(true); cout << "----------\n"; cout << "CLK: 1\n"; cout << "D: 1\n"; topLevel.Evaluate(); dynamic_cast<CircuitInput*>(topLevel.Lookup("CLK").body())->SetState(true); dynamic_cast<CircuitInput*>(topLevel.Lookup("D").body())->SetState(false); cout << "----------\n"; cout << "CLK: 1\n"; cout << "D: 0\n"; topLevel.Evaluate(); dynamic_cast<CircuitInput*>(topLevel.Lookup("CLK").body())->SetState(false); dynamic_cast<CircuitInput*>(topLevel.Lookup("D").body())->SetState(false); cout << "----------\n"; cout << "CLK: 0\n"; cout << "D: 0\n"; topLevel.Evaluate(); dynamic_cast<CircuitInput*>(topLevel.Lookup("CLK").body())->SetState(false); dynamic_cast<CircuitInput*>(topLevel.Lookup("D").body())->SetState(true); cout << "----------\n"; cout << "CLK: 0\n"; cout << "D: 1\n"; topLevel.Evaluate(); dynamic_cast<CircuitInput*>(topLevel.Lookup("CLK").body())->SetState(true); dynamic_cast<CircuitInput*>(topLevel.Lookup("D").body())->SetState(true); cout << "----------\n"; cout << "CLK: 1\n"; cout << "D: 1\n"; topLevel.Evaluate(); dynamic_cast<CircuitInput*>(topLevel.Lookup("CLK").body())->SetState(false); dynamic_cast<CircuitInput*>(topLevel.Lookup("D").body())->SetState(false); cout << "----------\n"; cout << "CLK: 0\n"; cout << "D: 0\n"; topLevel.Evaluate(); return 0; }
/** * Function that return a neighbour of the function randomly * if we have nb_sta stations, we pick a position in 0,nb_sta-1 and we select the * corresponding station in circuit */ void AnnealingSolver::get_neighbour(Solution* sol, Solution* old_sol, int recuit_variant) { // Clearing the new sol and copying the old solution into the new one. sol->clear(); sol->copy(old_sol); // Chosing a station randomly, to be removed. Station* station; bool found = false; while(!found) { int station_id = rand() % inst->nb_stations; logn4("We selected the station at position : " + to_string(station_id)); for (Circuit* circuit : *(sol->circuits)) { list<Station*>* stations = circuit->stations; logn5("Circuit " + to_string(circuit->remorque->id) + " whith size " + to_string(stations->size())); if (station_id < stations->size()) { if (stations->size() == 1) { break; } else { // Finding station std::list<Station*>::iterator it = stations->begin(); std::advance(it, station_id); station = *(it); // Removing station from circuit stations->erase(it); found = true; break; } } else station_id -= stations->size(); } } // We remove the station from the circuit if (recuit_variant == 0) { //// INSERT BEST // Chosing a cuircuit where we will insert_best the solution to. int remorque_id = rand() % inst->nb_remorques; logn4("We selected the remorque with id : " + to_string(remorque_id)); Circuit* circuit = sol->circuits->at(remorque_id); circuit->insert_best(station); } else if (recuit_variant == 1) { //// NORMAL INSERT // Chosing a cuircuit where we will insert_best the solution to. int position_id = rand() % (inst->nb_remorques + inst->nb_stations -1); logn4("We selected the position number : " + to_string(position_id)); for (Circuit* circuit : *(sol->circuits)) { list<Station*>* stations = circuit->stations; logn5("Circuit " + to_string(circuit->remorque->id) + " whith size " + to_string(stations->size())); if (position_id < stations->size()) { // Finding position std::list<Station*>::iterator it = stations->begin(); std::advance(it, position_id); logn5("Adding station at position"+ to_string(position_id) + " of remorque : " + to_string(circuit->remorque->id)); // Removing station from circuit stations->insert(it,station); break; } else if (position_id == stations->size()) { logn5("Adding station at last position of remorque : " + to_string(circuit->remorque->id)); stations->push_back(station); break; } else position_id -= stations->size() + 1; } } else { logn1("Please set option --recuit-variant to 0 or 1"); exit(2); } // Update and return sol->update(); return; }
void VerifyIdea::singleVerify(Circuit &cir, Wave *waves, pgNs::PowerGrid &pg, const Transition *trans, VERIFY_TYPE type) { std::string fileName = "../../spCombine/circuit/" + cir.getName() + ".sp"; std::ifstream fin(fileName.c_str()); if(!fin) { std::cout << "**ERROR VerifyIdea::verify: Can't find file " << fileName << std::endl; return; } string spFileName = "./verify/test.sp"; SpMaker sp(spFileName); std::string line; while(std::getline(fin , line)) { //cout << line << endl; sp.add( line ); if(line == "* INPUT") break; } /* V1 G0 0 PWL(0ns 0v 2ns 0v 2.001ns 1.1v 4ns 1.1v) V2 G1 0 PWL(0ns 0v 2ns 0v 2.001ns 1.1v 4ns 1.1v) V3 G2 0 PWL(0ns 1.1v 2ns 1.1v 2.001ns 0v 4ns 0v) V4 G3 0 PWL(0ns 1.1v 2ns 1.1v 2.001ns 0v 4ns 0v) V5 test_se 0 0v V6 test_si 0 1.1v*/ // setup voltage source for(unsigned i = 0 ; i < pg.vddNodes.size() ; ++i){ string nodeName(pg.getNodes()[pg.vddNodes[i]].getName()); size_t found = nodeName.find("."); assert(found != string::npos); nodeName[found] = '_'; sp.add("VDDSOURCE " + nodeName + " 0 1.1v"); } for(unsigned i = 0 ; i < pg.gndNodes.size() ; ++i){ string nodeName(pg.getNodes()[pg.gndNodes[i]].getName()); size_t found = nodeName.find("."); assert(found != string::npos); nodeName[found] = '_'; sp.add("VSSSOURCE " + nodeName + " 0 0v"); } // setup PPI const vector<Cell> &cells = cir.getCells(); const vector<Net> &nets = cir.getNets(); string ffstring = "* flip-flop switch"; sp.add( ffstring ); int qPin = lib->getFanoutIndex(cells[cir.ff[0]].type, "Q"); int qnPin = lib->getFanoutIndex(cells[cir.ff[0]].type, "QN"); for(unsigned i = 0 ; i < cir.ff.size() ; ++i) { int cellID = cir.ff[i]; // print Q int netQ = cells[cellID].opt_net_id[qPin]; if(netQ != -1){ // string line = printNet(cells[cellID].name + "_Q" ,waves[netQ]); string qNode = cells[cellID].name + "_Q"; double val = (waves[netQ].initialValue == Wave::H)?pg.getSupplyVoltage():0; stringstream ss; ss << val; sp.add(".ic v("+qNode+")="+ss.str()); if(val != 0){ sp.add(".ic v(X"+cells[cellID].name+"."+"N_8_M8_s"+")=1.1v"); sp.add(".ic v(X"+cells[cellID].name+"."+"n_5_m20_g"+")=1.1v"); }else { sp.add(".ic v(X"+cells[cellID].name+"."+"N_8_M8_s"+")=0v"); sp.add(".ic v(X"+cells[cellID].name+"."+"n_5_m20_g"+")=0v"); } } // print QN int netQN = cells[cellID].opt_net_id[qnPin]; if(netQN != -1){ //string line = printNet(cells[cellID].name + "_QN",waves[netQN]) ; //sp.add( line); string qNode = cells[cellID].name + "_QN"; double val = (waves[netQN].initialValue == Wave::H)?pg.getSupplyVoltage():0; stringstream ss; ss << val; sp.add(".ic v("+qNode+")="+ss.str()); } } sp.add("* PI switch"); // setup PI for(unsigned i = 0 ; i < cir.pi.size() ; ++i) { int netID = cir.pi[i]; string line = printNet(nets[netID].name,waves[netID]); sp.add( line ); } if(trans == NULL) { spicePathDelay.push_back(0); spicePathDelayIR.push_back(0); ideaPathDelay.push_back(0); ideaPathDelayIR.push_back(0); } // setup measurement setPathMeasurement(true, sp, trans, cir); while(std::getline(fin,line)) { if(line == ".END") setPathMeasurement(false, sp, trans, cir); sp.add( line ); } if(type == HSPICE) sp.spiceSim(); else sp.nanoSim(); printResult(sp, trans, cir, waves); }
Skillset::Rating GetWorstMatchscore() const { return ComputeMatchscore(circuit_.skills(), jugglers_.front().skills()); }
int main(int argc, char* argv[]) { Circuit circ; Node *p[10]; p[0] = circ.addInput("X"); p[1] = circ.addInput("Y"); p[2] = circ.addInput("C"); p[3] = circ.addGate(AND, "D"); p[4] = circ.addGate(XOR, "E"); p[5] = circ.addGate(AND, "F"); p[6] = circ.addGate(XOR, "G"); p[7] = circ.addGate(OR, "H"); p[8] = circ.addOutput("Cout"); p[9] = circ.addOutput("S"); circ.addWire(p[0], p[3]); circ.addWire(p[1], p[3]); circ.addWire(p[0], p[4]); circ.addWire(p[1], p[4]); circ.addWire(p[3], p[7]); circ.addWire(p[4], p[5]); circ.addWire(p[2], p[5]); circ.addWire(p[4], p[6]); circ.addWire(p[2], p[6]); circ.addWire(p[5], p[7]); circ.addWire(p[7], p[8]); circ.addWire(p[6], p[9]); cout << circ.getInputNames() << "-" << circ.getOutputNames() << endl; for(int i=0;i<2;i++) { for(int j=0;j<2;j++) { for(int k=0;k<2;k++) { string input; input=string2int(i); // here we convert int to string input+=string2int(j); input+=string2int(k); circ.setInputs(input); circ.eval(); cout << circ.getInputStates() << "-" << circ.getOutputs() << endl; } } } }
void VerifyIdea::setPathMeasurement(bool ideal, SpMaker &sp , const Transition *trans, Circuit &cir) { sp.add("* Measurement"); const vector<Cell> &cells = cir.getCells(); const vector<Net> &nets = cir.getNets(); const Transition *t = trans; while(t) { // get the net of transition int netID = t->netID; // get the net of previous transition int prevNetID = -1; if(t->prevTransition) prevNetID = t->prevTransition->netID; else break;// there are no previous transition anymore // get the cell between above two transition int cellID = nets[netID].ipt_cell_id; string cellName = cells[cellID].name; // get pin name connected the cell and net vector<int>::const_iterator optPinIDIter;// = find(cells[cellID].opt_net_id.begin() , cells[cellID].opt_net_id.end() , netID); for(optPinIDIter = cells[cellID].opt_net_id.begin() ; optPinIDIter != cells[cellID].opt_net_id.end() ; optPinIDIter++) if(*optPinIDIter == netID) break; assert(optPinIDIter != cells[cellID].opt_net_id.end()); int optPinID = optPinIDIter - cells[cellID].opt_net_id.begin(); string optPinName = lib->getFanoutName(cells[cellID].type , optPinID); // get pin name connected the cell and previous net vector<int>::const_iterator iptPinIDIter;// = find(cells[cellID].ipt_net_id.begin() , cells[cellID].ipt_net_id.end() , prevNetID); for(iptPinIDIter = cells[cellID].ipt_net_id.begin() ; iptPinIDIter != cells[cellID].ipt_net_id.end() ; iptPinIDIter++) if(*iptPinIDIter == prevNetID) break; assert(iptPinIDIter != cells[cellID].ipt_net_id.end()); int iptPinID = iptPinIDIter - cells[cellID].ipt_net_id.begin(); string iptPinName = lib->getFaninName(cells[cellID].type , iptPinID); string nodeOptPin = cellName + "_" + optPinName; string nodeIptPin = cellName + "_" + iptPinName; bool optPinRise = t->value == Wave::H; bool iptPinRise = t->prevTransition->value == Wave::H; double averageV = 0.55; sp.setMeasure(nodeIptPin , averageV , iptPinRise , nodeOptPin , averageV , optPinRise , cellName + "_delay"); double vstart = (iptPinRise)?0.33:0.77; double vend = (iptPinRise)?0.77:0.33; sp.setMeasure(nodeIptPin , vstart , iptPinRise , nodeIptPin , vend , iptPinRise , cellName + "_transition"); vstart = (optPinRise)?0.33:0.77; vend = (optPinRise)?0.77:0.33; //.meas TRAN U11_transition TRIG v(U11_A1) VAL=0.77 fall=1 TARG v(U11_A1) VAL=0.33 fall=1 //os << ".meas TRAN " << cellName << "_vh TRIG v(" << nodeOptPin << ") VAL=" << vstart << " fall=" << optPinRise << " TRAG v(" << nodeOptPin << ") VAL=" << vend << " fall=" << optPinRise; //sp.add(os.str()); //sp.setMeasure(nodeOptPin , vstart , optPinRise , nodeOptPin , vend , optPinRise , cellName + "_vh"); t = t->prevTransition; } /*void setMeasure(const std::string &node1 ,double value1, bool rise1, const std::string &node2, double value2, bool rise2 , const std::string& measureName);*/ }
bool VerifyIdea::verify(Circuit &cir, Wave *waves, int patternID , const string &workspace) { cir_ = ○ // circuit directory stringstream ss; ss << patternID; string patDir = workspace + "/pat" + ss.str(); // open hspice simulation result string simResult = patDir + "/sp_result.txt"; ifstream fin(simResult.c_str()); // if hspice result doesn't exist, try nanosim simulation result if(!fin) { cout << "**WARRN: can't find result in " << patDir << "/sp_result.txt" << endl; return false; string simResult2 = patDir + "/nano_result.txt"; fin.open(simResult2.c_str()); } // if both result not exist, stop verify if(!fin) { cout << "**WARRN: can't find result in " << patDir << "/nano_result.txt" << endl; return false; } string measName; double pathDelay; double extraDelay; fin >> measName >> measName >> pathDelay >> extraDelay; // there is no transition in po or ppo // happend at s27 pattern 1 if(pathDelay == 0 && extraDelay == 0) return true; // measure names in sp_result have an addition character '=' // we need to delete it if(*measName.rbegin() == '=') measName.erase(measName.end()-1); // remove _r_delay or _f_delay measName.erase(measName.end()-8,measName.end()); cout << "test: " << measName << endl; int cellID = cir.getCellID(measName); int netID = -1; if(cellID == -1) netID = cir.getNetID(measName); if(cellID == -1 && netID == -1) { cout << "can't match po or ppo" << endl; return false; } if(netID == -1) netID = cir.cells[cellID].ipt_net_id[0]; cout << "net name: " << cir.nets[netID].name << endl; if(waves[netID].transition.size() == 0) return false; const Transition *lastTrans = &waves[netID].transition.back(); pathVerify(lastTrans , pathDelay , extraDelay); cout << "success" << endl; return true; }
void VerifyIdea::printResult(SpMaker &sp , const Transition *trans, Circuit &cir, Wave *wave) { const vector<Cell> &cells = cir.getCells(); const vector<Net> &nets = cir.getNets(); const Transition *t = trans; cout << "=========================Critical Path=============================" << endl; cout << endl; double pathDelaySpiceIR(0); double extraPathDelayIdea(0); double pathDelaySpice(0); double pathDelayIdea(0); bool lastGate = true; while(t) { // get the net of transition int netID = t->netID; // get the net of previous transition int prevNetID = -1; if(t->prevTransition) prevNetID = t->prevTransition->netID; else break;// there are no previous transition anymore // get the cell between above two transition int cellID = nets[netID].ipt_cell_id; string cellName = cells[cellID].name; double cap = (t->value==Wave::H)?nets[netID].totalRiseCap:nets[netID].totalFallCap; vector<Measurement >measure = sp.getAlterMeasure(cellName + "_delay"); vector<Measurement >measuret = sp.getAlterMeasure(cellName + "_transition"); double spiceDelay = measure[0].gateDelay*1e9; double spiceDelay2 = measure[1].gateDelay*1e9; double gateDelay = t->time - t->prevTransition->time; int transitionID = idea->transitionIDs[t]; double extraGateDelay = idea->extraGateDelays[idea->extraGateDelays.size()/2][transitionID]; double vl = idea->vls[transitionID]; double vh = idea->vhs[transitionID]; cout << "----------------------------------" << endl; cout << "cell name : \t" << cellName << endl; cout << "cell type : \t" << cir.cell_types[cells[cellID].type] << endl; cout << "value : \t" << t->value << endl; cout << "time : \t" << t->time << endl; cout << "spice delay : \t" << measure[0].gateDelay*1e9 <<endl; cout << "spice extra delay: \t" << measure[1].gateDelay*1e9 - measure[0].gateDelay*1e9 <<endl; cout << "spice ir factor : \t" << (measure[1].gateDelay*1e9 - measure[0].gateDelay*1e9)/measure[0].gateDelay*1e-9<<endl; cout << "library delay : \t" << gateDelay << " " << gateDelay/spiceDelay << " " << gateDelay/spiceDelay2<< endl; cout << "idea extra delay : \t" << extraGateDelay << endl; cout << "idea ir factor : \t" << extraGateDelay/gateDelay << endl; cout << "vdd, gnd : \t" << vh << " " << vl << endl; cout << "real transition: : \t" << measuret[0].gateDelay*1e9 <<" " << measuret[1].gateDelay*1e9 << endl; cout << "idea ipt transition : \t" << t->prevTransition->period << endl; cout << "idea opt cap : \t" << cap << endl; if(lastGate){ pathDelaySpiceIR = measure[1].endTime; pathDelaySpice = measure[0].endTime; pathDelayIdea = t->time; lastGate = false; } extraPathDelayIdea += extraGateDelay; t = t->prevTransition; } cout << "path delay spice : " << pathDelaySpice << endl; cout << "path delay spice IR: " << pathDelaySpiceIR << endl; cout << "path delay idea : " << pathDelayIdea << endl; cout << "path delay idea IR : " << pathDelayIdea + extraPathDelayIdea << endl; cout << "error : " << (pathDelayIdea - pathDelaySpice*1e9)/pathDelaySpice<<endl; cout << "extra error: " << (extraPathDelayIdea - (pathDelaySpiceIR - pathDelaySpice)*1e9)/(pathDelaySpiceIR - pathDelaySpice)/1e9<<endl; cout << "portion : " << (pathDelaySpiceIR - pathDelaySpice) / pathDelaySpiceIR<<endl; }
int main(int argc , char ** argv) { // set timer clock_t t1, t2; t1 = clock(); // check files if(argc < 4) { cout << "please input verlog, sdf and pat file" <<endl; return 0; } // ================================================================================ // cell manager contain nangate45 library information(pin name and cell type names) // ================================================================================ Library lib; LibraryParser libp(&lib); if(!libp.read(argv[1])) { cout << "**ERROR main(): LIB parser failed" <<endl; return 0; } // =============================================================================== // use circuit builder to build a circuit // =============================================================================== CircuitBuilder cb; // tell circuit builder to build the circuit using cells in cell manager cb.set(&lib); // tell circuit builder to build the levelized circuit whose clk is set to level 0 cb.set("CK"); // set flip flop functional pins cb.set("Q","QN","D","SI","SE","CK"); // read the circuit if(!cb.read(argv[2])) { cout << "read verlog file fail" <<endl; return 0; } // get the circuit Circuit cir = cb.getCircuit(); // =============================================================================== // use pattern set to read the pattern // =============================================================================== cout << "read pattern" <<endl; PatternSet ps; // tell pattern set to build ppi and pi order according to cell ID in the circuit ps.set(&cir); // read the pattern file if(!ps.setFile(argv[4])) { cout << "read pattern file fail" <<endl; return 0; } ps.readAll(); // =============================================================================== // use circuit simulator to simulate the circuit // =============================================================================== CircuitSimulator cs; // tell which circuit will be simulated cs.set(&cir); // set cell manager to get pin name when simulation cs.set(&lib); // set clk wave of the simulation Wave clkWave; clkWave.initialValue = Wave::L; // set rise transition of clk Transition riseTrans; riseTrans.value = Wave::H; riseTrans.time = 0.0; riseTrans.period = 0.002; riseTrans.prevTransition = NULL; clkWave.addTransition(Wave::H , riseTrans);//0.0 , 0.002, NULL, 0); // set fall transition of clk Transition fallTrans; fallTrans = riseTrans; fallTrans.value = Wave::L; fallTrans.time = 0.25; clkWave.addTransition(Wave::L , fallTrans);//0.25 , 0.002, NULL, 0); cs.set("CK", &clkWave , 1.0); // set pattern pi and ppi order cs.set(&ps.piOrder , &ps.poOrder , &ps.ppiOrder); // =============================================================================== // perform circuit simulation // =============================================================================== cout << "start!" << endl; for(unsigned i = 0 ; i < ps.patterns.size() ; ++i) { // system("clear"); Pattern pat = ps.patterns[i]; cs.initial(pat.pis[0] , pat.ppi); string ppo = cs.getPPO(); if(pat.cycle[0] == Pattern::CAPTURE) cout << "pattern " << i << "\t" <<ppo << endl; else cout << "pattern " << i << "\t" << pat.ppi << endl; } //} t2 = clock(); cout << "total cost: " << (t2-t1)/(double)(CLOCKS_PER_SEC)/12 << " second!" <<endl; ofstream fout; fout.open("time.txt",ios::app); fout << cir.getName() << "," << cir.getNets().size() << "," << ps.patterns.size()<< ","<< (t2-t1)/(double)(CLOCKS_PER_SEC)/12 << endl; return 0; }
/***************************************************************************** * Main ****************************************************************************/ int main(int argc, char **argv) { srand ( time(NULL) ); /****************************** * Command Line Parser ******************************/ bool mono_lib(false), print_gate(false), print_solns(false), print_sat(false), print_blif(false), print_verilog(false); int num_threads, budget; float remove_percent(0.6); vector<string> test_args; po::options_description optional_args("Usage: [options]"); optional_args.add_options() ("circuit", po::value<string>(), "input circuit") ("tech_lib", po::value<string>(), "tech library") ("continue_file,c", po::value<string>(), "input report to continue from") ("mono_lib,m", po::value(&mono_lib)->zero_tokens(), "treat each gate as a nand") ("budget,b", po::value<int>(&budget)->default_value(100000000), "minisat conflict budget (-1 = unlimited)") ("remove_edges,e", po::value<float>(&remove_percent)->default_value(0.6), "edge percent to remove") ("print_graph", po::value(&print_gate)->zero_tokens(), "print H graph") ("print_solns", po::value(&print_solns)->zero_tokens(), "print isos") ("print_blif", po::value(&print_blif)->zero_tokens(), "print G blif circuit") ("print_verilog", po::value(&print_verilog)->zero_tokens(), "print verilog circuits") ("test,t", po::value< vector<string> >(&test_args), "Run test suite #: \n" " -99: Beta Testing \n" " -1: Mem Testing \n" " 0: L0 [count, remove_percent] \n" " 1: L1 [count, remove_percent] \n" " 2: S1 - Random [min S1] \n" " 3: S1 - Greedy [min S1] \n") ("num_threads,n", po::value<int>(&num_threads)->default_value(1), "Number of threads") ("wdir,w", po::value<string>()->default_value("./wdir"), "Output directory") ("help,h", "produce help message") ; po::positional_options_description positional_args; positional_args.add("circuit", 1); positional_args.add("tech_lib", 1); positional_args.add("test", -1); po::variables_map vm; try { po::store(po::command_line_parser(argc, argv).options(optional_args).positional(positional_args).run(), vm); po::notify(vm); } catch(exception& e) { cerr << "error: " << e.what() << "\n"; return 1; } catch(...) { cerr << "Exception of unknown type!\n"; } if (vm.count("help")) { cout << optional_args << "\n"; return 0; } string circuit_filename, circuit_name, tech_filename, tech_name, working_dir, report_filename; // input circuit if (vm.count("circuit") == 1) { circuit_filename = vm["circuit"].as<string>(); circuit_name = circuit_filename.substr(circuit_filename.rfind('/')+1); circuit_name = circuit_name.substr(0, circuit_name.find('.')); } else { cout << optional_args << "\n"; return 0; } // input tech lib if (vm.count("tech_lib")) { tech_filename = vm["tech_lib"].as<string>(); tech_name = tech_filename.substr(tech_filename.rfind('/')+1); tech_name = tech_name.substr(0, tech_name.find('.')); } else { cout << optional_args << "\n"; return 0; } cout << "Circuit : " << circuit_filename << "\n"; cout << "Tech Lib: " << tech_filename << "\n"; /****************************** * Setup working dir ******************************/ working_dir = vm["wdir"].as<string>(); mkdir(working_dir.c_str(), S_IRWXU); cout << "WDIR : " << working_dir << "\n"; /****************************** * Convert circuit using tech_lib ******************************/ string outfile = working_dir + circuit_filename.substr(circuit_filename.rfind('/')); cout << "Outfile : " << outfile << "\n"; // sis_convert(circuit_filename, tech_filename, outfile); cout << "I'm here!\n"; circuit_filename = outfile; // copy tech_lib if ( tech_filename != string(working_dir + tech_filename.substr(tech_filename.rfind('/')) ) ) { ifstream src( tech_filename.c_str() ); ofstream dst( string(working_dir + tech_filename.substr(tech_filename.rfind('/')) ).c_str() ); dst << src.rdbuf(); dst.close(); } /****************************** * Load circuit ******************************/ Circuit circuit; load_circuit(&circuit, circuit_filename, mono_lib); Security *security; Circuit G, H; G.copy(&circuit); G.remove_io(); circuit.save( working_dir + "/circuit.gml" ); G.save( working_dir + "/G_circuit.gml" ); /**************************************************************** * print G ****************************************************************/ if ( test_args.size() > 0 && -1 == atoi(test_args[0].c_str())) { G.print(); } /**************************************************************** * L0 ****************************************************************/ if ( test_args.size() > 0 && 0 == atoi(test_args[0].c_str())) { int max_count(2); if (test_args.size() == 2) max_count = atoi(test_args[1].c_str()); H.copy(&G); H.rand_del_edges(remove_percent); H.save( working_dir + "/H_circuit.gml" ); security = new Security(&G, &H); security->setConfBudget(budget); cout << "Rand L0: |V(G)| = " << (int) igraph_vcount(&G); cout << ", |E(G)| = " << (int) igraph_ecount(&G); cout << ", |V(H)| = " << (int) igraph_vcount(&H); cout << ", |E(H)| = " << (int) igraph_ecount(&H) << "\n"; cout << " " << boolalpha << security->L0(max_count, false) << endl; } /**************************************************************** * L1 ****************************************************************/ if ( test_args.size() > 0 && 1 == atoi(test_args[0].c_str())) { int max_L1(2); if (test_args.size() == 2) max_L1 = atoi(test_args[1].c_str()); H.copy(&G); H.rand_del_edges(remove_percent); if (vm.count("continue_file")) { H.rand_del_edges((float) 1.0); string filename = vm["continue_file"].as<string>(); ifstream file; try { file.open(filename.c_str()); while (file.good()) { string line; int L0, L1; Edge edge; getline(file, line); if (parse(line, &G, L1, L0, edge)) { if (L1 >= max_L1) { H.add_edge(edge); cout << "L1 = " << max_L1 << ", +<" << edge.first << "," << edge.second << ">" << endl; } } } } catch(...) {} } H.save( working_dir + "/H_circuit.gml" ); security = new Security(&G, &H); security->setConfBudget(budget); cout << "Rand L1: |V(G)| = " << (int) igraph_vcount(&G); cout << ", |E(G)| = " << (int) igraph_ecount(&G); cout << ", |V(H)| = " << (int) igraph_vcount(&H); cout << ", |E(H)| = " << (int) igraph_ecount(&H) << "\n"; cout << " " << boolalpha << security->L1(max_L1, false) << endl; } /**************************************************************** * #L1 ****************************************************************/ if ( test_args.size() == 1 && 2 == atoi(test_args[0].c_str())) { int max_L1(2); if (test_args.size() == 2) max_L1 = atoi(test_args[1].c_str()); H.copy(&G); H.rand_del_edges(remove_percent); if (vm.count("continue_file")) { H.rand_del_edges((float) 1.0); string filename = vm["continue_file"].as<string>(); ifstream file; try { file.open(filename.c_str()); while (file.good()) { string line; int L0, L1; Edge edge; getline(file, line); if (parse(line, &G, L1, L0, edge)) { H.add_edge(edge); max_L1 = L1; cout << "L1 = " << max_L1 << ", +<" << edge.first << "," << edge.second << ">" << endl; } } } catch(...) {} } H.save( working_dir + "/H_circuit.gml" ); security = new Security(&G, &H); security->setConfBudget(budget); cout << "Rand L1: |V(G)| = " << (int) igraph_vcount(&G); cout << ", |E(G)| = " << (int) igraph_ecount(&G); cout << ", |V(H)| = " << (int) igraph_vcount(&H); cout << ", |E(H)| = " << (int) igraph_ecount(&H) << "\n"; cout << " " << security->L1(false); } /**************************************************************** * S1_rand ****************************************************************/ if ( test_args.size() == 1 && 3 == atoi(test_args[0].c_str())) { int max_L1 = G.max_L1(); H.copy(&G); H.rand_del_edges((float) 1.0); security = new Security(&G, &H); security->setConfBudget(budget); string output; output = "S1_rand (" + G.get_name() + ")"; output = report(output, &G, &H, max_L1); cout << output; security->S1_rand(num_threads); } /**************************************************************** * S1_greedy ****************************************************************/ if ( test_args.size() >= 1 && 4 == atoi(test_args[0].c_str())) { int min_L1(2), max_L1 = G.max_L1(); H.copy(&G); H.rand_del_edges((float) 1.0); bool done(false); if ( test_args.size() == 3 ) { min_L1 = atoi(test_args[1].c_str()); max_L1 = atoi(test_args[2].c_str()); } else if ( test_args.size() == 2 ) min_L1 = atoi(test_args[1].c_str()); if (vm.count("continue_file")) { string filename = vm["continue_file"].as<string>(); ifstream file; for (int eid = 0; eid < igraph_ecount(&G); eid++) SETEAS(&G, "style", eid, "invis"); try { file.open(filename.c_str()); // int last_sec; // Edge prev_edge; // bool first = true; while (file.good()) { string line; int L0, L1; Edge edge; getline(file, line); if (parse(line, &G, L1, L0, edge)) { if (L1 < min_L1) { done = true; break; } // if (first) { last_sec = L1; first = false; prev_edge = edge;} // else // { // if (last_sec != L1) // { // H.del_edge(prev_edge); // string gmlfilename; // char num[3]; // sprintf(num, "%d", last_sec); // gmlfilename = working_dir + "/H_circuit_" + num + ".gml"; // string gvfilename = working_dir + "/H_circuit_" + num + ".gv"; // string psfilename = working_dir + "/H_circuit_" + num + ".ps"; //H.save( gmlfilename ); // G.save( gmlfilename ); // H.add_edge(prev_edge); // string command = "gml2gv -o" + gvfilename + " " + gmlfilename; // system(command.c_str()); // command = "dot -Tps -Nstyle=filled -Ncolorscheme=accent8 -Nshape=circle -Nlabel=\"\" -o " + psfilename + " " + gvfilename; // system(command.c_str()); // last_sec = L1; // } // prev_edge = edge; // int eid; // igraph_get_eid(&G, &eid, edge.first, edge.second, true, false); // SETEAS(&G, "style", eid, "solid"); // } H.add_edge(edge); max_L1 = L1; cout << "L1 = " << max_L1 << ", +<" << edge.first << "," << edge.second << ">" << endl; } } // return 0; } catch(...) {} } if ( test_args.size() == 3 ) { min_L1 = atoi(test_args[1].c_str()); max_L1 = atoi(test_args[2].c_str()); } else if ( test_args.size() == 2 ) min_L1 = atoi(test_args[1].c_str()); security = new Security(&G, &H); security->setConfBudget(budget); string output; output = "S1_greedy (" + G.get_name() + ")"; output = report(output, &G, &H, max_L1); cout << output; fstream report; if (!done) { clock_t tic = clock(); security->S1_greedy(num_threads, min_L1, max_L1); clock_t toc = clock(); cout << endl << "Heuristic took: "; cout << (double) (toc-tic)/CLOCKS_PER_SEC << endl; } } /**************************************************************** * k-isomorphism ****************************************************************/ if ( test_args.size() >= 1 && 10 == atoi(test_args[0].c_str())) { int min_L1(2), max_L1 = G.max_L1(); if ( test_args.size() == 3 ) { min_L1 = atoi(test_args[1].c_str()); max_L1 = atoi(test_args[2].c_str()); } else if ( test_args.size() == 2 ) min_L1 = atoi(test_args[1].c_str()); igraph_vector_t match_vert; igraph_vector_init(&match_vert, 0); for (int i = 0; i < igraph_vcount(&G); i++) { int color = VAN(&G, "colour", i); if (igraph_vector_size(&match_vert) < color + 1) for (int j = igraph_vector_size(&match_vert); j <= color; j++) { igraph_vector_push_back(&match_vert, 0); } VECTOR(match_vert)[color]++; } igraph_t temp; // igraph_copy(&temp, &G); // igraph_destroy(&G); // for (min_L1 = max_L1; min_L1 >= 1; min_L1--) { // igraph_copy(&G, &temp); int count = 0; for (int i = 0; i < igraph_vector_size(&match_vert); i++) { int n = ((int) VECTOR(match_vert)[i]) % min_L1; if (n == 0) continue; for (int j = 0; j < min_L1 - n; j++) { count++; igraph_add_vertices(&G, 1, 0); SETVAN(&G, "colour", igraph_vcount(&G) - 1, i); } } cout << count << " "; cout.flush(); H.copy(&G); H.rand_del_edges((float) 1.0); bool done(false); security = new Security(&G, &H); security->setConfBudget(budget); string output; output = "S1_greedy (" + G.get_name() + ")"; output = report(output, &G, &H, max_L1); // cout << output; fstream report; if (!done) { clock_t tic = clock(); security->kiso(min_L1, max_L1); clock_t toc = clock(); // cout << endl << "Heuristic took: "; // cout << (double) (toc-tic)/CLOCKS_PER_SEC << endl; } //igraph_destroy(&G);} } /**************************************************************** * Tree test ****************************************************************/ if ( test_args.size() >= 1 && 7 == atoi(test_args[0].c_str())) { int min_L1(2), max_L1 = G.max_L1(); //G.erase(); igraph_vs_t vs; igraph_vs_all(&vs); igraph_delete_vertices(&G, vs); const int depth = 7; igraph_add_vertices(&G, pow(2,depth)-1, 0); for (int i=0; i < pow(2,depth-1); i++) { int level = floor(log(i+1)/log(2)); igraph_add_edge(&G,i,pow(2,level+1) + (i-pow(2,level))*2 - 1); igraph_add_edge(&G,i,pow(2,level+1) + (i-pow(2,level))*2); } for (int i=0; i < igraph_vcount(&G); i++) { SETVAN(&G, "colour", i, 0); SETVAS(&G, "type", i, "invf101"); string label = "label"; SETVAS(&G, "label", i, label.c_str()); } H.copy(&G); for (int i=0; i < igraph_vcount(&H); i++) { SETVAN(&H, "colour", i, 0); } H.rand_del_edges((float) 1.0); if ( test_args.size() == 3 ) { min_L1 = atoi(test_args[1].c_str()); max_L1 = atoi(test_args[2].c_str()); } else if ( test_args.size() == 2 ) min_L1 = atoi(test_args[1].c_str()); if ( test_args.size() == 3 ) { min_L1 = atoi(test_args[1].c_str()); max_L1 = atoi(test_args[2].c_str()); } else if ( test_args.size() == 2 ) min_L1 = atoi(test_args[1].c_str()); cout << "I'm here!"; cout.flush(); security = new Security(&G, &H); security->setConfBudget(budget); string output; cout << "I'm here!"; output = "S1_greedy (" + G.get_name() + ")"; cout << "I'm here!"; output = report(output, &G, &H, max_L1); cout << output; cout << "I'm here!"; security->S1_greedy(num_threads, min_L1, max_L1); } /**************************************************************** * Compute security level G if no wires are lifted ****************************************************************/ if ( test_args.size() >= 1 && 5 == atoi(test_args[0].c_str())) { H.copy(&G); security = new Security(&G, &H); security->setConfBudget(budget); H.rand_del_edges((float) 0.0); // security->clean_solutions(); string output; output = "Security of circuit (" + G.get_name() + ") if no wires are lifted: "; cout << output; security->S1_self(); } /**************************************************************** * Solve LIFT(G, k, eta) ****************************************************************/ if ( test_args.size() >= 1 && 6 == atoi(test_args[0].c_str())) { int min_L1(2), max_L1 = G.max_L1(), eta = igraph_ecount(&G); H.copy(&G); // H.rand_del_edges((float) 1.0); if ( test_args.size() == 3 ) { min_L1 = atoi(test_args[1].c_str()); eta = atoi(test_args[2].c_str()); } else if ( test_args.size() == 2 ) min_L1 = atoi(test_args[1].c_str()); security = new Security(&G, &H); security->setConfBudget(budget); clock_t tic = clock(); security->rSAT(min_L1, max_L1, eta); clock_t toc = clock(); cout << endl << "SAT took: "; cout << (double) (toc-tic)/CLOCKS_PER_SEC << endl; } /**************************************************************** * Solve LIFT(G, k, eta, u) ****************************************************************/ if ( test_args.size() >= 1 && 8 == atoi(test_args[0].c_str())) { int min_L1(2), max_L1 = G.max_L1(), eta = igraph_ecount(&G), u; H.copy(&G); // H.rand_del_edges((float) 1.0); if ( test_args.size() == 4 ) { u = atoi(test_args[1].c_str()); min_L1 = atoi(test_args[2].c_str()); eta = atoi(test_args[3].c_str()); } else if ( test_args.size() == 3 ) { u = atoi(test_args[1].c_str()); min_L1 = atoi(test_args[2].c_str()); } else if ( test_args.size() == 2 ) u = atoi(test_args[1].c_str()); security = new Security(&G, &H); security->setConfBudget(budget); clock_t tic = clock(); security->rSAT(min_L1, max_L1, eta, u, true); clock_t toc = clock(); cout << endl << "SAT took: "; cout << (double) (toc-tic)/CLOCKS_PER_SEC << endl; } /**************************************************************** * Solve LIFT(G, k, eta, u) ****************************************************************/ if ( test_args.size() >= 1 && 9 == atoi(test_args[0].c_str())) { int min_L1(2), max_L1 = G.max_L1(), eta = igraph_ecount(&G), u; H.copy(&G); // H.rand_del_edges((float) 1.0); if ( test_args.size() == 4 ) { u = atoi(test_args[1].c_str()); min_L1 = atoi(test_args[2].c_str()); eta = atoi(test_args[3].c_str()); } else if ( test_args.size() == 3 ) { u = atoi(test_args[1].c_str()); min_L1 = atoi(test_args[2].c_str()); } else if ( test_args.size() == 2 ) u = atoi(test_args[1].c_str()); security = new Security(&G, &H); security->setConfBudget(budget); clock_t tic = clock(); security->rSAT(min_L1,max_L1, eta, u); clock_t toc = clock(); cout << endl << "SAT took: "; cout << (double) (toc-tic)/CLOCKS_PER_SEC << endl; } /**************************************************************** * simulated annealing ****************************************************************/ if ( test_args.size() >= 1 && 10 == atoi(test_args[0].c_str())) { const double MAX_TEMP = 100000.0; const int MAX_ITERATIONS = 2000; const double TEMP_CHANGE = 0.98; int no_of_edges = 20; int min_L1(2), max_L1 = G.max_L1(); H.copy(&G); H.rand_del_edges(igraph_ecount(&G) - no_of_edges); security = new Security(&G, &H); security->setConfBudget(budget); int current_k_security = security->L1(); int best_k_security = current_k_security; delete security; double temperature = MAX_TEMP; srand( time(NULL)); for (int iter = 0; iter < MAX_ITERATIONS; iter++) { bool done(false); // H.rand_del_edges(1); vector<Edge> unlifted_edge_list; for (int eid = 0; eid < igraph_ecount(&H); eid++) { Edge edge = H.get_edge(eid); unlifted_edge_list.push_back(edge); } random_shuffle(unlifted_edge_list.begin(), unlifted_edge_list.end()); H.del_edge(unlifted_edge_list[0]); vector<Edge> edge_list; for (int eid = 0; eid < igraph_ecount(&G); eid++) { Edge edge = G.get_edge(eid); if (!H.test_edge(edge)) edge_list.push_back(edge); } random_shuffle(edge_list.begin(), edge_list.end()); H.add_edge(edge_list[0]); security = new Security(&G, &H); security->setConfBudget(budget); int new_k_security = security->L1(); if (new_k_security >= current_k_security) { current_k_security = new_k_security; if (current_k_security >= best_k_security) best_k_security = current_k_security; } else { if (exp((new_k_security-current_k_security)/temperature) >= ((double) rand())/ RAND_MAX); else { H.add_edge(unlifted_edge_list[0]); H.add_edge(edge_list[0]); } } temperature *= TEMP_CHANGE; if ((iter + 1 )% 10 == 0) cout << " > iteration " << iter + 1 << ", temp=" << temperature << ", best=" << best_k_security << endl; } } /**************************************************************** * L1(label) ****************************************************************/ if ( test_args.size() >= 1 && 5 == atoi(test_args[0].c_str())) { string label = ""; if (test_args.size() == 2) label = test_args[1]; int max_L1(2); H.copy(&G); H.rand_del_edges(remove_percent); if (vm.count("continue_file")) { H.rand_del_edges((float) 1.0); string filename = vm["continue_file"].as<string>(); ifstream file; try { file.open(filename.c_str()); while (file.good()) { string line; int L0, L1; Edge edge; getline(file, line); if (parse(line, &G, L1, L0, edge)) { H.add_edge(edge); max_L1 = L1; cout << "L1 = " << max_L1 << ", +<" << edge.first << "," << edge.second << ">" << endl; } } } catch(...) {} } H.save( working_dir + "/H_circuit.gml" ); security = new Security(&G, &H); security->setConfBudget(budget); security->L1(label); } if ( test_args.size() >= 1 && atoi(test_args[0].c_str()) >= 0) { H.save( working_dir + "/H_circuit.gml" ); delete security; } if (print_gate) G.print(); if (print_blif) print_file(circuit_filename); if (print_solns) security->print_solutions(); if (print_verilog) security->print_solutions(); printf("\n\ndone 0 \n"); return 0; }
int main() { // Create the top-level circuit Circuit topLevel; // Create the components. topLevel.AddComponent("in", new Button()); topLevel.AddComponent("spl", new Splitter(2)); topLevel.AddComponent("and", new And()); topLevel.AddComponent("not", new Not()); topLevel.AddComponent("out", new LED()); // Link the components. topLevel.Connect("in",0,"spl",0); topLevel.Connect("spl",0,"and",0); topLevel.Connect("spl",1,"not",0); topLevel.Connect("not",0,"and",1); topLevel.Connect("and",0,"out",0); // Specify the input and output components. topLevel.AddInput("in"); topLevel.AddOutput("out"); // Evaluate the circuit. topLevel.Evaluate(); return 0; }
bp::object Circuit_getRotations( const Circuit& circuit, bp::object gids ) { return toNumpy( circuit.getRotations( gidsFromPython( gids ))); }