Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @Main.java
- import org.knowm.xchart.*;
- import org.knowm.xchart.style.Styler;
- import org.knowm.xchart.style.markers.SeriesMarkers;
- import javax.media.MediaLocator;
- import java.awt.*;
- import java.io.*;
- import java.net.MalformedURLException;
- import java.util.ArrayList;
- import java.util.Scanner;
- import java.util.StringTokenizer;
- import java.util.Vector;
- public class Main {
- FastScanner in;
- PrintWriter out;
- public void solve() throws IOException {
- short[][] b = new short[16][4];
- double left = -10, right = 10;
- double leftx = -1, rightx = 1, lefty = -1, righty = 1;
- Scanner scanner = new Scanner(System.in);
- System.out.println("Введите номер задачи: ");
- int choice = scanner.nextInt();
- if (choice == 1) {
- Genetic genetic = new Genetic(16, 14, 1357, left, right, -100.223161d); // интервал вкупе с количеством генов задают точность.
- int steps = genetic.solve(1000);
- double[] solutionx = new double[1];
- double[] solutiony = new double[1];
- solutionx[0] = genetic.getSolutionx();
- solutiony[0] = genetic.getSolutiony();
- System.out.println("X = " + solutionx[0]);
- System.out.println("Y = " + solutiony[0]);
- System.out.println("Steps to get solution: " + steps);
- int n = 100;
- double[] x = new double[n];
- double[] y = new double[n];
- for (int i = 0; i < n; i++) {
- x[i] = left + i * (right - left) / (double) n;
- y[i] = Function.get(x[i]);
- }
- XYChart chart = QuickChart.getChart("Sample", "X", "Y", "y(x)", x, y);
- new SwingWrapper(chart).displayChart();
- XYSeries solution = chart.addSeries("Solution", solutionx, solutiony);
- solution.setMarker(SeriesMarkers.CIRCLE);
- solution.setMarkerColor(Color.RED);
- ArrayList listY = genetic.getListY();
- ArrayList<Double> m = new ArrayList();
- for (int i = 0; i < genetic.counter; i++) {
- m.add((double)i + 1);
- }
- XYChart chart2 = new XYChartBuilder().width(800).height(600).title("Best chromosomes of each iteration").xAxisTitle("Iteration").yAxisTitle("f(x)").build();
- chart2.getStyler().setChartTitleVisible(true);
- chart2.getStyler().setLegendPosition(Styler.LegendPosition.InsideNW);
- XYSeries best = chart2.addSeries("Best", m, listY);
- new SwingWrapper(chart2).displayChart();
- } else {
- GeneticXY genetic = new GeneticXY(20, 14, 13337L, leftx, rightx, lefty, righty, -2.598202d);
- // for (int i = 0; i < 1000; i++) {
- // System.out.println(genetic);
- // genetic.iterate();
- // }
- int steps = genetic.solve(10000);
- double solutionx, solutiony, solutionz;
- solutionx = genetic.getSolutionx();
- solutiony = genetic.getSolutiony();
- solutionz = genetic.getSolutionz();
- System.out.println("X = " + solutionx);
- System.out.println("Y = " + solutiony);
- System.out.println("Z = " + solutionz);
- System.out.println("Steps to get solution: " + steps);
- ArrayList listY = genetic.getListY();
- ArrayList<Double> m = new ArrayList();
- for (int i = 0; i < genetic.counter; i++) {
- m.add((double)i + 1);
- }
- XYChart chart2 = new XYChartBuilder().width(800).height(600).title("Best chromosomes of each iteration").xAxisTitle("Iteration").yAxisTitle("f(x)").build();
- chart2.getStyler().setChartTitleVisible(true);
- chart2.getStyler().setLegendPosition(Styler.LegendPosition.InsideNW);
- XYSeries best = chart2.addSeries("Best", m, listY);
- new SwingWrapper(chart2).displayChart();
- }
- }
- public void run() {
- try {
- in = new FastScanner(new File("Main.in"));
- out = new PrintWriter(new File("Main.out"));
- solve();
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- class FastScanner {
- BufferedReader br;
- StringTokenizer st;
- FastScanner(File f) {
- try {
- br = new BufferedReader(new FileReader(f));
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- }
- String next() {
- while (st == null || !st.hasMoreTokens()) {
- try {
- st = new StringTokenizer(br.readLine());
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return st.nextToken();
- }
- int nextInt() {
- return Integer.parseInt(next());
- }
- }
- public static void main(String[] arg) {
- new Main().run();
- }
- }
- @Analyze.java
- import org.knowm.xchart.SwingWrapper;
- import org.knowm.xchart.XYChart;
- import org.knowm.xchart.XYChartBuilder;
- import org.knowm.xchart.XYSeries;
- import org.knowm.xchart.style.Styler;
- import java.io.File;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.ArrayList;
- import java.util.Random;
- import java.util.Scanner;
- /**
- * Proger: Dmitry Savelin, kr4m, vk.com/savelin
- * Date: 25.09.2017
- * Time: 13:56
- */
- public class Analyze {
- public static void main(String[] args) throws IOException {
- double left = -10, right = 10;
- double leftx = -1, rightx = 1, lefty = -1, righty = 1;
- Scanner scanner = new Scanner(System.in);
- PrintWriter out;
- out = new PrintWriter(new File("Main.out"));
- System.out.println("Введите номер задачи: ");
- int choice = scanner.nextInt();
- if (choice == 1) {
- ArrayList<Integer> iterations = new ArrayList<Integer>();
- Random rnd = new Random(1337);
- for (int i = 0; i < 1000; i++) {
- Genetic genetic = new Genetic(16, 14, rnd.nextInt(), left, right, -100.223161d); // интервал вкупе с количеством генов задают точность.
- int steps = genetic.solve(100000);
- iterations.add(genetic.counter);
- }
- int n = 100;
- double[] x = new double[n];
- double[] y = new double[n];
- for (int i = 0; i < n; i++) {
- x[i] = left + i * (right - left) / (double) n;
- y[i] = Function.get(x[i]);
- }
- ArrayList<Integer> m = new ArrayList();
- long sum = 0;
- for (int i = 0; i < iterations.size(); i++) {
- m.add(i + 1);
- sum += iterations.get(i);
- }
- double average = sum / 1000.0d;
- for (int i = 0; i < 1000; i++) {
- out.write(iterations.get(i) + "\n");
- }
- System.out.println("Average: " + average);
- XYChart chart2 = new XYChartBuilder().width(800).height(600).title("Quantity of iterations on each experiment").xAxisTitle("# experiment").yAxisTitle("Iterations").build();
- chart2.getStyler().setChartTitleVisible(true);
- chart2.getStyler().setLegendPosition(Styler.LegendPosition.InsideNW);
- XYSeries best = chart2.addSeries("Best", m, iterations);
- chart2.getStyler().setDefaultSeriesRenderStyle(XYSeries.XYSeriesRenderStyle.Scatter);
- new SwingWrapper(chart2).displayChart();
- } else {
- Random rnd = new Random(1337);
- for (int i = 0; i < 1000; i++) {
- Genetic genetic = new GeneticXY(20, 14, rnd.nextInt(), leftx, rightx, lefty, righty, -2.598202d); // интервал вкупе с количеством генов задают точность.
- int steps = genetic.solve(100000);
- out.write(genetic.counter + "\n");
- }
- }
- out.close();
- }
- }
- @Genetic.java
- import java.util.*;
- /**
- * Класс, реализующий генетический алгоритм для нахождения инфимума.
- *
- * @author Dmitri Savelin
- * @version 1.0
- */
- public class Genetic {
- int genes, population;
- long seed;
- double leftx, rightx, righty, lefty, offset;
- double v[];
- Random rnd;
- Phenotype[] m;
- int counter = 0;
- double solutionx, solutiony, solutionz;
- double trueSolution, epsilon = 3d;
- ArrayList<Double> listx, listy;
- Genetic() {
- }
- /**
- * Конструктор
- *
- * @param genes - количество генов в хромосоме
- * @param population - количество популяции (хромосом)
- * @param seed - сид для создания псевдослучайных наборов генов в хромосомах
- * @param leftx - левая граница интервала
- * @param rightx - правая граница интервала
- */
- Genetic(int genes, int population, long seed, double leftx, double rightx) {
- listx = new ArrayList<Double>();
- listy = new ArrayList<Double>();
- this.genes = genes;
- this.population = population;
- this.seed = seed;
- this.leftx = leftx;
- this.rightx = rightx;
- m = new Phenotype[population];
- rnd = new Random(seed);
- for (int i = 0; i < population; i++) {
- short[] ch = new short[genes];
- for (int j = 0; j < genes; j++) {
- ch[j] = (short) rnd.nextInt(2);
- }
- m[i] = new Phenotype(genes, ch, leftx, rightx);
- }
- trueSolution = Double.NaN;
- }
- Genetic(int genes, int population, long seed, double leftx, double rightx, double trueSolution) {
- this(genes, population, seed, leftx, rightx);
- this.trueSolution = trueSolution;
- }
- public int solve(int maxSteps) {
- while (trueSolution != Double.NaN && Math.abs(trueSolution - getSolutiony()) > epsilon && counter < maxSteps) {
- iterate();
- }
- if (counter > maxSteps - 1) return -1;
- return counter;
- }
- public void makeOffset() {
- for (int i = 0; i < population; i++) {
- m[i].f += 300;
- }
- }
- void undoOffset() {
- for (int i = 0; i < population; i++) {
- m[i].f -= offset;
- }
- }
- void selection() {
- v = new double[population];
- double sum = 0, tmp = 0;
- for (int i = 0; i < population; i++) {
- sum += m[i].f;
- }
- for (int i = 0; i < population; i++) {
- v[i] = m[i].f * 1000 / sum;
- tmp += v[i];
- v[i] = tmp;
- System.out.println(v[i]);
- }
- }
- int roulette() {
- int val = rnd.nextInt(1001);
- int i = 0;
- while (i < population - 1 && val > v[i]) {
- i++;
- }
- System.out.println(val + " " + i);
- return i;
- }
- public void crossing() {
- System.out.println();
- System.out.println("Making crossing\n");
- Phenotype[] children = new Phenotype[population];
- selection();
- Stack<Integer> list = new Stack();
- for (int i = 0; i < population; i++) {
- list.push(roulette());
- }
- Collections.shuffle(list, rnd);
- for (int i = 0; i < population / 2; i++) {
- int a = list.pop(), b = list.pop();
- System.out.println("Pairs " + a + " and " + b);
- int delim = rnd.nextInt(genes - 1); // число разрезов на 1 меньше, чем число элементов
- System.out.println(genes);
- // System.out.println(m[a].ch.length);
- System.out.println("a = " + a);
- short[] m1 = Arrays.copyOf(m[a].ch, genes);
- short[] m2 = Arrays.copyOf(m[b].ch, genes);
- for (int j = delim + 1; j < genes; j++) {
- short tmp = m1[j];
- m1[j] = m2[j];
- m2[j] = tmp;
- }
- Phenotype first = new Phenotype(genes, m1, leftx, rightx);
- Phenotype second = new Phenotype(genes, m2, leftx, rightx);
- children[i * 2] = first;
- children[i * 2 + 1] = second;
- }
- m = children;
- }
- void iterate() {
- counter++;
- System.out.println("\nIteration " + counter + ": \n\n");
- makeOffset();
- crossing();
- mutation();
- System.out.println(this);
- findBestSolution();
- }
- void findBestSolution() {
- double maxx = m[0].genotypeX, maxy = m[0].f;
- for (int i = 1; i < population; i++) {
- if (maxy < m[i].f) {
- maxy = m[i].f;
- maxx = m[i].genotypeX;
- }
- }
- System.out.println("Best solution this step:");
- System.out.println("X = " + maxx + "\nY = " + Function.get(maxx));
- listx.add(maxx);
- listy.add(Function.get(maxx));
- if (maxy > solutiony) {
- solutionx = maxx;
- solutiony = maxy;
- }
- }
- ArrayList<Double> getListY() {
- return listy;
- }
- double getSolutionx() {
- return solutionx;
- }
- double getSolutiony() {
- return Function.get(solutionx);
- }
- void mutation() {
- if ((counter + 1) % 4 != 0) return;
- for (int i = 0; i < population; i += 10) {
- for (int j = 0; j < 2; j++) {
- int k = rnd.nextInt(genes);
- m[i].ch[k] = (short) (1 - m[i].ch[k]);
- }
- }
- }
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < population; i++) {
- for (int j = 0; j < genes; j++) {
- sb.append(m[i].ch[j]).append(" ");
- }
- sb.append(m[i].genotypeX).append(" ").append(m[i].f).append(" ").append("\n");
- }
- return sb.toString();
- }
- // более строгий оффсет
- // void makeOffset() {
- // System.out.println("Making offset");
- // double min = m[0].f;
- // for (int i = 1; i < population; i++) {
- // if (m[i].f < min) {
- // min = m[i].f;
- // }
- // }
- // if (min < 0) {
- // offset = -min * 1.05d;
- // } else {
- // offset = min * 0.95d;
- // }
- // System.out.println("Offset is " + offset);
- // for (int i = 0; i < population; i++) {
- // m[i].f = m[i].f + offset;
- // }
- // }
- }
- @GenotypeXY.java
- import java.util.*;
- /**
- * Proger: Dmitry Savelin, kr4m, vk.com/savelin
- * Date: 23.09.2017
- * Time: 18:17
- */
- public class GeneticXY extends Genetic {
- GeneticXY(int genes, int population, long seed, double leftx, double rightx, double lefty, double righty) {
- this.listy = new ArrayList<Double>();
- this.genes = genes;
- this.population = population;
- this.seed = seed;
- this.leftx = leftx;
- this.rightx = rightx;
- this.lefty = lefty;
- this.righty = righty;
- m = new PhenotypeXY[population];
- rnd = new Random(seed);
- for (int i = 0; i < population; i++) {
- short[] ch = new short[genes];
- for (int j = 0; j < genes; j++) {
- ch[j] = (short) rnd.nextInt(2);
- }
- m[i] = new PhenotypeXY(genes, ch, leftx, rightx, lefty, righty);
- }
- epsilon = 0.02d;
- }
- GeneticXY(int genes, int population, long seed, double leftx, double rightx, double lefty, double righty, double trueSolution) {
- this(genes, population, seed, leftx, rightx, lefty, righty);
- this.trueSolution = trueSolution;
- }
- @Override
- public int solve(int maxSteps) {
- while (trueSolution != Double.NaN && Math.abs(trueSolution - getSolutionz()) > epsilon && counter < maxSteps) {
- iterate();
- }
- if (counter > maxSteps - 1) return -1;
- return counter;
- }
- @Override
- public void makeOffset() {
- for (int i = 0; i < population; i++) {
- m[i].f += 2.62d;
- }
- }
- @Override
- double getSolutiony() {
- return solutiony;
- }
- double getSolutionz() {
- return FunctionXY.get(solutionx, solutiony);
- }
- @Override
- void findBestSolution() {
- double maxx = m[0].genotypeX, maxy = m[0].genotypeY, maxz = m[0].f;
- for (int i = 1; i < population; i++) {
- if (maxz < m[i].f) {
- maxz = m[i].f;
- maxx = m[i].genotypeX;
- maxy = m[i].genotypeY;
- }
- }
- System.out.println("Best solution this step:");
- System.out.println("X = " + maxx + "\nZ = " + FunctionXY.get(maxx, maxy));
- listy.add(FunctionXY.get(maxx, maxy));
- if (maxz > solutionz) {
- solutionx = maxx;
- solutiony = maxy;
- solutionz = maxz;
- }
- }
- @Override
- public void crossing() {
- System.out.println();
- System.out.println("Making crossing\n");
- Phenotype[] children = new Phenotype[population];
- selection();
- Stack<Integer> list = new Stack();
- for (int i = 0; i < population; i++) {
- list.push(roulette());
- }
- Collections.shuffle(list, rnd);
- for (int i = 0; i < population / 2; i++) {
- int a = list.pop(), b = list.pop();
- System.out.println("Pairs " + a + " and " + b);
- int delim = rnd.nextInt(genes - 1); // число разрезов на 1 меньше, чем число элементов
- System.out.println(genes);
- // System.out.println(m[a].ch.length);
- System.out.println("a = " + a);
- short[] m1 = Arrays.copyOf(m[a].ch, genes);
- short[] m2 = Arrays.copyOf(m[b].ch, genes);
- for (int j = delim + 1; j < genes; j++) {
- short tmp = m1[j];
- m1[j] = m2[j];
- m2[j] = tmp;
- }
- Phenotype first = new PhenotypeXY(genes, m1, leftx, rightx, lefty, righty);
- Phenotype second = new PhenotypeXY(genes, m2, leftx, rightx, lefty, righty);
- children[i * 2] = first;
- children[i * 2 + 1] = second;
- }
- m = children;
- }
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < population; i++) {
- for (int j = 0; j < genes; j++) {
- sb.append(m[i].ch[j]).append(" ");
- }
- sb.append(m[i].genotypeX).append(" ").append(m[i].genotypeY).append(" ").append(m[i].f).append(" ").append("\n");
- }
- return sb.toString();
- }
- }
- @Phenotype.java
- import java.util.Arrays;
- /**
- * Класс, реализующий хромосому
- */
- class Phenotype {
- short[] ch;
- double genotypeX, genotypeY;
- double f;
- /**
- * Конструктор сразу при создании фенотипа переводит двоичный код в код Грея
- *
- * @param genes - количество генов в хромосоме
- * @param ch - массив генов
- * @param left - левая граница интервала
- * @param right - правая граница интервала
- */
- Phenotype(int genes, short[] ch, double left, double right) {
- this.ch = Arrays.copyOf(ch, genes);
- genotypeX = countGenotype(left, right);
- f = countFunction();
- }
- Phenotype() {
- }
- private double countGenotype(double left, double right) {
- ch = GrayTranslator.grayToBinary(ch);
- long value = 0;
- long mul = 1;
- for (int i = 0; i < ch.length; i++) {
- value += ch[ch.length - 1 - i] * mul;
- mul *= 2;
- }
- ch = GrayTranslator.binaryToGray(ch);
- return left + value * (right - left) / Math.pow(2, ch.length);
- }
- private double countFunction() {
- return -Function.get(genotypeX); // ф-я приспособленности
- }
- }
- @PhenotypeXY.java
- import java.util.Arrays;
- /**
- * Proger: Dmitry Savelin, kr4m, vk.com/savelin
- * Date: 23.09.2017
- * Time: 18:27
- */
- class PhenotypeXY extends Phenotype {
- /**
- * Конструктор сразу при создании фенотипа переводит двоичный код в код Грея
- *
- * @param genes - количество генов в хромосоме
- * @param ch - массив генов
- * @param leftx - левая граница интервала переменной x
- * @param rightx - правая граница интервала переменной x
- * @param lefty - левая граница интервала переменной y
- * @param righty - правая граница интервала переменной y
- */
- PhenotypeXY(int genes, short[] ch, double leftx, double rightx, double lefty, double righty) {
- this.ch = Arrays.copyOf(ch, genes);
- genotypeY = countGenotypeY(lefty, righty);
- genotypeX = countGenotypeX(leftx, rightx);
- f = countFunction();
- }
- private double countGenotypeY(double lefty, double righty) {
- ch = GrayTranslator.grayToBinary(ch);
- long value = 0;
- long mul = 1;
- for (int i = 0; i < ch.length / 2; i++) {
- value += ch[ch.length - 1 - i] * mul;
- mul *= 2;
- }
- return lefty + value * (righty - lefty) / Math.pow(2, ch.length / 2);
- }
- private double countGenotypeX(double leftx, double rightx) {
- long value = 0;
- long mul = 1;
- for (int i = ch.length / 2; i < ch.length; i++) {
- value += ch[ch.length - 1 - i] * mul;
- mul *= 2;
- }
- ch = GrayTranslator.binaryToGray(ch);
- return leftx + value * (rightx - leftx) / Math.pow(2, ch.length / 2);
- }
- private double countFunction() {
- return -FunctionXY.get(genotypeX, genotypeY); // ф-я приспособленности
- }
- }
- @Function.java
- /**
- * Proger: Dmitry Savelin, kr4m, vk.com/savelin
- * Date: 23.09.2017
- * Time: 19:20
- */
- class Function {
- static double get(double x) {
- return (x * x + x) * Math.cos(x);
- }
- }
- @FunctionXY.java
- /**
- * Proger: Dmitry Savelin, kr4m, vk.com/savelin
- * Date: 23.09.2017
- * Time: 20:22
- */
- class FunctionXY {
- static double get(double x, double y) {
- return Math.atan(x + y) * (Math.acos(x) + Math.asin(y));
- }
- }
- @GrayTranslator.java
- /**
- * Proger: Dmitry Savelin, kr4m, vk.com/savelin
- * Date: 23.09.2017
- * Time: 21:18
- */
- class GrayTranslator {
- static short[] binaryToGray(short[] b) {
- short[] g = new short[b.length];
- g[0] = b[0];
- for (int i = 1; i < b.length; i++) {
- g[i] = (short)(b[i - 1] ^ b[i]);
- }
- return g;
- }
- static short[] grayToBinary(short[] g) {
- short[] b = new short[g.length];
- short value = g[0];
- b[0] = value;
- for (int i = 1; i < g.length; i++) {
- if (g[i] == 1) {
- value = (short)(1 - value);
- }
- b[i] = value;
- }
- return b;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement