idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
29,700
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 script = new String ( Files . readAllBytes ( _template ) ) ; for ( Map . Entry < String , String > entry : _environment . entrySet ( ) ) { final String key = format ( "${%s}" , entry . getKey ( ) ) ; script = script . replace ( key , entry . getValue ( ) ) ; } final Path scriptPath = tempPath ( ) ; try { IO . write ( script , scriptPath ) ; final List < String > command = Arrays . asList ( "gnuplot" , "-e" , params , scriptPath . toString ( ) ) ; final Process process = new ProcessBuilder ( ) . command ( command ) . start ( ) ; System . out . println ( IO . toText ( process . getErrorStream ( ) ) ) ; try { process . waitFor ( ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } } finally { deleteIfExists ( scriptPath ) ; } }
Generate the Gnuplot graph .
29,701
public static Timer of ( final Clock clock ) { requireNonNull ( clock ) ; return clock instanceof NanoClock ? new Timer ( System :: nanoTime ) : new Timer ( ( ) -> nanos ( clock ) ) ; }
Return an new timer object which uses the given clock for measuring the execution time .
29,702
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 [ 1 ] = mm ; } mm = _n [ 2 ] - 1.0 ; mp = _n [ 2 ] + 1.0 ; if ( _nn [ 1 ] >= mp && _n [ 3 ] > mp ) { _q [ 2 ] = qPlus ( mp , _n [ 1 ] , _n [ 2 ] , _n [ 3 ] , _q [ 1 ] , _q [ 2 ] , _q [ 3 ] ) ; _n [ 2 ] = mp ; } else if ( _nn [ 1 ] <= mm && _n [ 1 ] < mm ) { _q [ 2 ] = qMinus ( mm , _n [ 1 ] , _n [ 2 ] , _n [ 3 ] , _q [ 1 ] , _q [ 2 ] , _q [ 3 ] ) ; _n [ 2 ] = mm ; } mm = _n [ 3 ] - 1.0 ; mp = _n [ 3 ] + 1.0 ; if ( _nn [ 2 ] >= mp && _n [ 4 ] > mp ) { _q [ 3 ] = qPlus ( mp , _n [ 2 ] , _n [ 3 ] , _n [ 4 ] , _q [ 2 ] , _q [ 3 ] , _q [ 4 ] ) ; _n [ 3 ] = mp ; } else if ( _nn [ 2 ] <= mm && _n [ 2 ] < mm ) { _q [ 3 ] = qMinus ( mm , _n [ 2 ] , _n [ 3 ] , _n [ 4 ] , _q [ 2 ] , _q [ 3 ] , _q [ 4 ] ) ; _n [ 3 ] = mm ; } }
Adjust heights of markers 0 to 2 if necessary
29,703
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 ( ) ; }
Not really batch eval . Just for testing .
29,704
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 ) ) ; }
Create a new concatenating evolution engine with the given array of engines .
29,705
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 ; points . set ( i , new double [ ] { x , y } ) ; } final Random random = RandomRegistry . getRandom ( ) ; for ( int j = points . length ( ) - 1 ; j > 0 ; -- j ) { final int i = random . nextInt ( j + 1 ) ; final double [ ] tmp = points . get ( i ) ; points . set ( i , points . get ( j ) ) ; points . set ( j , tmp ) ; } return new TravelingSalesman ( points . toISeq ( ) ) ; }
of stops . All stops lie on a circle with the given radius .
29,706
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 ( ) ; }
Return the parameter with the given name .
29,707
public Optional < Integer > intArg ( final String name ) { return arg ( name ) . flatMap ( s -> parse ( s , Integer :: valueOf ) ) ; }
Return the int - argument with the given name .
29,708
public Optional < Long > longArg ( final String name ) { return arg ( name ) . flatMap ( s -> parse ( s , Long :: valueOf ) ) ; }
Return the long - argument with the given name .
29,709
public Optional < Double > doubleArg ( final String name ) { return arg ( name ) . flatMap ( s -> parse ( s , Double :: valueOf ) ) ; }
Return the double - argument with the given name .
29,710
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 ; }
Return the minimum value of the given double array .
29,711
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 ) ; }
Reads the genotypes by using the given chromosome reader .
29,712
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 ; }
Returns an char array containing all of the elements in this chromosome in proper sequence . If the chromosome fits in the specified array it is returned therein . Otherwise a new array is allocated with the length of this chromosome .
29,713
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 ) ; }
Return a new adaptive evolution engine with the given engine generation function .
29,714
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 ) ; }
Create an integer permutation chromosome with the given range .
29,715
public static PermutationChromosome < Integer > ofInteger ( final IntRange range , final int length ) { return of ( range . stream ( ) . boxed ( ) . collect ( ISeq . toISeq ( ) ) , length ) ; }
Create an integer permutation chromosome with the given range and length
29,716
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 ( ) ) ; } }
Return the district capitals we want to visit .
29,717
public static < A > EnumGene < A > of ( final ISeq < ? extends A > validAlleles ) { return new EnumGene < > ( RandomRegistry . getRandom ( ) . nextInt ( validAlleles . length ( ) ) , validAlleles ) ; }
Return a new enum gene with an allele randomly chosen from the given valid alleles .
29,718
public static < A > EnumGene < A > of ( final int alleleIndex , final A ... validAlleles ) { return new EnumGene < > ( alleleIndex , ISeq . of ( validAlleles ) ) ; }
Create a new enum gene from the given valid genes and the chosen allele index .
29,719
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 ; }
Returns an double array containing all of the elements in this chromosome in proper sequence . If the chromosome fits in the specified array it is returned therein . Otherwise a new array is allocated with the length of this chromosome .
29,720
public static < C extends Comparable < ? super C > > Collector < C , ? , ParetoFront < C > > toParetoFront ( ) { return toParetoFront ( Comparator . naturalOrder ( ) ) ; }
Return a pareto - front collector . The natural order of the elements is used as pareto - dominance order .
29,721
public static < C extends Comparable < ? super C > > Predicate < EvolutionResult < ? , C > > byFitnessThreshold ( final C threshold ) { return new FitnessThresholdLimit < > ( threshold ) ; }
Return a predicate which will truncated the evolution stream if the best fitness of the current population becomes less than the specified threshold and the objective is set to minimize the fitness . This predicate also stops the evolution if the best fitness in the current population becomes greater than the user - specified fitness threshold when the objective is to maximize the fitness .
29,722
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 , proceed ) ; }
Return a predicate which will truncate the evolution stream if the fitness is converging . Two filters of different lengths are used to smooth the best fitness across the generations .
29,723
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 range [0, 1]: %f" , epsilon ) ) ; } return new FitnessConvergenceLimit < > ( shortFilterSize , longFilterSize , ( s , l ) -> eps ( s . getMean ( ) , l . getMean ( ) ) >= epsilon ) ; }
Return a predicate which will truncate the evolution stream if the fitness is converging . Two filters of different lengths are used to smooth the best fitness across the generations . When the smoothed best fitness from the long filter is less than a user - specified percentage away from the smoothed best fitness from the short filter the fitness is deemed as converged and the evolution terminates .
29,724
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 ) ; }
Calculate the relative mean difference between short and long filter .
29,725
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 PopulationConvergenceLimit < > ( ( best , moments ) -> eps ( best , moments . getMean ( ) ) >= epsilon ) ; }
A termination method that stops the evolution when the population is deemed as converged . The population is deemed as converged when the average fitness across the current population is less than a user - specified percentage away from the best fitness of the current population .
29,726
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 ) ) ; }
Combine the given alterers .
29,727
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 ) ; }
Joins the given alterer and returns a new CompositeAlterer object . If one of the given alterers is a CompositeAlterer the sub alterers of it are unpacked and appended to the newly created CompositeAlterer .
29,728
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 ) ; }
Return a new phenotype with the the genotype of this and with new fitness function fitness scaler and generation .
29,729
public Phenotype < G , C > newInstance ( final long generation , final Function < ? super Genotype < G > , ? extends C > function ) { return of ( _genotype , generation , function , a -> a ) ; }
Return a new phenotype with the the genotype of this and with new fitness function and generation .
29,730
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 , function , scaler , null ) ; }
Create a new phenotype from the given arguments .
29,731
public static TreePattern compile ( final String pattern ) { return new TreePattern ( TreeNode . parse ( pattern , Decl :: of ) ) ; }
Compiles the given tree pattern string .
29,732
public void sort ( final int from , final int until , final Comparator < ? super T > comparator ) { _store . sort ( from + _start , until + _start , comparator ) ; }
Sort the store .
29,733
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 ) ) ; }
Return a new trial measure environment .
29,734
private static Integer count ( final Genotype < BitGene > gt ) { return gt . getChromosome ( ) . as ( BitChromosome . class ) . bitCount ( ) ; }
This method calculates the fitness for a given genotype .
29,735
private void accept ( final EvolutionDurations durations ) { final double selection = toSeconds ( durations . getOffspringSelectionDuration ( ) ) + toSeconds ( durations . getSurvivorsSelectionDuration ( ) ) ; final double alter = toSeconds ( durations . getOffspringAlterDuration ( ) ) + toSeconds ( durations . getOffspringFilterDuration ( ) ) ; _selectionDuration . accept ( selection ) ; _alterDuration . accept ( alter ) ; _evaluationDuration . accept ( toSeconds ( durations . getEvaluationDuration ( ) ) ) ; _evolveDuration . accept ( toSeconds ( durations . getEvolveDuration ( ) ) ) ; }
Calculate duration statistics
29,736
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 . toBestEvolutionResult ( ) ) ; }
Run the evolution .
29,737
public void accept ( final double value ) { super . accept ( value ) ; _min = Math . min ( _min , value ) ; _max = Math . max ( _max , value ) ; _sum . add ( value ) ; }
Records a new value into the moments information
29,738
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 ; }
Return the corresponding BitSet of this BitChromosome .
29,739
public BitChromosome invert ( ) { final byte [ ] data = _genes . clone ( ) ; bit . invert ( data ) ; return new BitChromosome ( data , _length , 1.0 - _p ) ; }
Invert the ones and zeros of this bit chromosome .
29,740
public static BitChromosome of ( final int length , final double p ) { return new BitChromosome ( bit . newArray ( length , p ) , length , p ) ; }
Construct a new BitChromosome with the given _length .
29,741
public void forEach ( final IntConsumer action ) { requireNonNull ( action ) ; final int size = _size ; for ( int i = 0 ; i < size ; ++ i ) { action . accept ( _data [ i ] ) ; } }
Performs the given action for each element of the list .
29,742
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 ; }
Appends all of the elements in the specified array to the end of this list .
29,743
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 ) ; _size += count ; return count != 0 ; }
Inserts all of the elements in the specified array into this list starting at the specified position .
29,744
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 ) ; }
Return the child gene with the given index .
29,745
@ 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 ) ) ; }
Mutates the given phenotype .
29,746
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 ) ) ; return MutatorResult . of ( Genotype . of ( result . map ( MutatorResult :: getResult ) ) , result . stream ( ) . mapToInt ( MutatorResult :: getMutations ) . sum ( ) ) ; }
Mutates the given genotype .
29,747
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 ( ) . isInterrupted ( ) ) . peek ( best ) . forEach ( r -> { waiting ( ) ; if ( callback != null ) { callback . accept ( r , best . getMax ( ) ) ; } } ) ; } ) ; thread . start ( ) ; _thread = thread ; }
Starts the evolution worker with the given evolution result callback . The callback may be null .
29,748
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 ; } } }
Stops the current evolution if running .
29,749
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 ) ; }
Return a new alter result for the given arguments .
29,750
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 ; }
Returns an long array containing all of the elements in this chromosome in proper sequence . If the chromosome fits in the specified array it is returned therein . Otherwise a new array is allocated with the length of this chromosome .
29,751
public double eval ( final double ... args ) { final double val = apply ( DoubleStream . of ( args ) . boxed ( ) . toArray ( Double [ ] :: new ) ) ; return val == - 0.0 ? 0.0 : val ; }
Convenient method which lets you apply the program function without explicitly create a wrapper array .
29,752
public static Tree < ? extends Op < Double > , ? > simplify ( final Tree < ? extends Op < Double > , ? > tree ) { return MathExprRewriter . prune ( TreeNode . ofTree ( tree ) ) ; }
Tries to simplify the given math tree .
29,753
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 ( c2 . get ( index ) . getGene ( ) ) ; crossover ( tree1 , tree2 ) ; final FlatTreeNode < A > flat1 = FlatTreeNode . of ( tree1 ) ; final FlatTreeNode < A > flat2 = FlatTreeNode . of ( tree2 ) ; @ SuppressWarnings ( "unchecked" ) final TreeGene < A , ? > template = ( TreeGene < A , ? > ) c1 . get ( 0 ) . getGene ( ) ; final ISeq < G > genes1 = flat1 . map ( tree -> gene ( template , tree ) ) ; final ISeq < G > genes2 = flat2 . map ( tree -> gene ( template , tree ) ) ; c1 . set ( index , c1 . get ( index ) . newInstance ( genes1 ) ) ; c2 . set ( index , c2 . get ( index ) . newInstance ( genes2 ) ) ; }
the abstract crossover method usually don t have to do additional casts .
29,754
public static < T > Const < T > of ( final String name , final T value ) { return new Const < > ( requireNonNull ( name ) , value ) ; }
Return a new constant with the given name and value .
29,755
public static CharacterGene of ( final CharSeq validCharacters ) { return new CharacterGene ( validCharacters , RandomRegistry . getRandom ( ) . nextInt ( validCharacters . length ( ) ) ) ; }
Create a new CharacterGene with a randomly chosen character from the set of valid characters .
29,756
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 ) ) ; summaryStream . forEach ( s -> { if ( params . size ( ) != s . parameterCount ( ) ) { throw new IllegalArgumentException ( format ( "Parameters have different size: %d" , params . size ( ) ) ) ; } } ) ; final Path templatePath = tempPath ( ) ; try { IO . write ( template . content ( ) , templatePath ) ; final Path dataPath = tempPath ( ) ; try { final String data = IntStream . range ( 0 , params . size ( ) ) . mapToObj ( i -> toLineString ( i , params , summary , summaries ) ) . collect ( Collectors . joining ( "\n" ) ) ; IO . write ( data , dataPath ) ; final Gnuplot gnuplot = new Gnuplot ( templatePath ) ; gnuplot . setEnv ( params ( input ) ) ; gnuplot . create ( dataPath , output ) ; } finally { deleteIfExists ( dataPath ) ; } } finally { deleteIfExists ( templatePath ) ; } }
Create a performance diagram .
29,757
public SampleSummary summary ( ) { return _samples . stream ( ) . filter ( Sample :: isFull ) . collect ( toSampleSummary ( sampleSize ( ) ) ) ; }
Calculate the sample summary of this data object .
29,758
public static < T > Params < T > of ( final String name , final ISeq < T > params ) { return new Params < > ( name , params ) ; }
Return a new parameters object .
29,759
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 ( ) ; }
Create gene sequence .
29,760
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 ) ; } }
Swap a given range with a range of the same size with another array .
29,761
public static byte [ ] flip ( final byte [ ] data , final int index ) { return get ( data , index ) ? unset ( data , index ) : set ( data , index ) ; }
Flip the bit at the given index .
29,762
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 || %d > %d" , start , start , data . length * 8 ) ) ; } final int to = min ( data . length << 3 , end ) ; final int byteStart = start >>> 3 ; final int bitStart = start & 7 ; final int bitLength = to - start ; final byte [ ] copy = new byte [ toByteLength ( to - start ) ] ; if ( copy . length > 0 ) { System . arraycopy ( data , byteStart , copy , 0 , copy . length ) ; shiftRight ( copy , bitStart ) ; if ( data . length > copy . length + byteStart ) { copy [ copy . length - 1 ] |= ( byte ) ( data [ byteStart + copy . length ] << ( Byte . SIZE - bitStart ) ) ; } copy [ copy . length - 1 ] &= 0xFF >>> ( ( copy . length << 3 ) - bitLength ) ; } return copy ; }
Copies the specified range of the specified array into a new array .
29,763
public static < T > MutatorResult < T > of ( final T result , final int mutations ) { return new MutatorResult < > ( result , mutations ) ; }
Create a new mutation result with the given values .
29,764
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 . length ( ) , p ) . peek ( i -> genes . swap ( i , random . nextInt ( genes . length ( ) ) ) ) . count ( ) ; result = MutatorResult . of ( chromosome . newInstance ( genes . toISeq ( ) ) , mutations ) ; } else { result = MutatorResult . of ( chromosome ) ; } return result ; }
Swaps the genes in the given array with the mutation probability of this mutation .
29,765
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 ; }
Check if the specified value is not negative .
29,766
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 ; } ; }
Creating the fitness function .
29,767
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 ) ; }
Create an immutable object which contains statistical values .
29,768
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 -> new ProgramGene < > ( n . getValue ( ) , n . childOffset ( ) , operations , terminals ) ) . collect ( ISeq . toISeq ( ) ) ; return new ProgramChromosome < > ( genes , validator , operations , terminals ) ; }
Create the chromosomes without checks .
29,769
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 ) { tokens . add ( new Token ( unescape ( token . toString ( ) ) , pos ) ) ; tokens . add ( new Token ( Character . toString ( c ) , i ) ) ; token . setLength ( 0 ) ; pos = i ; } else { token . append ( c ) ; } pc = c ; } if ( token . length ( ) > 0 ) { tokens . add ( new Token ( unescape ( token . toString ( ) ) , pos ) ) ; } return tokens ; }
Tokenize the given parentheses string .
29,770
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 : tokenize ( value . trim ( ) ) ) { switch ( token . seq ) { case "(" : if ( current == null ) { throw new IllegalArgumentException ( format ( "Illegal parentheses tree string: '%s'." , value ) ) ; } final TreeNode < B > tn1 = TreeNode . of ( ) ; current . attach ( tn1 ) ; parents . push ( current ) ; current = tn1 ; break ; case "," : if ( parents . isEmpty ( ) ) { throw new IllegalArgumentException ( format ( "Expect '(' at position %d." , token . pos ) ) ; } final TreeNode < B > tn2 = TreeNode . of ( ) ; assert parents . peek ( ) != null ; parents . peek ( ) . attach ( tn2 ) ; current = tn2 ; break ; case ")" : if ( parents . isEmpty ( ) ) { throw new IllegalArgumentException ( format ( "Unbalanced parentheses at position %d." , token . pos ) ) ; } current = parents . pop ( ) ; if ( parents . isEmpty ( ) ) { current = null ; } break ; default : if ( current == null ) { throw new IllegalArgumentException ( format ( "More than one root element at pos %d: '%s'." , token . pos , value ) ) ; } if ( current . getValue ( ) == null ) { current . setValue ( mapper . apply ( token . seq ) ) ; } break ; } } if ( ! parents . isEmpty ( ) ) { throw new IllegalArgumentException ( "Unbalanced parentheses." ) ; } return root ; }
Parses the given parentheses tree string
29,771
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 , childOffset ( ) , _operations , _terminals ) ; }
Create a new program gene with the given operation .
29,772
private ISeq < Phenotype < G , C > > selectSurvivors ( final ISeq < Phenotype < G , C > > population ) { return _survivorsCount > 0 ? _survivorsSelector . select ( population , _survivorsCount , _optimize ) : ISeq . empty ( ) ; }
Selects the survivors population . A new population object is returned .
29,773
private ISeq < Phenotype < G , C > > selectOffspring ( final ISeq < Phenotype < G , C > > population ) { return _offspringCount > 0 ? _offspringSelector . select ( population , _offspringCount , _optimize ) : ISeq . empty ( ) ; }
Selects the offspring population . A new population object is returned .
29,774
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 ( ! _validator . test ( individual ) ) { pop . set ( i , newPhenotype ( generation ) ) ; ++ invalidCount ; } else if ( individual . getAge ( generation ) > _maximalPhenotypeAge ) { pop . set ( i , newPhenotype ( generation ) ) ; ++ killCount ; } } return new FilterResult < > ( pop . toISeq ( ) , killCount , invalidCount ) ; }
Filters out invalid and old individuals . Filtering is done in place .
29,775
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 ( phenotype ) ) ; return phenotype ; }
Create a new and valid phenotype
29,776
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 , variables ) ) . toArray ( size -> newArray ( variables . getClass ( ) , size ) ) ) ; }
Evaluates the given operation tree with the given variables .
29,777
public static void check ( final Tree < ? extends Op < ? > , ? > program ) { requireNonNull ( program ) ; program . forEach ( Program :: checkArity ) ; }
Validates the given program tree .
29,778
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 ( ) ; } return offsets ; }
Create the offset array for the given nodes . The offsets are calculated using the arity of the stored operations .
29,779
public static void divide ( final double [ ] values , final double divisor ) { for ( int i = values . length ; -- i >= 0 ; ) { values [ i ] /= divisor ; } }
Component wise division of the given double array .
29,780
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 ; }
Binary exponentiation algorithm .
29,781
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 or equal then zero, but was %s" , count ) ) ; } final MSeq < Phenotype < G , C > > selection = MSeq . ofLength ( population . isEmpty ( ) ? 0 : count ) ; if ( count > 0 && ! population . isEmpty ( ) ) { final MSeq < Phenotype < G , C > > copy = population . asISeq ( ) . copy ( ) ; copy . sort ( ( a , b ) -> opt . < C > descending ( ) . compare ( a . getFitness ( ) , b . getFitness ( ) ) ) ; int size = count ; do { final int length = min ( min ( copy . size ( ) , size ) , _n ) ; for ( int i = 0 ; i < length ; ++ i ) { selection . set ( ( count - size ) + i , copy . get ( i ) ) ; } size -= length ; } while ( size > 0 ) ; } return selection . toISeq ( ) ; }
This method sorts the population in descending order while calculating the selection probabilities . If the selection size is greater the the population size the whole population is duplicated until the desired sample size is reached .
29,782
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_EXECUTOR ) { return SERIAL_EXECUTOR ; } else { return new ExecutorConcurrency ( executor ) ; } }
Return an new Concurrency object from the given executor .
29,783
public ISeq < Genotype < G > > getGenotypes ( ) { return _population . stream ( ) . map ( Phenotype :: getGenotype ) . collect ( ISeq . toISeq ( ) ) ; }
Return the current list of genotypes of this evolution result .
29,784
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 ( ) . withTotalGenerations ( mm . getCount ( ) ) : null ) ; }
Return a collector which collects the best result of an evolution stream .
29,785
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 ( ) : null ) ; }
Return a collector which collects the best phenotype of an evolution stream .
29,786
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 ? mm . getMax ( ) . getBestPhenotype ( ) . getGenotype ( ) : null : null ) ; }
Return a collector which collects the best genotype of an evolution stream .
29,787
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 > > unifier = toUniquePopulation ( factory , maxRetries ) ; return unifier . apply ( result ) ; } ; }
Return a mapping function which removes duplicate individuals from the population and replaces it with newly created one by the existing genotype factory .
29,788
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 ( ) . collect ( ISeq . toISeq ( ) ) ; final int changed ; if ( seq1 . length ( ) > 1 && seq2 . length ( ) > 1 ) { final TreeNode < A > n1 = seq1 . get ( random . nextInt ( seq1 . length ( ) - 1 ) + 1 ) ; final TreeNode < A > p1 = n1 . getParent ( ) . orElseThrow ( AssertionError :: new ) ; final TreeNode < A > n2 = seq2 . get ( random . nextInt ( seq2 . length ( ) - 1 ) + 1 ) ; final TreeNode < A > p2 = n2 . getParent ( ) . orElseThrow ( AssertionError :: new ) ; final int i1 = p1 . getIndex ( n1 ) ; final int i2 = p2 . getIndex ( n2 ) ; p1 . insert ( i1 , n2 . detach ( ) ) ; p2 . insert ( i2 , n1 . detach ( ) ) ; changed = 2 ; } else { changed = 0 ; } return changed ; }
The static method makes it easier to test .
29,789
static double [ ] sortAndRevert ( final double [ ] array ) { final int [ ] indexes = sort ( array ) ; 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 ; }
Package private for testing .
29,790
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 ; ) { probabilities [ i ] = value ; } } }
Checks if the given probability values are finite . If not all values are set to the same probability .
29,791
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 ; }
Check if the given probabilities sum to one .
29,792
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 ) { imin = imid + 1 ; } else if ( incr [ imid ] > v ) { imax = imid ; } } return index ; }
Perform a binary - search on the summed probability array .
29,793
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 ; }
Perform a serial - search on the summed probability array .
29,794
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 ; }
In - place summation of the probability array .
29,795
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 ) ; }
Returns the child at the specified index in this node s child array .
29,796
public static void ensureValidResource ( JsonNode resource ) { if ( ! resource . has ( JSONAPISpecConstants . DATA ) && ! resource . has ( JSONAPISpecConstants . META ) ) { throw new InvalidJsonApiResourceException ( ) ; } }
Asserts that provided resource has required data or meta node .
29,797
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 ) { throw new RuntimeException ( e ) ; } } }
Ensures that provided node does not hold errors attribute .
29,798
public static JSONAPIDocument < ? > createErrorDocument ( Iterable < ? extends Error > errors ) { JSONAPIDocument < ? > result = new JSONAPIDocument ( ) ; result . errors = errors ; return result ; }
Factory method for creating JSONAPIDocument that holds the Error object .
29,799
public void addLink ( String linkName , Link link ) { if ( links == null ) { links = new Links ( new HashMap < String , Link > ( ) ) ; } links . addLink ( linkName , link ) ; }
Adds a named link .