/* * Improved q-intersection algorithm. */ IntervalVector qinter2(const Array<IntervalVector>& _boxes, int q) { #ifndef _WIN32 assert(q>0); assert(_boxes.size()>0); int n = _boxes[0].size(); /* Remove the empty boxes from the list */ int p=0; for (int i=0; i<_boxes.size(); i++) { if (!_boxes[i].is_empty()) p++; } if (p==0) return IntervalVector::empty(n); Array<IntervalVector> boxes(p); int j=0; for (int i=0; i<_boxes.size(); i++) { if (!_boxes[i].is_empty()) boxes.set_ref(j++,_boxes[i]); } /* Create the sets of available boxes for each direction */ IntStack ***dirboxes = (IntStack ***)malloc(n*sizeof(IntStack **)); for (int i=0; i<n; i++) { dirboxes[i] = (IntStack **)malloc(2*sizeof(IntStack *)); for (int j=0; j<2;j++) { dirboxes[i][j] = new IntStack(0,p-1,true); } } /* Create the original intersection graph */ KCoreGraph *origin = new KCoreGraph(p,q-1,true); /* Add edges */ for (int i=0; i<p; i++) { for (int j=i+1; j<p; j++) { if (boxes[i].intersects(boxes[j])) origin->add_edge(i,j); } } /* Initialize the data structures */ vector<BitSet *> nogoods; nogoods.reserve(2*n); BitSet *curr_set = new BitSet(0,p-1,BitSet::empt); IntervalVector curr_qinter(n); curr_qinter.set_empty(); IntervalVector hull_qinter(n); hull_qinter.set_empty(); vector<IntervalVector *> neighboxes; neighboxes.reserve(p); vector<int> n_indices; n_indices.reserve(p); int b,b2,nboxes; pair<double,int> *x = new pair<double,int>[p]; bool first_pass = true; bool ng; /* Compute the q-inter hull */ for (int i=0; i<n; i++) { /* ######################################################## */ /* ##### ##### */ /* ##### Left ----> Right ##### */ /* ##### ##### */ /* ######################################################## */ nboxes = dirboxes[i][0]->size; /* Sort the boxes by increasing order of their left bounds */ b = dirboxes[i][0]->head(); for (int k=0; k<nboxes; k++) { x[k] = make_pair(boxes[b][i].lb(), b); b = dirboxes[i][0]->next(b); } sort(x,x+nboxes,leftpaircomp); /* For each box, look for a (q-1)-inter in its left neighbourhood */ for (int k=q-1; k<nboxes; k++) { curr_set->clear(); b = x[k].second; curr_set->add(b); /* Find the left neighbors */ neighboxes.clear(); n_indices.clear(); for (int l=0; l<k; l++) { b2 = x[l].second; if (origin->is_edge(b,b2)) { neighboxes.push_back(&(boxes[b2])); n_indices.push_back(b2); curr_set->add(b2); } } if (((int)neighboxes.size() )< q-1) continue; /* Check if it's a nogood */ ng = false; for (unsigned int z=0; z<nogoods.size(); z++) { if (nogoods.at(z)->includes(curr_set)) { ng = true; break; } } if (ng) continue; /* Call to the existence procedure */ curr_qinter = qinterex_cliquer(neighboxes, n_indices, q-1, origin); curr_qinter = curr_qinter & boxes[b]; if (curr_qinter.is_empty()) continue; /* Optimal q-inter found : extend the q-inter hull and propagate the bounds */ hull_qinter = hull_qinter | curr_qinter; propagate(boxes, dirboxes, i, true, curr_qinter, nogoods); break; } if (first_pass && curr_qinter.is_empty()) { /* No q-inter on the whole problem. No need to process the other dimensions. */ break; } first_pass = false; if (curr_qinter.is_empty()) { /* A face of the q-inter hull has been proved optimal, but has not been updated. * There is still some information we can propagate. */ propagate_no_ub(boxes, dirboxes, i, true, hull_qinter, nogoods); } /* ######################################################## */ /* ##### ##### */ /* ##### Right ----> Left ##### */ /* ##### ##### */ /* ######################################################## */ nboxes = dirboxes[i][1]->size; /* Sort the boxes by decreasing order of their right bounds */ b = dirboxes[i][1]->head(); for (int k=0; k<nboxes; k++) { x[k] = make_pair(boxes[b][i].ub(), b); b = dirboxes[i][1]->next(b); } sort(x,x+nboxes,rightpaircomp); /* For each box, look for a (q-1)-inter in its right neighbourhood */ for (int k=q-1; k<nboxes; k++) { curr_set->clear(); b = x[k].second; curr_set->add(b); /* Find the right neighbors */ neighboxes.clear(); n_indices.clear(); for (int l=0; l<k; l++) { b2 = x[l].second; if (origin->is_edge(b,b2)) { neighboxes.push_back(&(boxes[b2])); n_indices.push_back(b2); curr_set->add(b2); } } if (((int)neighboxes.size()) < q-1) continue; /* Check if it's a nogood */ ng = false; for (unsigned int z=0; z<nogoods.size(); z++) { if (nogoods.at(z)->includes(curr_set)) { ng = true; break; } } if (ng) continue; /* Call to the existence procedure */ curr_qinter = qinterex_cliquer(neighboxes, n_indices, q-1, origin); curr_qinter = curr_qinter & boxes[b]; if (curr_qinter.is_empty()) continue; /* Optimal q-inter found : extend the q-inter hull and propagate the bounds */ hull_qinter = hull_qinter | curr_qinter; if (i!=n) propagate(boxes, dirboxes, i, false, curr_qinter, nogoods); break; } if (curr_qinter.is_empty() && (i!=n)) { /* A face of the q-inter hull has been proved optimal, but has not been updated. * There is still some information we can propagate. */ propagate_no_ub(boxes, dirboxes, i, false, hull_qinter, nogoods); } } /* Cleanup */ for (int i=0; i<n; i++) { for (int j=0; j<2;j++) { delete(dirboxes[i][j]); } free(dirboxes[i]); } free(dirboxes); delete [] x; delete(origin); delete(curr_set); for (unsigned int i=0; i<nogoods.size(); i++) delete(nogoods.at(i)); return hull_qinter; #else not_implemented("Cliquer-based q-intersection under Windows"); return IntervalVector::empty(_boxes[0].size()); #endif }
siglist realPropagate (Tree slotenv, Tree path, Tree box, const siglist& lsig) { int i; double r; prim0 p0; prim1 p1; prim2 p2; prim3 p3; prim4 p4; prim5 p5; Tree t1, t2, ff, label, cur, min, max, step, type, name, file, slot, body, chan; tvec wf; xtended* xt = (xtended*)getUserData(box); // Extended Primitives if (xt) { faustassert(lsig.size() == xt->arity()); return makeList(xt->computeSigOutput(lsig)); } // Numbers and Constants else if (isBoxInt(box, &i)) { faustassert(lsig.size()==0); return makeList(sigInt(i)); } else if (isBoxReal(box, &r)) { faustassert(lsig.size()==0); return makeList(sigReal(r)); } // A Waveform has two outputs it size and a period signal representing its content else if (isBoxWaveform(box)) { faustassert(lsig.size()==0); const tvec br = box->branches(); return listConcat(makeList(sigInt(int(br.size()))), makeList(sigWaveform(br))); } else if (isBoxFConst(box, type, name, file)) { faustassert(lsig.size()==0); return makeList(sigFConst(type, name, file)); } else if (isBoxFVar(box, type, name, file)) { faustassert(lsig.size()==0); return makeList(sigFVar(type, name, file)); } // Wire and Cut else if (isBoxCut(box)) { faustassert(lsig.size()==1); return siglist(); } else if (isBoxWire(box)) { faustassert(lsig.size()==1); return lsig; } // Slots and Symbolic Boxes else if (isBoxSlot(box)) { Tree sig; faustassert(lsig.size()==0); if (!searchEnv(box,sig,slotenv)) { // test YO simplification des diagrames //fprintf(stderr, "propagate : internal error (slot undefined)\n"); sig = sigInput(++gGlobal->gDummyInput); } return makeList(sig); } else if (isBoxSymbolic(box, slot, body)) { faustassert(lsig.size()>0); return propagate(pushEnv(slot,lsig[0],slotenv), path, body, listRange(lsig, 1, (int)lsig.size())); } // Primitives else if (isBoxPrim0(box, &p0)) { faustassert(lsig.size()==0); return makeList(p0()); } else if (isBoxPrim1(box, &p1)) { faustassert(lsig.size()==1); return makeList(p1(lsig[0])); } else if (isBoxPrim2(box, &p2)) { // printf("prim2 recoit : "); print(lsig); printf("\n"); faustassert(lsig.size()==2); if (p2 == &sigEnable) { if (gGlobal->gEnableFlag) { // special case for sigEnable that requires a transformation // enable(X,Y) -> sigEnable(X*Y, Y>0) return makeList(sigEnable( sigMul(lsig[0],lsig[1]), sigGT(lsig[1],sigReal(0.0)))); } else { // We gEnableFlag is false we replace enable by a simple multiplication return makeList(sigMul(lsig[0],lsig[1])); } } else if (p2 == &sigControl) { if (gGlobal->gEnableFlag) { // special case for sigEnable that requires a transformation // enable(X,Y) -> sigEnable(X*Y, Y>0) return makeList(sigEnable( lsig[0], lsig[1])); } else { // We gEnableFlag is false we replace control by identity function return makeList(lsig[0]); } } return makeList( p2(lsig[0],lsig[1]) ); } else if (isBoxPrim3(box, &p3)) { faustassert(lsig.size()==3); return makeList(p3(lsig[0],lsig[1],lsig[2])); } else if (isBoxPrim4(box, &p4)) { faustassert(lsig.size()==4); return makeList(p4(lsig[0],lsig[1],lsig[2],lsig[3])); } else if (isBoxPrim5(box, &p5)) { faustassert(lsig.size()==5); return makeList(p5(lsig[0],lsig[1],lsig[2],lsig[3],lsig[4])); } else if (isBoxFFun(box, ff)) { //cerr << "propagate en boxFFun of arity " << ffarity(ff) << endl; faustassert(int(lsig.size())==ffarity(ff)); return makeList(sigFFun(ff, listConvert(lsig))); } // User Interface Widgets else if (isBoxButton(box, label)) { faustassert(lsig.size()==0); return makeList(sigButton(normalizePath(cons(label, path)))); } else if (isBoxCheckbox(box, label)) { faustassert(lsig.size()==0); return makeList(sigCheckbox(normalizePath(cons(label, path)))); } else if (isBoxVSlider(box, label, cur, min, max, step)) { faustassert(lsig.size()==0); return makeList(sigVSlider(normalizePath(cons(label, path)), cur, min, max, step)); } else if (isBoxHSlider(box, label, cur, min, max, step)) { faustassert(lsig.size()==0); return makeList(sigHSlider(normalizePath(cons(label, path)), cur, min, max, step)); } else if (isBoxNumEntry(box, label, cur, min, max, step)) { faustassert(lsig.size()==0); return makeList(sigNumEntry(normalizePath(cons(label, path)), cur, min, max, step)); } else if (isBoxVBargraph(box, label, min, max)) { faustassert(lsig.size()==1); return makeList(sigVBargraph(normalizePath(cons(label, path)), min, max, lsig[0])); } else if (isBoxHBargraph(box, label, min, max)) { faustassert(lsig.size()==1); return makeList(sigHBargraph(normalizePath(cons(label, path)), min, max, lsig[0])); } else if (isBoxSoundfile(box, label, chan)) { faustassert(lsig.size()==1); Tree fullpath = normalizePath(cons(label, path)); Tree soundfile = sigSoundfile(fullpath); int c = tree2int(chan); siglist lsig2(c+3); lsig2[0] = sigSoundfileLength(soundfile); lsig2[1] = sigSoundfileRate(soundfile); lsig2[2] = sigSoundfileChannels(soundfile); // compute bound limited read index : int(max(0, min(ridx,length-1))) Tree ridx = sigIntCast(tree(gGlobal->gMaxPrim->symbol(), sigInt(0), tree(gGlobal->gMinPrim->symbol(), lsig[0], sigAdd(lsig2[0],sigInt(-1))))); for (int i = 0; i<c; i++) { lsig2[i+3] = sigSoundfileBuffer(soundfile, sigInt(i), ridx); } return lsig2; } // User Interface Groups else if (isBoxVGroup(box, label, t1)) { return propagate(slotenv,cons(cons(tree(0),label), path), t1, lsig); } else if (isBoxHGroup(box, label, t1)) { return propagate(slotenv, cons(cons(tree(1),label), path), t1, lsig); } else if (isBoxTGroup(box, label, t1)) { return propagate(slotenv, cons(cons(tree(2),label), path), t1, lsig); } // Block Diagram Composition Algebra else if (isBoxSeq(box, t1, t2)) { int in1, out1, in2, out2; getBoxType(t1, &in1, &out1); getBoxType(t2, &in2, &out2); faustassert(out1==in2); if (out1 == in2) { return propagate(slotenv, path, t2, propagate(slotenv, path,t1,lsig)); } else if (out1 > in2) { siglist lr = propagate(slotenv, path, t1,lsig); return listConcat(propagate(slotenv, path, t2, listRange(lr, 0, in2)), listRange(lr, in2, out1)); } else { return propagate(slotenv, path, t2, listConcat( propagate(slotenv, path, t1, listRange(lsig,0,in1)), listRange(lsig,in1,in1+in2-out1))); } } else if (isBoxPar(box, t1, t2)) { int in1, out1, in2, out2; getBoxType(t1, &in1, &out1); getBoxType(t2, &in2, &out2); return listConcat(propagate(slotenv, path, t1, listRange(lsig, 0, in1)), propagate(slotenv, path, t2, listRange(lsig, in1, in1+in2))); } else if (isBoxSplit(box, t1, t2)) { int in1, out1, in2, out2; getBoxType(t1, &in1, &out1); getBoxType(t2, &in2, &out2); siglist l1 = propagate(slotenv, path, t1, lsig); siglist l2 = split(l1, in2); return propagate(slotenv, path, t2, l2); } else if (isBoxMerge(box, t1, t2)) { int in1, out1, in2, out2; getBoxType(t1, &in1, &out1); getBoxType(t2, &in2, &out2); siglist l1 = propagate(slotenv, path, t1, lsig); siglist l2 = mix(l1, in2); return propagate(slotenv, path, t2, l2); } else if (isBoxRec(box, t1, t2)) { // Bug Corrected int in1, out1, in2, out2; getBoxType(t1, &in1, &out1); getBoxType(t2, &in2, &out2); Tree slotenv2 = lift(slotenv); // the environment must also be lifted siglist l0 = makeMemSigProjList(ref(1), in2); siglist l1 = propagate(slotenv2, path, t2, l0); siglist l2 = propagate(slotenv2, path, t1, listConcat(l1,listLift(lsig))); siglist l3 = (gGlobal->gFTZMode > 0) ? wrapWithFTZ(l2) : l2; Tree g = rec(listConvert(l3)); return makeSigProjList(g, out1); } stringstream error; error << "ERROR in file " << __FILE__ << ':' << __LINE__ << ", unrecognised box expression : " << boxpp(box) << endl; throw faustexception(error.str()); return siglist(); }
void operator() ( double t, grid2D<> & u0, grid2D<> & v0, grid2D<> & u1, grid2D<> & v1 ) { propagate( t, u0, v0, u1, v1 ); }
pass2() { register struct dinode *dp; register struct inoinfo **inpp, *inp; struct inoinfo **inpend; struct inodesc curino; struct dinode dino; char pathbuf[MAXPATHLEN + 1]; switch (statemap[ROOTINO]) { case USTATE: pfatal("ROOT INODE UNALLOCATED"); if (reply("ALLOCATE") == 0) errexit(""); if (allocdir(ROOTINO, ROOTINO, 0755) != ROOTINO) errexit("CANNOT ALLOCATE ROOT INODE\n"); break; case DCLEAR: pfatal("DUPS/BAD IN ROOT INODE"); if (reply("REALLOCATE")) { freeino(ROOTINO); if (allocdir(ROOTINO, ROOTINO, 0755) != ROOTINO) errexit("CANNOT ALLOCATE ROOT INODE\n"); break; } if (reply("CONTINUE") == 0) errexit(""); break; case FSTATE: case FCLEAR: pfatal("ROOT INODE NOT DIRECTORY"); if (reply("REALLOCATE")) { freeino(ROOTINO); if (allocdir(ROOTINO, ROOTINO, 0755) != ROOTINO) errexit("CANNOT ALLOCATE ROOT INODE\n"); break; } if (reply("FIX") == 0) errexit(""); dp = ginode(ROOTINO); dp->di_mode &= ~IFMT; dp->di_mode |= IFDIR; inodirty(); break; case DSTATE: break; default: errexit("BAD STATE %d FOR ROOT INODE", statemap[ROOTINO]); } statemap[ROOTINO] = DFOUND; /* * Sort the directory list into disk block order. */ qsort((char *)inpsort, (size_t)inplast, sizeof *inpsort, blksort); /* * Check the integrity of each directory. */ bzero((char *)&curino, sizeof(struct inodesc)); curino.id_type = DATA; curino.id_func = pass2check; dp = &dino; inpend = &inpsort[inplast]; for (inpp = inpsort; inpp < inpend; inpp++) { inp = *inpp; if (inp->i_isize == 0) continue; if (inp->i_isize < MINDIRSIZE) { direrror(inp->i_number, "DIRECTORY TOO SHORT"); inp->i_isize = roundup(MINDIRSIZE, DIRBLKSIZ); if (reply("FIX") == 1) { dp = ginode(inp->i_number); dp->di_size = inp->i_isize; inodirty(); dp = &dino; } } else if ((inp->i_isize & (DIRBLKSIZ - 1)) != 0) { getpathname(pathbuf, inp->i_number, inp->i_number); pwarn("DIRECTORY %s: LENGTH %d NOT MULTIPLE OF %d", pathbuf, inp->i_isize, DIRBLKSIZ); if (preen) printf(" (ADJUSTED)\n"); inp->i_isize = roundup(inp->i_isize, DIRBLKSIZ); if (preen || reply("ADJUST") == 1) { dp = ginode(inp->i_number); dp->di_size = roundup(inp->i_isize, DIRBLKSIZ); inodirty(); dp = &dino; } } bzero((char *)&dino, sizeof(struct dinode)); dino.di_mode = IFDIR; dp->di_size = inp->i_isize; bcopy((char *)&inp->i_blks[0], (char *)&dp->di_db[0], (size_t)inp->i_numblks); curino.id_number = inp->i_number; curino.id_parent = inp->i_parent; (void)ckinode(dp, &curino); } /* * Now that the parents of all directories have been found, * make another pass to verify the value of `..' */ for (inpp = inpsort; inpp < inpend; inpp++) { inp = *inpp; if (inp->i_parent == 0 || inp->i_isize == 0) continue; if (statemap[inp->i_parent] == DFOUND && statemap[inp->i_number] == DSTATE) statemap[inp->i_number] = DFOUND; if (inp->i_dotdot == inp->i_parent || inp->i_dotdot == (ino_t)-1) continue; if (inp->i_dotdot == 0) { inp->i_dotdot = inp->i_parent; fileerror(inp->i_parent, inp->i_number, "MISSING '..'"); if (reply("FIX") == 0) continue; (void)makeentry(inp->i_number, inp->i_parent, ".."); lncntp[inp->i_parent]--; continue; } fileerror(inp->i_parent, inp->i_number, "BAD INODE NUMBER FOR '..'"); if (reply("FIX") == 0) continue; lncntp[inp->i_dotdot]++; lncntp[inp->i_parent]--; inp->i_dotdot = inp->i_parent; (void)changeino(inp->i_number, "..", inp->i_parent); } /* * Mark all the directories that can be found from the root. */ propagate(); }
int propagate( int state , Config_set *A , Config_set *B ) { STATE *shift_state; Config_set *C_ptr , *ptr; TOKEN *T_ptr , *first; TOKEN *dot; TOKEN *L2; TOKEN *L1; int i; L1 = A->lookahead; dot = A->dot; L2 = B->lookahead; //First(£^L) for( T_ptr = dot->next ; T_ptr != NULL ; T_ptr = T_ptr->next ) { first = search_token( first_set_start , T_ptr->string ); if (first == NULL ) continue; if ( search_set(first,"£f") == TRUE ) { add_set(L2,first); delete_set( &(L2->set) , "£f" ); continue; } else { if ( add_set(L2,first) == FALSE ) return 0; break; } } //First(£^L) , £^ is lambda if(T_ptr == NULL) { add_set( L2 , L1 ); } //printf("%d\n", parser_table[state][make_id(dot->string)].go_to ); if( B->dot == NULL ) return 0; i = parser_table[state][make_id(B->dot->string)-1].go_to; //printf("%d %s -> %d\n",state , B->dot->string , i ); //view_state(state); if( i == state ) return 0; // shift state for( shift_state = state_start ; i != shift_state->statenum ; shift_state = shift_state->next ); for( C_ptr = shift_state->config_set ; C_ptr != NULL && B->rule != C_ptr->rule ; C_ptr = C_ptr->set_next ); { // if ( i == 105 ) // printf("hit\n"); propagate_link( i , B , C_ptr ); } //comput lookahead by closue 0 C_ptr = shift_state->config_set; for( C_ptr = shift_state->config_set ; C_ptr != NULL && C_ptr->set_next != NULL ; C_ptr = C_ptr->set_next ) { for( ptr = shift_state->config_set ; ptr != NULL ; ptr = ptr->set_next ) { if ( C_ptr->dot == NULL ) continue; if ( strcmp( C_ptr->dot->string , ptr->rule->lhs ) == 0 ) { propagate( shift_state->statenum , C_ptr , ptr ); } } } return 0; }
void propagate (Treelog& msg) const { daisy_assert (!closed); for (size_t i = 0; i < entries.size (); i++) propagate (msg, entries[i].nest, entries[i].text); }
void assign(int varIndex) { assert(connected()); wcsp->revise(this); if (x->assigned() && y->assigned()) { deconnect(); if (x->getValue() >= xinfty && y->getValue() >= yinfty && costx + costy > deltaCost) { projectLB(costx + costy - deltaCost); } else if (x->getValue() >= xinfty && y->getValue() < yinfty && costx > deltaCost) { projectLB(costx - deltaCost); } else if (y->getValue() >= yinfty && x->getValue() < xinfty && costy > deltaCost) { projectLB(costy - deltaCost); } else if (x->getValue() < xinfty && y->getValue() < yinfty && x->getValue() < y->getValue() + csty && y->getValue() < x->getValue() + cstx) { THROWCONTRADICTION; } } else { if (varIndex == 0 && x->getValue() >= xinfty) { if (y->getInf() == deltaValueYinf) { Cost cost = deltaCostYinf; deltaCostYinf = MIN_COST; y->projectInfCost(-cost); } if (y->getSup() == deltaValueYsup) { Cost cost = deltaCostYsup; deltaCostYsup = MIN_COST; y->projectSupCost(-cost); } Cost cost = costx - deltaCost; if (cost > MIN_COST) { deltaCost += cost; projectLB(cost); } if (y->getSup() < yinfty) { deconnect(); } else { assert(y->getSup() == yinfty); deltaValueYsup = yinfty; deltaCostYsup = costy; y->projectSupCost(costy); } } else if (varIndex == 1 && y->getValue() >= yinfty) { if (x->getInf() == deltaValueXinf) { Cost cost = deltaCostXinf; deltaCostXinf = MIN_COST; x->projectInfCost(-cost); } if (x->getSup() == deltaValueXsup) { Cost cost = deltaCostXsup; deltaCostXsup = MIN_COST; x->projectSupCost(-cost); } Cost cost = costy - deltaCost; if (cost > MIN_COST) { deltaCost += cost; projectLB(cost); } if (x->getSup() < xinfty) { deconnect(); } else { assert(x->getSup() == xinfty); deltaValueXsup = xinfty; deltaCostXsup = costx; x->projectSupCost(costx); } } else { propagate(); } } }
void FlatUCBMod::propagate(Node* node, double score, bool invalidate, int UCTPlayer) { if (!node->isRoot && node->playerPlaying != UCTPlayer) propagate(node->parentPtr, score, invalidate, UCTPlayer); else { node->visited++; if (true) { if (node->opt.type != DRAW && node->opt.type != THIEFFLIP) { node->sum += score; node->value = double(node->sum) / double(node->visited); } } else { /* Explanation If we are calculating the score for a node, that is not a node HAVING -CHILDREN, then we simply take the SCORE and check whether it is better than what we already have. If it is, then we replace the old score with the new score (optimal and guaranteed path) However, if we are calculating the score for a node that HAS draw-children, (either all or none are draw-children), then we calculate the score to be child.value * child.probability / totalAccumulatedProbability. Where the totalAccumulatedProbability is equal to all the addition of all VISITED children's probability. (Visited = 2 or more, since we initialize all to Draw-Nodes to visited = 1). Note that we omit the propagated score value from the last node. After the value is calculated, we propagate this new value, instead of the old score, forcing ancestors to receive it, regardless of old score, so that the ancestor-nodes receive a weighted average of the draws, instead of the best possible node, based on an unlikely draw. The reasoning behind the force is (not midi-clorians) that as more draws are explored, their weighted average is becoming more precise, thus we want to propagate a precise value, rather than the best value. */ if (node->childrenPtrs.size() == 0) { node->value = score; } else if (node->childrenPtrs[0]->opt.type == DRAW) { double totalAccumulatedProbability = 0; for (std::vector<Node*>::iterator child = node->childrenPtrs.begin(); child != node->childrenPtrs.end(); ++child) { if ((*child)->visited > 1) totalAccumulatedProbability += (*child)->probability; } double newValue = 0; for (std::vector<Node*>::iterator child = node->childrenPtrs.begin(); child != node->childrenPtrs.end(); ++child) { if ((*child)->visited > 1) { if ((*child)->value < 0) int n = 5; newValue += ((*child)->probability / totalAccumulatedProbability) * (*child)->value; } } node->value = newValue; score = newValue; invalidate = true; } else if (0 == node->childrenPtrs[0]->playerPlaying) // Maximize value { /*if (invalidate) {*/ node->value = score; for (std::vector<Node*>::iterator child = node->childrenPtrs.begin(); child != node->childrenPtrs.end(); ++child) { if ((*child)->value > node->value && (*child)->visited > 0) { if ((*child)->value < 0) int n = 5; node->value = (*child)->value; } } /*} else { if (score > node->value) node->value = score; }*/ } else// Minimize value { /*if (invalidate) {*/ node->value = score; for (std::vector<Node*>::iterator child = node->childrenPtrs.begin(); child != node->childrenPtrs.end(); ++child) { if ((*child)->value < node->value && (*child)->visited > 0) { if ((*child)->value < 0) int n = 5; node->value = (*child)->value; } } /*} else { if (score < node->value) node->value = score; }*/ } } if (!node->isRoot) // As long as root is not reached, we should keep propagating recursively. propagate(node->parentPtr, score, invalidate, UCTPlayer); } }
void pass2(void) { struct ext2fs_dinode *dp; struct inoinfo **inpp, *inp; struct inoinfo **inpend; struct inodesc curino; struct ext2fs_dinode dino; char pathbuf[MAXPATHLEN + 1]; switch (statemap[EXT2_ROOTINO]) { case USTATE: pfatal("ROOT INODE UNALLOCATED"); if (reply("ALLOCATE") == 0) errexit("%s\n", ""); if (allocdir(EXT2_ROOTINO, EXT2_ROOTINO, 0755) != EXT2_ROOTINO) errexit("CANNOT ALLOCATE ROOT INODE\n"); break; case DCLEAR: pfatal("DUPS/BAD IN ROOT INODE"); if (reply("REALLOCATE")) { freeino(EXT2_ROOTINO); if (allocdir(EXT2_ROOTINO, EXT2_ROOTINO, 0755) != EXT2_ROOTINO) errexit("CANNOT ALLOCATE ROOT INODE\n"); break; } if (reply("CONTINUE") == 0) errexit("%s\n", ""); break; case FSTATE: case FCLEAR: pfatal("ROOT INODE NOT DIRECTORY"); if (reply("REALLOCATE")) { freeino(EXT2_ROOTINO); if (allocdir(EXT2_ROOTINO, EXT2_ROOTINO, 0755) != EXT2_ROOTINO) errexit("CANNOT ALLOCATE ROOT INODE\n"); break; } if (reply("FIX") == 0) errexit("%s\n", ""); dp = ginode(EXT2_ROOTINO); dp->e2di_mode = htole16((letoh16(dp->e2di_mode) & ~IFMT) | IFDIR); inodirty(); break; case DSTATE: break; default: errexit("BAD STATE %d FOR ROOT INODE\n", statemap[EXT2_ROOTINO]); } /* * Sort the directory list into disk block order. */ qsort((char *)inpsort, (size_t)inplast, sizeof *inpsort, blksort); /* * Check the integrity of each directory. */ memset(&curino, 0, sizeof(struct inodesc)); curino.id_type = DATA; curino.id_func = pass2check; inpend = &inpsort[inplast]; for (inpp = inpsort; inpp < inpend; inpp++) { inp = *inpp; if (inp->i_isize == 0) continue; if (inp->i_isize < MINDIRSIZE) { direrror(inp->i_number, "DIRECTORY TOO SHORT"); inp->i_isize = roundup(MINDIRSIZE, sblock.e2fs_bsize); if (reply("FIX") == 1) { dp = ginode(inp->i_number); inossize(dp, inp->i_isize); inodirty(); } } else if ((inp->i_isize & (sblock.e2fs_bsize - 1)) != 0) { getpathname(pathbuf, sizeof pathbuf, inp->i_number, inp->i_number); pwarn("DIRECTORY %s: LENGTH %lu NOT MULTIPLE OF %d", pathbuf, (u_long)inp->i_isize, sblock.e2fs_bsize); if (preen) printf(" (ADJUSTED)\n"); inp->i_isize = roundup(inp->i_isize, sblock.e2fs_bsize); if (preen || reply("ADJUST") == 1) { dp = ginode(inp->i_number); inossize(dp, inp->i_isize); inodirty(); } } memset(&dino, 0, sizeof(struct ext2fs_dinode)); dino.e2di_mode = htole16(IFDIR); inossize(&dino, inp->i_isize); memcpy(&dino.e2di_blocks[0], &inp->i_blks[0], (size_t)inp->i_numblks); curino.id_number = inp->i_number; curino.id_parent = inp->i_parent; (void)ckinode(&dino, &curino); } /* * Now that the parents of all directories have been found, * make another pass to verify the value of `..' */ for (inpp = inpsort; inpp < inpend; inpp++) { inp = *inpp; if (inp->i_parent == 0 || inp->i_isize == 0) continue; if (inp->i_dotdot == inp->i_parent || inp->i_dotdot == (ino_t)-1) continue; if (inp->i_dotdot == 0) { inp->i_dotdot = inp->i_parent; fileerror(inp->i_parent, inp->i_number, "MISSING '..'"); if (reply("FIX") == 0) continue; (void)makeentry(inp->i_number, inp->i_parent, ".."); lncntp[inp->i_parent]--; continue; } fileerror(inp->i_parent, inp->i_number, "BAD INODE NUMBER FOR '..'"); if (reply("FIX") == 0) continue; lncntp[inp->i_dotdot]++; lncntp[inp->i_parent]--; inp->i_dotdot = inp->i_parent; (void)changeino(inp->i_number, "..", inp->i_parent); } /* * Mark all the directories that can be found from the root. */ propagate(); }
void gradient_descent_local_planner_t::gradient_steer(const state_t* start, const state_t* goal, plan_t& plan) { //for now only going to do piecewise constant plans plan.clear(); traj.link_space(world_model->get_state_space()); plan.append_onto_front(max_multiple * simulation::simulation_step); const space_t* control_space = world_model->get_control_space(); sampler->sample(control_space, plan[0].control); unsigned count = 0; std::vector<double> old_control(control_space->get_dimension()); std::vector<double> test_control(control_space->get_dimension()); std::vector<double> control_below(control_space->get_dimension()); std::vector<double> control_above(control_space->get_dimension()); std::vector<std::pair<double, double> > diffs(control_space->get_dimension()); while( count < attempts ) { traj.clear(); plan[0].duration = max_multiple * simulation::simulation_step; propagate(start, plan, traj); unsigned num_sim_steps = 0; unsigned best_sim_step = 0; double best_dist = PRX_INFINITY; for( trajectory_t::iterator it = traj.begin(); it != traj.end(); it++ ) { num_sim_steps++; if( metric->distance_function(*it, goal) < best_dist ) { best_dist = metric->distance_function(*it, goal); best_sim_step = num_sim_steps; } } plan[0].duration = best_sim_step * simulation::simulation_step; if( best_dist < accepted_radius ) { return; } else { state_t* state = world_model->get_state_space()->alloc_point(); for( unsigned i = 0; i < control_space->get_dimension(); i++ ) { old_control[i] = plan[0].control->at(i); control_below[i] = old_control[i] - .01 * (control_space->get_bounds()[i]->get_upper_bound() - control_space->get_bounds()[i]->get_lower_bound()); control_above[i] = old_control[i] + .01 * (control_space->get_bounds()[i]->get_upper_bound() - control_space->get_bounds()[i]->get_lower_bound()); diffs[i].first = diffs[i].second = 0; } for( unsigned i = 0; i < control_space->get_dimension(); i++ ) { test_control = old_control; test_control[i] = control_below[i]; control_space->set_from_vector(test_control, plan[0].control); propagate_step(start, plan, state); diffs[i].first = metric->distance_function(state, goal); test_control[i] = control_above[i]; control_space->set_from_vector(test_control, plan[0].control); propagate_step(start, plan, state); diffs[i].second = metric->distance_function(state, goal); } world_model->get_state_space()->free_point(state); //now that all the differences have been computed, determine the direction to move test_control = old_control; for( unsigned i = 0; i < control_space->get_dimension(); i++ ) { test_control[i] += (diffs[i].first - diffs[i].second)*(learning_rate); } control_space->set_from_vector(test_control, plan[0].control); } count++; } // PRX_INFO_S(plan.print()); }
int main(int argc, const char * argv[]) { // Implementing MNIST character recognition /* * RESULTS: * 50 trainings - 50 hidden, .45 learning : 96.77% (only trial) <-- CURRENT BEST!! * 50 trainings - 45 hidden, .4 learning : 96.74% (only trial) * 50 trainings - 40 hidden, .25 learning : 96.16% (best trial of 2) * 50 trainings - 35 hidden, .35 learning : 96.18% (only trial) * 50 trainings - 30 hidden, .4 learning : 95.47% (only trial) * 50 trainings - 25 hidden, .4 learning : 94.95% (only trial) * 50 trainings - 20 hidden, .5 learning : 93.97% (only trial) * * * Note: It seems I was overfitting, not sure if this was * a waste of time or a lesson (probably both). I can train * 10 or more times less than the 50 trainings I was using * before and still get ~96% accuracy on the testing set. * However, with less training, I don't overfit the training * set as much, allowing better accuracy with more general * testing data, e.g. the handwritten digits collected from * my friends and colleagues. * * P.S. Even with only 3 trainings, 96% accuracy is still achievable * * P.S.S. Two trainings yielded poorer results on friend set * * Higher hidden layer widths seem to do better - getting into 97% * */ // If changing parameters, make sure to change export filename /* * Preprocessor macros/conditionals to make * switching between training and utilizing * easier - relies on this TRAINING definition */ // #define TRAINING #define IMAGE_START 16 #define LABEL_START 8 #define NUM_PIXELS 784 #define NUM_OUTPUTS 10 #ifdef TRAINING // EACH LEARNING FROM SCRATCH VERSION std::vector<unsigned int> hiddenSizes = {80}; auto netTest = new NeuralNetwork(NUM_PIXELS, 1, NUM_OUTPUTS, hiddenSizes, sigmoid, sigmoidPrime, 0.5, 0.4, 0.2); #endif #ifndef TRAINING // CONTINUED LESSONS VERSION auto netTest = new NeuralNetwork("saved/mnist_048545.json"); #endif std::vector<double> input = {}; std::vector<double> expected = {}; #ifdef TRAINING std::ifstream trainingImages; std::ifstream trainingLabels; trainingImages.open("mnist_data/train_images", ios::in | ios::binary); trainingLabels.open("mnist_data/train_labels", ios::in | ios::binary); #endif char read; #define NUM_TRAININGS 4 #define NUM_TRAINING_DIGITS 60000 #define HUNDREDTHS_OF_PERCENT_PER_TRAINING 2500 // 100 * (100 / NUM_TRAININGS) #define TRAININGS_PER_HUNDREDTH_OF_PERCENT 24 // NUM_TRAINING_DIGITS / HUNDREDTHS_OF_PERCENT_PER_TRAINING #ifdef TRAINING //Training loop for (unsigned int j = 0; j < NUM_TRAININGS; j++) { trainingImages.seekg(IMAGE_START); trainingLabels.seekg(LABEL_START); for (unsigned int i = 0; i < NUM_TRAINING_DIGITS; i++) { if (i % TRAININGS_PER_HUNDREDTH_OF_PERCENT == 0) { int curr_percent = (j * HUNDREDTHS_OF_PERCENT_PER_TRAINING) + (1 * i/TRAININGS_PER_HUNDREDTH_OF_PERCENT); if (curr_percent) printf("\r"); std::cout << curr_percent/100 << "."; std::cout << ((curr_percent%100 < 10) ? "0" : "") << curr_percent%100; std::cout << "% done training..." << std::flush; } // Setup input.clear(); expected.clear(); for (unsigned int k = 0; k < NUM_PIXELS; k++) { trainingImages.read((&read), 1); input.push_back((double)((unsigned char)read)/255); } trainingLabels.read((&read), 1); for (unsigned int k = 0; k < 10; k++) { expected.push_back(0); } expected.at(read) = 1; netTest->propagate(&input, &expected); } } std::cout << "\r100% done training!" << std::endl; #endif std::ifstream testImages; std::ifstream testLabels; #ifndef TRAINING testImages.open("mnist_preprocessing/converted/converted_images", ios::in | ios::out | ios::binary); testLabels.open("mnist_preprocessing/converted/converted_labels", ios::in | ios::out | ios::binary); #endif #ifdef TRAINING testImages.open("mnist_data/test_images", ios::in | ios::out | ios::binary); testLabels.open("mnist_data/test_labels", ios::in | ios::out | ios::binary); #endif testImages.seekg(IMAGE_START); testLabels.seekg(LABEL_START); unsigned int numCorrect = 0; #ifndef TRAINING #define NUM_TESTS 80 #else #define NUM_TESTS 10000 #endif for (unsigned int j = 0; j < NUM_TESTS; j++) { // Setup input.clear(); expected.clear(); for (unsigned int k = 0; k < NUM_PIXELS; k++) { testImages.read((&read), 1); input.push_back((double)((unsigned char)read)/255); } testLabels.read((&read), 1); for (unsigned int k = 0; k < 10; k++) { expected.push_back(0); } expected.at(read) = 1; std::cout << "Expected digit: " << (unsigned int)read << std::endl; printDigitAscii(&input); std::vector<double> output = netTest->getOutputs(&input); unsigned int outputDigit = determineDigit(&output); std::cout << "Output digit: " << outputDigit << std::endl; if (outputDigit == (unsigned int)read) { numCorrect++; } } #ifndef TRAINING #define DIVISOR 0.8 #else #define DIVISOR 100 #endif std::cout << "Total number correct: " << numCorrect << std::endl; std::cout << "Percentage correct: " << (double)numCorrect / DIVISOR << '%' << std::endl; #ifdef TRAINING std::cout << "Writing network to file..." << std::endl; netTest->exportNN("saved/mnist_0480504020.json"); // Export network to file std::cout << "File written!" << std::endl; #endif return 0; }
void PbSolver::solve(solve_Command cmd) { if (!ok) return; // Convert constraints: pb_n_vars = nVars(); pb_n_constrs = constrs.size(); if (opt_verbosity >= 1) reportf("Converting %d PB-constraints to clauses...\n", constrs.size()); propagate(); if (!convertPbs(true)){ assert(!ok); return; } // Freeze goal function variables (for SatELite): if (goal != NULL){ for (int i = 0; i < goal->size; i++) sat_solver.freeze(var((*goal)[i])); } // Solver (optimize): sat_solver.setVerbosity(opt_verbosity); vec<Lit> goal_ps; if (goal != NULL){ for (int i = 0; i < goal->size; i++) goal_ps.push((*goal)[i]); } vec<Int> goal_Cs; if (goal != NULL){ for (int i = 0; i < goal->size; i++) goal_Cs.push((*goal)(i)); } assert(best_goalvalue == Int_MAX); if (opt_polarity_sug != 0){ for (int i = 0; i < goal_Cs.size(); i++) sat_solver.suggestPolarity(var(goal_ps[i]), ((goal_Cs[i]*opt_polarity_sug > 0 && !sign(goal_ps[i])) || (goal_Cs[i]*opt_polarity_sug < 0 && sign(goal_ps[i]))) ? l_False : l_True); } if (opt_convert_goal != ct_Undef) opt_convert = opt_convert_goal; opt_sort_thres *= opt_goal_bias; if (opt_goal != Int_MAX) addConstr(goal_ps, goal_Cs, opt_goal, -1), convertPbs(false); if (opt_cnf != NULL) reportf("Exporting CNF to: \b%s\b\n", opt_cnf), sat_solver.exportCnf(opt_cnf), exit(0); bool sat = false; int n_solutions = 0; // (only for AllSolutions mode) while (sat_solver.solve()){ sat = true; if (cmd == sc_AllSolutions){ vec<Lit> ban; n_solutions++; reportf("MODEL# %d:", n_solutions); for (Var x = 0; x < pb_n_vars; x++){ assert(sat_solver.model()[x] != l_Undef); ban.push(Lit(x, sat_solver.model()[x] == l_True)); reportf(" %s%s", (sat_solver.model()[x] == l_False)?"-":"", index2name[x]); } reportf("\n"); sat_solver.addClause(ban); }else{ best_model.clear(); for (Var x = 0; x < pb_n_vars; x++) assert(sat_solver.model()[x] != l_Undef), best_model.push(sat_solver.model()[x] == l_True); if (goal == NULL) // ((fix: moved here Oct 4, 2005)) break; best_goalvalue = evalGoal(*goal, sat_solver.model()); if (cmd == sc_FirstSolution) break; if (opt_verbosity >= 1){ char* tmp = toString(best_goalvalue); reportf("\bFound solution: %s\b\n", tmp); xfree(tmp); } if (!addConstr(goal_ps, goal_Cs, best_goalvalue, -2)) break; convertPbs(false); } } if (goal == NULL && sat) best_goalvalue = Int_MIN; // (found model, but don't care about it) if (opt_verbosity >= 1){ if (!sat) reportf("\bUNSATISFIABLE\b\n"); else if (goal == NULL) reportf("\bSATISFIABLE: No goal function specified.\b\n"); else if (cmd == sc_FirstSolution){ char* tmp = toString(best_goalvalue); reportf("\bFirst solution found: %s\b\n", tmp); xfree(tmp); }else{ char* tmp = toString(best_goalvalue); reportf("\bOptimal solution: %s\b\n", tmp); xfree(tmp); } } }
/*! */ double RBFNetwork::train( const input_vector & input, const output_vector & teacher ) { if ( input.size() != M_input_dim ) { std::cerr << __FILE__ << ":" << __LINE__ << " illegal input vector size. " << input.size() << "(input) != " << M_input_dim << "(required)" << std::endl; return 0.0; } if ( teacher.size() != M_output_dim ) { std::cerr << __FILE__ << ":" << __LINE__ << " illegal output vector size. " << teacher.size() << "(input) != " << M_output_dim << "(required)" << std::endl; return 0.0; } const std::size_t OUTPUT = M_output_dim; output_vector output( OUTPUT, 0.0 ); propagate( input, output ); output_vector output_back( OUTPUT, 0.0 ); // calculate output error back for ( std::size_t i = 0; i < OUTPUT; ++i ) { output_back[i] = teacher[i] - output[i]; } // update each unit const std::vector< Unit >::iterator end = M_units.end(); for ( std::vector< Unit >::iterator it = M_units.begin(); it != end; ++it ) { const double unit_value = it->calc( input ); #if 0 const double dist2 = it->dist2( input ); const double sigma3 = std::pow( it->sigma_, 3 ); double back_sum = 0.0; for ( std::size_t i = 0; i < OUTPUT; ++i ) { back_sum += output_back[i] * it->weights_[i]; } // update sigma (d_gaussian) it->delta_sigma_ = M_eta * back_sum * ( dist2 / sigma3 ) * unit_value + M_alpha * it->delta_sigma_; it->sigma_ += it->delta_sigma_; #endif // update weights for ( std::size_t i = 0; i < OUTPUT; ++i ) { it->delta_weights_[i] = M_eta * output_back[i] * unit_value + M_alpha * it->delta_weights_[i]; it->weights_[i] += it->delta_weights_[i]; } } propagate( input, output ); double total_error = 0.0; for ( std::size_t i = 0; i < OUTPUT; ++i ) { double err = teacher[i] - output[i]; total_error += err * err; } return total_error; }
void localizerGVG::handleOdom(const nav_msgs::Odometry::ConstPtr& odom) { double x=odom->pose.pose.position.x; double y=odom->pose.pose.position.y; tf::Pose pose; tf::poseMsgToTF(odom->pose.pose, pose); double yaw=tf::getYaw(pose.getRotation()); ROS_DEBUG("IN [x=%f, y=%f, yaw=%f]",x,y,yaw); if(std::isnan(yaw) || std::isnan(x) || std::isnan(y)){ ROS_WARN("Odom read nan, skipping iteration of publishing and hoping for recovery."); return; } if(!initOdom) { oldX=x; oldY=y; oldYaw=yaw; initOdom=true; oldStamp=odom->header.stamp; Vector3d odomVector(x, y, yaw); X.segment(0, 3) = odomVector; return; } if(this->filterOn) { if((oldX==x)&&(oldY==y)&&(oldYaw==yaw)){ oldStamp=odom->header.stamp; return; } // Calculate the measurement double dx=x-oldX; double dy=y-oldY; double dYaw=angleDiff(yaw,oldYaw); double dt=odom->header.stamp.toSec()-oldStamp.toSec(); if(dt==0) { ROS_DEBUG("dt in localizer equal to zero, will lead to nan. skipping and hoping for recovery"); return; } double Vm=sqrt(dx*dx+dy*dy)/dt; double Wm=dYaw/dt; X(0)=X(0)+Vm*dt*cos(X(2)); X(1)=X(1)+Vm*dt*sin(X(2)); X(2)=thetapp(X(2)+Wm*dt); propagate(Vm,Wm,dt); // Publish the odometry with covariance topic geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(X(2)); nav_msgs::Odometry outputPose; outputPose.header.frame_id = "odom"; outputPose.header.stamp =odom->header.stamp; outputPose.pose.pose.position.x = X(0); outputPose.pose.pose.position.y = X(1); outputPose.pose.pose.position.z = 0; outputPose.pose.pose.orientation=odom_quat; if(std::isnan(X(0)),std::isnan(X(1))) { ROS_WARN("Filter made something nan, skipping publishing and hoping for recovery."); return; } for (unsigned int i=0; i<2; i++) for (unsigned int j=0; j<2; j++) outputPose.pose.covariance[6*i+j] = P(i,j); posePub.publish(outputPose); } oldX=x; oldY=y; oldYaw=yaw; oldStamp=odom->header.stamp; }
// This doesn't rewrite changes through properly so needs to have a substitution // applied to its output. ASTNode PropagateEqualities::propagate(const ASTNode& a, ArrayTransformer* at) { ASTNode output; // if the variable has been solved for, then simply return it if (simp->InsideSubstitutionMap(a, output)) return output; if (!alreadyVisited.insert(a.GetNodeNum()).second) { return a; } output = a; // traverse a and populate the SubstitutionMap const Kind k = a.GetKind(); if (SYMBOL == k && BOOLEAN_TYPE == a.GetType()) { bool updated = simp->UpdateSubstitutionMap(a, ASTTrue); output = updated ? ASTTrue : a; } else if (NOT == k) { bool updated = searchXOR(a[0], ASTFalse); output = updated ? ASTTrue : a; } else if (IFF == k || EQ == k) { const ASTVec& c = a.GetChildren(); if (c[0] == c[1]) return ASTTrue; bool updated = simp->UpdateSubstitutionMap(c[0], c[1]); if (updated) { // fill the arrayname readindices vector if e0 is a // READ(Arr,index) and index is a BVCONST int to; if ((to = TermOrder(c[0], c[1])) == 1 && c[0].GetKind() == READ) at->FillUp_ArrReadIndex_Vec(c[0], c[1]); else if (to == -1 && c[1].GetKind() == READ) at->FillUp_ArrReadIndex_Vec(c[1], c[0]); } if (!updated) updated = searchTerm(c[0], c[1]); if (!updated) updated = searchTerm(c[1], c[0]); output = updated ? ASTTrue : a; } else if (XOR == k) { bool updated = searchXOR(a, ASTTrue); output = updated ? ASTTrue : a; if (updated) return output; // The below block should be subsumed by the searchXOR function which // generalises it. // So the below block should never do anything.. #ifndef NDEBUG if (a.Degree() != 2) return output; int to = TermOrder(a[0], a[1]); if (0 == to) { if (a[0].GetKind() == NOT && a[0][0].GetKind() == EQ && a[0][0][0].GetValueWidth() == 1 && a[0][0][1].GetKind() == SYMBOL) { // (XOR (NOT(= (1 v))) ... ) const ASTNode& symbol = a[0][0][1]; const ASTNode newN = nf->CreateTerm( ITE, 1, a[1], a[0][0][0], nf->CreateTerm(BVNEG, 1, a[0][0][0])); if (simp->UpdateSolverMap(symbol, newN)) { assert(false); output = ASTTrue; } } else if (a[1].GetKind() == NOT && a[1][0].GetKind() == EQ && a[1][0][0].GetValueWidth() == 1 && a[1][0][1].GetKind() == SYMBOL) { const ASTNode& symbol = a[1][0][1]; const ASTNode newN = nf->CreateTerm( ITE, 1, a[0], a[1][0][0], nf->CreateTerm(BVNEG, 1, a[1][0][0])); if (simp->UpdateSolverMap(symbol, newN)) { assert(false); output = ASTTrue; } } else if (a[0].GetKind() == EQ && a[0][0].GetValueWidth() == 1 && a[0][1].GetKind() == SYMBOL) { // XOR ((= 1 v) ... ) const ASTNode& symbol = a[0][1]; const ASTNode newN = nf->CreateTerm( ITE, 1, a[1], nf->CreateTerm(BVNEG, 1, a[0][0]), a[0][0]); if (simp->UpdateSolverMap(symbol, newN)) { assert(false); output = ASTTrue; } } else if (a[1].GetKind() == EQ && a[1][0].GetValueWidth() == 1 && a[1][1].GetKind() == SYMBOL) { const ASTNode& symbol = a[1][1]; const ASTNode newN = nf->CreateTerm( ITE, 1, a[0], nf->CreateTerm(BVNEG, 1, a[1][0]), a[1][0]); if (simp->UpdateSolverMap(symbol, newN)) { assert(false); output = ASTTrue; } } else return output; } else { ASTNode symbol, rhs; if (to == 1) { symbol = a[0]; rhs = a[1]; } else { symbol = a[1]; rhs = a[0]; } assert(symbol.GetKind() == SYMBOL); if (simp->UpdateSolverMap(symbol, nf->CreateNode(NOT, rhs))) { assert(false); output = ASTTrue; } } #endif } else if (AND == k) { const ASTVec& c = a.GetChildren(); ASTVec o; o.reserve(c.size()); for (ASTVec::const_iterator it = c.begin(), itend = c.end(); it != itend; it++) { if (always_true) simp->UpdateAlwaysTrueFormSet(*it); ASTNode aaa = propagate(*it, at); if (ASTTrue != aaa) { if (ASTFalse == aaa) return ASTFalse; else o.push_back(aaa); } } if (o.size() == 0) output = ASTTrue; else if (o.size() == 1) output = o[0]; else if (o != c) output = nf->CreateNode(AND, o); else output = a; } return output; }
void pass2(void) { union dinode *dp; struct inoinfo **inpp, *inp, *pinp; struct inoinfo **inpend; struct inodesc curino; union dinode dino; char pathbuf[MAXPATHLEN + 1]; int i; switch (GET_ISTATE(ROOTINO)) { case USTATE: pfatal("ROOT INODE UNALLOCATED"); if (reply("ALLOCATE") == 0) { ckfini(0); errexit("%s", ""); } if (allocdir(ROOTINO, ROOTINO, 0755) != ROOTINO) errexit("CANNOT ALLOCATE ROOT INODE\n"); break; case DCLEAR: pfatal("DUPS/BAD IN ROOT INODE"); if (reply("REALLOCATE")) { freeino(ROOTINO); if (allocdir(ROOTINO, ROOTINO, 0755) != ROOTINO) errexit("CANNOT ALLOCATE ROOT INODE\n"); break; } if (reply("CONTINUE") == 0) { ckfini(0); errexit("%s", ""); } break; case FSTATE: case FCLEAR: pfatal("ROOT INODE NOT DIRECTORY"); if (reply("REALLOCATE")) { freeino(ROOTINO); if (allocdir(ROOTINO, ROOTINO, 0755) != ROOTINO) errexit("CANNOT ALLOCATE ROOT INODE\n"); break; } if (reply("FIX") == 0) { ckfini(0); errexit("%s", ""); } dp = ginode(ROOTINO); DIP_SET(dp, di_mode, DIP(dp, di_mode) & ~IFMT); DIP_SET(dp, di_mode, DIP(dp, di_mode) | IFDIR); inodirty(); break; case DSTATE: break; default: errexit("BAD STATE %d FOR ROOT INODE\n", GET_ISTATE(ROOTINO)); } SET_ISTATE(ROOTINO, DFOUND); /* * Sort the directory list into disk block order. */ qsort(inpsort, (size_t)inplast, sizeof *inpsort, blksort); /* * Check the integrity of each directory. */ memset(&curino, 0, sizeof(struct inodesc)); curino.id_type = DATA; curino.id_func = pass2check; inpend = &inpsort[inplast]; info_pos = 0; info_max = inpend - inpsort; info_fn = pass2_info1; for (inpp = inpsort; inpp < inpend; inpp++) { inp = *inpp; info_pos ++; if (inp->i_isize == 0) continue; if (inp->i_isize < MINDIRSIZE) { direrror(inp->i_number, "DIRECTORY TOO SHORT"); inp->i_isize = roundup(MINDIRSIZE, DIRBLKSIZ); if (reply("FIX") == 1) { dp = ginode(inp->i_number); DIP_SET(dp, di_size, inp->i_isize); inodirty(); } } else if ((inp->i_isize & (DIRBLKSIZ - 1)) != 0) { getpathname(pathbuf, sizeof pathbuf, inp->i_number, inp->i_number); if (usedsoftdep) pfatal("%s %s: LENGTH %ld NOT MULTIPLE of %d", "DIRECTORY", pathbuf, (long)inp->i_isize, DIRBLKSIZ); else pwarn("%s %s: LENGTH %ld NOT MULTIPLE OF %d", "DIRECTORY", pathbuf, (long)inp->i_isize, DIRBLKSIZ); if (preen) printf(" (ADJUSTED)\n"); inp->i_isize = roundup(inp->i_isize, DIRBLKSIZ); if (preen || reply("ADJUST") == 1) { dp = ginode(inp->i_number); DIP_SET(dp, di_size, inp->i_isize); inodirty(); } } memset(&dino, 0, sizeof(union dinode)); dp = &dino; DIP_SET(dp, di_mode, IFDIR); DIP_SET(dp, di_size, inp->i_isize); for (i = 0; i < (inp->i_numblks<NDADDR ? inp->i_numblks : NDADDR); i++) DIP_SET(dp, di_db[i], inp->i_blks[i]); if (inp->i_numblks > NDADDR) for (i = 0; i < NIADDR; i++) DIP_SET(dp, di_ib[i], inp->i_blks[NDADDR + i]); curino.id_number = inp->i_number; curino.id_parent = inp->i_parent; (void)ckinode(dp, &curino); } /* * Now that the parents of all directories have been found, * make another pass to verify the value of `..' */ info_pos = 0; info_fn = pass2_info2; for (inpp = inpsort; inpp < inpend; inpp++) { inp = *inpp; info_pos++; if (inp->i_parent == 0 || inp->i_isize == 0) continue; if (inp->i_dotdot == inp->i_parent || inp->i_dotdot == (ino_t)-1) continue; if (inp->i_dotdot == 0) { inp->i_dotdot = inp->i_parent; fileerror(inp->i_parent, inp->i_number, "MISSING '..'"); if (reply("FIX") == 0) continue; (void)makeentry(inp->i_number, inp->i_parent, ".."); lncntp[inp->i_parent]--; continue; } fileerror(inp->i_parent, inp->i_number, "BAD INODE NUMBER FOR '..'"); if (reply("FIX") == 0) continue; lncntp[inp->i_dotdot]++; lncntp[inp->i_parent]--; inp->i_dotdot = inp->i_parent; (void)changeino(inp->i_number, "..", inp->i_parent); } info_fn = NULL; /* * Create a list of children for each directory. */ inpend = &inpsort[inplast]; for (inpp = inpsort; inpp < inpend; inpp++) { inp = *inpp; if (inp->i_parent == 0 || inp->i_number == ROOTINO) continue; pinp = getinoinfo(inp->i_parent); inp->i_parentp = pinp; inp->i_sibling = pinp->i_child; pinp->i_child = inp; } /* * Mark all the directories that can be found from the root. */ propagate(ROOTINO); }
void add_client (boost::shared_ptr<Treelog> msg) { daisy_assert (msg.get ()); client.push_back (msg); propagate (*msg); }
void thread_liveness(void *args) { arg_struct_t* t = (arg_struct_t*)args; arena_list_t** worklist = t->worklist; size_t id = t->size; set_t* prev; vertex_t* u; size_t j; list_t* p; list_t* h; vertex_t* v; size_t count = 0; size_t sum = 0; //printf("this shoudl be zero workload %zu, id %zu\n", count,id); do{ pthread_mutex_lock(&work_mutex); u = aremove_first(worklist); pthread_mutex_unlock(&work_mutex); count++; if(u ==NULL){ printf("workload %zu, id %zu\n", count,id); return; } u->listed = false; reset(u->set[OUT]); //pthread_mutex_lock(&work_mutex); for( j = 0; j< u->nsucc; ++j){ pthread_mutex_lock(&u->succ[j]->mutex); or(u->set[OUT], u->set[OUT], u->succ[j]->set[IN]); pthread_mutex_unlock(&u->succ[j]->mutex); } /* in our case liveness information... */ pthread_mutex_lock(&u->mutex); prev = u->prev; u->prev = u->set[IN]; u->set[IN] = prev; propagate(u->set[IN], u->set[OUT], u->set[DEF], u->set[USE]); pthread_mutex_unlock(&u->mutex); if (u->pred != NULL && !equal(u->prev, u->set[IN])) { p = h = u->pred; do { v = p->data; if (!v->listed) { v->listed = true; pthread_mutex_lock(&work_mutex); ainsert_last(worklist, v); pthread_mutex_unlock(&work_mutex); } p = p->succ; } while (p != h); //pthread_mutex_unlock(&work_mutex); } }while(u != NULL); }
void propagate (int nest, const std::string& text) { for (size_t i = 0; i < client.size (); i++) propagate (*client[i], nest, text); }
// Modified line // bool MiniSATP::addClause(vec<Lit>& ps, Enode * e) bool MiniSATP::addClause(vec<Lit>& psin, Enode * e) { assert( decisionLevel() == 0 ); assert( ok ); // Added Lines vec< Lit > ps; psin.copyTo( ps ); if (!ok) return false; // Check if clause is satisfied and remove false/duplicate literals: sort(ps); Lit p; int i, j; for (i = j = 0, p = lit_Undef; i < ps.size(); i++) { if (value(ps[i]) == l_True || ps[i] == ~p) return true; else if (value(ps[i]) != l_False && ps[i] != p) ps[j++] = p = ps[i]; } ps.shrink(i - j); //================================================================================================= // Modified Code assert( psin.size( ) == 1 || ps.size() > 0 ); // // This case happens only when deductions are enabled // if (ps.size() == 0) { Clause * confl = Clause_new( psin ); if ( confl == NULL ) return ok = true; initExpDup( ); explanation.push_back( e ); storeExpDup( e ); fillExplanation( confl ); doneExpDup( ); assert( !explanation.empty( ) ); return ok = false; } if (ps.size() == 1) { assert(value(ps[0]) == l_Undef); uncheckedEnqueue(ps[0]); /* const Var v = var(ps[0]); if ( var_to_enode.size( ) <= v ) var_to_enode.resize( v + 1, NULL ); var_to_enode[ v ] = e; */ /* if ( e != NULL && seen_in_conflict.insert( e->getId( ) ).second ) explanation.push_back( e ); */ // undo_stack_oper.push_back( NEWUNIT ); // undo_stack_elem.push_back( (void *)v ); #define LAZY_PROPAGATION 0 #if LAZY_PROPAGATION #else // Modified Line // return ok = (propagate() == NULL); #if LIMIT_DEDUCTIONS deductions_done_in_call = 0; #endif Clause * confl = propagate( theory_prop ); if ( confl == NULL ) return ok = true; initExpDup( ); fillExplanation( confl ); doneExpDup( ); assert( !explanation.empty( ) ); return ok = false; #endif // Modified Code //================================================================================================= } else { Clause* c = Clause_new(ps, false); clauses.push(c); attachClause(*c); // Added Lines undo_stack_oper.push_back( NEWCLAUSE ); undo_stack_elem.push_back( (void *)c ); } return true; }
void assign(int varIndex) { if (x->assigned() && y->assigned()) deconnect(); propagate(); }
/*_________________________________________________________________________________________________ | | search : (nof_conflicts : int) (nof_learnts : int) (params : const SearchParams&) -> [lbool] | | Description: | Search for a model the specified number of conflicts, keeping the number of learnt clauses | below the provided limit. NOTE! Use negative value for 'nof_conflicts' or 'nof_learnts' to | indicate infinity. | | Output: | 'l_True' if a partial assigment that is consistent with respect to the clauseset is found. If | all variables are decision variables, this means that the clause set is satisfiable. 'l_False' | if the clause set is unsatisfiable. 'l_Undef' if the bound on number of conflicts is reached. |________________________________________________________________________________________________@*/ lbool MiniSATP::search(int nof_conflicts, int nof_learnts) { assert(ok); int backtrack_level; int conflictC = 0; vec<Lit> learnt_clause; starts++; bool first = true; for (;;){ Clause* confl = propagate(); if (confl != NULL){ // CONFLICT conflicts++; conflictC++; if (decisionLevel() == 0) { // Added Lines fillExplanation(confl); return l_False; } first = false; learnt_clause.clear(); analyze(confl, learnt_clause, backtrack_level); cancelUntil(backtrack_level); assert(value(learnt_clause[0]) == l_Undef); if (learnt_clause.size() == 1){ uncheckedEnqueue(learnt_clause[0]); }else{ Clause* c = Clause_new(learnt_clause, true); learnts.push(c); attachClause(*c); claBumpActivity(*c); uncheckedEnqueue(learnt_clause[0], c); } varDecayActivity(); claDecayActivity(); }else{ // NO CONFLICT if (nof_conflicts >= 0 && conflictC >= nof_conflicts){ // Reached bound on number of conflicts: progress_estimate = progressEstimate(); cancelUntil(0); return l_Undef; } // Simplify the set of problem clauses: if (decisionLevel() == 0 && !simplify()) { return l_False; } if (nof_learnts >= 0 && learnts.size()-nAssigns() >= nof_learnts) // Reduce the set of learnt clauses: reduceDB(); Lit next = lit_Undef; while (decisionLevel() < assumptions.size()){ // Perform user provided assumption: Lit p = assumptions[decisionLevel()]; if (value(p) == l_True){ // Dummy decision level: newDecisionLevel(); }else if (value(p) == l_False){ analyzeFinal(~p, conflict); return l_False; }else{ next = p; break; } } if (next == lit_Undef){ // New variable decision: decisions++; next = pickBranchLit(polarity_mode, random_var_freq); if (next == lit_Undef) { // Added Line // Clear explanation vector if satisfiable explanation.clear( ); // Model found: return l_True; } } // Increase decision level and enqueue 'next' assert(value(next) == l_Undef); newDecisionLevel(); uncheckedEnqueue(next); } } }
bool SPTGSolver::makeImpSwitchesP2(){ cout << "==>Imp2" << endl; bool allDone = false; bool changed = false; while (!allDone){ //For all states allDone = true; for (unsigned int state = 1; state < size; ++state){ //Owned by P2 because we are checking the improving switches for the P2 if(!sptg->getOwner(state)){ cout << "State: " << state << endl; cout << "Actual value: " << (*vals)[state][0] << "+" << (*vals)[state][1] << "e" << endl; //We don't need to take a look at the bottom transitions because the lambda transitions will always be better for P2 /*if(solvePTG && ((*bottoms)[state] > (*vals)[state][0])){//If we have an improvement, we update the values found (*vals)[state][0] = (*bottoms)[state]; (*vals)[state][1] = 0; strategies->front().insert(state, 0, 2); allDone = false; changed = true; }*/ //Check the lambda transition if((lambdas[state][0] > (*vals)[state][0]) || ((lambdas[state][0] == (*vals)[state][0]) && (lambdas[state][1] > (*vals)[state][1]))){ cout << "lambda is better" << endl; //If we have an improvement, we update the values found (*vals)[state][0] = lambdas[state][0]; (*vals)[state][1] = lambdas[state][1]; cout << (*vals)[state][0] << "+" << (*vals)[state][1] << "e" << endl; strategies->front().insert(state, 0, 1); (*pathsLengths)[state] = 1; allDone = false; changed = true; } for (unsigned int nextState = 0; nextState < size; ++nextState){ if(sptg->getTransition(state, nextState) != -1){//If the transition exists Fraction tempVal = (*vals)[nextState][0] + sptg->getTransition(state, nextState); if(tempVal > ifnty) tempVal = ifnty; unsigned int tempLength = (*pathsLengths)[nextState] + 1; //Check if the reset exists and is better if(solvePTG && ((*resets)[state][nextState] != -1) && ((*resets)[state][nextState] > (*vals)[state][0])){//If we have an improvement, we update the values found cout << "reset to " << nextState << "is better" << endl; (*vals)[state][0] = (*resets)[state][nextState]; (*vals)[state][1] = 0; cout << (*vals)[state][0] << "+" << (*vals)[state][1] << "e" << endl; strategies->front().insert(state, nextState, 3); allDone = false; changed = true; } //cout << state << ": " << (*vals)[state][0] << " " << (*vals)[state][1] << endl; //cout << "to: " << nextState << ": " << tempVal << " " << (*vals)[nextState][1] << endl; if((tempVal > (*vals)[state][0]) || ((tempVal == (*vals)[state][0]) && ((*vals)[nextState][1] > (*vals)[state][1])) ||((tempVal == (*vals)[state][0]) && ((*vals)[nextState][1] == (*vals)[state][1]) && (tempLength > (*pathsLengths)[state]))){ cout << "to " << nextState << " is better" << endl; //If we have an improvement, we update the values found (*vals)[state][0] = tempVal; (*vals)[state][1] = (*vals)[nextState][1]; cout << (*vals)[state][0] << "+" << (*vals)[state][1] << "e" << endl; cout << tempLength << endl; (*pathsLengths)[state] = tempLength; strategies->front().insert(state, nextState, 0); allDone = false; changed = true; } } } } if(changed)//If a change has been made, it can have an impact on the values of other states propagate(state); } } return changed; }
void pass2(void) { union dinode *dp; struct inoinfo **inpp, *inp; struct inoinfo **inpend; struct inodesc curino; union dinode dino; int i; char pathbuf[MAXPATHLEN + 1]; switch (inoinfo(ROOTINO)->ino_state) { case USTATE: pfatal("ROOT INODE UNALLOCATED"); if (reply("ALLOCATE") == 0) { ckfini(0); exit(EEXIT); } if (allocdir(ROOTINO, ROOTINO, 0755) != ROOTINO) errx(EEXIT, "CANNOT ALLOCATE ROOT INODE"); break; case DCLEAR: pfatal("DUPS/BAD IN ROOT INODE"); if (reply("REALLOCATE")) { freeino(ROOTINO); if (allocdir(ROOTINO, ROOTINO, 0755) != ROOTINO) errx(EEXIT, "CANNOT ALLOCATE ROOT INODE"); break; } if (reply("CONTINUE") == 0) { ckfini(0); exit(EEXIT); } break; case FSTATE: case FCLEAR: case FZLINK: pfatal("ROOT INODE NOT DIRECTORY"); if (reply("REALLOCATE")) { freeino(ROOTINO); if (allocdir(ROOTINO, ROOTINO, 0755) != ROOTINO) errx(EEXIT, "CANNOT ALLOCATE ROOT INODE"); break; } if (reply("FIX") == 0) { ckfini(0); exit(EEXIT); } dp = ginode(ROOTINO); DIP_SET(dp, di_mode, DIP(dp, di_mode) & ~IFMT); DIP_SET(dp, di_mode, DIP(dp, di_mode) | IFDIR); inodirty(); break; case DSTATE: case DZLINK: break; default: errx(EEXIT, "BAD STATE %d FOR ROOT INODE", inoinfo(ROOTINO)->ino_state); } inoinfo(ROOTINO)->ino_state = DFOUND; inoinfo(WINO)->ino_state = FSTATE; inoinfo(WINO)->ino_type = DT_WHT; /* * Sort the directory list into disk block order. */ qsort((char *)inpsort, (size_t)inplast, sizeof *inpsort, blksort); /* * Check the integrity of each directory. */ memset(&curino, 0, sizeof(struct inodesc)); curino.id_type = DATA; curino.id_func = pass2check; inpend = &inpsort[inplast]; for (inpp = inpsort; inpp < inpend; inpp++) { if (got_siginfo) { printf("%s: phase 2: dir %td of %d (%d%%)\n", cdevname, inpp - inpsort, (int)inplast, (int)((inpp - inpsort) * 100 / inplast)); got_siginfo = 0; } if (got_sigalarm) { setproctitle("%s p2 %d%%", cdevname, (int)((inpp - inpsort) * 100 / inplast)); got_sigalarm = 0; } inp = *inpp; if (inp->i_isize == 0) continue; if (inp->i_isize < MINDIRSIZE) { direrror(inp->i_number, "DIRECTORY TOO SHORT"); inp->i_isize = roundup(MINDIRSIZE, DIRBLKSIZ); if (reply("FIX") == 1) { dp = ginode(inp->i_number); DIP_SET(dp, di_size, inp->i_isize); inodirty(); } } else if ((inp->i_isize & (DIRBLKSIZ - 1)) != 0) { getpathname(pathbuf, inp->i_number, inp->i_number); if (usedsoftdep) pfatal("%s %s: LENGTH %jd NOT MULTIPLE OF %d", "DIRECTORY", pathbuf, (intmax_t)inp->i_isize, DIRBLKSIZ); else pwarn("%s %s: LENGTH %jd NOT MULTIPLE OF %d", "DIRECTORY", pathbuf, (intmax_t)inp->i_isize, DIRBLKSIZ); if (preen) printf(" (ADJUSTED)\n"); inp->i_isize = roundup(inp->i_isize, DIRBLKSIZ); if (preen || reply("ADJUST") == 1) { dp = ginode(inp->i_number); DIP_SET(dp, di_size, roundup(inp->i_isize, DIRBLKSIZ)); inodirty(); } } dp = &dino; memset(dp, 0, sizeof(struct ufs2_dinode)); DIP_SET(dp, di_mode, IFDIR); DIP_SET(dp, di_size, inp->i_isize); for (i = 0; i < (inp->i_numblks<NDADDR ? inp->i_numblks : NDADDR); i++) DIP_SET(dp, di_db[i], inp->i_blks[i]); if (inp->i_numblks > NDADDR) for (i = 0; i < NIADDR; i++) DIP_SET(dp, di_ib[i], inp->i_blks[NDADDR + i]); curino.id_number = inp->i_number; curino.id_parent = inp->i_parent; (void)ckinode(dp, &curino); } /* * Now that the parents of all directories have been found, * make another pass to verify the value of `..' */ for (inpp = inpsort; inpp < inpend; inpp++) { inp = *inpp; if (inp->i_parent == 0 || inp->i_isize == 0) continue; if (inoinfo(inp->i_parent)->ino_state == DFOUND && INO_IS_DUNFOUND(inp->i_number)) inoinfo(inp->i_number)->ino_state = DFOUND; if (inp->i_dotdot == inp->i_parent || inp->i_dotdot == (ino_t)-1) continue; if (inp->i_dotdot == 0) { inp->i_dotdot = inp->i_parent; fileerror(inp->i_parent, inp->i_number, "MISSING '..'"); if (reply("FIX") == 0) continue; (void)makeentry(inp->i_number, inp->i_parent, ".."); inoinfo(inp->i_parent)->ino_linkcnt--; continue; } /* * Here we have: * inp->i_number is directory with bad ".." in it. * inp->i_dotdot is current value of "..". * inp->i_parent is directory to which ".." should point. */ getpathname(pathbuf, inp->i_parent, inp->i_number); printf("BAD INODE NUMBER FOR '..' in DIR I=%d (%s)\n", inp->i_number, pathbuf); getpathname(pathbuf, inp->i_dotdot, inp->i_dotdot); printf("CURRENTLY POINTS TO I=%d (%s), ", inp->i_dotdot, pathbuf); getpathname(pathbuf, inp->i_parent, inp->i_parent); printf("SHOULD POINT TO I=%d (%s)", inp->i_parent, pathbuf); if (cursnapshot != 0) { /* * We need to: * setcwd(inp->i_number); * setdotdot(inp->i_dotdot, inp->i_parent); */ cmd.value = inp->i_number; if (sysctlbyname("vfs.ffs.setcwd", 0, 0, &cmd, sizeof cmd) == -1) { /* kernel lacks support for these functions */ printf(" (IGNORED)\n"); continue; } cmd.value = inp->i_dotdot; /* verify same value */ cmd.size = inp->i_parent; /* new parent */ if (sysctlbyname("vfs.ffs.setdotdot", 0, 0, &cmd, sizeof cmd) == -1) { printf(" (FIX FAILED: %s)\n", strerror(errno)); continue; } printf(" (FIXED)\n"); inoinfo(inp->i_parent)->ino_linkcnt--; inp->i_dotdot = inp->i_parent; continue; } if (preen) printf(" (FIXED)\n"); else if (reply("FIX") == 0) continue; inoinfo(inp->i_dotdot)->ino_linkcnt++; inoinfo(inp->i_parent)->ino_linkcnt--; inp->i_dotdot = inp->i_parent; (void)changeino(inp->i_number, "..", inp->i_parent); } /* * Mark all the directories that can be found from the root. */ propagate(); }
int genPlacementRoutingMatrix( BOARD* aBrd, EDA_MSG_PANEL* messagePanel ) { wxString msg; RoutingMatrix.UnInitRoutingMatrix(); EDA_RECT bbox = aBrd->ComputeBoundingBox( true ); if( bbox.GetWidth() == 0 || bbox.GetHeight() == 0 ) { DisplayError( NULL, _( "No PCB edge found, unknown board size!" ) ); return 0; } RoutingMatrix.ComputeMatrixSize( aBrd, true ); int nbCells = RoutingMatrix.m_Ncols * RoutingMatrix.m_Nrows; messagePanel->EraseMsgBox(); msg.Printf( wxT( "%d" ), RoutingMatrix.m_Ncols ); messagePanel->SetMessage( 1, _( "Cols" ), msg, GREEN ); msg.Printf( wxT( "%d" ), RoutingMatrix.m_Nrows ); messagePanel->SetMessage( 7, _( "Lines" ), msg, GREEN ); msg.Printf( wxT( "%d" ), nbCells ); messagePanel->SetMessage( 14, _( "Cells." ), msg, YELLOW ); // Choose the number of board sides. RoutingMatrix.m_RoutingLayersCount = 2; RoutingMatrix.InitRoutingMatrix(); // Display memory usage. msg.Printf( wxT( "%d" ), RoutingMatrix.m_MemSize / 1024 ); messagePanel->SetMessage( 24, wxT( "Mem(Kb)" ), msg, CYAN ); g_Route_Layer_BOTTOM = LAYER_N_FRONT; if( RoutingMatrix.m_RoutingLayersCount > 1 ) g_Route_Layer_BOTTOM = LAYER_N_BACK; g_Route_Layer_TOP = LAYER_N_FRONT; // Place the edge layer segments TRACK TmpSegm( NULL ); TmpSegm.SetLayer( UNDEFINED_LAYER ); TmpSegm.SetNet( -1 ); TmpSegm.SetWidth( RoutingMatrix.m_GridRouting / 2 ); EDA_ITEM* PtStruct = aBrd->m_Drawings; for( ; PtStruct != NULL; PtStruct = PtStruct->Next() ) { DRAWSEGMENT* DrawSegm; switch( PtStruct->Type() ) { case PCB_LINE_T: DrawSegm = (DRAWSEGMENT*) PtStruct; if( DrawSegm->GetLayer() != EDGE_N ) break; TmpSegm.SetStart( DrawSegm->GetStart() ); TmpSegm.SetEnd( DrawSegm->GetEnd() ); TmpSegm.SetShape( DrawSegm->GetShape() ); TmpSegm.m_Param = DrawSegm->GetAngle(); TraceSegmentPcb( &TmpSegm, HOLE | CELL_is_EDGE, RoutingMatrix.m_GridRouting, WRITE_CELL ); break; case PCB_TEXT_T: default: break; } } // Mark cells of the routing matrix to CELL_is_ZONE // (i.e. availlable cell to place a module ) // Init a starting point of attachment to the area. RoutingMatrix.OrCell( RoutingMatrix.m_Nrows / 2, RoutingMatrix.m_Ncols / 2, BOTTOM, CELL_is_ZONE ); // find and mark all other availlable cells: for( int ii = 1; ii != 0; ) ii = propagate(); // Initialize top layer. to the same value as the bottom layer if( RoutingMatrix.m_BoardSide[TOP] ) memcpy( RoutingMatrix.m_BoardSide[TOP], RoutingMatrix.m_BoardSide[BOTTOM], nbCells * sizeof(MATRIX_CELL) ); return 1; }
void SemanticObject::update(const Evidence& ev) { propagate(ev.getTimestamp()); // first update class property Attribute class_att = AttributeConv::attribute("class_label"); const Property* ev_class = ev.getProperty(class_att); if (ev_class) { Property* my_class = getProperty(class_att); if (my_class) { my_class->update(ev_class->getValue(), ev.getTimestamp()); } else { const IStateEstimator* prototype = getExpectedObjectModel().getEstimator(class_att); if (prototype) { Property* new_prop = new Property(class_att, *prototype); new_prop->update(ev_class->getValue(), ev.getTimestamp()); addProperty(new_prop); } else { printf("Could not find prototype estimator for attribute '%s'\n", AttributeConv::attribute_str(class_att).c_str()); } } } bool class_changed = false; const ClassModel& class_model = getExpectedObjectModel(); if (expected_class_ != class_model.getModelName()) { expected_class_ = class_model.getModelName(); class_changed = true; } // then update rest for(map<Attribute, Property*>::const_iterator it = ev.getPropertyMap().begin(); it != ev.getPropertyMap().end(); ++it) { const Attribute& attribute = it->first; const Property* ev_prop = it->second; if (attribute != class_att) { Property* my_prop = getProperty(attribute); if (my_prop && !class_changed) { my_prop->update(ev_prop->getValue(), ev.getTimestamp()); //cout << "Updating " << AttributeConv::attribute_str(attribute) << " with " << ev_prop->getValue().toString() << endl; //cout << "Result: " << my_prop->toString() << endl; } else { const IStateEstimator* prototype = getExpectedObjectModel().getEstimator(attribute); if (prototype) { Property* new_prop = new Property(attribute, *prototype); new_prop->update(ev_prop->getValue(), ev.getTimestamp()); addProperty(new_prop); } else { printf("Could not find prototype estimator for attribute '%s'\n", AttributeConv::attribute_str(it->first).c_str()); } } } } }
Tree boxPropagateSig (Tree path, Tree box, const siglist& lsig) { return listConvert(propagate(gGlobal->nil, path, box, lsig)); }
void ArcAgenda::propagate(const HyperGraph& g, const BitSet& m) { for (int i=0; i<nb_var; i++) if (m[i]) propagate(g,-1,i); }
static int searchnode(int level, int n, int *e, int nblue, int nred) { boolean ok; int i,status,nbest; addrval *valptr; int best,score,bestscore; int fe,fc; long ran; ok = propagate(n,e,&nblue,&nred); #if DEBUG if (ok) dumpdata(level,nblue,nred,n); else { printf("FAIL\n"); return NO; } #else if (!ok) return NO; #endif if (nblue == n && nred == n) return YES; #if FISHTAIL status = fishtail(n,&nblue,&nred); if (status == NO) return NO; if (status == YES) return searchnode(level+1,n,e,nblue,nred); #endif valptr = valstacktop; bestscore = -1; nbest = 0; for (i = 0; i < 2*n; ++i) if (colour[i] == WHITE) { score = (bluedeg[v1[i]] == 1) + (bluedeg[v2[i]] == 1) + (reddeg[v1[i]] == 1) + (reddeg[v2[i]] == 1); if (score > bestscore) { bestscore = score; beste[0] = i; nbest = 1; } else if (score == bestscore) beste[nbest++] = i; } if (bestscore == 0 && nred + nblue > 0) return FALSE; /* Disconnected */ ran = KRAN(2*nbest); best = beste[ran/2]; if ((ran&1)) { if (makeblue(best,nblue==n-1)) { #if DEBUG printf(" setting %d(%d-%d) blue\n",best,v1[best],v2[best]); #endif status = searchnode(level+1,n,e,nblue+1,nred); if (status != NO) return status; while (valstacktop > valptr) UNSETVAL; } if (++nodes == limit) return TIMEOUT; if (makered(best,nred==n-1)) { #if DEBUG printf(" setting %d(%d-%d) red\n",best,v1[best],v2[best]); #endif status = searchnode(level+1,n,e,nblue,nred+1); if (status != NO) return status; while (valstacktop > valptr) UNSETVAL; } } else { if (makered(best,nred==n-1)) { #if DEBUG printf(" setting %d(%d-%d) red\n",best,v1[best],v2[best]); #endif status = searchnode(level+1,n,e,nblue,nred+1); if (status != NO) return status; while (valstacktop > valptr) UNSETVAL; } if (++nodes == limit) return TIMEOUT; if (makeblue(best,nblue==n-1)) { #if DEBUG printf(" setting %d(%d-%d) blue\n",best,v1[best],v2[best]); #endif status = searchnode(level+1,n,e,nblue+1,nred); if (status != NO) return status; while (valstacktop > valptr) UNSETVAL; } } return NO; }
RESULT Engine::search() { int starts = 0; int nof_conflicts = so.restart_base; int conflictC = 0; while (true) { if (so.parallel && slave.checkMessages()) return RES_UNK; if (!propagate()) { clearPropState(); Conflict: conflicts++; conflictC++; if (time(NULL) > so.time_out) { printf("Time limit exceeded!\n"); return RES_UNK; } if (decisionLevel() == 0) { return RES_GUN; } // Derive learnt clause and perform backjump if (so.lazy) { sat.analyze(); } else { sat.confl = NULL; DecInfo& di = dec_info.last(); sat.btToLevel(decisionLevel()-1); makeDecision(di, 1); } if (!so.vsids && !so.toggle_vsids && conflictC >= so.switch_to_vsids_after) { if (so.restart_base >= 1000000000) so.restart_base = 100; sat.btToLevel(0); toggleVSIDS(); } } else { if (conflictC >= nof_conflicts) { starts++; nof_conflicts += getRestartLimit((starts+1)/2); sat.btToLevel(0); sat.confl = NULL; if (so.lazy && so.toggle_vsids && (starts % 2 == 0)) toggleVSIDS(); continue; } if (decisionLevel() == 0) { topLevelCleanUp(); if (opt_var && so.verbosity >= 3) { printf("%% root level bounds on objective: min %d max %d\n", opt_var->getMin(), opt_var->getMax()); } } DecInfo *di = NULL; // Propagate assumptions while (decisionLevel() < assumptions.size()) { int p = assumptions[decisionLevel()]; if (sat.value(toLit(p)) == l_True) { // Dummy decision level: assert(sat.trail.last().size() == sat.qhead.last()); engine.dec_info.push(DecInfo(NULL, p)); newDecisionLevel(); } else if (sat.value(toLit(p)) == l_False) { return RES_LUN; } else { di = new DecInfo(NULL, p); break; } } if (!di) di = branching->branch(); if (!di) { solutions++; if (so.print_sol) { problem->print(); printf("----------\n"); fflush(stdout); } if (!opt_var) { if (solutions == so.nof_solutions) return RES_SAT; if (so.lazy) blockCurrentSol(); goto Conflict; } if (!constrain()) { return RES_GUN; } continue; } engine.dec_info.push(*di); newDecisionLevel(); doFixPointStuff(); makeDecision(*di, 0); delete di; } } }