use of org.eclipse.collections.api.tuple.Pair in project eclipse-collections by eclipse.
the class AbstractMutableSortedBagTestCase method zip.
@Override
@Test
public void zip() {
super.zip();
MutableSortedBag<Integer> revInt = this.newWith(Collections.reverseOrder(), 2, 2, 3, 5, 1, 4);
MutableSortedBag<Integer> integers = this.newWith(1, 3, 2, 2, 4, 5);
MutableList<Pair<Integer, Integer>> zip = integers.zip(revInt);
Verify.assertSize(6, zip);
Assert.assertEquals(FastList.newListWith(Tuples.pair(1, 5), Tuples.pair(2, 4), Tuples.pair(2, 3), Tuples.pair(3, 2), Tuples.pair(4, 2), Tuples.pair(5, 1)), zip);
MutableList<Pair<Integer, Integer>> revZip = revInt.zip(integers);
Verify.assertSize(6, revZip);
Assert.assertEquals(FastList.newListWith(Tuples.pair(5, 1), Tuples.pair(4, 2), Tuples.pair(3, 2), Tuples.pair(2, 3), Tuples.pair(2, 4), Tuples.pair(1, 5)), revZip);
Person john = new Person("John", "Smith");
Person johnDoe = new Person("John", "Doe");
MutableSortedBag<Person> people = this.newWith(john, johnDoe);
MutableList<Integer> list = FastList.newListWith(1, 2, 3);
MutableList<Pair<Person, Integer>> pairs = people.zip(list);
Assert.assertEquals(FastList.newListWith(Tuples.pair(johnDoe, 1), Tuples.pair(john, 2)), pairs);
Assert.assertTrue(pairs.add(Tuples.pair(new Person("Jack", "Baker"), 3)));
Assert.assertEquals(Tuples.pair(new Person("Jack", "Baker"), 3), pairs.getLast());
}
use of org.eclipse.collections.api.tuple.Pair in project narchy by automenta.
the class Optimize method run.
public Result<X> run(int maxIterations, int repeats, FloatFunction<Supplier<X>> eval) {
assert (repeats >= 1);
final int dim = tweaks.size();
double[] mid = new double[dim];
// double[] sigma = new double[n];
double[] min = new double[dim];
double[] max = new double[dim];
double[] inc = new double[dim];
// double[] range = new double[dim];
X example = subject.get();
int i = 0;
for (Tweak w : tweaks) {
TweakFloat s = (TweakFloat) w;
// initial guess: get from sample, otherwise midpoint of min/max range
Object guess = s.get(example);
mid[i] = guess != null ? ((float) guess) : ((s.getMax() + s.getMin()) / 2f);
min[i] = (s.getMin());
max[i] = (s.getMax());
inc[i] = s.getInc();
// range[i] = max[i] - min[i];
// sigma[i] = Math.abs(max[i] - min[i]) * 0.75f; //(s.getInc());
i++;
}
FasterList<DoubleObjectPair<double[]>> experiments = new FasterList<>(maxIterations);
final double[] maxScore = { Double.NEGATIVE_INFINITY };
ObjectiveFunction func = new ObjectiveFunction(point -> {
double score;
try {
double sum = 0;
for (int r = 0; r < repeats; r++) {
Supplier<X> x = () -> subject(point);
sum += eval.floatValueOf(x);
}
score = sum / repeats;
} catch (Exception e) {
logger.error("{} {} {}", this, point, e);
score = Float.NEGATIVE_INFINITY;
}
if (trace)
csv.out(ArrayUtils.add(point, (int) 0, score));
maxScore[0] = Math.max(maxScore[0], score);
// System.out.println(
// n4(score) + " / " + n4(maxScore[0]) + "\t" + n4(point)
// );
experiments.add(pair(score, point));
experimentIteration(point, score);
return score;
});
if (trace)
csv = new CSVOutput(System.out, Stream.concat(Stream.of("score"), tweaks.stream().map(t -> t.id)).toArray(String[]::new));
experimentStart();
try {
solve(dim, func, mid, min, max, inc, maxIterations);
} catch (Throwable t) {
logger.info("solve {} {}", func, t);
}
return new Result<>(experiments, tweaks);
}
use of org.eclipse.collections.api.tuple.Pair in project narchy by automenta.
the class DeriveTime method solveMerged.
@Nullable
Function<long[], Term> solveMerged(ArrayHashSet<Event> solutions, int dur) {
int ss = solutions.size();
// callee will use the only solution by default
if (ss <= 1)
return null;
SortedSetMultimap<Term, LongLongPair> m = MultimapBuilder.hashKeys(ss).treeSetValues().build();
solutions.forEach(x -> {
long w = x.when();
if (w != TIMELESS)
m.put(x.id, PrimitiveTuples.pair(w, w));
});
int ms = m.size();
switch(ms) {
case 0:
return null;
case 1:
Map.Entry<Term, LongLongPair> ee = m.entries().iterator().next();
LongLongPair ww = ee.getValue();
long s = ww.getOne();
long e = ww.getTwo();
return (w) -> {
w[0] = s;
w[1] = e;
return ee.getKey();
};
}
FasterList<Pair<Term, long[]>> choices = new FasterList(ms);
// coalesce adjacent events
m.asMap().forEach((t, cw) -> {
int cws = cw.size();
if (cws > 1) {
long[][] ct = new long[cws][2];
int i = 0;
for (LongLongPair p : cw) {
long[] cc = ct[i++];
cc[0] = p.getOne();
cc[1] = p.getTwo();
}
// TODO more complete comparison
long[] prev = ct[0];
for (int j = 1; j < cws; j++) {
long[] next = ct[j];
if (prev[0] == ETERNAL) {
assert (j == 1);
assert (ct[0][0] == ETERNAL);
// ignore eternal solution amongst other temporal solutions
ct[0] = null;
} else if (Math.abs(prev[1] - next[0]) <= dur) {
// stretch
prev[1] = next[1];
ct[j] = null;
continue;
}
prev = next;
}
for (int j = 0; j < cws; j++) {
long[] nn = ct[j];
if (nn != null)
choices.add(pair(t, nn));
}
} else {
LongLongPair f = ((SortedSet<LongLongPair>) cw).first();
choices.add(pair(t, new long[] { f.getOne(), f.getTwo() }));
}
});
if (choices.size() > 1) {
// random fallback
return (w) -> {
Pair<Term, long[]> pp = choices.get(d.random);
long[] cw = pp.getTwo();
w[0] = cw[0];
w[1] = cw[1];
return pp.getOne();
};
} else {
Pair<Term, long[]> c = choices.get(0);
long[] cw = c.getTwo();
Term cct = c.getOne();
return (w) -> {
w[0] = cw[0];
w[1] = cw[1];
return cct;
};
}
}
use of org.eclipse.collections.api.tuple.Pair in project narchy by automenta.
the class Conclude method match.
public static void match(final DeriveRuleProto rule, List<PrediTerm<PreDerivation>> pre, List<PrediTerm<Derivation>> post, PatternIndex index, NAR nar) {
Term pattern = rule.conclusion().sub(0);
// TODO may interfere with constraints, functors, etc or other features, ie.
// if the pattern is a product for example?
// pattern = pattern.replace(ta, Derivation._taskTerm);
// determine if any cases where a shortcut like this can work (ie. no constraints, not a product etc)
// //substitute compound occurrences of the exact task and belief terms with the short-cut
// Term ta = rule.getTask();
// if (!ta.op().var) {
// if (pattern.equals(ta))
// pattern = Derivation.TaskTerm;
// }
// Term tb = rule.getBelief();
// if (!tb.op().var) {
// //pattern = pattern.replace(tb, Derivation._beliefTerm);
// if (pattern.equals(tb))
// pattern = Derivation.BeliefTerm;
// }
// HACK unwrap varIntro so we can apply it at the end of the derivation process, not before like other functors
boolean introVars1;
Pair<Termed, Term> outerFunctor = Op.functor(pattern, (i) -> i.equals(VAR_INTRO) ? VAR_INTRO : null);
if (outerFunctor != null) {
introVars1 = true;
pattern = outerFunctor.getTwo().sub(0);
} else {
introVars1 = false;
}
pattern = index.get(pattern, true).term();
Taskify taskify = new Taskify(nar.newCause((s) -> new RuleCause(rule, s)));
PrediTerm<Derivation> conc = AndCondition.the(new Termify($.func("derive", pattern), pattern, rule), introVars1 ? AndCondition.the(introVars, taskify) : taskify);
final Term taskPattern = rule.getTask();
final Term beliefPattern = rule.getBelief();
Op to = taskPattern.op();
boolean taskIsPatVar = to == Op.VAR_PATTERN;
Op bo = beliefPattern.op();
boolean belIsPatVar = bo == Op.VAR_PATTERN;
if (!taskIsPatVar) {
pre.add(new TaskBeliefOp(to, true, false));
pre.addAll(SubTermStructure.get(0, taskPattern.structure()));
}
if (!belIsPatVar) {
if (to == bo) {
pre.add(new AbstractPatternOp.TaskBeliefOpEqual());
} else {
pre.add(new TaskBeliefOp(bo, false, true));
pre.addAll(SubTermStructure.get(1, beliefPattern.structure()));
}
}
if (taskPattern.equals(beliefPattern)) {
post.add(new UnifyTerm.UnifySubtermThenConclude(0, taskPattern, conc));
}
if (taskFirst(taskPattern, beliefPattern)) {
// task first
post.add(new UnifyTerm.UnifySubterm(0, taskPattern));
post.add(new UnifyTerm.UnifySubtermThenConclude(1, beliefPattern, conc));
} else {
// belief first
post.add(new UnifyTerm.UnifySubterm(1, beliefPattern));
post.add(new UnifyTerm.UnifySubtermThenConclude(0, taskPattern, conc));
}
// Term beliefPattern = pattern.term(1);
// if (Global.DEBUG) {
// if (beliefPattern.structure() == 0) {
// if nothing else in the rule involves this term
// which will be a singular VAR_PATTERN variable
// then allow null
// if (beliefPattern.op() != Op.VAR_PATTERN)
// throw new RuntimeException("not what was expected");
// }
// }
/*System.out.println( Long.toBinaryString(
pStructure) + " " + pattern
);*/
}
use of org.eclipse.collections.api.tuple.Pair in project eclipse-collections by eclipse.
the class ImmutableTreeMapTest method entrySet.
@Override
public void entrySet() {
super.entrySet();
Interval interval = Interval.oneTo(100);
LazyIterable<Pair<String, Integer>> pairs = interval.collect(Object::toString).zip(interval);
MutableSortedMap<String, Integer> mutableSortedMap = new TreeSortedMap<>(pairs.toArray(new Pair[] {}));
ImmutableSortedMap<String, Integer> immutableSortedMap = mutableSortedMap.toImmutable();
MutableList<Map.Entry<String, Integer>> entries = FastList.newList(immutableSortedMap.castToSortedMap().entrySet());
MutableList<Map.Entry<String, Integer>> sortedEntries = entries.toSortedListBy(Map.Entry::getKey);
Assert.assertEquals(sortedEntries, entries);
}
Aggregations