예제 #1
0
파일: rtastar.hpp 프로젝트: sanluis/search
    // bestkids returns a vector of all of the successors that have the
    // best f value.
    std::vector<Current> bestkids(D &d, Current &cur, Cost &sndf) {
        sndf = Cost(-1);
        std::vector<Current> bests;

        this->res.expd++;
        typename D::Operators ops(d, cur.state);
        for (unsigned int n = 0; n < ops.size(); n++) {

            this->res.gend++;
            typename D::Edge e(d, cur.state, ops[n]);
            Cost h = heuristic(d, e.state, e.revop);
            Cost f = h == Cost(-1) ? h : h + e.cost;

            if (bests.empty() || better(f, bests[0].f)) {
                if (!bests.empty())
                    sndf = bests[0].f;
                bests.clear();
                bests.push_back(Current(e.state, ops[n], e.revop, e.cost, f));
            } else if (bests[0].f == f) {
                assert (!bests.empty());
                bests.push_back(Current(e.state, ops[n], e.revop, e.cost, f));
            } else if (better(f, sndf)) {
                sndf = f;
            }
        }

        return bests;
    }
예제 #2
0
$printpopulation_details$
void print_population(population& P, parameters& par)
{
	int n = P.n;
	int m = P.m;
	if( par.printpopulation )
		for( int i=0; i<m; i++ )
		{
			cout << P.fitness[i] << " ";
			for( int j=0; j<n; j++ )
				cout << P.data[i*n+j] << " ";
			cout << endl;
		}	
	double average_target = 0.0;
	int best = 0;
	for( int i=1; i<m; i++ )
	{
		if( better(P.fitness[i], P.fitness[best]) )
			best = i;
		average_target += P.fitness[i];
	}
	average_target /= m;
	if( par.printbestsolution )
	{
		for( int k=0; k<n; k++ )
			cout << " " << P.data[best*n+k];
		cout << endl;
	}
	if( par.printstatistics )
		cout << P.fitness[best] << " " << average_target << endl;
}
예제 #3
0
파일: Downhill.cpp 프로젝트: droundy/deft
bool PreconditionedDownhillType::improve_energy(bool verbose) {
  iter++;
  const double old_energy = energy();
  const VectorXd g = pgrad();
  // Let's immediately free the cached gradient stored internally!
  invalidate_cache();
  // We waste some memory storing newx (besides *x itself), but this
  // avoids roundoff weirdness of trying to add nu*g back to *x, which
  // won't always get us back to the same value.
  Grid newx(gd, *x - nu*g);
  double newE = f.integral(kT, newx);
  int num_tries = 0;
  while (better(old_energy,newE)) {
    nu *= 0.5;
    newx = *x - nu*g;
    newE = f.integral(kT, newx);
    if (num_tries++ > 40) {
      printf("PreconditionedDownhill giving up after %d tries...\n", num_tries);
      return false; // It looks like we can't do any better with this algorithm.
    }
  }
  *x = newx;
  invalidate_cache();
  nu *= 1.1;
  if (verbose) {
    //lm->print_info();
    print_info();
  }
  return true;
}
예제 #4
0
 int build(int u, int l, int r) {
     if (l == r) return tree[u] = l;
     int m = (l + r) / 2;
     int a = build(2*u+1, l, m);
     int b = build(2*u+2, m+1, r);
     return tree[u] = better(a, b);
 }
예제 #5
0
$select_details$
void select(population& P, int x, int y, parameters& par)
{ 
	if( better(P.fitness[x], P.fitness[y]) )
		copy(P, y, x);
	else
		copy(P, x, y);
}
예제 #6
0
 // Returns the INDEX of the best element in range [p, q]
 int get(int u, int l, int r, int p, int q) {
     assert(l <= p and q <= r and p <= q);
     if (l == p and r == q) return tree[u];
     int m = (l + r) / 2;
     if (q <= m) return get(2*u+1, l, m, p, q);
     if (m + 1 <= p) return get(2*u+2, m+1, r, p, q);
     int a = get(2*u+1, l, m, p, m);
     int b = get(2*u+2, m+1, r, m+1, q);
     return better(a, b);
 }
예제 #7
0
int Directed_MST(int root, int n, int m) {
	int ret = 0;
	while (true) {
		for (int i = 0; i < n; i++)
			In[i] = 0;
		for (int i = 0; i < m; i++)	{
			int u = e[i].u;
			int v = e[i].v;
			if (better(e[i].cost, In[v]) && u != v) {
				pre[v] = u;
				In[v] = e[i].cost;
			}
		}
		for (int i = 0; i < n; i++) {
			if (i == root)
				continue;
			if (In[i] == 0)
				return -1;
		}
		int cntnode = 0;
		memset(hash1, -1, sizeof(hash1));
		memset(vis, -1, sizeof(vis));
		for (int i = 0; i < n; i++)
			if (i != root) {
				ret += In[i]->c;
				In[i]->useIt();
				int v = i;
				while (vis[v] != i && hash1[v] == -1 && v != root) {
					vis[v] = i;
					v = pre[v];
				}
				if (v != root && hash1[v] == -1) {
					for (int u = pre[v]; u != v; u = pre[u])
						hash1[u] = cntnode;
					hash1[v] = cntnode++;
				}
			}
		if (cntnode == 0)
			break;
		for (int i = 0; i < n; i++)
			if (hash1[i] == -1)
				hash1[i] = cntnode++;
		for (int i = 0; i < m; i++) {
			int v = e[i].v;
			e[i].u = hash1[e[i].u];
			e[i].v = hash1[e[i].v];
			if (e[i].u != e[i].v) {
				e[i].cost = new Cost(e[i].cost, In[v]);
			}
		}
		n = cntnode;
		root = hash1[root];
	}
	return ret;
}
예제 #8
0
 // Update the tree by setting the element `what` at position
 // `at`. Height is modified accordingly.
 void set(int u, int l, int r, int at, int what) {
     assert(l <= at and at <= r);
     if (l == at and at == r) { // leaf
         height[at] = what;
         assert(tree[u] == at);
     } else {
         int m = (l + r) / 2;
         if (at <= m)  set(2*u+1, l, m, at, what);
         if (m + 1 <= at) set(2*u+2, m+1, r, at, what);
         tree[u] = better(tree[2*u+1], tree[2*u+2]);
     }
 }
예제 #9
0
파일: dominance.c 프로젝트: renaudlr/hbda
int bi_weak_dom (const cost_t * v1, const cost_t * v2, int dim) {
	int i = 0;
	while (v1[i] == v2[i]) {
		i++;
		if (i == dim)
			return 1;
	}
	// i < first + p
	if (better (v1[i], v2[i])) {
		// return 0 or 1
		for ( ; i<dim; i++)
			if (worse (v1[i], v2[i]))
				return 0;
		return 1;
	}
	else {
		// return 0 or -1
		for ( ; i<dim; i++)
			if (better (v1[i], v2[i]))
				return 0;
		return -1;
	}
}
예제 #10
0
파일: dominance.c 프로젝트: renaudlr/hbda
bool dom (const cost_t * v1, const cost_t * v2, int p) {
	int i;
	bool one_ineq = false;
	for (i=0; i < p; i++) {
#ifdef DOM_COUNT_COMP
		other_comp++;
#endif
		if (worse (v1[i], v2[i]))
			return false;
		else if (better (v1[i], v2[i]))
			one_ineq = true;
	}
	return one_ineq;
}
int main() {
	freopen("approximate.in", "r", stdin);
	freopen("approximate2.out", "w", stdout);
	int a, b, n;
	scanf("%d%d%d", &a, &b, &n);
	int ans = 1;
	Ratio const need(a, b);
	Ratio best(2 * a > b ? 1 : 0, 1);
	if (a * 2 == b) {
		++ans;
	}
	for (int y = 2; y <= n; ++y) {
		int x = (long long) y * a / b;
		Ratio now1 = Ratio(x, y);
		Ratio now2 = Ratio(x + 1, y);
		bool ok1 = better(now1, best, need);
		bool ok2 = better(now2, best, need);
		if (!ok1 || !ok2) {
			ans += ok1 + ok2;
			if (ok1) best = now1;
			if (ok2) best = now2;
		} else {
			if (better(now1, now2, need)) {
				++ans;
				best = now1;
			} else if (better(now2, now1, need)) {
				++ans;
				best = now2;
			} else {
				ans += 2;
				best = now1;
			}
		}
	}
	printf("%d\n", ans);
}
예제 #12
0
파일: rtastar.hpp 프로젝트: sanluis/search
    // look returns the lookahead cost via a depth-limited,
    // alpha pruned, depth-first search.
    Cost look(D &d, State &state, Cost &alpha, Oper pop, Cost g, unsigned int left) {
        Cost f = d.h(state) + g;
        if (this->limit() || left == 0 || !better(f, alpha) || d.isgoal(state)) {
            if (better(f, alpha))
                alpha = f;
            return f;
        }

        this->res.expd++;
        Cost bestf = Cost(-1);
        typename D::Operators ops(d, state);
        for (unsigned int n = 0; n < ops.size(); n++) {
            if (ops[n] == pop)
                continue;

            this->res.gend++;
            typename D::Edge e(d, state, ops[n]);
            f = look(d, e.state, alpha, e.revop, g + e.cost, left-1);
            if (better(f, bestf))
                bestf = f;
        }

        return bestf;
    }
예제 #13
0
void MaxSearch<Item,Value,Compare>::Do(const Item& current)
{
    Value val = Func(current);
    if ( !Cond(current) ) return;
    if (l){
        if (better(val,opt)){
            opt = val;
            optelem = current;
        }
    }
    else {
        l = true;
        opt = val;
        optelem = current;
    }

}
예제 #14
0
파일: maxset.hpp 프로젝트: t-crest/poseidon
	bool insert(const T& x) 
	{
		auto y = this->store.find(x);
		const bool same_major = (y != this->store.end());

		if (!same_major) {
			this->store.insert(x);
			return true;
		}
		
		minor_comparator better;
		if (better(x, *y)) { // if x is better, replace *y
			this->store.erase(y);
			this->store.insert(x);
			return true;
		}
		
		return false;
	}
예제 #15
0
// Select the best matching function for 'call' from 'candidateList'.
//
// Assumptions
//
// There is no exact match, so a selection algorithm needs to run. That is, the
// language-specific handler should check for exact match first, to
// decide what to do, before calling this selector.
//
// Input
//
//  * list of candidate signatures to select from
//  * the call
//  * a predicate function convertible(from, to) that says whether or not type
//    'from' can implicitly convert to type 'to' (it includes the case of what
//    the calling language would consider a matching type with no conversion
//    needed)
//  * a predicate function better(from1, from2, to1, to2) that says whether or
//    not a conversion from <-> to2 is considered better than a conversion
//    from <-> to1 (both in and out directions need testing, as declared by the
//    formal parameter)
//
// Output
//
//  * best matching candidate (or none, if no viable candidates found)
//  * whether there was a tie for the best match (ambiguous overload selection,
//    caller's choice for how to report)
//
const TFunction* TParseContextBase::selectFunction(
    const TVector<const TFunction*> candidateList,
    const TFunction& call,
    std::function<bool(const TType& from, const TType& to, TOperator op, int arg)> convertible,
    std::function<bool(const TType& from, const TType& to1, const TType& to2)> better,
    /* output */ bool& tie)
{
//
// Operation
//
// 1. Prune the input list of candidates down to a list of viable candidates,
// where each viable candidate has
//
//  * at least as many parameters as there are calling arguments, with any
//    remaining parameters being optional or having default values
//  * each parameter is true under convertible(A, B), where A is the calling
//    type for in and B is the formal type, and in addition, for out B is the
//    calling type and A is the formal type
//
// 2. If there are no viable candidates, return with no match.
//
// 3. If there is only one viable candidate, it is the best match.
//
// 4. If there are multiple viable candidates, select the first viable candidate
// as the incumbent. Compare the incumbent to the next viable candidate, and if
// that candidate is better (bullets below), make it the incumbent. Repeat, with
// a linear walk through the viable candidate list. The final incumbent will be
// returned as the best match. A viable candidate is better than the incumbent if
//
//  * it has a function argument with a better(...) conversion than the incumbent,
//    for all directions needed by in and out
//  * the incumbent has no argument with a better(...) conversion then the
//    candidate, for either in or out (as needed)
//
// 5. Check for ambiguity by comparing the best match against all other viable
// candidates. If any other viable candidate has a function argument with a
// better(...) conversion than the best candidate (for either in or out
// directions), return that there was a tie for best.
//

    tie = false;

    // 1. prune to viable...
    TVector<const TFunction*> viableCandidates;
    for (auto it = candidateList.begin(); it != candidateList.end(); ++it) {
        const TFunction& candidate = *(*it);

        // to even be a potential match, number of arguments must be >= the number of
        // fixed (non-default) parameters, and <= the total (including parameter with defaults).
        if (call.getParamCount() < candidate.getFixedParamCount() ||
            call.getParamCount() > candidate.getParamCount())
            continue;

        // see if arguments are convertible
        bool viable = true;

        // The call can have fewer parameters than the candidate, if some have defaults.
        const int paramCount = std::min(call.getParamCount(), candidate.getParamCount());
        for (int param = 0; param < paramCount; ++param) {
            if (candidate[param].type->getQualifier().isParamInput()) {
                if (! convertible(*call[param].type, *candidate[param].type, candidate.getBuiltInOp(), param)) {
                    viable = false;
                    break;
                }
            }
            if (candidate[param].type->getQualifier().isParamOutput()) {
                if (! convertible(*candidate[param].type, *call[param].type, candidate.getBuiltInOp(), param)) {
                    viable = false;
                    break;
                }
            }
        }

        if (viable)
            viableCandidates.push_back(&candidate);
    }

    // 2. none viable...
    if (viableCandidates.size() == 0)
        return nullptr;

    // 3. only one viable...
    if (viableCandidates.size() == 1)
        return viableCandidates.front();

    // 4. find best...
    const auto betterParam = [&call, &better](const TFunction& can1, const TFunction& can2) -> bool {
        // is call -> can2 better than call -> can1 for any parameter
        bool hasBetterParam = false;
        for (int param = 0; param < call.getParamCount(); ++param) {
            if (better(*call[param].type, *can1[param].type, *can2[param].type)) {
                hasBetterParam = true;
                break;
            }
        }
        return hasBetterParam;
    };

    const auto equivalentParams = [&call, &better](const TFunction& can1, const TFunction& can2) -> bool {
        // is call -> can2 equivalent to call -> can1 for all the call parameters?
        for (int param = 0; param < call.getParamCount(); ++param) {
            if (better(*call[param].type, *can1[param].type, *can2[param].type) ||
                better(*call[param].type, *can2[param].type, *can1[param].type))
                return false;
        }
        return true;
    };

    const TFunction* incumbent = viableCandidates.front();
    for (auto it = viableCandidates.begin() + 1; it != viableCandidates.end(); ++it) {
        const TFunction& candidate = *(*it);
        if (betterParam(*incumbent, candidate) && ! betterParam(candidate, *incumbent))
            incumbent = &candidate;
    }

    // 5. ambiguity...
    for (auto it = viableCandidates.begin(); it != viableCandidates.end(); ++it) {
        if (incumbent == *it)
            continue;
        const TFunction& candidate = *(*it);

        // In the case of default parameters, it may have an identical initial set, which is
        // also ambiguous
        if (betterParam(*incumbent, candidate) || equivalentParams(*incumbent, candidate))
            tie = true;
    }

    return incumbent;
}
예제 #16
0
bool QuadraticLineMinimizerType::improve_energy(bool verbose) {
  //if (verbose) printf("\t\tI am running QuadraticLineMinimizerType::improve_energy with verbose==%d\n", verbose);
  //fflush(stdout);
  // FIXME: The following probably double-computes the energy!
  const double E0 = energy();
  if (verbose) {
    printf("\t\tQuad: E0 = %25.15g", E0);
    fflush(stdout);
  }
  if (isnan(E0)) {
    // There is no point continuing, since we're starting with a NaN!
    // So we may as well quit here.
    if (verbose) {
      printf(" which is a NaN, so I'm quitting early.\n");
      fflush(stdout);
    }
    return false;
  }
  if (isnan(slope)) {
    // The slope here is a NaN, so there is no point continuing!
    // So we may as well quit here.
    if (verbose) {
      printf(", but the slope is a NaN, so I'm quitting early.\n");
      fflush(stdout);
    }
    return false;
  }
  if (slope == 0) {
    // When the slope is precisely zero, there's no point continuing,
    // as the gradient doesn't have any information about how to
    // improve things.  Or possibly we're at the minimum to numerical
    // precision.
    if (verbose) {
      printf(" which means we've arrived at the minimum!\n");
      fflush(stdout);
    }
    return false;
  }

  if (slope*(*step) > 0) {
    if (verbose) printf("Swapping sign of step with slope %g...\n", slope);
    *step *= -1;
  }
  // Here we're going to keep halving step1 until it's small enough
  // that the energy drops a tad.  This hopefully will give us a
  // reasonable starting guess.
  double step1 = *step;
  *x += step1*direction; // Step away a bit...
  double Etried = -137;
  do {
    step1 *= 0.5;
    *x -= step1*direction; // and then step back a bit less...
    invalidate_cache();
    if (energy() == Etried) {
      if (verbose) {
        printf("\tThis is silly in QuadraticLineMinimizerType::improve_energy: %g (%g vs %g)\n",
               step1, energy(), Etried);
        Grid foo(gd, *x);
        f.run_finite_difference_test("In QuadraticLineMinimizerType", kT, foo, &direction);
        fflush(stdout);
      }
      break;
    }
    Etried = energy();
  } while (energy() > E0 || isnan(energy()));
  
  const double E1 = energy();

  // Do a parabolic extrapolation with E0, E1, and gd to get curvature
  // and new step
  const double curvature = 2.0*(E1-E0-step1*slope)/(step1*step1);
  double step2 = -slope/curvature;
  if (verbose) {
    printf("   E1 = %25.15g\n", E1);
    printf("\t\tQuad: slope = %14.7g  curvature = %14.7g\n", slope, curvature);
    fflush(stdout);
  }
 
  if (curvature <= 0.0) {
    if (verbose) {
      printf("\t\tCurvature has wrong sign... %g\n", curvature);
      fflush(stdout);
    }
    if (better(E0, E1)) {
      // It doesn't look to be working, so let's panic!
      invalidate_cache();
      *x -= step1*direction;
      if (verbose) printf("\t\tQuadratic linmin not working properly!!!\n");
      //assert(!"Quadratic linmin not working well!!!\n");
      return false;
    } else {
      // It looks like we aren't moving far enough, so let's try
      // progressively doubling how far we're going.
      double Ebest = E0;
      while (energy() <= Ebest) {
        Ebest = energy();
        *x += step1*direction;
        invalidate_cache();
        step1 *= 2;
      }
      step1 *= 0.5;
      *x -= step1*direction;
      *step = step1;
    }
  } else if (E1 == E0) {
    if (verbose) {
      printf("\t\tNo change in energy... step1 is %g, direction has mag %g pos is %g\n",
             step1, direction.norm(), x->norm());
      fflush(stdout);
    }
    do {
      invalidate_cache();
      *x -= step1*direction;
      step1 *= 2;
      *x += step1*direction;
      // printf("From step1 of %10g I get delta E of %g\n", step1, energy()-E0);
    } while (energy() == E0);
    if (energy() > E0) {
      *x -= step1*direction;
      invalidate_cache();
      step1 = 0;
      printf("\t\tQuad: failed to find any improvement!  :(\n");
    } else if (isnan(energy())) {
      printf("\t\tQuad: found NaN with smallest possible step!!!\n");
      *x -= step1*direction;
      invalidate_cache();
      step1 = 0;
      //printf("\t\tQuad: put energy back to %g...\n", energy());
    }
  } else {
    *step = step2; // output the stepsize for later reuse.
    invalidate_cache();
    *x += (step2-step1)*direction; // and move to the expected minimum.
    if (verbose) {
      printf("\t\tQuad: step1 = %14.7g  step2 = %14.7g\n", step1, step2);
      printf("\t\tQuad: E2 = %25.15g\n", energy());
      fflush(stdout);
    }

    // Check that the energy did indeed drop!  FIXME: this may do
    // extra energy calculations, since it's not necessarily shared
    // with the driver routine!
    if (better(E1, energy()) && better(E1, E0)) {
      // The first try was better, so let's go with that one!
      if (verbose) printf("\t\tGoing back to the first try...\n");
      invalidate_cache();
      *x -= (step2-step1)*direction;
    } else if (energy() > E0) {
      const double E2 = energy();
      invalidate_cache();
      *x -= step2*direction;
      if (verbose) {
        printf("\t\tQuadratic linmin not working well!!! (E2 = %14.7g, E0 = %14.7g)\n", E2, energy());
        fflush(stdout);
      }
      return false;
      //assert(!"Quadratic linmin not working well!!!\n");
    }
  }
  // We always return false, because it's never recommended to call
  // improve_energy again with this algorithm.
  return false;
}