code
stringlengths
73
34.1k
label
stringclasses
1 value
public void create(final Path data, final Path output) throws IOException { _parameters.put(DATA_NAME, data.toString()); _parameters.put(OUTPUT_NAME, output.toString()); final String params = _parameters.entrySet().stream() .map(Gnuplot::toParamString) .collect(Collectors.joining("; ")); String scrip...
java
public static Timer of(final Clock clock) { requireNonNull(clock); return clock instanceof NanoClock ? new Timer(System::nanoTime) : new Timer(() -> nanos(clock)); }
java
private void adjustMarkerHeights() { double mm = _n[1] - 1.0; double mp = _n[1] + 1.0; if (_nn[0] >= mp && _n[2] > mp) { _q[1] = qPlus(mp, _n[0], _n[1], _n[2], _q[0], _q[1], _q[2]); _n[1] = mp; } else if (_nn[0] <= mm && _n[0] < mm) { _q[1] = qMinus(mm, _n[0], _n[1], _n[2], _q[0], _q[1], _q[2]); _n[...
java
private static <G extends Gene<?, G>, C extends Comparable<? super C>> ISeq<C> batchEval( final Seq<Genotype<G>> genotypes, final Function<? super Genotype<G>, ? extends C> function ) { return genotypes.<C>map(function).asISeq(); }
java
@SafeVarargs public static <G extends Gene<?, G>, C extends Comparable<? super C>> ConcatEngine<G, C> of(final EvolutionStreamable<G, C>... engines) { return new ConcatEngine<>(Arrays.asList(engines)); }
java
public static TravelingSalesman of(int stops, double radius) { final MSeq<double[]> points = MSeq.ofLength(stops); final double delta = 2.0*PI/stops; for (int i = 0; i < stops; ++i) { final double alpha = delta*i; final double x = cos(alpha)*radius + radius; final double y = sin(alpha)*radius + radius; ...
java
public Optional<String> arg(final String name) { int index = _args.indexOf("--" + name); if (index == -1) index = _args.indexOf("-" + name); return index >= 0 && index < _args.length() - 1 ? Optional.of(_args.get(index + 1)) : Optional.empty(); }
java
public Optional<Integer> intArg(final String name) { return arg(name) .flatMap(s -> parse(s, Integer::valueOf)); }
java
public Optional<Long> longArg(final String name) { return arg(name) .flatMap(s -> parse(s, Long::valueOf)); }
java
public Optional<Double> doubleArg(final String name) { return arg(name) .flatMap(s -> parse(s, Double::valueOf)); }
java
public static double min(final double[] values) { double min = NaN; if (values.length > 0) { min = values[0]; for (int i = 0; i < values.length; ++i) { if (values[i] < min) { min = values[i]; } } } return min; }
java
public static < A, G extends Gene<A, G>, C extends Chromosome<G> > List<io.jenetics.Genotype<G>> read(final InputStream in, final Reader<? extends C> chromosomeReader) throws XMLStreamException { return Genotypes.read(in, chromosomeReader); }
java
public char[] toArray(final char[] array) { final char[] a = array.length >= length() ? array : new char[length()]; for (int i = length(); --i >= 0;) { a[i] = charAt(i); } return a; }
java
public static <G extends Gene<?, G>, C extends Comparable<? super C>> AdaptiveEngine<G, C> of( final Function< ? super EvolutionResult<G, C>, ? extends EvolutionStreamable<G, C>> engine ) { return new AdaptiveEngine<>(engine); }
java
public static PermutationChromosome<Integer> ofInteger(final int start, final int end) { if (end <= start) { throw new IllegalArgumentException(format( "end <= start: %d <= %d", end, start )); } return ofInteger(IntRange.of(start, end), end - start); }
java
public static PermutationChromosome<Integer> ofInteger(final IntRange range, final int length) { return of( range.stream() .boxed() .collect(ISeq.toISeq()), length ); }
java
private static ISeq<WayPoint> districtCapitals() throws IOException { final String capitals = "/io/jenetics/example/DistrictCapitals.gpx"; try (InputStream in = TravelingSalesman .class.getResourceAsStream(capitals)) { return ISeq.of(GPX.read(in).getWayPoints()); } }
java
public static <A> EnumGene<A> of(final ISeq<? extends A> validAlleles) { return new EnumGene<>( RandomRegistry.getRandom().nextInt(validAlleles.length()), validAlleles ); }
java
@SafeVarargs public static <A> EnumGene<A> of( final int alleleIndex, final A... validAlleles ) { return new EnumGene<>(alleleIndex, ISeq.of(validAlleles)); }
java
public double[] toArray(final double[] array) { final double[] a = array.length >= length() ? array : new double[length()]; for (int i = length(); --i >= 0;) { a[i] = doubleValue(i); } return a; }
java
public static <C extends Comparable<? super C>> Collector<C, ?, ParetoFront<C>> toParetoFront() { return toParetoFront(Comparator.naturalOrder()); }
java
public static <C extends Comparable<? super C>> Predicate<EvolutionResult<?, C>> byFitnessThreshold(final C threshold) { return new FitnessThresholdLimit<>(threshold); }
java
public static <N extends Number & Comparable<? super N>> Predicate<EvolutionResult<?, N>> byFitnessConvergence( final int shortFilterSize, final int longFilterSize, final BiPredicate<DoubleMoments, DoubleMoments> proceed ) { return new FitnessConvergenceLimit<>( shortFilterSize, longFilterSize, proce...
java
public static <N extends Number & Comparable<? super N>> Predicate<EvolutionResult<?, N>> byFitnessConvergence( final int shortFilterSize, final int longFilterSize, final double epsilon ) { if (epsilon < 0.0 || epsilon > 1.0) { throw new IllegalArgumentException(format( "The given epsilon is not in the...
java
private static double eps(final double s, final double l) { final double div = max(abs(s), abs(l)); return abs(s - l)/(div <= 10E-20 ? 1.0 : div); }
java
public static <N extends Number & Comparable<? super N>> Predicate<EvolutionResult<?, N>> byPopulationConvergence(final double epsilon) { if (epsilon < 0.0 || epsilon > 1.0) { throw new IllegalArgumentException(format( "The given epsilon is not in the range [0, 1]: %f", epsilon )); } return new Popul...
java
@SafeVarargs static <G extends Gene<?, G>, C extends Comparable<? super C>> CompositeAlterer<G, C> of(final Alterer<G, C>... alterers) { return new CompositeAlterer<>(ISeq.of(alterers)); }
java
static <T extends Gene<?, T>, C extends Comparable<? super C>> CompositeAlterer<T, C> join( final Alterer<T, C> a1, final Alterer<T, C> a2 ) { return CompositeAlterer.of(a1, a2); }
java
@Deprecated public Phenotype<G, C> newInstance( final long generation, final Function<? super Genotype<G>, ? extends C> function, final Function<? super C, ? extends C> scaler ) { return of(_genotype, generation, function, scaler); }
java
@Deprecated public Phenotype<G, C> newInstance( final long generation, final Function<? super Genotype<G>, ? extends C> function ) { return of(_genotype, generation, function, a -> a); }
java
public static <G extends Gene<?, G>, C extends Comparable<? super C>> Phenotype<G, C> of( final Genotype<G> genotype, final long generation, final Function<? super Genotype<G>, ? extends C> function, final Function<? super C, ? extends C> scaler ) { return new Phenotype<>( genotype, generation, fun...
java
public static TreePattern compile(final String pattern) { return new TreePattern(TreeNode.parse(pattern, Decl::of)); }
java
public void sort( final int from, final int until, final Comparator<? super T> comparator ) { _store.sort(from + _start, until + _start, comparator); }
java
public static <T> TrialMeter<T> of( final String name, final String description, final Params<T> params, final String... dataSetNames ) { return new TrialMeter<T>( name, description, Env.of(), params, DataSet.of(params.size(), dataSetNames) ); }
java
private static Integer count(final Genotype<BitGene> gt) { return gt.getChromosome() .as(BitChromosome.class) .bitCount(); }
java
private void accept(final EvolutionDurations durations) { final double selection = toSeconds(durations.getOffspringSelectionDuration()) + toSeconds(durations.getSurvivorsSelectionDuration()); final double alter = toSeconds(durations.getOffspringAlterDuration()) + toSeconds(durations.getOffspringFilter...
java
private EvolutionResult<BitGene, Double> run( final EvolutionResult<BitGene, Double> last, final AtomicBoolean proceed ) { System.out.println("Starting evolution with existing result."); return (last != null ? ENGINE.stream(last) : ENGINE.stream()) .limit(r -> proceed.get()) .collect(EvolutionResult.toB...
java
@Override public void accept(final double value) { super.accept(value); _min = Math.min(_min, value); _max = Math.max(_max, value); _sum.add(value); }
java
public BitSet toBitSet() { final BitSet set = new BitSet(length()); for (int i = 0, n = length(); i < n; ++i) { set.set(i, getGene(i).getBit()); } return set; }
java
public BitChromosome invert() { final byte[] data = _genes.clone(); bit.invert(data); return new BitChromosome(data, _length, 1.0 - _p); }
java
public static BitChromosome of(final int length, final double p) { return new BitChromosome(bit.newArray(length, p), length, p); }
java
public void forEach(final IntConsumer action) { requireNonNull(action); final int size = _size; for (int i = 0; i < size; ++i) { action.accept(_data[i]); } }
java
public boolean addAll(final int[] elements) { final int count = elements.length; ensureSize(_size + count); arraycopy(elements, 0, _data, _size, count); _size += count; return count != 0; }
java
public boolean addAll(final int index, final int[] elements) { addRangeCheck(index); final int count = elements.length; ensureSize(_size + count); final int moved = _size - index; if (moved > 0) { arraycopy(_data, index, _data, index + count, moved); } arraycopy(elements, 0, _data, index, count); ...
java
@Override public G getChild(final int index) { checkTreeState(); if (index < 0 || index >= childCount()) { throw new IndexOutOfBoundsException(format( "Child index out of bounds: %s", index )); } assert _genes != null; return _genes.get(_childOffset + index); }
java
@SuppressWarnings("deprecation") protected MutatorResult<Phenotype<G, C>> mutate( final Phenotype<G, C> phenotype, final long generation, final double p, final Random random ) { return mutate(phenotype.getGenotype(), p, random) .map(gt -> phenotype.newInstance(gt, generation)); }
java
protected MutatorResult<Genotype<G>> mutate( final Genotype<G> genotype, final double p, final Random random ) { final int P = probability.toInt(p); final ISeq<MutatorResult<Chromosome<G>>> result = genotype.toSeq() .map(gt -> random.nextInt() < P ? mutate(gt, p, random) : MutatorResult.of(gt)); ...
java
public void start( final BiConsumer< EvolutionResult<PolygonGene, Double>, EvolutionResult<PolygonGene, Double>> callback ) { final Thread thread = new Thread(() -> { final MinMax<EvolutionResult<PolygonGene, Double>> best = MinMax.of(); _engine.stream() .limit(result -> !Thread.currentThread().is...
java
public void stop() { resume(); final Thread thread = _thread; if (thread != null) { thread.interrupt(); try { thread.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { _thread = null; } } }
java
public static <G extends Gene<?, G>, C extends Comparable<? super C>> AltererResult<G, C> of( final ISeq<Phenotype<G, C>> population, final int alterations ) { return new AltererResult<>(population, alterations); }
java
public long[] toArray(final long[] array) { final long[] a = array.length >= length() ? array : new long[length()]; for (int i = length(); --i >= 0;) { a[i] = longValue(i); } return a; }
java
public double eval(final double... args) { final double val = apply( DoubleStream.of(args) .boxed() .toArray(Double[]::new) ); return val == -0.0 ? 0.0 : val; }
java
public static Tree<? extends Op<Double>, ?> simplify(final Tree<? extends Op<Double>, ?> tree) { return MathExprRewriter.prune(TreeNode.ofTree(tree)); }
java
private <A> void crossover( final MSeq<Chromosome<G>> c1, final MSeq<Chromosome<G>> c2, final int index ) { @SuppressWarnings("unchecked") final TreeNode<A> tree1 = (TreeNode<A>)TreeNode.ofTree(c1.get(index).getGene()); @SuppressWarnings("unchecked") final TreeNode<A> tree2 = (TreeNode<A>)TreeNode.ofTree...
java
public static <T> Const<T> of(final String name, final T value) { return new Const<>(requireNonNull(name), value); }
java
public static CharacterGene of(final CharSeq validCharacters) { return new CharacterGene( validCharacters, RandomRegistry.getRandom().nextInt(validCharacters.length()) ); }
java
public static void create( final Path input, final Template template, final Params<?> params, final Path output, final SampleSummary summary, final SampleSummary... summaries ) throws IOException { final Stream<SampleSummary> summaryStream = Stream.concat( Stream.of(summary), Stream.of(summaries) ...
java
public SampleSummary summary() { return _samples.stream() .filter(Sample::isFull) .collect(toSampleSummary(sampleSize())); }
java
public static <T> Params<T> of( final String name, final ISeq<T> params ) { return new Params<>(name, params); }
java
static <A> ISeq<AnyGene<A>> seq( final IntRange lengthRange, final Supplier<? extends A> supplier, final Predicate<? super A> validator ) { return MSeq.<AnyGene<A>>ofLength(random.nextInt(lengthRange, getRandom())) .fill(() -> of(supplier.get(), supplier, validator)) .toISeq(); }
java
public static void swap( final byte[] data, final int start, final int end, final byte[] otherData, final int otherStart ) { for (int i = end - start; --i >= 0;) { final boolean temp = get(data, i + start); set(data, i + start, get(otherData, otherStart + i)); set(otherData, otherStart + i, temp); } ...
java
public static byte[] flip(final byte[] data, final int index) { return get(data, index) ? unset(data, index) : set(data, index); }
java
public static byte[] copy(final byte[] data, final int start, final int end) { if (start > end) { throw new IllegalArgumentException(String.format( "start > end: %d > %d", start, end )); } if (start < 0 || start > data.length << 3) { throw new ArrayIndexOutOfBoundsException(String.format( "%d < 0...
java
public static <T> MutatorResult<T> of(final T result, final int mutations) { return new MutatorResult<>(result, mutations); }
java
@Override protected MutatorResult<Chromosome<G>> mutate( final Chromosome<G> chromosome, final double p, final Random random ) { final MutatorResult<Chromosome<G>> result; if (chromosome.length() > 1) { final MSeq<G> genes = chromosome.toSeq().copy(); final int mutations = (int)indexes(random, genes.l...
java
public static double nonNegative(final double value, final String message) { if (value < 0) { throw new IllegalArgumentException(format( "%s must not be negative: %f.", message, value )); } return value; }
java
static Function<ISeq<Item>, Double> fitness(final double size) { return items -> { final Item sum = items.stream().collect(Item.toSum()); return sum.size <= size ? sum.value : 0; }; }
java
public static DoubleMoments of( final long count, final double min, final double max, final double sum, final double mean, final double variance, final double skewness, final double kurtosis ) { return new DoubleMoments( count, min, max, sum, mean, variance, skewness, kurtosis...
java
private static <A> ProgramChromosome<A> create( final Tree<? extends Op<A>, ?> program, final Predicate<? super ProgramChromosome<A>> validator, final ISeq<? extends Op<A>> operations, final ISeq<? extends Op<A>> terminals ) { final ISeq<ProgramGene<A>> genes = FlatTreeNode.of(program).stream() .map(n -> ...
java
static List<Token> tokenize(final String value) { final List<Token> tokens = new ArrayList<>(); char pc = '\0'; int pos = 0; final StringBuilder token = new StringBuilder(); for (int i = 0; i < value.length(); ++i) { final char c = value.charAt(i); if (isTokenSeparator(c) && pc != ESCAPE_CHAR) { t...
java
static <B> TreeNode<B> parse( final String value, final Function<? super String, ? extends B> mapper ) { requireNonNull(value); requireNonNull(mapper); final TreeNode<B> root = TreeNode.of(); final Deque<TreeNode<B>> parents = new ArrayDeque<>(); TreeNode<B> current = root; for (Token token : tokeniz...
java
@Override public ProgramGene<A> newInstance(final Op<A> op) { if (getValue().arity() != op.arity()) { throw new IllegalArgumentException(format( "New operation must have same arity: %s[%d] != %s[%d]", getValue().name(), getValue().arity(), op.name(), op.arity() )); } return new ProgramGene<>(op, ch...
java
private ISeq<Phenotype<G, C>> selectSurvivors(final ISeq<Phenotype<G, C>> population) { return _survivorsCount > 0 ?_survivorsSelector.select(population, _survivorsCount, _optimize) : ISeq.empty(); }
java
private ISeq<Phenotype<G, C>> selectOffspring(final ISeq<Phenotype<G, C>> population) { return _offspringCount > 0 ? _offspringSelector.select(population, _offspringCount, _optimize) : ISeq.empty(); }
java
private FilterResult<G, C> filter( final Seq<Phenotype<G, C>> population, final long generation ) { int killCount = 0; int invalidCount = 0; final MSeq<Phenotype<G, C>> pop = MSeq.of(population); for (int i = 0, n = pop.size(); i < n; ++i) { final Phenotype<G, C> individual = pop.get(i); if (!_vali...
java
private Phenotype<G, C> newPhenotype(final long generation) { int count = 0; Phenotype<G, C> phenotype; do { phenotype = Phenotype.of( _genotypeFactory.newInstance(), generation, _fitnessFunction, _fitnessScaler ); } while (++count < _individualCreationRetries && !_validator.test(pheno...
java
@SafeVarargs public static <T> T eval( final Tree<? extends Op<T>, ?> tree, final T... variables ) { requireNonNull(tree); requireNonNull(variables); final Op<T> op = tree.getValue(); return op.isTerminal() ? eval(op, variables) : eval(op, tree.childStream() .map(child -> eval(child, var...
java
public static void check(final Tree<? extends Op<?>, ?> program) { requireNonNull(program); program.forEach(Program::checkArity); }
java
static int[] offsets(final ISeq<? extends FlatTree<? extends Op<?>, ?>> nodes) { final int[] offsets = new int[nodes.size()]; int offset = 1; for (int i = 0; i < offsets.length; ++i) { final Op<?> op = nodes.get(i).getValue(); offsets[i] = op.isTerminal() ? -1 : offset; offset += op.arity(); } re...
java
public static void divide(final double[] values, final double divisor) { for (int i = values.length; --i >= 0;) { values[i] /= divisor; } }
java
public static long pow(final long b, final long e) { long base = b; long exp = e; long result = 1; while (exp != 0) { if ((exp & 1) != 0) { result *= base; } exp >>>= 1; base *= base; } return result; }
java
@Override public ISeq<Phenotype<G, C>> select( final Seq<Phenotype<G, C>> population, final int count, final Optimize opt ) { requireNonNull(population, "Population"); requireNonNull(opt, "Optimization"); if (count < 0) { throw new IllegalArgumentException(format( "Selection count must be greater o...
java
public static Concurrency with(final Executor executor) { if (executor instanceof ForkJoinPool) { return new ForkJoinPoolConcurrency((ForkJoinPool)executor); } else if (executor instanceof ExecutorService) { return new ExecutorServiceConcurrency((ExecutorService)executor); } else if (executor == SERIAL_EXEC...
java
public ISeq<Genotype<G>> getGenotypes() { return _population.stream() .map(Phenotype::getGenotype) .collect(ISeq.toISeq()); }
java
public static <G extends Gene<?, G>, C extends Comparable<? super C>> Collector<EvolutionResult<G, C>, ?, EvolutionResult<G, C>> toBestEvolutionResult() { return Collector.of( MinMax::<EvolutionResult<G, C>>of, MinMax::accept, MinMax::combine, mm -> mm.getMax() != null ? mm.getMax().withTotalGenerat...
java
public static <G extends Gene<?, G>, C extends Comparable<? super C>> Collector<EvolutionResult<G, C>, ?, Phenotype<G, C>> toBestPhenotype() { return Collector.of( MinMax::<EvolutionResult<G, C>>of, MinMax::accept, MinMax::combine, mm -> mm.getMax() != null ? mm.getMax().getBestPhenotype() : nul...
java
public static <G extends Gene<?, G>, C extends Comparable<? super C>> Collector<EvolutionResult<G, C>, ?, Genotype<G>> toBestGenotype() { return Collector.of( MinMax::<EvolutionResult<G, C>>of, MinMax::accept, MinMax::combine, mm -> mm.getMax() != null ? mm.getMax().getBestPhenotype() != null ?...
java
public static <G extends Gene<?, G>, C extends Comparable<? super C>> UnaryOperator<EvolutionResult<G, C>> toUniquePopulation(final int maxRetries) { return result -> { final Factory<Genotype<G>> factory = result .getPopulation().get(0) .getGenotype(); final UnaryOperator<EvolutionResult<G, C>> unifie...
java
static <A> int swap(final TreeNode<A> that, final TreeNode<A> other) { assert that != null; assert other != null; final Random random = RandomRegistry.getRandom(); final ISeq<TreeNode<A>> seq1 = that.breadthFirstStream() .collect(ISeq.toISeq()); final ISeq<TreeNode<A>> seq2 = other.breadthFirstStream() ...
java
static double[] sortAndRevert(final double[] array) { final int[] indexes = sort(array); // Copy the elements in reversed order. final double[] result = new double[array.length]; for (int i = 0; i < result.length; ++i) { result[indexes[result.length - 1 - i]] = array[indexes[i]]; } return result; }
java
private static void checkAndCorrect(final double[] probabilities) { boolean ok = true; for (int i = probabilities.length; --i >= 0 && ok;) { ok = Double.isFinite(probabilities[i]); } if (!ok) { final double value = 1.0/probabilities.length; for (int i = probabilities.length; --i >= 0;) { probabili...
java
static boolean sum2one(final double[] probabilities) { final double sum = probabilities.length > 0 ? DoubleAdder.sum(probabilities) : 1.0; return abs(ulpDistance(sum, 1.0)) < MAX_ULP_DISTANCE; }
java
static int indexOfBinary(final double[] incr, final double v) { int imin = 0; int imax = incr.length; int index = -1; while (imax > imin && index == -1) { final int imid = (imin + imax) >>> 1; if (imid == 0 || (incr[imid] >= v && incr[imid - 1] < v)) { index = imid; } else if (incr[imid] <= v) { ...
java
static int indexOfSerial(final double[] incr, final double v) { int index = -1; for (int i = 0; i < incr.length && index == -1; ++i) { if (incr[i] >= v) { index = i; } } return index; }
java
static double[] incremental(final double[] values) { final DoubleAdder adder = new DoubleAdder(values[0]); for (int i = 1; i < values.length; ++i) { values[i] = adder.add(values[i]).doubleValue(); } return values; }
java
@Override public TreeNode<T> getChild(final int index) { if (_children == null) { throw new ArrayIndexOutOfBoundsException(format( "Child index is out of bounds: %s", index )); } return _children.get(index); }
java
public static void ensureValidResource(JsonNode resource) { if (!resource.has(JSONAPISpecConstants.DATA) && !resource.has(JSONAPISpecConstants.META)) { throw new InvalidJsonApiResourceException(); } }
java
public static void ensureNotError(ObjectMapper mapper, JsonNode resourceNode) { if (resourceNode != null && resourceNode.hasNonNull(JSONAPISpecConstants.ERRORS)) { try { throw new ResourceParseException(ErrorUtils.parseError(mapper, resourceNode, Errors.class)); } catch (JsonProcessingException e) { thr...
java
@NotNull public static JSONAPIDocument<?> createErrorDocument(Iterable<? extends Error> errors) { JSONAPIDocument<?> result = new JSONAPIDocument(); result.errors = errors; return result; }
java
public void addLink(String linkName, Link link) { if (links == null) { links = new Links(new HashMap<String, Link>()); } links.addLink(linkName, link); }
java