Program rozwiązujący problem maksymalnej kiliki

This commit is contained in:
Mariusz Pacek committed 2013-03-12 13:16:50 +01:00
1 parent b73b4453d7
commit ecde820ff9
57 files changed
+6267

No files matched your search

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 554 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.3 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

+225
View File
@@ -0,0 +1,225 @@
<?xml version="1.1" encoding="UTF-8" ?>
<Form version="1.3" maxVersion="1.7" type="org.netbeans.modules.form.forminfo.JFrameFormInfo">
<NonVisualComponents>
<Container class="javax.swing.JDialog" name="jDialog1">
<Events>
<EventHandler event="keyPressed" listener="java.awt.event.KeyListener" parameters="java.awt.event.KeyEvent" handler="jDialog1KeyPressed"/>
</Events>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="0" attributes="0">
<Component id="jLabel2" alignment="0" min="-2" max="-2" attributes="0"/>
<Component id="jLabel1" alignment="0" min="-2" max="-2" attributes="0"/>
<Component id="jLabel3" alignment="0" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="0" max="-2" attributes="0">
<Component id="jTextField3" alignment="0" pref="115" max="32767" attributes="1"/>
<Component id="jTextField2" alignment="0" max="32767" attributes="1"/>
<Component id="jTextField1" alignment="0" max="32767" attributes="1"/>
</Group>
<EmptySpace pref="122" max="32767" attributes="0"/>
</Group>
<Group type="102" alignment="1" attributes="0">
<EmptySpace pref="165" max="32767" attributes="0"/>
<Component id="jButton3" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="jButton2" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="jTextField1" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="jLabel1" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="jLabel2" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="jTextField2" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="jLabel3" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="jTextField3" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace min="-2" pref="94" max="-2" attributes="0"/>
</Group>
<Group type="102" alignment="1" attributes="0">
<EmptySpace pref="132" max="32767" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="jButton2" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="jButton3" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace min="-2" pref="22" max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Component class="javax.swing.JButton" name="jButton2">
<Properties>
<Property name="text" type="java.lang.String" value="Close"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButton2ActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JButton" name="jButton3">
<Properties>
<Property name="text" type="java.lang.String" value="Generate"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButton3ActionPerformed"/>
</Events>
<AuxValues>
<AuxValue name="JavaCodeGenerator_InitCodePost" type="java.lang.String" value="jButton3.grabFocus();"/>
</AuxValues>
</Component>
<Component class="javax.swing.JTextField" name="jTextField1">
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jTextField1ActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JTextField" name="jTextField2">
</Component>
<Component class="javax.swing.JTextField" name="jTextField3">
</Component>
<Component class="javax.swing.JLabel" name="jLabel1">
<Properties>
<Property name="text" type="java.lang.String" value="Size of qlicue"/>
</Properties>
</Component>
<Component class="javax.swing.JLabel" name="jLabel2">
<Properties>
<Property name="text" type="java.lang.String" value="Random node"/>
</Properties>
</Component>
<Component class="javax.swing.JLabel" name="jLabel3">
<Properties>
<Property name="text" type="java.lang.String" value="Random edge"/>
</Properties>
</Component>
</SubComponents>
</Container>
<Menu class="javax.swing.JMenuBar" name="jMenuBar1">
<SubComponents>
<Menu class="javax.swing.JMenu" name="jMenu1">
<Properties>
<Property name="text" type="java.lang.String" value="File"/>
</Properties>
<SubComponents>
<MenuItem class="javax.swing.JMenuItem" name="jMenuItem1">
<Properties>
<Property name="accelerator" type="javax.swing.KeyStroke" editor="org.netbeans.modules.form.editors.KeyStrokeEditor">
<KeyStroke key="Ctrl+O"/>
</Property>
<Property name="text" type="java.lang.String" value="Open"/>
</Properties>
<Events>
<EventHandler event="mouseClicked" listener="java.awt.event.MouseListener" parameters="java.awt.event.MouseEvent" handler="jMenuItem1MouseClicked"/>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jMenuItem1ActionPerformed"/>
</Events>
</MenuItem>
<MenuItem class="javax.swing.JMenuItem" name="jMenuItem4">
<Properties>
<Property name="accelerator" type="javax.swing.KeyStroke" editor="org.netbeans.modules.form.editors.KeyStrokeEditor">
<KeyStroke key="Ctrl+G"/>
</Property>
<Property name="text" type="java.lang.String" value="Generate grah"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jMenuItem4ActionPerformed"/>
</Events>
</MenuItem>
<MenuItem class="javax.swing.JMenuItem" name="jMenuItem3">
<Properties>
<Property name="accelerator" type="javax.swing.KeyStroke" editor="org.netbeans.modules.form.editors.KeyStrokeEditor">
<KeyStroke key="Ctrl+S"/>
</Property>
<Property name="text" type="java.lang.String" value="Save"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jMenuItem3ActionPerformed"/>
</Events>
</MenuItem>
<MenuItem class="javax.swing.JMenuItem" name="jMenuItem2">
<Properties>
<Property name="accelerator" type="javax.swing.KeyStroke" editor="org.netbeans.modules.form.editors.KeyStrokeEditor">
<KeyStroke key="Ctrl+Q"/>
</Property>
<Property name="text" type="java.lang.String" value="Exit"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jMenuItem2ActionPerformed"/>
</Events>
</MenuItem>
</SubComponents>
</Menu>
<Menu class="javax.swing.JMenu" name="jMenu3">
<Properties>
<Property name="text" type="java.lang.String" value="View"/>
</Properties>
</Menu>
</SubComponents>
</Menu>
</NonVisualComponents>
<Properties>
<Property name="defaultCloseOperation" type="int" value="3"/>
</Properties>
<SyntheticProperties>
<SyntheticProperty name="menuBar" type="java.lang.String" value="jMenuBar1"/>
<SyntheticProperty name="formSizePolicy" type="int" value="1"/>
</SyntheticProperties>
<AuxValues>
<AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
<AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
<AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
</AuxValues>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" attributes="0">
<EmptySpace pref="471" max="32767" attributes="0"/>
<Component id="jButton1" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="1" attributes="0">
<EmptySpace pref="315" max="32767" attributes="0"/>
<Component id="jButton1" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Component class="javax.swing.JButton" name="jButton1">
<Properties>
<Property name="text" type="java.lang.String" value="Slove"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButton1ActionPerformed"/>
</Events>
</Component>
</SubComponents>
</Form>
+74
View File
@@ -0,0 +1,74 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- You may freely edit this file. See commented blocks below for -->
<!-- some examples of how to customize the build. -->
<!-- (If you delete it and reopen the project it will be recreated.) -->
<!-- By default, only the Clean and Build commands use this build script. -->
<!-- Commands such as Run, Debug, and Test only use this build script if -->
<!-- the Compile on Save feature is turned off for the project. -->
<!-- You can turn off the Compile on Save (or Deploy on Save) setting -->
<!-- in the project's Project Properties dialog box.-->
<project name="Klika1" default="default" basedir=".">
<description>Builds, tests, and runs the project Klika1.</description>
<import file="nbproject/build-impl.xml"/>
<!--
There exist several targets which are by default empty and which can be
used for execution of your tasks. These targets are usually executed
before and after some main targets. They are:
-pre-init: called before initialization of project properties
-post-init: called after initialization of project properties
-pre-compile: called before javac compilation
-post-compile: called after javac compilation
-pre-compile-single: called before javac compilation of single file
-post-compile-single: called after javac compilation of single file
-pre-compile-test: called before javac compilation of JUnit tests
-post-compile-test: called after javac compilation of JUnit tests
-pre-compile-test-single: called before javac compilation of single JUnit test
-post-compile-test-single: called after javac compilation of single JUunit test
-pre-jar: called before JAR building
-post-jar: called after JAR building
-post-clean: called after cleaning build products
(Targets beginning with '-' are not intended to be called on their own.)
Example of inserting an obfuscator after compilation could look like this:
<target name="-post-compile">
<obfuscate>
<fileset dir="${build.classes.dir}"/>
</obfuscate>
</target>
For list of available properties check the imported
nbproject/build-impl.xml file.
Another way to customize the build is by overriding existing main targets.
The targets of interest are:
-init-macrodef-javac: defines macro for javac compilation
-init-macrodef-junit: defines macro for junit execution
-init-macrodef-debug: defines macro for class debugging
-init-macrodef-java: defines macro for class execution
-do-jar-with-manifest: JAR building (if you are using a manifest)
-do-jar-without-manifest: JAR building (if you are not using a manifest)
run: execution of project
-javadoc-build: Javadoc generation
test-report: JUnit report generation
An example of overriding the target for project execution could look like this:
<target name="run" depends="Klika1-impl.jar">
<exec dir="bin" executable="launcher.exe">
<arg file="${dist.jar}"/>
</exec>
</target>
Notice that the overridden target depends on the jar target and not only on
the compile target as the regular run target does. Again, for a list of available
properties which you can use, check the target you are overriding in the
nbproject/build-impl.xml file.
-->
</project>
+4
View File
@@ -0,0 +1,4 @@
#Sun, 10 Jun 2012 17:18:37 +0200
/mnt/dysk1/Katalog\ bez\ nazwy/NetBeansProjects/klikaa=
Whitespace-only changes.
Whitespace-only changes.
+32
View File
@@ -0,0 +1,32 @@
========================
BUILD OUTPUT DESCRIPTION
========================
When you build an Java application project that has a main class, the IDE
automatically copies all of the JAR
files on the projects classpath to your projects dist/lib folder. The IDE
also adds each of the JAR files to the Class-Path element in the application
JAR files manifest file (MANIFEST.MF).
To run the project from the command line, go to the dist folder and
type the following:
java -jar "Klika1.jar"
To distribute this project, zip up the dist folder (including the lib folder)
and distribute the ZIP file.
Notes:
* If two JAR files on the project classpath have the same name, only the first
JAR file is copied to the lib folder.
* Only JAR files are copied to the lib folder.
If the classpath contains other types of files or folders, these files (folders)
are not copied.
* If a library on the projects classpath also has a Class-Path element
specified in the manifest,the content of the Class-Path element has to be on
the projects runtime path.
* To set a main class in a standard Java project, right-click the project node
in the Projects window and choose Properties. Then click Run and enter the
class name in the Main Class field. Alternatively, you can manually type the
class name in the manifest Main-Class element.
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

+3
View File
@@ -0,0 +1,3 @@
Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build
File diff suppressed because it is too large. Load diff
+8
View File
@@ -0,0 +1,8 @@
build.xml.data.CRC32=9f9c4abb
build.xml.script.CRC32=452c06ff
build.xml.stylesheet.CRC32=28e38971@1.44.1.45
# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml.
# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you.
nbproject/build-impl.xml.data.CRC32=9f9c4abb
nbproject/build-impl.xml.script.CRC32=4bd743ca
nbproject/build-impl.xml.stylesheet.CRC32=fcddb364@1.50.2.46
View File
Whitespace-only changes.
+6
View File
@@ -0,0 +1,6 @@
compile.on.save=true
do.depend=false
do.jar=true
javac.debug=true
javadoc.preview=true
user.properties.file=/home/mar/.netbeans/7.1.2/build.properties
+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project-private xmlns="http://www.netbeans.org/ns/project-private/1">
<editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/1"/>
</project-private>
@@ -0,0 +1,113 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="2_profiler.settings.code.region.cpu.res.buf.size">1000</entry>
<entry key="2_profiler.settings.sort.results.by.thread.cpu.time">false</entry>
<entry key="0_profiler.settings.instrumentation.filter.selectedprofiler.filter.type">profiler.simple.filter</entry>
<entry key="0_profiler.settings.instrument.empty.methods">false</entry>
<entry key="0_profiler.settings.instrumentation.filter.selectedprofiler.simple.filter.name"/>
<entry key="1_profiler.settings.profiling.type">8</entry>
<entry key="0_profiler.settings.cpu.exclude.wait.time">true</entry>
<entry key="0_profiler.settings.override.working.dir"/>
<entry key="2_profiler.settings.cpu.sampling.frequency">10</entry>
<entry key="1_profiler.settings.thread.cpu.timer.on">false</entry>
<entry key="1_profiler.settings.instrumentation.root.methods.size">0</entry>
<entry key="2_profiler.settings.override">false</entry>
<entry key="1_profiler.settings.threads.sampling.enabled">true</entry>
<entry key="profiler.settings.lastselected">1</entry>
<entry key="0_profiler.settings.threads.monitoring.enabled">false</entry>
<entry key="2_profiler.settings.instrument.spawned.threads">false</entry>
<entry key="0_profiler.settings.istrument.getter.setter.methods">false</entry>
<entry key="2_profiler.settings.instrumentation.filter.selectedprofiler.filter.type">profiler.simple.filter</entry>
<entry key="2_profiler.settings.n.profiled.threads.limit">32</entry>
<entry key="1_profiler.settings.sort.results.by.thread.cpu.time">false</entry>
<entry key="2_profiler.settings.instr.scheme">1</entry>
<entry key="1_profiler.settings.instrument.method.invoke">true</entry>
<entry key="1_profiler.settings.instr.scheme">3</entry>
<entry key="2_profiler.settings.sampling.interval">10</entry>
<entry key="0_profiler.settings.instr.scheme">1</entry>
<entry key="1_profiler.settings.run.gc.on.get.results.in.memory.profiling">true</entry>
<entry key="2_profiler.settings.settings.name">Analyze Memory</entry>
<entry key="0_profiler.settings.sort.results.by.thread.cpu.time">false</entry>
<entry key="1_profiler.settings.cpu.sampling.frequency">10</entry>
<entry key="0_profiler.settings.profiling.type">1</entry>
<entry key="1_profiler.settings.cpu.exclude.wait.time">true</entry>
<entry key="2_profiler.settings.obj.alloc.stack.sampling.interval">10</entry>
<entry key="1_profiler.settings.obj.alloc.stack.sampling.depth">0</entry>
<entry key="1_profiler.settings.cpu.quick.filterprofiler.filter.type">profiler.simple.filter</entry>
<entry key="1_profiler.settings.instrumentation.marker.methods.size">0</entry>
<entry key="2_profiler.settings.thread.cpu.timer.on">false</entry>
<entry key="0_profiler.settigns.ispreset">true</entry>
<entry key="0_profiler.settings.instrumentation.filter.selectedprofiler.simple.filter.value"/>
<entry key="0_profiler.settings.cpu.quick.filterprofiler.simple.filter.type">1</entry>
<entry key="2_profiler.settings.override.working.dir"/>
<entry key="0_profiler.settings.threads.sampling.enabled">true</entry>
<entry key="2_profiler.settings.cpu.quick.filterprofiler.simple.filter.value"/>
<entry key="2_profiler.settings.override.jvm.args"/>
<entry key="0_profiler.settings.profile.underlying.framework">false</entry>
<entry key="0_profiler.settings.cpu.sampling.frequency">10</entry>
<entry key="2_profiler.settings.profile.underlying.framework">false</entry>
<entry key="2_profiler.settings.cpu.exclude.wait.time">true</entry>
<entry key="2_profiler.settings.threads.monitoring.enabled">false</entry>
<entry key="1_profiler.settings.instrument.spawned.threads">false</entry>
<entry key="1_profiler.settings.n.profiled.threads.limit">32</entry>
<entry key="0_profiler.settings.cpu.quick.filterprofiler.simple.filter.name">Quick filter...</entry>
<entry key="2_profiler.settings.instrumentation.root.methods.size">0</entry>
<entry key="2_profiler.settings.instrument.empty.methods">false</entry>
<entry key="2_profiler.settings.instrumentation.filter.selectedprofiler.simple.filter.type">0</entry>
<entry key="1_profiler.settings.instrumentation.filter.selectedprofiler.simple.filter.value"/>
<entry key="1_profiler.settings.sampling.interval">10</entry>
<entry key="2_profiler.settings.cpu.profiling.type">0</entry>
<entry key="0_profiler.settings.run.gc.on.get.results.in.memory.profiling">true</entry>
<entry key="1_profiler.settigns.ispreset">true</entry>
<entry key="2_profiler.settings.instrumentation.filter.selectedprofiler.simple.filter.name"/>
<entry key="0_profiler.settings.instrument.method.invoke">true</entry>
<entry key="0_profiler.settings.obj.alloc.stack.sampling.interval">10</entry>
<entry key="1_profiler.settings.cpu.quick.filterprofiler.simple.filter.value"/>
<entry key="1_profiler.settings.code.region.cpu.res.buf.size">1000</entry>
<entry key="0_profiler.settings.instrumentation.marker.methods.size">0</entry>
<entry key="1_profiler.settings.instrumentation.filter.selectedprofiler.filter.type">profiler.simple.filter</entry>
<entry key="0_profiler.settings.override">false</entry>
<entry key="1_profiler.settings.settings.name">Analyze Performance</entry>
<entry key="2_profiler.settings.instrumentation.filter.selectedprofiler.simple.filter.value"/>
<entry key="1_profiler.settings.cpu.quick.filterprofiler.simple.filter.type">1</entry>
<entry key="1_profiler.settings.cpu.profiling.type">0</entry>
<entry key="1_profiler.settings.override.jvm.args"/>
<entry key="1_profiler.settings.instrument.empty.methods">false</entry>
<entry key="2_profiler.settings.obj.alloc.stack.sampling.depth">0</entry>
<entry key="0_profiler.settings.cpu.quick.filterprofiler.filter.type">profiler.simple.filter</entry>
<entry key="1_profiler.settings.cpu.quick.filterprofiler.simple.filter.name">Quick filter...</entry>
<entry key="1_profiler.settings.threads.monitoring.enabled">false</entry>
<entry key="2_profiler.settigns.ispreset">true</entry>
<entry key="0_profiler.settings.instrumentation.root.methods.size">0</entry>
<entry key="2_profiler.settings.threads.sampling.enabled">true</entry>
<entry key="1_profiler.settings.override.working.dir"/>
<entry key="1_profiler.settings.instrumentation.filter.selectedprofiler.simple.filter.type">0</entry>
<entry key="0_profiler.settings.cpu.quick.filterprofiler.simple.filter.value"/>
<entry key="0_profiler.settings.n.profiled.threads.limit">32</entry>
<entry key="0_profiler.settings.cpu.profiling.type">0</entry>
<entry key="0_profiler.settings.instrument.spawned.threads">false</entry>
<entry key="1_profiler.settings.instrumentation.filter.selectedprofiler.simple.filter.name">Profile all classes</entry>
<entry key="2_profiler.settings.instrumentation.marker.methods.size">0</entry>
<entry key="0_profiler.settings.obj.alloc.stack.sampling.depth">0</entry>
<entry key="0_profiler.settings.profilingpoints.enabled">true</entry>
<entry key="2_profiler.settings.cpu.quick.filterprofiler.filter.type">profiler.simple.filter</entry>
<entry key="2_profiler.settings.cpu.quick.filterprofiler.simple.filter.type">1</entry>
<entry key="1_profiler.settings.obj.alloc.stack.sampling.interval">10</entry>
<entry key="1_profiler.settings.override">false</entry>
<entry key="0_profiler.settings.sampling.interval">10</entry>
<entry key="2_profiler.settings.istrument.getter.setter.methods">false</entry>
<entry key="1_profiler.settings.profile.underlying.framework">false</entry>
<entry key="2_profiler.settings.instrument.method.invoke">true</entry>
<entry key="1_profiler.settings.profilingpoints.enabled">true</entry>
<entry key="1_profiler.settings.istrument.getter.setter.methods">false</entry>
<entry key="0_profiler.settings.instrumentation.filter.selectedprofiler.simple.filter.type">0</entry>
<entry key="2_profiler.settings.cpu.quick.filterprofiler.simple.filter.name">Quick filter...</entry>
<entry key="0_profiler.settings.thread.cpu.timer.on">false</entry>
<entry key="0_profiler.settings.override.jvm.args"/>
<entry key="0_profiler.settings.settings.name">Monitor Application</entry>
<entry key="2_profiler.settings.profiling.type">2</entry>
<entry key="0_profiler.settings.code.region.cpu.res.buf.size">1000</entry>
<entry key="2_profiler.settings.run.gc.on.get.results.in.memory.profiling">true</entry>
<entry key="2_profiler.settings.profilingpoints.enabled">true</entry>
</properties>
+149
View File
@@ -0,0 +1,149 @@
annotation.processing.enabled=true
annotation.processing.enabled.in.editor=false
annotation.processing.processors.list=
annotation.processing.run.all.processors=true
annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output
application.title=Klika1
application.vendor=-
build.classes.dir=${build.dir}/classes
build.classes.excludes=**/*.java,**/*.form
# This directory is removed when the project is cleaned:
build.dir=build
build.generated.dir=${build.dir}/generated
build.generated.sources.dir=${build.dir}/generated-sources
# Only compile against the classpath explicitly listed here:
build.sysclasspath=ignore
build.test.classes.dir=${build.dir}/test/classes
build.test.results.dir=${build.dir}/test/results
# Uncomment to specify the preferred debugger connection transport:
#debug.transport=dt_socket
debug.classpath=\
${run.classpath}
debug.test.classpath=\
${run.test.classpath}
# This directory is removed when the project is cleaned:
dist.dir=dist
dist.jar=${dist.dir}/Klika1.jar
dist.javadoc.dir=${dist.dir}/javadoc
endorsed.classpath=
excludes=
file.reference.collections-generic-4.01.jar=/mnt/dysk1/jung/collections-generic-4.01.jar
file.reference.colt-1.2.0.jar=/mnt/dysk1/jung/colt-1.2.0.jar
file.reference.concurrent-1.3.4.jar=/mnt/dysk1/jung/concurrent-1.3.4.jar
file.reference.gnujaxp.jar=/mnt/dysk1/jfreechart-1.0.14/jfreechart-1.0.14/lib/gnujaxp.jar
file.reference.iText-2.1.5.jar=/mnt/dysk1/jfreechart-1.0.14/jfreechart-1.0.14/lib/iText-2.1.5.jar
file.reference.j3d-core-1.3.1.jar=/mnt/dysk1/jung/j3d-core-1.3.1.jar
file.reference.jcommon-1.0.17.jar=/mnt/dysk1/jfreechart-1.0.14/jfreechart-1.0.14/lib/jcommon-1.0.17.jar
file.reference.jfreechart-1.0.14-experimental.jar=/mnt/dysk1/jfreechart-1.0.14/jfreechart-1.0.14/lib/jfreechart-1.0.14-experimental.jar
file.reference.jfreechart-1.0.14-swt.jar=/mnt/dysk1/jfreechart-1.0.14/jfreechart-1.0.14/lib/jfreechart-1.0.14-swt.jar
file.reference.jfreechart-1.0.14.jar=/mnt/dysk1/jfreechart-1.0.14/jfreechart-1.0.14/lib/jfreechart-1.0.14.jar
file.reference.jung-3d-2.0.1-sources.jar=/mnt/dysk1/jung/jung-3d-2.0.1-sources.jar
file.reference.jung-3d-2.0.1.jar=/mnt/dysk1/jung/jung-3d-2.0.1.jar
file.reference.jung-3d-demos-2.0.1-sources.jar=/mnt/dysk1/jung/jung-3d-demos-2.0.1-sources.jar
file.reference.jung-3d-demos-2.0.1.jar=/mnt/dysk1/jung/jung-3d-demos-2.0.1.jar
file.reference.jung-algorithms-2.0.1-sources.jar=/mnt/dysk1/jung/jung-algorithms-2.0.1-sources.jar
file.reference.jung-algorithms-2.0.1.jar=/mnt/dysk1/jung/jung-algorithms-2.0.1.jar
file.reference.jung-api-2.0.1-sources.jar=/mnt/dysk1/jung/jung-api-2.0.1-sources.jar
file.reference.jung-api-2.0.1.jar=/mnt/dysk1/jung/jung-api-2.0.1.jar
file.reference.jung-graph-impl-2.0.1-sources.jar=/mnt/dysk1/jung/jung-graph-impl-2.0.1-sources.jar
file.reference.jung-graph-impl-2.0.1.jar=/mnt/dysk1/jung/jung-graph-impl-2.0.1.jar
file.reference.jung-io-2.0.1-sources.jar=/mnt/dysk1/jung/jung-io-2.0.1-sources.jar
file.reference.jung-io-2.0.1.jar=/mnt/dysk1/jung/jung-io-2.0.1.jar
file.reference.jung-jai-2.0.1-sources.jar=/mnt/dysk1/jung/jung-jai-2.0.1-sources.jar
file.reference.jung-jai-2.0.1.jar=/mnt/dysk1/jung/jung-jai-2.0.1.jar
file.reference.jung-jai-samples-2.0.1-sources.jar=/mnt/dysk1/jung/jung-jai-samples-2.0.1-sources.jar
file.reference.jung-jai-samples-2.0.1.jar=/mnt/dysk1/jung/jung-jai-samples-2.0.1.jar
file.reference.jung-samples-2.0.1-sources.jar=/mnt/dysk1/jung/jung-samples-2.0.1-sources.jar
file.reference.jung-samples-2.0.1.jar=/mnt/dysk1/jung/jung-samples-2.0.1.jar
file.reference.jung-visualization-2.0.1-sources.jar=/mnt/dysk1/jung/jung-visualization-2.0.1-sources.jar
file.reference.jung-visualization-2.0.1.jar=/mnt/dysk1/jung/jung-visualization-2.0.1.jar
file.reference.jung2-2_0_1-apidocs.zip=/mnt/dysk1/jung/jung2-2_0_1-apidocs.zip
file.reference.jung2-2_0_1-sources.zip=/mnt/dysk1/jung/jung2-2_0_1-sources.zip
file.reference.junit.jar=/mnt/dysk1/jfreechart-1.0.14/jfreechart-1.0.14/lib/junit.jar
file.reference.servlet.jar=/mnt/dysk1/jfreechart-1.0.14/jfreechart-1.0.14/lib/servlet.jar
file.reference.stax-api-1.0.1.jar=/mnt/dysk1/jung/stax-api-1.0.1.jar
file.reference.swtgraphics2d.jar=/mnt/dysk1/jfreechart-1.0.14/jfreechart-1.0.14/lib/swtgraphics2d.jar
file.reference.vecmath-1.3.1.jar=/mnt/dysk1/jung/vecmath-1.3.1.jar
file.reference.wstx-asl-3.2.6.jar=/mnt/dysk1/jung/wstx-asl-3.2.6.jar
includes=**
jar.compress=false
javac.classpath=\
${file.reference.gnujaxp.jar}:\
${file.reference.iText-2.1.5.jar}:\
${file.reference.jcommon-1.0.17.jar}:\
${file.reference.jfreechart-1.0.14-experimental.jar}:\
${file.reference.jfreechart-1.0.14-swt.jar}:\
${file.reference.jfreechart-1.0.14.jar}:\
${file.reference.junit.jar}:\
${file.reference.servlet.jar}:\
${file.reference.swtgraphics2d.jar}:\
${file.reference.collections-generic-4.01.jar}:\
${file.reference.colt-1.2.0.jar}:\
${file.reference.concurrent-1.3.4.jar}:\
${file.reference.j3d-core-1.3.1.jar}:\
${file.reference.jung-3d-2.0.1-sources.jar}:\
${file.reference.jung-3d-2.0.1.jar}:\
${file.reference.jung-3d-demos-2.0.1-sources.jar}:\
${file.reference.jung-3d-demos-2.0.1.jar}:\
${file.reference.jung-algorithms-2.0.1-sources.jar}:\
${file.reference.jung-algorithms-2.0.1.jar}:\
${file.reference.jung-api-2.0.1-sources.jar}:\
${file.reference.jung-api-2.0.1.jar}:\
${file.reference.jung-graph-impl-2.0.1-sources.jar}:\
${file.reference.jung-graph-impl-2.0.1.jar}:\
${file.reference.jung-io-2.0.1-sources.jar}:\
${file.reference.jung-io-2.0.1.jar}:\
${file.reference.jung-jai-2.0.1-sources.jar}:\
${file.reference.jung-jai-2.0.1.jar}:\
${file.reference.jung-jai-samples-2.0.1-sources.jar}:\
${file.reference.jung-jai-samples-2.0.1.jar}:\
${file.reference.jung-samples-2.0.1-sources.jar}:\
${file.reference.jung-samples-2.0.1.jar}:\
${file.reference.jung-visualization-2.0.1-sources.jar}:\
${file.reference.jung-visualization-2.0.1.jar}:\
${file.reference.jung2-2_0_1-apidocs.zip}:\
${file.reference.jung2-2_0_1-sources.zip}:\
${file.reference.stax-api-1.0.1.jar}:\
${file.reference.vecmath-1.3.1.jar}:\
${file.reference.wstx-asl-3.2.6.jar}
# Space-separated list of extra javac options
javac.compilerargs=
javac.deprecation=false
javac.processorpath=\
${javac.classpath}
javac.source=1.6
javac.target=1.6
javac.test.classpath=\
${javac.classpath}:\
${build.classes.dir}
javac.test.processorpath=\
${javac.test.classpath}
javadoc.additionalparam=
javadoc.author=false
javadoc.encoding=${source.encoding}
javadoc.noindex=false
javadoc.nonavbar=false
javadoc.notree=false
javadoc.private=false
javadoc.splitindex=true
javadoc.use=true
javadoc.version=false
javadoc.windowtitle=
main.class=gui.Frame
manifest.file=manifest.mf
meta.inf.dir=${src.dir}/META-INF
mkdist.disabled=false
platform.active=default_platform
run.classpath=\
${javac.classpath}:\
${build.classes.dir}
# Space-separated list of JVM arguments used when running the project
# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value
# or test-sys-prop.name=value to set system properties for unit tests):
run.jvmargs=
run.test.classpath=\
${javac.test.classpath}:\
${build.test.classes.dir}
source.encoding=windows-1250
src.dir=src
test.src.dir=test
+15
View File
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
<type>org.netbeans.modules.java.j2seproject</type>
<configuration>
<data xmlns="http://www.netbeans.org/ns/j2se-project/3">
<name>Klika1</name>
<source-roots>
<root id="src.dir"/>
</source-roots>
<test-roots>
<root id="test.src.dir"/>
</test-roots>
</data>
</configuration>
</project>
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

+32
View File
@@ -0,0 +1,32 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Graph;
/**
*
* @author -
*/
public class Edge {
private int id; //numer krawedzi
Edge(int _id)
{
id=_id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString()
{
return "E" + id;
}
}
+25
View File
@@ -0,0 +1,25 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Graph;
import org.apache.commons.collections15.Factory;
/**
*
* @author -
*/
public class EdgeFactory implements Factory
{
private int e = 0;
public Edge create()
{
return (new Edge(e++));
}
public void clear()
{
e=0;
}
}
+41
View File
@@ -0,0 +1,41 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Graph;
/**
*
* @author -
*/
public class Node {
private int id; //numer wierzcho³ka
boolean selected=false;
public Node(int _id)
{
id=_id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
@Override
public String toString()
{
return Integer.toString(id);
}
}
+24
View File
@@ -0,0 +1,24 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Graph;
import org.apache.commons.collections15.Factory;
/**
*
* @author -
*/
public class VertexFactory implements Factory
{
private int n = 0;
public Node create()
{
return (new Node(n++));
}
public void clear()
{
n=0;
}
}
+44
View File
@@ -0,0 +1,44 @@
/*
* To change this template, choose Tools | Templates
* and Io the template in the editor.
*/
package GraphIO;
import Graph.Edge;
import Graph.EdgeFactory;
import Graph.Node;
import Graph.VertexFactory;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.UndirectedSparseGraph;
import edu.uci.ics.jung.io.PajekNetReader;
import edu.uci.ics.jung.io.PajekNetWriter;
import gui.Jung;
import java.io.File;
import java.io.IOException;
/**
*
* @author -
*/
public class Io {
public static Graph getGraph(File file,Jung jung) throws IOException {
jung.setNewEdge(new EdgeFactory());
jung.setNewNode(new VertexFactory());
PajekNetReader< Graph<Node,Edge>,Node,Edge> pnr =
new PajekNetReader< Graph<Node,Edge>,Node,Edge>(jung.getNewNode(), jung.getNewEdge());
Graph<Node,Edge> g =
new UndirectedSparseGraph<Node, Edge>();
pnr.load(file.getPath(), g);
return g;
}
public static void saveGraph(Graph<Node, Edge> g, String file) throws IOException {
PajekNetWriter<Node,Edge> pnw=new PajekNetWriter();
pnw.save(g, file);
}
}
+245
View File
@@ -0,0 +1,245 @@
package genetic;
import java.util.LinkedList;
import java.util.Random;
public class Crossing
{
private int crossingType;
private int count;
private double crossingProb;
private int popSize;
public Crossing (int type, double prob, int size)
{
crossingType = type;
count=0;
crossingProb = prob;
popSize = size;
}
public void setCrossingType(int type)
{
crossingType = type;
}
public int getCount()
{
return count;
}
public void setCrossingProb(double prob)
{
crossingProb = prob;
}
public LinkedList<Indyvidual> crossing(LinkedList<Indyvidual> pop)
{
//System.out.println("Crossing popsize " + pop.size() + " typ " + crossingType);
LinkedList<Indyvidual> newPop = null;
count=0;
switch (crossingType)
{
case 1:
{
newPop = onePointTwoChildren(pop);
break;
}
case 2:
{
newPop = onePointOneChild(pop);
break;
}
case 3:
{
newPop = manyPointsOneChild(pop);
break;
}
case 4:
{
newPop = manyPointsTwoChildren(pop);
break;
}
}
return newPop;
}
private LinkedList<Indyvidual> onePointTwoChildren(LinkedList<Indyvidual> pop)
{
int sizeToRandom = pop.size();
int nodes = pop.get(0).getChromosome().length; //dlugosc tablicy chromosomow
Random r = new Random();
int div = r.nextInt(nodes); //punkt podzialu
int size = 0; //rozmiar aktualnej,nowej populacji
int iter = 0;
//System.out.println("Podzial - " + div);
LinkedList<Indyvidual> newPop = new LinkedList<Indyvidual>(); //lista na nowa populacje
//System.out.println("Onepoint poopSize " + pop.size() + " Popsize " + popSize);
while (size<popSize)
{
//System.out.println("Petla");
double prob = r.nextDouble();
if (prob<=crossingProb)
{
count++;
int par1 = iter;
int par2 = iter+1;
if (iter==sizeToRandom-1)
{
par2=0;
iter=-1;
}
//System.out.println("Par2 " + par2);
boolean[] chrom1 = new boolean[nodes];
boolean[] chrom2 = new boolean[nodes];
//System.out.println("Przed kopiowaniem");
System.arraycopy(pop.get(par1).getChromosome(), 0, chrom1, 0, div);
//System.out.println("Przed kopiowaniem 2");
System.arraycopy(pop.get(par2).getChromosome(), div, chrom1, div, nodes - div);
System.arraycopy(pop.get(par2).getChromosome(), 0, chrom2, 0, div);
System.arraycopy(pop.get(par1).getChromosome(), div, chrom2, div, nodes - div);
//System.out.println("Srodek");
Indyvidual child1 = new Indyvidual(nodes);
child1.setChromosome(chrom1);
Indyvidual child2 = new Indyvidual(nodes);
child2.setChromosome(chrom2);
if (size<popSize)
{
newPop.add(child1);
size++;
//System.out.println("Dodaje 1 - size "+ size);
}
if (size<popSize)
{
newPop.add(child2);
size++;
//System.out.println("Dodaje 2 - size "+ size);
}
iter++;
//System.out.println("Przed koncem warunku - iter " + iter);
}
//System.out.println("Po warunku");
}
//System.out.println("czy zwraca");
return newPop;
}
private LinkedList<Indyvidual> onePointOneChild(LinkedList<Indyvidual> pop)
{
int sizeToRandom = pop.size();
int nodes = pop.get(0).getChromosome().length; //dlugosc tablicy chromosomow
Random r = new Random();
int div = r.nextInt(nodes); //punkt podzialu
int size = 0; //rozmiar aktualnej,nowej populacji
//System.out.println("Podzial - " + div);
LinkedList<Indyvidual> newPop = new LinkedList<Indyvidual>(); //lista na nowa populacje
while (size<popSize)
{
double prob = r.nextDouble();
if (prob<=crossingProb)
{
count++;
int par1 = r.nextInt(sizeToRandom);
int par2 = r.nextInt(sizeToRandom);
boolean[] chrom = new boolean[nodes];
System.arraycopy(pop.get(par1).getChromosome(), 0, chrom, 0, div);
System.arraycopy(pop.get(par2).getChromosome(), div, chrom, div, nodes - div);
Indyvidual child = new Indyvidual(nodes);
child.setChromosome(chrom);
newPop.add(child);
size++;
}
}
return newPop;
}
private LinkedList<Indyvidual> manyPointsOneChild(LinkedList<Indyvidual> pop)
{
int sizeToRandom = pop.size();
int nodes = pop.get(0).getChromosome().length; //dlugosc tablicy chromosomow
Random r = new Random();
int size = 0; //rozmiar aktualnej,nowej populacji
LinkedList<Indyvidual> newPop = new LinkedList<Indyvidual>(); //lista na nowa populacje
while (size<popSize)
{
double prob = r.nextDouble();
if (prob<=crossingProb)
{
count++;
int par1 = r.nextInt(sizeToRandom);
int par2 = r.nextInt(sizeToRandom);
boolean[] chrom = new boolean[nodes];
for (int i=0;i<nodes;i++)
{
boolean choice = r.nextBoolean();
if (choice==false)
chrom[i]=pop.get(par1).getChromosome()[i];
if (choice==true)
chrom[i]=pop.get(par2).getChromosome()[i];
}
Indyvidual child = new Indyvidual(nodes);
child.setChromosome(chrom);
newPop.add(child);
size++;
}
}
return newPop;
}
private LinkedList<Indyvidual> manyPointsTwoChildren(LinkedList<Indyvidual> pop)
{
int sizeToRandom = pop.size();
int nodes = pop.get(0).getChromosome().length; //dlugosc tablicy chromosomow
Random r = new Random();
int size = 0; //rozmiar aktualnej,nowej populacji
LinkedList<Indyvidual> newPop = new LinkedList<Indyvidual>(); //lista na nowa populacje
while (size<popSize)
{
double prob = r.nextDouble();
if (prob<=crossingProb)
{
count++;
int par1 = r.nextInt(sizeToRandom);
int par2 = r.nextInt(sizeToRandom);
boolean[] chrom1 = new boolean[nodes];
boolean[] chrom2 = new boolean[nodes];
for (int i=0;i<nodes;i++)
{
boolean choice = r.nextBoolean();
if (choice==false)
{
chrom1[i]=pop.get(par1).getChromosome()[i];
chrom2[i]=pop.get(par2).getChromosome()[i];
}
if (choice==true)
{
chrom1[i]=pop.get(par2).getChromosome()[i];
chrom2[i]=pop.get(par1).getChromosome()[i];
}
}
Indyvidual child1 = new Indyvidual(nodes);
child1.setChromosome(chrom1);
Indyvidual child2 = new Indyvidual(nodes);
child2.setChromosome(chrom2);
if (size<popSize)
{
newPop.add(child1);
size++;
}
if (size<popSize)
{
newPop.add(child2);
size++;
}
}
}
return newPop;
}
}
+114
View File
@@ -0,0 +1,114 @@
package genetic;
import java.util.LinkedList;
import Graph.Edge;
import Graph.Node;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.UndirectedSparseGraph;
import edu.uci.ics.jung.graph.util.EdgeType;
public class Fitness {
private Graph<Node, Edge> graph;
private Node[] nodeTab;
private int HashTab[]; //tablica hashujaca wierzchołki w grafie
private int nodeCount; //ilosc wierzcholkow w grafie
private int edgeCount; //ilosc krawedzi w grafie
public Fitness(Graph<Node, Edge> _graph) {
graph = _graph;
edgeCount = graph.getEdgeCount();
nodeCount = graph.getVertexCount();
nodeTab = new Node[graph.getVertexCount()];
graph.getVertices().toArray(nodeTab);
HashTab = new int[graph.getVertexCount()];
for (int j = 0; j < graph.getVertexCount(); j++) {
HashTab[nodeTab[j].getId()] = j;
}
}
public void fitness(LinkedList<Indyvidual> pop) {
int popSize = pop.size();
for (int i = 0; i < popSize; i++) {
fitnessOne(pop.get(i));
}
}
private void fitnessOne(Indyvidual ind)
{
Graph<Node, Edge> subGraph = new UndirectedSparseGraph<Node, Edge>();
for (int i = 0; i < ind.getChromosome().length; i++) {
if (ind.getChromosome()[i] == true) {
subGraph.addVertex(new Node(i));
}
}
if (subGraph.getVertexCount() > 2) {
Node[] nodeTab2 = new Node[subGraph.getVertexCount()];
subGraph.getVertices().toArray(nodeTab2); //tablica nowych wierzcholkow
for (int i = 0; i < nodeTab2.length; i++) {
for (int j = i + 1; j < nodeTab2.length; j++) {
Edge e = (Edge) graph.findEdge(nodeTab[HashTab[nodeTab2[i].getId()]], nodeTab[HashTab[nodeTab2[j].getId()]]);
if (e != null) {
//System.out.println("Dodawanie krawedzi");
subGraph.addEdge(e, nodeTab2[i], nodeTab2[j], EdgeType.UNDIRECTED);
}
}
// System.out.println();
}
//obliczanie ilosci krawedzi
int subNodeCount = subGraph.getVertexCount();
int edgeSubFullCount = subNodeCount * (subNodeCount - 1) / 2; //ilosc krawedzi w podgrafie, gdyby byl klika
int edgeSubCount = subGraph.getEdgeCount(); //ilosc krawedzi w podgrafie
int dif = edgeSubFullCount - edgeSubCount; //ilosc brakujacych krawedzi w podgrafie do bycia klika
//ilosc wierzcholkow w podgrafie
//nodes - ilosc wierzcholkow w podgrafie
//czy graf jest klika
double weight;
//w zaleznosci od tego czy podgraf jest klika czy nie dastaje odpowiednia
//ilosc punktow
if (dif == 0) {
weight = 100 * subNodeCount * edgeSubCount;
} else {
//jezeli graf nie jest klika to punktowany podgraf jest ten ktory
//posiada jak najmniej wierzchołkow z jak najwieksza lisoscia krawedzi
//czyli punktowany jes podgraf ktory jest najblizszy klice
weight = 10*(nodeCount - subNodeCount) * edgeSubCount / (dif * subNodeCount);
}
//wzor obliczajacy dostosowanie
double rating = weight * subNodeCount;
if (rating < 0) {
rating = 0;
}
ind.setFitness(rating);
}
}
public int[] getHashTab() {
return HashTab;
}
public Node[] getNodeTab() {
return nodeTab;
}
}
+361
View File
@@ -0,0 +1,361 @@
package genetic;
import java.beans.PropertyChangeEvent;
import java.util.Collections;
import java.util.LinkedList;
import Graph.Edge;
import Graph.Node;
import edu.uci.ics.jung.graph.Graph;
import gui.JDialogSolution;
import gui.JPanelChart;
import gui.Jung;
import java.beans.PropertyChangeListener;
import java.lang.Void;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
public class Genetic extends SwingWorker<Boolean, String> implements PropertyChangeListener {
private LinkedList<Indyvidual> oldPop;
private LinkedList<Indyvidual> tmpPop;
private LinkedList<Indyvidual> newPop;
private Graph<Node, Edge> graph;
int currGener;
//pola klas
private PreSelection preSelect;
private Crossing cross;
private Mutation mut;
private Fitness fit;
private Statistics stat;
private PostSelection postSelect;
//pola paramatrow dla klas
int popSize;
int nodes; //ilosc wierzcholkow=wielkosc tablicy
double mutProb;
double crossProb;
int preSelectType;
int crossType;
int postSelectType;
int continueType;
int iteration;
int i;
private Komparator<Indyvidual> komp;
private Jung jung;
private static boolean isWorking = false;
private JDialogSolution solution;
private Node[] nodeTab; //tablica wierzcho³kow grafu
private int HashTab[]; //tablica odwzoruwujaca nr wierzcho³ka numer w tablicy nodeTab[]
private String action;
private int initPopvar;
private boolean pause=false;
double bestValue; //najlepsza wartosc
int iterChanged; //iteracja w ktorej zmienila sie najlepsza wartosc
int refresh;
public Genetic(Graph<Node, Edge> _graph, int _popSize, double _mutProb, double _crosProb, int _preSelect,
int _crossTyp, int _postSelect, int _iteration, JPanelChart _panel, Jung _jung,
JDialogSolution _solution, int _contType, int _refresh) {
solution = _solution;
graph = _graph;
nodes = graph.getVertexCount();
currGener = 0;
oldPop = new LinkedList<Indyvidual>();
iteration = _iteration;
popSize = _popSize;
mutProb = _mutProb;
crossProb = _crosProb;
preSelectType = _preSelect;
crossType = _crossTyp;
postSelectType = _postSelect;
jung = _jung;
preSelect = new PreSelection(preSelectType);
cross = new Crossing(crossType, crossProb, popSize);
mut = new Mutation(mutProb);
fit = new Fitness(graph);
stat = new Statistics(_panel);
postSelect = new PostSelection(postSelectType);
komp = new Komparator<Indyvidual>();
nodeTab = new Node[graph.getVertexCount()];
nodeTab = graph.getVertices().toArray(nodeTab);
HashTab = new int[graph.getVertexCount()];
//zmienna do status bara
action = "";
addPropertyChangeListener(this);
continueType = _contType;
bestValue=0;
iterChanged=0;
refresh = _refresh;
}
private void initPop() {
boolean done = true;
solution.getFrame().getjProgressBar().setIndeterminate(true);
action = "Initializing the population...";
initPopvar = 0;
oldPop.clear();
for (int i = 0; i < popSize; i++) {
Indyvidual osobnik = new Indyvidual(nodes);
osobnik.init();
oldPop.add(osobnik);
}
initPopvar++;
action = "Initializing the population " + initPopvar;
solution.getFrame().getjProgressBar().setString(action);
fit.fitness(oldPop);
Collections.sort(oldPop, komp);
solution.getFrame().getjProgressBar().setIndeterminate(false);
}
@Override
protected Boolean doInBackground() throws Exception {
isWorking = true;
setProgress(0);
i = 0;
initPop();
int shown = 0;
HashTab = fit.getHashTab();
action = "Runing...";
//gdzies jest b³ad bo bez tego powinno dzia³aæ
solution.reInitDialog();//bez
solution.goUpdate();//bez
solution.stopUpdate();//bez
boolean stop = true;
if (continueType==2 || continueType==3)
solution.getFrame().getjProgressBar().setIndeterminate(true);
while (stop)
//for (;i<iteration;i++)
{
if (continueType==1)
setProgress( 100*i/iteration);
//publish(dupa);
tmpPop = preSelect.selection(oldPop);
Collections.sort(tmpPop, komp);
newPop = cross.crossing(tmpPop);
mut.mutate(newPop);
fit.fitness(newPop);
Collections.sort(newPop, komp);
stat.findStat(newPop);
stat.toPanel(i);
while (pause) {
try {
Thread.sleep(500); // half a second
} catch (InterruptedException e) {
}
}
if (shown * refresh == i) {
// deselect();
if (solution.getFrame().getjPanelControl().getjCheckBoxShowSolution().isSelected()) {
solution.goUpdate();
}
printVertex taskPrint = new printVertex(newPop);
taskPrint.execute();
shown++;
}
i++;
oldPop = postSelect.postSelection(oldPop, newPop); //postselekcja
//oldPop = newPop;
stop = continueAlgo();
//System.out.println("Stop " + stop + " " + iterChanged);
}
solution.stopUpdate();
printVertex taskPrint = new printVertex(newPop);
taskPrint.execute();
isWorking = false;
solution.getFrame().getjProgressBar().setIndeterminate(false);
setProgress( 100);
JOptionPane.showMessageDialog(null, "Done");
if (solution.getControls().getjCheckBoxShowSolution().isSelected()) {
solution.setVisible(true);
solution.reInitDialog();
}
action = "Done";
return true;
}
public void myStop() {
i = iteration + 10;
JOptionPane.showMessageDialog(null, "Stoped");
if (solution.getControls().getjCheckBoxShowSolution().isSelected()) {
solution.setVisible(true);
solution.reInitDialog();
}
action = "Done";
}
public void printPop() {
for (int i = 0; i < popSize; i++) {
//newPop.get(i).printTab();
//.println(newPop.get(i).getFitness());
// System.out.println();
}
//System.out.println(graph.toString());
//System.out.println(graph.getVertexCount());
}
private boolean continueAlgo()
{
boolean contValue = true;
switch (continueType)
{
case 1:
{
//System.out.println("Case 1");
contValue = iterCont();
break;
}
case 2:
{
//System.out.println("Case 2");
return changeCont();
//break;
}
case 3:
{
//System.out.println("Case 3");
contValue = (iterCont() && changeCont());
break;
}
}
return contValue;
}
private boolean iterCont()
{
if (i<iteration)
return true;
else
return false;
}
private boolean changeCont()
{
//System.out.println(iterChanged);
if (oldPop.getFirst().getFitness()==bestValue)
{
iterChanged++;
}
else
{
iterChanged=0;
bestValue=oldPop.getFirst().getFitness();
}
if (iterChanged>=100 || action.equals("Done"))
return false;
return true;
}
//funkcja ktora ktora zaznacza najlepsze rozwiazanie na gówynym grafie
class printVertex extends SwingWorker<Void, Void> {
LinkedList<Indyvidual> pop;
public printVertex(LinkedList<Indyvidual> _pop) {
pop = _pop;
}
@Override
protected Void doInBackground() {
if (pop != null) {
int best = stat.getMax();
Indyvidual ind = pop.get(best);
boolean[] chrom = ind.getChromosome();
for (int i = 0; i < chrom.length; i++) {
//odznaczenie wszystkich wierzcho³ków
nodeTab[HashTab[i]].setSelected(false);
//zaznczenie najlepszego osbnika
if (chrom[i] == true) {
nodeTab[HashTab[i]].setSelected(true);
}
}
jung.getVv().repaint();
return null;
}
return null;
}
}
private void deselect() {
for (int i = 0; i < nodeTab.length; i++) {
nodeTab[i].setSelected(false);
}
jung.getVv().repaint();
}
static public boolean isIsWorking() {
return isWorking;
}
static public void setIsWorking(boolean _isWorking) {
isWorking = _isWorking;
}
public LinkedList<Indyvidual> getNewPop() {
return newPop;
}
public Statistics getStat() {
return stat;
}
public Fitness getFit() {
return fit;
}
public boolean isPause() {
return pause;
}
public void setPause(boolean pause) {
this.pause = pause;
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
//solution.getFrame().getjProgressBar().setStringPainted(true);
//solution.getFrame().getjProgressBar().setString(action);
if ("progress".equals(evt.getPropertyName()))
solution.getFrame().getjProgressBar().setValue((Integer)evt.getNewValue());
}
}
+65
View File
@@ -0,0 +1,65 @@
package genetic;
import java.util.Random;
public class Indyvidual
{
private boolean chromosome[]; //chromosom
private double fitness; //dostosowanie osobnika
private int nodes; //dlugosc chromosomu
public Indyvidual(int _nodes)
{
nodes = _nodes;
chromosome = new boolean [nodes];
fitness = 0;
}
public void setChromosome(boolean chrom[])
{
chromosome = chrom;
}
public boolean[] getChromosome()
{
return chromosome;
}
public void setFitness(double fit)
{
fitness = fit;
}
public double getFitness()
{
return fitness;
}
public void init()
{
Random r = new Random();
for (int i=0;i<nodes;i++)
{
chromosome[r.nextInt(nodes)]=r.nextBoolean();
}
}
//testowa do wypisywania chromosomu
public void printTab()
{
for (int i=0;i<nodes;i++)
{
if (chromosome[i]==true)
System.out.print("1 ");
else
System.out.print("0 ");
}
System.out.println();
}
public void printFit()
{
// System.out.println("Dopasowanie - " + fitness);
}
}
+18
View File
@@ -0,0 +1,18 @@
package genetic;
import java.util.Comparator;
public class Komparator<T> implements Comparator<Indyvidual> {
public int compare(Indyvidual o1, Indyvidual o2)
{
if (o1.getFitness()>o2.getFitness())
return -1;
if (o1.getFitness()==o2.getFitness())
return 0;
if (o1.getFitness()<o2.getFitness())
return 1;
return 0;
}
}
+63
View File
@@ -0,0 +1,63 @@
package genetic;
import java.util.LinkedList;
import java.util.Random;
public class Mutation
{
private double mutationProb;
private int count;
public Mutation(double prob)
{
mutationProb = prob;
count=0;
}
public void setMutationProb(double prob)
{
mutationProb = prob;
}
private void mutateOne(Indyvidual ind)
{
boolean[] chrom = ind.getChromosome();
int nodes = chrom.length;
Random r = new Random();
for (int i=0;i<nodes;i++)
{
double prob = r.nextDouble();
if (prob<=mutationProb)
{
chrom[i]=!chrom[i];
count++;
}
}
//System.out.println("Mutowan - " + count);
}
public void mutate(LinkedList<Indyvidual> pop)
{
int size = pop.size();
for (int i=1;i<size;i++)
mutateOne(pop.get(i));
/*
int size = pop.size();
Random r = new Random();
double prob;
for (int i = 0; i < 10; i++) {
prob = r.nextDouble();
if (prob<=mutationProb)
mutateOne(pop.get(r.nextInt(size)));
}
*
*/
}
}
+81
View File
@@ -0,0 +1,81 @@
package genetic;
import java.util.LinkedList;
public class PostSelection
{
private int postSelectType;
private int popSize;
public PostSelection(int type)
{
postSelectType = type;
}
public LinkedList<Indyvidual> postSelection(LinkedList<Indyvidual> oldPop, LinkedList<Indyvidual> newPop)
{
LinkedList<Indyvidual> curPop = new LinkedList<Indyvidual>();
popSize = newPop.size();
switch(postSelectType)
{
case 1:
{
curPop = fullReplace(newPop);
break;
}
case 2:
{
curPop = eliteReplace(oldPop, newPop);
break;
}
}
return curPop;
}
private LinkedList<Indyvidual> fullReplace(LinkedList<Indyvidual> pop)
{
LinkedList<Indyvidual> curPop = new LinkedList<Indyvidual>();
curPop = pop;
return curPop;
}
private LinkedList<Indyvidual> partialReplace(LinkedList<Indyvidual> oldPop, LinkedList<Indyvidual> newPop)
{
LinkedList<Indyvidual> curPop = new LinkedList<Indyvidual>();
return curPop;
}
private LinkedList<Indyvidual> eliteReplace(LinkedList<Indyvidual> oldPop, LinkedList<Indyvidual> newPop)
{
LinkedList<Indyvidual> curPop = new LinkedList<Indyvidual>();
int oldInd=0;
int newInd=0;
int i=0;
//System.out.println("OldPop "+oldPop.size());
//System.out.println("NewPop "+newPop.size());
while(i<popSize)
{
if (oldPop.get(oldInd).getFitness()>newPop.get(newInd).getFitness() && oldInd<oldPop.size())
{
curPop.add(oldPop.get(oldInd));
oldInd++;
}
else
{
curPop.add(newPop.get(newInd));
newInd++;
}
i++;
//System.out.println("Petla " + i + " OldPop");
}
//System.out.println("CurPop " + curPop.size());
return curPop;
}
}
+249
View File
@@ -0,0 +1,249 @@
package genetic;
import java.util.LinkedList;
import java.util.Random;
public class PreSelection
{
private int selectType;
public PreSelection(int type)
{
selectType = type;
}
public void setSelectType(int type)
{
selectType = type;
}
public LinkedList<Indyvidual> selection(LinkedList<Indyvidual> pop)
{
LinkedList<Indyvidual> newPop = new LinkedList<Indyvidual>();
switch (selectType)
{
case 1:
{
newPop = rouletteSelection(pop);
break;
}
case 2:
{
newPop = tournamentSelection(pop);
break;
}
}
//System.out.println("Po preselekcji " + newPop.size());
return newPop;
}
private LinkedList<Indyvidual> rouletteSelection(LinkedList<Indyvidual> pop)
{
LinkedList<Indyvidual> newPop = new LinkedList<Indyvidual>();
int popSize = pop.size();
//sumowanie przystosowan
double sumFit = 0;
for (int i=0;i<popSize;i++)
{
sumFit+=pop.get(i).getFitness();
}
//System.out.println("Suma przystosowan - " + sumFit);
//usuniecie osobnikow o przystosowaniu 0
//delZero(pop);
//losowanie kolejnych osobnikow do nowej populacji
Random r = new Random();
for (int i=0;i<popSize;i++)
{
double rand = r.nextDouble(); //losowanie liczby do pomnozenia przez sume przystosowan
double choice = rand * sumFit; //obliczanie miejsca, w ktorym bedzie osobnik do nowej populacji
double check = 0; //suma dostosowan osobnikow, ktore przeszly przez petle while
int ind=0;
while (check<choice && ind<pop.size()-1)
{
check+=pop.get(ind).getFitness();
ind++;
}
newPop.add(pop.get(ind));
}
return newPop;
}
private LinkedList<Indyvidual> tournamentSelection(LinkedList<Indyvidual> pop)
{
System.out.println("dziala " + pop.size());
LinkedList<Indyvidual> newPop = new LinkedList<Indyvidual>();
int popSize = pop.size();
int tabCount = popSize/4; //tyle tablic 4-osobnikowych
int newPopInd=0;
LinkedList<Indyvidual[]> tabList = new LinkedList<Indyvidual[]>();
int check=tabCount;
for (int i=0;i<tabCount;i++)
{
Indyvidual[] tmpTab = new Indyvidual[4];
tmpTab[0]=pop.get(newPopInd);
tmpTab[1]=pop.get(newPopInd+1);
tmpTab[2]=pop.get(newPopInd+2);
tmpTab[3]=pop.get(newPopInd+3);
newPopInd=newPopInd+4;
tabList.add(tmpTab);
}
if (tabCount*4!=popSize)
{
int size=popSize-newPopInd;
Indyvidual[] tmpTab = new Indyvidual[size];
for (int i=0;i<size;i++)
{
tmpTab[i]=pop.get(newPopInd+i);
}
tabList.add(tmpTab);
check++;
}
for (int i=0;i<tabCount;i++)
{
Indyvidual[] tmpTab=tabList.get(i);
double max1=tmpTab[0].getFitness();
double max2=tmpTab[1].getFitness();
int add1=0;
int add2=1;
if (max2>max1)
{
double tmp=max1;
max1=max2;
max2=tmp;
tmp=add1;
add1=add2;
add2=(int) tmp;
}
for (int g=2;g<4;g++)
{
if (tmpTab[g].getFitness()>max2)
{
if (tmpTab[g].getFitness()>max1)
{
max2=max1;
add2=add1;
max1=tmpTab[g].getFitness();
add1=g;
}
else
{
max2=tmpTab[g].getFitness();
add2=g;
}
}
}
newPop.add(tmpTab[add1]);
newPop.add(tmpTab[add2]);
//System.out.println("Max1 "+max1 + " Add1 " + add1);
//System.out.println("Max1 "+max2 + " Add2 " + add2);
//System.out.println();
}
if (tabCount!=check)
{
Indyvidual[] tmpTab=tabList.getLast();
if (tmpTab.length==1)
{
newPop.add(tmpTab[0]);
}
if (tmpTab.length==2)
{
newPop.add(tmpTab[0]);
newPop.add(tmpTab[1]);
}
if (tmpTab.length>2)
{
double max1=tmpTab[0].getFitness();
double max2=tmpTab[1].getFitness();
int add1=0;
int add2=1;
if (max2>max1)
{
double tmp=max1;
max1=max2;
max2=tmp;
tmp=add1;
add1=add2;
add2=(int) tmp;
}
for (int g=2;g<tmpTab.length;g++)
{
if (tmpTab[g].getFitness()>max2)
{
if (tmpTab[g].getFitness()>max1)
{
max2=max1;
add2=add1;
max1=tmpTab[g].getFitness();
add1=g;
}
else
{
max2=tmpTab[g].getFitness();
add2=g;
}
}
}
newPop.add(tmpTab[add1]);
newPop.add(tmpTab[add2]);
//System.out.println("Max1 "+max1 + " Add1 " + add1);
//System.out.println("Max1 "+max2 + " Add2 " + add2);
//System.out.println();
}
}
else
System.out.println("takie same");
System.out.println("Nowa populacja " + newPop.size());
/*
for (int k=0;k<check;k++)
{
for (int l=0;l<tabList.get(k).length;l++)
{
System.out.println(tabList.get(k)[l].getFitness());
}
System.out.println();
}
*/
return newPop;
}
private void delZero(LinkedList<Indyvidual> pop)
{
int j=0;
while (j<pop.size())
{
if (pop.get(j).getFitness()==0)
pop.remove(j);
else
j++;
}
}
}
+110
View File
@@ -0,0 +1,110 @@
package genetic;
import gui.JPanelChart;
import java.util.LinkedList;
public class Statistics
{
//private LinkedList<Double> minList;
//private LinkedList<Double> avgList;
//private LinkedList<Double> maxList;
//private int maxInd; //indeks w populacji osobnika o najwyzszym przystosowaniu
private JPanelChart panel;
double minFit;
double avgFit;
double maxFit;
public Statistics(JPanelChart _panel)
{
//minList = new LinkedList<Double>();
//avgList = new LinkedList<Double>();
//maxList = new LinkedList<Double>();
panel = _panel;
}
/*
public LinkedList<Double> getMinList()
{
return minList;
}
public LinkedList<Double> getAvgList()
{
return avgList;
}
public LinkedList<Double> getMaxList()
{
return maxList;
}
*/
public void findStat(LinkedList<Indyvidual> pop)
{
findMin(pop);
findAvg(pop);
findMax(pop);
}
private void findMin(LinkedList<Indyvidual> pop)
{
minFit=pop.getLast().getFitness();
/*
for (int i=1;i<pop.size();i++)
{
if (pop.get(i).getFitness()<min)
min=pop.get(i).getFitness();
}
*/
// System.out.println("Fitness Min " + minFit);
//minList.add(min);
}
private void findAvg(LinkedList<Indyvidual> pop)
{
double sum=0;
for (int i=0;i<pop.size();i++)
{
sum+=pop.get(i).getFitness();
}
avgFit = sum/pop.size();
//System.out.println("Fitness avg " + avgFit);
//avgList.add(avg);
}
private void findMax(LinkedList<Indyvidual> pop)
{
maxFit = pop.getFirst().getFitness();
/*
int maxI=0;
for (int i=1;i<pop.size();i++)
{
if (pop.get(i).getFitness()>max)
{
max=pop.get(i).getFitness();
maxI = i;
}
}
*/
//System.out.println("Fitness Max " + maxFit);
//System.out.println();
//maxList.add(max);
//maxInd = maxI;
}
public int getMax()
{
return 0;
}
public void toPanel(int iter)
{
panel.setMin(minFit, iter);
panel.setAv(avgFit, iter);
panel.setMax(maxFit, iter);
}
}
+198
View File
@@ -0,0 +1,198 @@
package genetic;
import java.util.Collections;
import java.util.LinkedList;
import Graph.Edge;
import Graph.Node;
import edu.uci.ics.jung.graph.Graph;
import gui.Jung;
import gui.Frame;
public class Tester
{
public static void main(String[] args)
{
//genTest();
//preSelectTest();
//mutTest();
//crosTest();
postSelect();
}
private static void postSelect()
{
int postSelectType = 2;
int popSize=10;
PostSelection postSelect = new PostSelection(postSelectType);
Komparator<Indyvidual> komp = new Komparator<Indyvidual>();
Frame fr = new Frame();
Jung jung = fr.getJung();
Graph<Node, Edge> graph = jung.generateGraph(5, 10, 10);
Fitness fit = new Fitness(graph);
LinkedList<Indyvidual> pop = new LinkedList<Indyvidual>();
for (int i=0;i<popSize;i++)
{
Indyvidual osobnik = new Indyvidual(15);
osobnik.init();
pop.add(osobnik);
}
fit.fitness(pop);
Collections.sort(pop, komp);
LinkedList<Indyvidual> pop2 = new LinkedList<Indyvidual>();
for (int i=0;i<popSize;i++)
{
Indyvidual osobnik = new Indyvidual(15);
osobnik.init();
pop2.add(osobnik);
}
fit.fitness(pop2);
Collections.sort(pop2, komp);
for (int i=0;i<popSize;i++)
{
System.out.println("Pop " + pop.get(i).getFitness());
}
System.out.println();
for (int i=0;i<popSize;i++)
{
System.out.println("Pop2 " + pop2.get(i).getFitness());
}
System.out.println();
LinkedList<Indyvidual> pop3 = postSelect.postSelection(pop, pop2);
for (int i=0;i<popSize;i++)
{
System.out.println("Pop3 " + pop3.get(i).getFitness());
}
}
private static void preSelectTest()
{
int selectType = 2;
int popSize = 8;
PreSelection preSel = new PreSelection(selectType);
Frame fr = new Frame();
Jung jung = fr.getJung();
Graph<Node, Edge> graph = jung.generateGraph(5, 10, 10);
LinkedList<Indyvidual> pop = new LinkedList<Indyvidual>();
for (int i=0;i<popSize;i++)
{
Indyvidual osobnik = new Indyvidual(15);
osobnik.init();
pop.add(osobnik);
}
//System.out.println("popSize" + pop.size());
Fitness fit = new Fitness(graph);
fit.fitness(pop);
//System.out.println("ok2");
for (int i=0;i<popSize;i++)
{
//System.out.println("Lol");
//pop.get(i).printFit();
}
//System.out.println("przed selekcja");
LinkedList<Indyvidual> newPop = preSel.selection(pop);
//System.out.println("po selekcja");
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println("Populcja po preselekcji " + popSize);
for (int i=0;i<popSize;i++)
{
//newPop.get(i).printFit();
}
}
private static void genTest()
{
int popSize=200;
double mutProb=0.05;
double crosProb=0.7;
int preSelect=1;
int crossTyp=1;
int postSelect=1;
Frame fr = new Frame();
Jung jung = fr.getJung();
Graph<Node, Edge> graph = jung.generateGraph(5, 10, 10);
//Genetic gen = new Genetic(graph, popSize, mutProb, crosProb, preSelect, crossTyp, postSelect, null);
for (int i=0;i<100;i++)
// gen.goAlgo();
//gen.printPop();
System.out.println("Done");
System.out.println("Wierzcholkow - " + graph.getVertexCount());
}
private static void mutTest()
{
int popSize = 1;
double mutationProb = 0.05;
Mutation mut = new Mutation(mutationProb);
LinkedList<Indyvidual> pop = new LinkedList<Indyvidual>();
for (int i=0;i<popSize;i++)
{
Indyvidual osobnik = new Indyvidual(20);
osobnik.init();
pop.add(osobnik);
osobnik.printTab();
}
mut.mutate(pop);
for (int i=0;i<popSize;i++)
pop.get(i).printTab();
}
private static void crosTest()
{
int popSize = 3;
double crossingProb = 0.8;
int crossingType = 1;
LinkedList<Indyvidual> pop = new LinkedList<Indyvidual>();
for (int i=0;i<popSize;i++)
{
Indyvidual osobnik = new Indyvidual(20);
osobnik.init();
pop.add(osobnik);
osobnik.printTab();
}
Crossing cros = new Crossing(crossingType,crossingProb,popSize);
LinkedList<Indyvidual> newPop = cros.crossing(pop);
System.out.println("Nowa populacja");
for (int i=0;i<popSize;i++)
newPop.get(i).printTab();
}
}
+42
View File
@@ -0,0 +1,42 @@
/*
*
* TODO lepsze zapisywanie w TXT
*/
package gui;
import java.io.File;
import javax.swing.filechooser.FileFilter;
public class FileFilterTxt extends FileFilter {
//akceptuje pliki tylko z roszerzeniem txts
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
String extension =f.getName();
int i=extension.lastIndexOf(".");
String txt=extension.substring(i+1,extension.length());
if (extension != null)
{
if (txt.equals("txt"))
{
return true;
} else
{
return false;
}
}
return false;
}
//opis filtru w oknie open/save
public String getDescription() {
return "Text file";
}
}
+446
View File
@@ -0,0 +1,446 @@
package gui;
import Graph.Node;
import GraphIO.Io;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import java.awt.event.InputEvent;
import java.io.FilePermission;
import java.security.AccessController;
import org.apache.commons.collections15.Transformer;
public class Frame extends JFrame implements WindowListener {
private JMenuBar JMenuBar1;
private JMenu JMenuView;
private JMenu JMenuFile;
private JMenu JMenuHelp;
private JMenuItem ItemOpen;
private JMenuItem ItemSave;
private JMenuItem ItemExit;
private JMenuItem ItemGenerate;
private JMenuItem ItemClearGraph;
private JMenuItem ItemAbout;
private JPanelControl jPanelControl;
private JComboBox jComboLayout;
private JComboBox modeMenu;
private JPanel jPanelJungControls;
private JDialogGenerate jDialogGenerate;
private JProgressBar jProgressBar;
private JCheckBoxMenuItem jItemVertexCount;
private JCheckBoxMenuItem jItemAutoFit;
Jung jung;
JFileChooser file;
public Frame() {
super("klika");
// sprawdza czy system na ktorym dzia³a program nie jest przypadkiem
// linuxem jezeli nie to zmienia wyglad okien ala windows
if (!System.getProperty("os.name").toString().equals("Linux")) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(Frame.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
jung = new Jung();
jung.init();
file = new JFileChooser();
file.setFileFilter(new FileFilterTxt());
init();
//TODO ustawic background na vv
// BufferedImage image;
// image=ImageIO.read(new File("DNA.jpg"));
jung.getVv().setBackground(Color.getHSBColor(0.5f, 0.05f, 0.95f));
setIconImage(new ImageIcon("icon.png").getImage());
jDialogGenerate = new JDialogGenerate(this, jung, jComboLayout);
}
private void init() {
//elemety gui
JMenuBar1 = new JMenuBar();
JMenuView = new JMenu("Widok");
JMenuFile = new JMenu("Graf");
JMenuHelp = new JMenu("Pomoc");
ItemOpen = new JMenuItem("Otwórz...", new ImageIcon("open.png"));
ItemSave = new JMenuItem("Zapisz...", new ImageIcon("Save.png"));
ItemExit = new JMenuItem("Wyjscie");
ItemAbout = new JMenuItem("O programie...");
jItemVertexCount = new JCheckBoxMenuItem("Liczba wierzcho³ków");
jItemAutoFit = new JCheckBoxMenuItem("Automatyczne dopasowanie wierzcho³ków");
ItemClearGraph = new JMenuItem("WyczyϾ");
ItemGenerate = new JMenuItem("Generuj nowy graf...");
jPanelControl = new JPanelControl(this);
jProgressBar = new JProgressBar();
addWindowListener(this);
setLayout(new BorderLayout());
JMenuFile.add(ItemOpen);
ItemOpen.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
ItemOpenAction();
}
});
JMenuFile.add(ItemSave);
ItemSave.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ItemSaveAction();
}
});
JMenuFile.addSeparator();
JMenuFile.add(ItemClearGraph);
ItemClearGraph.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
jung.setG(jung.generateGraph(0, 0, 0));
jung.getVv().getGraphLayout().setGraph(jung.getG());
jDialogGenerate.getJung().setG(jung.generateGraph(0, 0, 0));
jPanelControl.getChart().setNewSeries();
jDialogGenerate.getJung().getVv().repaint();
jung.getVv().repaint();
}
});
JMenuFile.add(ItemGenerate);
ItemGenerate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!genetic.Genetic.isIsWorking()) {
jDialogGenerate.setVisible(true);
} else {
JOptionPane.showMessageDialog(rootPane, "Aby wygenerowaæ nowy graf najpierw zatrzymaj algorytm");
}
}
});
JMenuFile.addSeparator();
JMenuFile.add(ItemExit);
ItemExit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ItemExitAction();
}
});
//zmiana edycji
JMenu jungItem = jung.getGm().getModeMenu();
jungItem.setIcon(null);
jungItem.setPreferredSize(new Dimension(120, 20));
jungItem.setText("Tryb kursora");
jItemVertexCount.setSelected(true);
jItemAutoFit.setSelected(true);
JMenuView.add(jungItem);
JMenuView.addSeparator();
JMenuView.add(jItemVertexCount);
JMenuView.add(jItemAutoFit);
//ustawanie podpisu pod wierzcho³ek
jItemVertexCount.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (jItemVertexCount.isSelected()) {
jung.getVv().getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
} else {
jung.getVv().getRenderContext().setVertexLabelTransformer(new Transformer<Node, String>() {
@Override
public String transform(Node i) {
return "";
}
});
}
jung.getVv().repaint();
}
});
ItemAbout.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JDialog okno = new JDialog();
okno.setVisible(true);
Box box = Box.createVerticalBox();
JLabel label = new JLabel("Jest to program znajduj¹cy maksymaln¹ klike w grafie ");
JLabel label4=new JLabel("nie skierowanym za pomoc¹ algorytmu genetycznego.");
JLabel label1 = new JLabel("Program wykonali:");
JLabel label2 = new JLabel("Mariusz Pacek");
JLabel label3 = new JLabel("Zbigniew Pieprzak");
JLabel label5 = new JLabel("");
JLabel label6 = new JLabel("");
label.setAlignmentX(CENTER_ALIGNMENT);
label1.setAlignmentX(CENTER_ALIGNMENT);
label2.setAlignmentX(CENTER_ALIGNMENT);
label3.setAlignmentX(CENTER_ALIGNMENT);
label4.setAlignmentX(CENTER_ALIGNMENT);
label5.setAlignmentX(CENTER_ALIGNMENT);
label6.setAlignmentX(CENTER_ALIGNMENT);
box.add(label5);
box.add(Box.createRigidArea(new Dimension(10, 10)));
box.add(label);
box.add(Box.createRigidArea(new Dimension(10, 10)));
box.add(label4);
box.add(Box.createRigidArea(new Dimension(10, 10)));
box.add(new JToolBar.Separator());
box.add(label5);
box.add(Box.createRigidArea(new Dimension(10, 10)));
box.add(label1);
box.add(Box.createRigidArea(new Dimension(10, 10)));
box.add(label6);
box.add(Box.createRigidArea(new Dimension(10, 10)));
box.add(label2);
box.add(Box.createRigidArea(new Dimension(10, 10)));
box.add(label3);
box.setBorder(BorderFactory.createTitledBorder("O programie:"));
okno.setMinimumSize(new Dimension(450, 300));
okno.add(box);
}
});
JMenuHelp.add(ItemAbout);
JMenuBar1.add(JMenuFile);
JMenuBar1.add(JMenuView);
JMenuBar1.add(JMenuHelp);
jPanelControl.setBorder(BorderFactory.createEtchedBorder());
JPanel jpanel2 = new JPanel();
jpanel2.add(jPanelControl);
jpanel2.setBorder(BorderFactory.createEmptyBorder(0, 0, 1, 1));
// jPanelControl.setBackground(Color.getHSBColor());
add(jPanelControl, BorderLayout.WEST);
setJMenuBar(JMenuBar1);
setJungControl();
getContentPane().add(jung.getVv());
JLabel jLabel = new JLabel("STATUS:");
// jLabel.add
JPanel jPanel = new JPanel();
jPanel.setLayout(new BoxLayout(jPanel, BoxLayout.LINE_AXIS));
//jPanel.add(jLabel,BorderLayout.EAST);
jPanel.setBorder(BorderFactory.createEtchedBorder());
add(jPanel, BorderLayout.SOUTH);
//skroty klawiszowe
ItemOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK));
ItemExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, InputEvent.CTRL_MASK));
ItemSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));
jProgressBar.setAlignmentX(RIGHT_ALIGNMENT);
JSeparator jSeparator = new JSeparator(JSeparator.VERTICAL);
jSeparator.setAlignmentX(RIGHT_ALIGNMENT);
jPanel.add(Box.createHorizontalGlue());
// jPanel.add(jSeparator,Box.RIGHT_ALIGNMENT);
jPanel.add(Box.createRigidArea(new Dimension(4, 0)));
jPanel.add(jProgressBar, Box.RIGHT_ALIGNMENT);
jProgressBar.setMinimumSize(new Dimension(200, 20));
jProgressBar.setMaximumSize(new Dimension(200, 20));
// jProgressBar.add(jPanelControl.gen);
//zmiana rozmiaru okna powoduje przerysowanie grafu a to powduje zakutu
//lizowanie jego wygladu i dopasowanie sie do okna
this.addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(ComponentEvent e) {
if (jItemAutoFit.isSelected()) {
jung.changeLayout(jComboLayout.getSelectedIndex());
}
}
});
}
protected void ItemExitAction() {
int ans = JOptionPane.showConfirmDialog(this, "Napewno chcesz wyjϾ z programu ?", "Exit?",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, new ImageIcon("Exit.png"));
if (ans == JOptionPane.YES_OPTION) {
// Zamkniêcie okna
if (jPanelControl.getGen() != null) {
jPanelControl.getGen().myStop();
}
removeAll();
dispose();
}
}
protected void ItemOpenAction() {
if (!genetic.Genetic.isIsWorking()) {
int returnVal = file.showOpenDialog(Frame.this);
try {
AccessController.checkPermission(new FilePermission(file.getSelectedFile().getAbsolutePath(), "read,write"));
} catch (SecurityException e) {
}
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
jung.setG(Io.getGraph(file.getSelectedFile(), jung));
jung.changeLayout(jComboLayout.getSelectedIndex());
} catch (IOException ex) {
Logger.getLogger(Frame.class.getName()).log(Level.SEVERE, null, ex);
}
}
} else {
JOptionPane.showMessageDialog(rootPane, "Aby otworzyc plik najpierw zatrzymaj algorytm");
}
}
protected void ItemSaveAction() {
int returnVal = file.showSaveDialog(Frame.this);
try {
AccessController.checkPermission(new FilePermission(file.getSelectedFile().getAbsolutePath(), "read,write"));
} catch (SecurityException e) {
}
if (returnVal == JFileChooser.APPROVE_OPTION) {
File f = file.getSelectedFile();
try {
String string = f.getPath();
if (!string.contains(".txt")) {
string = string + ".txt";
}
Io.saveGraph(jung.getG(), string);
} catch (IOException ex) {
Logger.getLogger(Frame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void setJungControl() {
String[] comboList = {"FRLayout2", "KKLayout", "CircleLayout",
"ISOMLayout", "SpringLayout", "SpringLayout2"};
jComboLayout = new JComboBox(comboList);
jComboLayout.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
jung.changeLayout(cb.getSelectedIndex());
}
});
// Border border = BorderFactory.createTitledBorder(
// BorderFactory.createRaisedBevelBorder(), "Edit graph layout and mouse mode:");
modeMenu = jung.getGm().getModeComboBox();
jPanelJungControls = new JPanel();
jPanelJungControls.setLayout(new BoxLayout(jPanelJungControls, BoxLayout.LINE_AXIS));
//jPanelJungControls.setBorder(BorderFactory.createRaisedBevelBorder());
jComboLayout.setBorder(BorderFactory.createTitledBorder("Uk³ad grafu"));
modeMenu.setBorder(BorderFactory.createTitledBorder("Tryby kursora:"));
Box box = Box.createHorizontalBox();
box.add(jComboLayout);
box.add(Box.createRigidArea(new Dimension(10, 10)));
box.add(modeMenu);
box.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
jPanelJungControls.add(box);
//jPanelJungControls.setBorder(BorderFactory.createRaisedBevelBorder());
//dolny panel do zmiany wugladu i edycji grafu
jPanelJungControls.setAlignmentY(BOTTOM_ALIGNMENT);
jPanelJungControls.setMaximumSize(new Dimension(350, 60));
jPanelControl.add(Box.createVerticalGlue());
jPanelControl.add(jPanelJungControls, BorderLayout.LINE_END);
}
/**
* @param args
*/
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
Frame newframe = new Frame();
newframe.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
newframe.setSize(1024, 768);
newframe.setLocationRelativeTo(null);
newframe.setVisible(true);
}
});
}
@Override
public void windowClosing(WindowEvent e) {
ItemExitAction();
}
@Override
public void windowOpened(WindowEvent e) {
}
@Override
public void windowClosed(WindowEvent e) {
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowActivated(WindowEvent e) {
}
@Override
public void windowDeactivated(WindowEvent e) {
}
public Jung getJung() {
return jung;
}
public JPanelControl getjPanelControl() {
return jPanelControl;
}
public JProgressBar getjProgressBar() {
return jProgressBar;
}
}
+446
View File
@@ -0,0 +1,446 @@
package gui;
import Graph.Node;
import GraphIO.Io;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import java.awt.event.InputEvent;
import java.io.FilePermission;
import java.security.AccessController;
import org.apache.commons.collections15.Transformer;
public class Frame extends JFrame implements WindowListener {
private JMenuBar JMenuBar1;
private JMenu JMenuView;
private JMenu JMenuFile;
private JMenu JMenuHelp;
private JMenuItem ItemOpen;
private JMenuItem ItemSave;
private JMenuItem ItemExit;
private JMenuItem ItemGenerate;
private JMenuItem ItemClearGraph;
private JMenuItem ItemAbout;
private JPanelControl jPanelControl;
private JComboBox jComboLayout;
private JComboBox modeMenu;
private JPanel jPanelJungControls;
private JDialogGenerate jDialogGenerate;
private JProgressBar jProgressBar;
private JCheckBoxMenuItem jItemVertexCount;
private JCheckBoxMenuItem jItemAutoFit;
Jung jung;
JFileChooser file;
public Frame() {
super("klika");
// sprawdza czy system na ktorym dzia³a program nie jest przypadkiem
// linuxem jezeli nie to zmienia wyglad okien ala windows
if (!System.getProperty("os.name").toString().equals("Linux")) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(Frame.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
jung = new Jung();
jung.init();
file = new JFileChooser();
file.setFileFilter(new FileFilterTxt());
init();
//TODO ustawic background na vv
// BufferedImage image;
// image=ImageIO.read(new File("DNA.jpg"));
jung.getVv().setBackground(Color.getHSBColor(0.5f, 0.05f, 0.95f));
setIconImage(new ImageIcon("icon.png").getImage());
jDialogGenerate = new JDialogGenerate(this, jung, jComboLayout);
}
private void init() {
//elemety gui
JMenuBar1 = new JMenuBar();
JMenuView = new JMenu("Widok");
JMenuFile = new JMenu("Graf");
JMenuHelp = new JMenu("Pomoc");
ItemOpen = new JMenuItem("Otwórz...", new ImageIcon("open.png"));
ItemSave = new JMenuItem("Zapisz...", new ImageIcon("Save.png"));
ItemExit = new JMenuItem("Wyjscie");
ItemAbout = new JMenuItem("O programie...");
jItemVertexCount = new JCheckBoxMenuItem("Liczba wierzcho³ków");
jItemAutoFit = new JCheckBoxMenuItem("Automatyczne dopasowanie wierzcho³ków");
ItemClearGraph = new JMenuItem("WyczyϾ");
ItemGenerate = new JMenuItem("Generuj nowy graf...");
jPanelControl = new JPanelControl(this);
jProgressBar = new JProgressBar();
addWindowListener(this);
setLayout(new BorderLayout());
JMenuFile.add(ItemOpen);
ItemOpen.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
ItemOpenAction();
}
});
JMenuFile.add(ItemSave);
ItemSave.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ItemSaveAction();
}
});
JMenuFile.addSeparator();
JMenuFile.add(ItemClearGraph);
ItemClearGraph.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
jung.setG(jung.generateGraph(0, 0, 0));
jung.getVv().getGraphLayout().setGraph(jung.getG());
jDialogGenerate.getJung().setG(jung.generateGraph(0, 0, 0));
jPanelControl.getChart().setNewSeries();
jDialogGenerate.getJung().getVv().repaint();
jung.getVv().repaint();
}
});
JMenuFile.add(ItemGenerate);
ItemGenerate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!genetic.Genetic.isIsWorking()) {
jDialogGenerate.setVisible(true);
} else {
JOptionPane.showMessageDialog(rootPane, "Aby wygenerowaæ nowy graf najpierw zatrzymaj algorytm");
}
}
});
JMenuFile.addSeparator();
JMenuFile.add(ItemExit);
ItemExit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ItemExitAction();
}
});
//zmiana edycji
JMenu jungItem = jung.getGm().getModeMenu();
jungItem.setIcon(null);
jungItem.setPreferredSize(new Dimension(120, 20));
jungItem.setText("Tryb kursora");
jItemVertexCount.setSelected(true);
jItemAutoFit.setSelected(true);
JMenuView.add(jungItem);
JMenuView.addSeparator();
JMenuView.add(jItemVertexCount);
JMenuView.add(jItemAutoFit);
//ustawanie podpisu pod wierzcho³ek
jItemVertexCount.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (jItemVertexCount.isSelected()) {
jung.getVv().getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
} else {
jung.getVv().getRenderContext().setVertexLabelTransformer(new Transformer<Node, String>() {
@Override
public String transform(Node i) {
return "";
}
});
}
jung.getVv().repaint();
}
});
ItemAbout.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JDialog okno = new JDialog();
okno.setVisible(true);
Box box = Box.createVerticalBox();
JLabel label = new JLabel("Jest to program znajduj¹cy maksymaln¹ klike w grafie ");
JLabel label4=new JLabel("nie skierowanym za pomoc¹ algorytmu genetycznego.");
JLabel label1 = new JLabel("Program wykonali:");
JLabel label2 = new JLabel("Mariusz Pacek");
JLabel label3 = new JLabel("Zbigniew Pieprzak");
JLabel label5 = new JLabel("");
JLabel label6 = new JLabel("");
label.setAlignmentX(CENTER_ALIGNMENT);
label1.setAlignmentX(CENTER_ALIGNMENT);
label2.setAlignmentX(CENTER_ALIGNMENT);
label3.setAlignmentX(CENTER_ALIGNMENT);
label4.setAlignmentX(CENTER_ALIGNMENT);
label5.setAlignmentX(CENTER_ALIGNMENT);
label6.setAlignmentX(CENTER_ALIGNMENT);
box.add(label5);
box.add(Box.createRigidArea(new Dimension(10, 10)));
box.add(label);
box.add(Box.createRigidArea(new Dimension(10, 10)));
box.add(label4);
box.add(Box.createRigidArea(new Dimension(10, 10)));
box.add(new JToolBar.Separator());
box.add(label5);
box.add(Box.createRigidArea(new Dimension(10, 10)));
box.add(label1);
box.add(Box.createRigidArea(new Dimension(10, 10)));
box.add(label6);
box.add(Box.createRigidArea(new Dimension(10, 10)));
box.add(label2);
box.add(Box.createRigidArea(new Dimension(10, 10)));
box.add(label3);
box.setBorder(BorderFactory.createTitledBorder("O programie:"));
okno.setMinimumSize(new Dimension(450, 300));
okno.add(box);
}
});
JMenuHelp.add(ItemAbout);
JMenuBar1.add(JMenuFile);
JMenuBar1.add(JMenuView);
JMenuBar1.add(JMenuHelp);
jPanelControl.setBorder(BorderFactory.createEtchedBorder());
JPanel jpanel2 = new JPanel();
jpanel2.add(jPanelControl);
jpanel2.setBorder(BorderFactory.createEmptyBorder(0, 0, 1, 1));
// jPanelControl.setBackground(Color.getHSBColor());
add(jPanelControl, BorderLayout.WEST);
setJMenuBar(JMenuBar1);
setJungControl();
getContentPane().add(jung.getVv());
JLabel jLabel = new JLabel("STATUS:");
// jLabel.add
JPanel jPanel = new JPanel();
jPanel.setLayout(new BoxLayout(jPanel, BoxLayout.LINE_AXIS));
//jPanel.add(jLabel,BorderLayout.EAST);
jPanel.setBorder(BorderFactory.createEtchedBorder());
add(jPanel, BorderLayout.SOUTH);
//skroty klawiszowe
ItemOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK));
ItemExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, InputEvent.CTRL_MASK));
ItemSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));
jProgressBar.setAlignmentX(RIGHT_ALIGNMENT);
JSeparator jSeparator = new JSeparator(JSeparator.VERTICAL);
jSeparator.setAlignmentX(RIGHT_ALIGNMENT);
jPanel.add(Box.createHorizontalGlue());
// jPanel.add(jSeparator,Box.RIGHT_ALIGNMENT);
jPanel.add(Box.createRigidArea(new Dimension(4, 0)));
jPanel.add(jProgressBar, Box.RIGHT_ALIGNMENT);
jProgressBar.setMinimumSize(new Dimension(200, 20));
jProgressBar.setMaximumSize(new Dimension(200, 20));
// jProgressBar.add(jPanelControl.gen);
//zmiana rozmiaru okna powoduje przerysowanie grafu a to powduje zakutu
//lizowanie jego wygladu i dopasowanie sie do okna
this.addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(ComponentEvent e) {
if (jItemAutoFit.isSelected()) {
jung.changeLayout(jComboLayout.getSelectedIndex());
}
}
});
}
protected void ItemExitAction() {
int ans = JOptionPane.showConfirmDialog(this, "Napewno chcesz wyjϾ z programu ?", "Exit?",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, new ImageIcon("Exit.png"));
if (ans == JOptionPane.YES_OPTION) {
// Zamkniêcie okna
if (jPanelControl.getGen() != null) {
jPanelControl.getGen().myStop();
}
removeAll();
dispose();
}
}
protected void ItemOpenAction() {
if (!genetic.Genetic.isIsWorking()) {
int returnVal = file.showOpenDialog(Frame.this);
try {
AccessController.checkPermission(new FilePermission(file.getSelectedFile().getAbsolutePath(), "read,write"));
} catch (SecurityException e) {
}
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
jung.setG(Io.getGraph(file.getSelectedFile(), jung));
jung.changeLayout(jComboLayout.getSelectedIndex());
} catch (IOException ex) {
Logger.getLogger(Frame.class.getName()).log(Level.SEVERE, null, ex);
}
}
} else {
JOptionPane.showMessageDialog(rootPane, "Aby otworzyc plik najpierw zatrzymaj algorytm");
}
}
protected void ItemSaveAction() {
int returnVal = file.showSaveDialog(Frame.this);
try {
AccessController.checkPermission(new FilePermission(file.getSelectedFile().getAbsolutePath(), "read,write"));
} catch (SecurityException e) {
}
if (returnVal == JFileChooser.APPROVE_OPTION) {
File f = file.getSelectedFile();
try {
String string = f.getPath();
if (!string.contains(".txt")) {
string = string + ".txt";
}
Io.saveGraph(jung.getG(), string);
} catch (IOException ex) {
Logger.getLogger(Frame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void setJungControl() {
String[] comboList = {"FRLayout2", "KKLayout", "CircleLayout",
"ISOMLayout", "SpringLayout", "SpringLayout2"};
jComboLayout = new JComboBox(comboList);
jComboLayout.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
jung.changeLayout(cb.getSelectedIndex());
}
});
// Border border = BorderFactory.createTitledBorder(
// BorderFactory.createRaisedBevelBorder(), "Edit graph layout and mouse mode:");
modeMenu = jung.getGm().getModeComboBox();
jPanelJungControls = new JPanel();
jPanelJungControls.setLayout(new BoxLayout(jPanelJungControls, BoxLayout.LINE_AXIS));
//jPanelJungControls.setBorder(BorderFactory.createRaisedBevelBorder());
jComboLayout.setBorder(BorderFactory.createTitledBorder("Uk³ad grafu"));
modeMenu.setBorder(BorderFactory.createTitledBorder("Tryby kursora:"));
Box box = Box.createHorizontalBox();
box.add(jComboLayout);
box.add(Box.createRigidArea(new Dimension(10, 10)));
box.add(modeMenu);
box.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
jPanelJungControls.add(box);
//jPanelJungControls.setBorder(BorderFactory.createRaisedBevelBorder());
//dolny panel do zmiany wugladu i edycji grafu
jPanelJungControls.setAlignmentY(BOTTOM_ALIGNMENT);
jPanelJungControls.setMaximumSize(new Dimension(350, 60));
jPanelControl.add(Box.createVerticalGlue());
jPanelControl.add(jPanelJungControls, BorderLayout.LINE_END);
}
/**
* @param args
*/
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
Frame newframe = new Frame();
newframe.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
newframe.setSize(1024, 768);
newframe.setLocationRelativeTo(null);
newframe.setVisible(true);
}
});
}
@Override
public void windowClosing(WindowEvent e) {
ItemExitAction();
}
@Override
public void windowOpened(WindowEvent e) {
}
@Override
public void windowClosed(WindowEvent e) {
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowActivated(WindowEvent e) {
}
@Override
public void windowDeactivated(WindowEvent e) {
}
public Jung getJung() {
return jung;
}
public JPanelControl getjPanelControl() {
return jPanelControl;
}
public JProgressBar getjProgressBar() {
return jProgressBar;
}
}
+183
View File
@@ -0,0 +1,183 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package gui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
import javax.swing.border.Border;
class JDialogGenerate extends JDialog {
private JComboBox jComboBoxLayout;
private JButton JButtonClose;
private JButton JButtonGenerate;
private JLabel jLabelClicque;
private JLabel jLabelNode;
private JLabel jLabelEdge;
private JSpinner jSpinnerClicque;
private JSpinner jSpinnerNode;
private JSpinner jSpinnerEdge;
private Jung jung;
private Frame frame;
public JDialogGenerate(Frame owener, Jung ju, JComboBox comboBox) {
super(owener,"Generowanie grafu");
jComboBoxLayout = comboBox;
jung = ju;
frame=owener;
JButtonClose = new JButton("Zamknij");
JButtonGenerate = new JButton("Generuj");
jLabelClicque = new JLabel("Rozmiar kliki");
jLabelNode = new JLabel("Liczba dodatkowych wierzcho³ków", JLabel.LEFT);
jLabelEdge = new JLabel("Liczba dodatkowych krawêdzi", JLabel.LEFT);
SpinnerNumberModel model = new SpinnerNumberModel(3, 3, 1000, 1);
jSpinnerClicque = new JSpinner(model);
model = new SpinnerNumberModel(0, 0, 1000, 1);
jSpinnerEdge = new JSpinner(model);
model = new SpinnerNumberModel(0, 0, 1000, 1);
jSpinnerNode = new JSpinner(model);
setjDialog();
}
private void setjDialog() {
Border border = BorderFactory.createTitledBorder("Graf");
setSize(300, 200);
setMinimumSize(new Dimension(250, 200));
setLayout(new BorderLayout());
jSpinnerClicque.setAlignmentX(RIGHT_ALIGNMENT);
jSpinnerEdge.setAlignmentX(RIGHT_ALIGNMENT);
jSpinnerNode.setAlignmentX(RIGHT_ALIGNMENT);
JPanel panel = new JPanel();
JPanel buttons = new JPanel();
buttons.setLayout(new BoxLayout(buttons, BoxLayout.LINE_AXIS));
buttons.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
buttons.add(Box.createHorizontalGlue());
buttons.add(JButtonGenerate);
buttons.add(Box.createRigidArea(new Dimension(10, 0)));
buttons.add(JButtonClose);
panel.setBorder(border);
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
Box box1 = Box.createHorizontalBox();
box1.setAlignmentX(LEFT_ALIGNMENT);
box1.setBorder(BorderFactory.createEmptyBorder(5, 10, 0, 0));
// box1.add(Box.createRigidArea(new Dimension(10,0)));
box1.add(jLabelClicque);
box1.add(Box.createRigidArea(new Dimension(5, 0)));
box1.add(jSpinnerClicque);
panel.add(box1);
Box box2 = Box.createHorizontalBox();
box2.setAlignmentX(LEFT_ALIGNMENT);
box2.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 0));
// box2.add(Box.createVerticalGlue());
box2.add(jLabelNode);
box2.add(Box.createRigidArea(new Dimension(10, 0)));
box2.add(jSpinnerNode);
panel.add(box2);
Box box3 = Box.createHorizontalBox();
box3.setAlignmentX(LEFT_ALIGNMENT);
box3.setBorder(BorderFactory.createEmptyBorder(0, 10, 5, 0));
// box3.add(Box.createVerticalGlue());
box3.add(jLabelEdge);
box3.add(Box.createRigidArea(new Dimension(10, 0)));
box3.add(jSpinnerEdge);
panel.add(box3);
jSpinnerClicque.setMaximumSize(new Dimension(70, 20));
jSpinnerNode.setMaximumSize(new Dimension(70, 20));
jSpinnerEdge.setMaximumSize(new Dimension(70, 20));
add(panel, BorderLayout.CENTER);
JButtonClose.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
JButtonGenerate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JButtonGenerateAction();
}
});
JButtonGenerate.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
JButtonGenerate.doClick();
System.out.println("KLawisz");
}
}
});
add(buttons, BorderLayout.PAGE_END);
addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
JButtonGenerate.doClick();
}
}
});
setFocusable(true); //po tym dzia³aja klawisze na danym oknie czyli
//na generowaniu grafu
}
public Jung getJung() {
return jung;
}
private void JButtonGenerateAction() {
//if (!jSpinnerClicque) {
jung.setG(jung.generateGraph((Integer)jSpinnerClicque.getValue(),
(Integer)jSpinnerNode.getValue(),(Integer)jSpinnerEdge.getValue()));
jung.getVv().getGraphLayout().setGraph(jung.getG());
jung.changeLayout(jComboBoxLayout.getSelectedIndex());
jung.getVv().repaint();
setVisible(false);
// }
}
}
+249
View File
@@ -0,0 +1,249 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*
*/
package gui;
import Graph.Edge;
import Graph.Node;
import GraphIO.Io;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.UndirectedSparseGraph;
import edu.uci.ics.jung.graph.util.EdgeType;
import edu.uci.ics.jung.visualization.control.ModalGraphMouse.Mode;
import genetic.Indyvidual;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.JMenuBar;
/**
*
* @author - Klasa ktora wyœwietla rozwiazanie algorytmu Genetic
*/
public class JDialogSolution extends JDialog {
private Jung newjung;
private JPanelControl controls;
private Graph<Node, Edge> graph;
private int HashTab[];
private Node nodeTab[];
private Graph<Node, Edge> subGraph;
private JComboBox jComboLayout;
private JComboBox modeMenu;
private JPanel jPanelJungControls;
private Frame frame;
private JLabel jLabelNodeCount;
private Task updateDialog;
public JDialogSolution(Frame _frame, JPanelControl _controls) {
super(_frame, "Rozwi¹zanie");
newjung = new Jung();
newjung.init();
controls = _controls;
frame = _frame;
newjung.setG(new UndirectedSparseGraph<Node, Edge>());
add(newjung.getVv(), BorderLayout.CENTER);
updateDialog = new Task();
//zmiana layoutu grafu
String[] comboList = {"FRLayout2", "KKLayout", "CircleLayout",
"ISOMLayout", "FRLayout2", "SpringLayout2",
"SpringLayout", "StaticLayout", "SpringLayout2"};
jComboLayout = new JComboBox(comboList);
jComboLayout.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
newjung.changeLayout(cb.getSelectedIndex());
}
});
//zmiana rodzaju edycji grafu
modeMenu = newjung.getGm().getModeComboBox();
jPanelJungControls = new JPanel();
jPanelJungControls.setLayout(new BoxLayout(jPanelJungControls, BoxLayout.LINE_AXIS));
jComboLayout.setBorder(BorderFactory.createTitledBorder("Uk³ad grafu:"));
modeMenu.setBorder(BorderFactory.createTitledBorder("tryb myszki:"));
Box box = Box.createHorizontalBox();
box.add(jComboLayout);
box.add(Box.createRigidArea(new Dimension(10, 10)));
box.add(modeMenu);
box.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
jLabelNodeCount = new JLabel();
jLabelNodeCount.setFont(jLabelNodeCount.getFont().deriveFont(20));
jLabelNodeCount.setBorder(BorderFactory.createEmptyBorder(4, 10, 2, 60));
Box box1 = Box.createHorizontalBox();
box1.add(jLabelNodeCount);
box1.setBorder(BorderFactory.createTitledBorder("Iloœæ wierzcho³ków:"));
jPanelJungControls.add(box1);
jPanelJungControls.add(Box.createRigidArea(new Dimension(5, 0)));
jPanelJungControls.add(box);
jPanelJungControls.setBorder(BorderFactory.createRaisedBevelBorder());
add(jPanelJungControls, BorderLayout.SOUTH);
setMinimumSize(new Dimension(400, 400));
Toolkit tool=Toolkit.getDefaultToolkit();
Dimension dim=tool.getScreenSize();
dim.width=dim.width-400;
dim.height=0;
setLocation(dim.width, dim.height);
//dodanie MenuBara z funkcja zapisu rozwiazania do pliku
JMenuBar menu = new JMenuBar();
JMenuItem ItemSave = new JMenuItem("Zapisz rozwi¹zanie");
menu.add(ItemSave);
ItemSave.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (subGraph == null || subGraph.getVertexCount() < 1) {
JOptionPane.showMessageDialog(frame, "Brak grafu do zapisania");
} else {
saveSolution();
}
}
});
setJMenuBar(menu);
newjung.getGm().setMode(Mode.TRANSFORMING);
}
public void reInitDialog() {
//pobranie gotowych tablic z klasy genetic w celu poleszenia wydajnosci
//generowania grafu
frame.getjProgressBar().setString("Preparing solution..");
nodeTab = controls.getGen().getFit().getNodeTab();
HashTab = controls.getGen().getFit().getHashTab();
graph = frame.jung.getG();
//jezeli algorytm nie wygeneriwa³ zadnej populacji to wyswietl puste okno
//w przeciwnym wypadku wygeneruj rozwiazanie
if (controls.getGen().getNewPop() != null) {
subGraph = buildGraph(graph);
jLabelNodeCount.setText(Integer.toString(subGraph.getVertexCount()));
newjung.setG(subGraph);
newjung.changeLayout(1);
jComboLayout.setSelectedIndex(1);
} else {
newjung.setG(new UndirectedSparseGraph<Node, Edge>());
newjung.changeLayout(1);
jComboLayout.setSelectedIndex(1);
jLabelNodeCount.setText("0");
}
frame.getjProgressBar().setString("Done");
}
private Graph buildGraph(Graph<Node, Edge> graph) {
//najlepsze rozwiazanie z ostatniej populacji
int best = controls.getGen().getStat().getMax();
//pobranie najlepszego osobnika
Indyvidual ind = controls.getGen().getNewPop().get(best);
boolean[] chrom = ind.getChromosome();
subGraph = new UndirectedSparseGraph<Node, Edge>();
//dodanie wierzcho³kow ktore jest rozwiazaniem
for (int i = 0; i < chrom.length; i++) {
if (chrom[i] == true) {
subGraph.addVertex(new Node(i));
}
}
Node[] nodeTab2 = new Node[subGraph.getVertexCount()];
subGraph.getVertices().toArray(nodeTab2); //tablica nowych wierzcholkow
for (int i = 0; i < nodeTab2.length; i++) {
for (int j = i + 1; j < nodeTab2.length; j++) {
//szukanie krawedzi pomiedzy wierzcho³kami
Edge e = (Edge) graph.findEdge(
nodeTab[HashTab[nodeTab2[i].getId()]],
nodeTab[HashTab[nodeTab2[j].getId()]]);
if (e != null) {
//System.out.println("Dodawanie krawedzi");
subGraph.addEdge(e, nodeTab2[i], nodeTab2[j], EdgeType.UNDIRECTED);
}
}
// System.out.println();
}
return subGraph;
}
public Frame getFrame() {
return frame;
}
public JPanelControl getControls() {
return controls;
}
//zadanie ktore jest wykonywane w celu wyswietlenia bierzacego najlepszego
//osbnika
class Task extends SwingWorker<Void, Void> {
@Override
protected Void doInBackground() {
nodeTab = controls.getGen().getFit().getNodeTab();
HashTab = controls.getGen().getFit().getHashTab();
graph = frame.jung.getG();
subGraph = buildGraph(graph);
jLabelNodeCount.setText(Integer.toString(subGraph.getVertexCount()));
newjung.setG(subGraph);
newjung.changeLayout(jComboLayout.getSelectedIndex());
return null;
}
}
public void goUpdate() {
if (updateDialog.isDone()) {
updateDialog = new Task();
updateDialog.execute();
}
}
public void stopUpdate() {
boolean cancel = updateDialog.cancel(true);
}
protected void saveSolution() {
JFileChooser file = new JFileChooser();
int returnVal = file.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File f = file.getSelectedFile();
try {
String string = f.getPath();
if(!string.contains(".txt"))
{
string = string + ".txt";
}
Io.saveGraph(subGraph, string);
} catch (IOException ex) {
Logger.getLogger(Frame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
+101
View File
@@ -0,0 +1,101 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
n */
package gui;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
/**
*
* @author -
*/
public class JPanelChart extends JPanel {
JFreeChart chart;
private XYSeries average;
private XYSeries maximum;
private XYSeries minimum;
private String title;
private String xTitle;
private String yTitle;
ChartPanel chartPanel;
public JPanelChart(String title,String yTitle , String xTitle) {
super(new BorderLayout());
average = new XYSeries("average");
maximum = new XYSeries("maximum");
minimum = new XYSeries("minimum");
XYSeriesCollection dataset = new XYSeriesCollection();
average.add(0, 0);
minimum.add(0, 0);
maximum.add(0, 0);
dataset.addSeries(minimum);
dataset.addSeries(average);
dataset.addSeries(maximum);
chart = ChartFactory.createXYLineChart(title, yTitle, xTitle, dataset, PlotOrientation.VERTICAL, true, true, true);
chartPanel = new ChartPanel(chart);
add(chartPanel);
}
//Nowa seria danych
public void setNewSeries() {
average.clear();
minimum.clear();
maximum.clear();
average.add(0, 0);
minimum.add(0, 0);
maximum.add(0, 0);
}
public void setMin(double min, int population) {
minimum.add(population, min);
}
public void setMax(double max, int population) {
maximum.add(population, max);
}
public void setAv(double av, int population) {
average.add(population, av);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getxTitle() {
return xTitle;
}
public void setxTitle(String xTitle) {
this.xTitle = xTitle;
}
public String getyTitle() {
return yTitle;
}
public void setyTitle(String yTitle) {
this.yTitle = yTitle;
}
public JFreeChart getChart() {
return chart;
}
}
+324
View File
@@ -0,0 +1,324 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
* TODO przerobienie ca³ego panelu na ³adniejszy
*/
package gui;
import genetic.Genetic;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import javax.swing.*;
/**
*
* @author -
*/
public class JPanelControl extends JPanel {
private JButton JButtonSolve;
private JButton JButtonStop;
private JButton JButtonPause;
private JDialog JDialogFitness;
private JPanelChart chart;
private JPanel tmp;
private int i = 0;
private Frame frame;
private Genetic gen;
private JSpinner jSpinnerPopSize;
private JSpinner jSpinnerMutProb;
private JSpinner jSpinnerCrosProb;
private JSpinner jSpinnerCrosType;
private JSpinner jSpinnerPostSlect;
private JSpinner jSpinnerPreSelect;
private JSpinner jSpinnerIteration;
private JSpinner jSpinnerContinueType;
private JSpinner jSpinnerRefresh;
private JCheckBox jCheckBoxShowSolution;
private JCheckBox jCheckBoxShowChart;
private JSpinner test;
private Timer t;
private JDialogSolution jDSolution;
private JComboBox jComboPreSelect;
private JComboBox jComboPostSelect;
private JComboBox jComboCrossType;
private JComboBox jComboContinueType;
public JPanelControl(Frame _frame) {
frame = _frame;
JDialogFitness = new JDialog(_frame);
jDSolution = new JDialogSolution(frame, this);
JButtonSolve = new JButton("Start");
JButtonPause = new JButton("Pause");
JButtonStop = new JButton("Stop");
chart = new JPanelChart("Fitness function", "Populacja", "WartoϾ");
chart.setBorder(BorderFactory.createTitledBorder("Wykres"));
jCheckBoxShowChart = new JCheckBox("Schowaj wykres");
jCheckBoxShowSolution = new JCheckBox("Schowaj rozwi¹zanie");
// setBorder(BorderFactory.createRaisedBevelBorder());
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
SpinnerModel model = new SpinnerNumberModel(new Integer(400), new Integer(10), new Integer(2000), new Integer(1));
jSpinnerPopSize = new JSpinner(model);
model = new SpinnerNumberModel(70, 0, 100, 1);
jSpinnerCrosProb = new JSpinner(model);
String[] tabCross = {"Jednopunktowe z 2 potomkami", "Jednopunktowe z 1 potomkiem", "Wielopunktowe z 2 potomkami", "Wielopunktowe z 1 potomkiem"};
jComboCrossType = new JComboBox(tabCross);
String[] tabPost = {"Zastêpywanie ca³kowite", "Selekcja elitarna"};
jComboPostSelect = new JComboBox(tabPost);
String[] tabPre = {"Selekcja ruletkowa", "Selekcja turniejowa"};
jComboPreSelect = new JComboBox(tabPre);
model = new SpinnerNumberModel(1, 0, 100, 1);
jSpinnerMutProb = new JSpinner(model);
model = new SpinnerNumberModel(1000, 1, 1000000, 1);
jSpinnerIteration = new JSpinner(model);
model = new SpinnerNumberModel(3, 1, 3, 1);
jSpinnerContinueType = new JSpinner(model);
//jComboContinueType
String[] tabCont = {"Limit iteracji", "Niezmiennoœæ rozwi¹zania", "Podwójne zakoñczenie"};
jComboContinueType = new JComboBox(tabCont);
model = new SpinnerNumberModel(10, 1, 50, 1);
jSpinnerRefresh = new JSpinner(model);
Dimension dimensionSmall = new Dimension(80, 20);
Dimension dimensionBig = new Dimension(140,20);
jSpinnerIteration.setMaximumSize(dimensionSmall);
jSpinnerCrosProb.setMaximumSize(new Dimension(70, 20));
jComboCrossType.setMaximumSize(new Dimension(190, 20));
jSpinnerMutProb.setMaximumSize(dimensionSmall);
jSpinnerPopSize.setMaximumSize(dimensionSmall);
jComboPostSelect.setMaximumSize(dimensionBig);
jComboPreSelect.setMaximumSize(dimensionBig);
jComboContinueType.setMaximumSize(new Dimension(160, 20));
jSpinnerRefresh.setMaximumSize(dimensionSmall);
Box box0 = Box.createVerticalBox();
box0.setBorder(BorderFactory.createEmptyBorder(5, 10, 10, 5));
box0.add(jSpinnerIteration);
Box box1 = Box.createHorizontalBox();
box1.setBorder(BorderFactory.createEmptyBorder(5, 10, 10, 5));
box1.add(JButtonSolve);
box1.add(Box.createRigidArea(new Dimension(10, 10)));
box1.add(JButtonStop);
box1.add(Box.createRigidArea(new Dimension(10, 10)));
box1.add(JButtonPause);
Box box2 = Box.createHorizontalBox();
box2.setBorder(BorderFactory.createEmptyBorder(5, 10, 10, 5));
box2.add(jSpinnerPopSize);
box2.add(Box.createRigidArea(new Dimension(10, 10)));
box2.add(jSpinnerMutProb);
Box box3 = Box.createHorizontalBox();
box3.setBorder(BorderFactory.createEmptyBorder(5, 10, 10, 5));
box3.add(jComboPreSelect);
box3.add(Box.createRigidArea(new Dimension(10, 10)));
box3.add(jComboPostSelect);
Box box4 = Box.createHorizontalBox();
box4.setBorder(BorderFactory.createEmptyBorder(5, 10, 10, 5));
box4.add(jComboCrossType);
box4.add(Box.createRigidArea(new Dimension(10, 10)));
box4.add(jSpinnerCrosProb);
Box box5 = Box.createHorizontalBox();
box5.setBorder(BorderFactory.createEmptyBorder(5, 10, 10, 5));
box5.add(jCheckBoxShowChart);
box5.add(Box.createRigidArea(new Dimension(10, 10)));
box5.add(jCheckBoxShowSolution);
Box box6 = Box.createHorizontalBox();
box6.setBorder(BorderFactory.createEmptyBorder(5, 10, 10, 5));
box6.add(jComboContinueType);
box6.add(Box.createRigidArea(new Dimension(10, 10)));
box6.add(jSpinnerRefresh);
JLabel lab0 = new JLabel("IloϾ iteracji");
lab0.setAlignmentX(JLabel.CENTER_ALIGNMENT);
add(lab0);
box0.setAlignmentX(CENTER_ALIGNMENT);
add(box0);
JLabel lab2 = new JLabel("Wielkoœæ populacji i prawdopodobieñstwo mutacji");
lab2.setAlignmentX(JLabel.CENTER_ALIGNMENT);
add(lab2, JLabel.CENTER_ALIGNMENT);
box2.setAlignmentX(CENTER_ALIGNMENT);
add(box2, Box.CENTER_ALIGNMENT);
JLabel lab3 = new JLabel("Preselekcja i postselekcja");
lab3.setAlignmentX(CENTER_ALIGNMENT);
add(lab3);
box3.setAlignmentX(CENTER_ALIGNMENT);
add(box3, Box.CENTER_ALIGNMENT);
JLabel lab4 = new JLabel("Typ i prawdopodobieñstwo krzyzowania");
lab4.setAlignmentX(CENTER_ALIGNMENT);
add(lab4);
box4.setAlignmentX(CENTER_ALIGNMENT);
add(box4, Box.CENTER_ALIGNMENT);
JLabel lab6 = new JLabel("Typ zakoñczenia i czêstoœæ odœwie¿ania");
lab6.setAlignmentX(CENTER_ALIGNMENT);
add(lab6);
box6.setAlignmentX(CENTER_ALIGNMENT);
add(box6, Box.CENTER_ALIGNMENT);
JLabel lab5 = new JLabel("Ustawienia dodoatkowe");
lab5.setAlignmentX(CENTER_ALIGNMENT);
add(lab5);
box5.setAlignmentX(CENTER_ALIGNMENT);
add(box5, Box.CENTER_ALIGNMENT);
JLabel lab1 = new JLabel("Sterowanie");
lab1.setAlignmentX(CENTER_ALIGNMENT);
add(lab1);
box1.setAlignmentX(CENTER_ALIGNMENT);
add(box1);
jCheckBoxShowChart.setSelected(true);
jCheckBoxShowSolution.setSelected(true);
jCheckBoxShowChart.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (jCheckBoxShowChart.isSelected()) {
jCheckBoxShowChart.setText("Schowaj wykres");
if (frame.jung.getG().getVertexCount() != 0 && gen != null) {
JDialogFitness.setVisible(true);
}
} else {
jCheckBoxShowChart.setText("Poka¿ wykres");
JDialogFitness.setVisible(false);
}
}
});
jCheckBoxShowSolution.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (jCheckBoxShowSolution.isSelected()) {
jCheckBoxShowSolution.setText("Schowaj rozwi¹zanie");
if (frame.jung.getG().getVertexCount() != 0 && gen != null) {
jDSolution.setVisible(true);
jDSolution.reInitDialog();
}
} else {
jCheckBoxShowSolution.setText("Poka¿ rozwi¹zanie");
jDSolution.setVisible(false);
}
}
});
JDialogFitness.setLayout(new BorderLayout());
JDialogFitness.setMinimumSize(new Dimension(500, 400));
JDialogFitness.add(chart, BorderLayout.CENTER);
JButtonStop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (Genetic.isIsWorking()) {
gen.myStop();
}
}
});
JButtonPause.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (Genetic.isIsWorking()) {
if(gen.isPause())
{
gen.setPause(false);
JButtonPause.setBackground(null);
}
else
{
gen.setPause(true);
JButtonPause.setBackground(Color.red);
}
}
}
});
JButtonSolve.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JButtonSlove(e);
}
});
}
private void JButtonSlove(ActionEvent e) {
if (!Genetic.isIsWorking() && frame.getJung().getG().getVertexCount() != 0) {
if (jCheckBoxShowChart.isSelected()) {
JDialogFitness.setVisible(true);
}
if (jCheckBoxShowSolution.isSelected()) {
jDSolution.setVisible(true);
}
chart.setNewSeries();
int mutProb = (Integer) jSpinnerMutProb.getValue();
int crosProb = (Integer) jSpinnerCrosProb.getValue();
gen = new Genetic(frame.getJung().getG(), (Integer) jSpinnerPopSize.getValue(),
((double) mutProb) / 100, ((double) crosProb) / 100,
(Integer) jComboPreSelect.getSelectedIndex()+1, (Integer) jComboCrossType.getSelectedIndex()+1,
(Integer) jComboPostSelect.getSelectedIndex()+1,
(Integer) jSpinnerIteration.getValue(), chart, frame.getJung(), jDSolution,
(Integer) jComboContinueType.getSelectedIndex()+1, (Integer) jSpinnerRefresh.getValue());
// gen.start();
gen.execute();
} else {
if (frame.getJung().getG().getVertexCount() == 0) {
JOptionPane.showMessageDialog(frame, "Najpierw wygeneruj lub za³aduj graf");
} else {
}
}
}
public JCheckBox getjCheckBoxShowChart() {
return jCheckBoxShowChart;
}
public JCheckBox getjCheckBoxShowSolution() {
return jCheckBoxShowSolution;
}
public JPanelChart getChart() {
return chart;
}
public Genetic getGen() {
return gen;
}
}
+192
View File
@@ -0,0 +1,192 @@
package gui;
import Graph.Edge;
import Graph.EdgeFactory;
import Graph.Node;
import Graph.VertexFactory;
import edu.uci.ics.jung.algorithms.layout.*;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.UndirectedSparseGraph;
import edu.uci.ics.jung.graph.util.EdgeType;
import edu.uci.ics.jung.visualization.VisualizationViewer;
import edu.uci.ics.jung.visualization.control.EditingModalGraphMouse;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Paint;
import java.util.Random;
import org.apache.commons.collections15.Transformer;
/**
*
*
*/
public class Jung {
private Graph<Node, Edge> g;
private VisualizationViewer<Node, Edge> vv; //okno junga
private EditingModalGraphMouse gm;//edycja grafu
private VertexFactory newNode = null;
private EdgeFactory newEdge = null;
/**
* Creates a new instance of SimpleGraphView
*/
public Jung() {
// Graph<V, E> where V is the type of the vertices and E is the type of the edges
g = new UndirectedSparseGraph<Node, Edge>();
}
/**
* @param args the command line arguments
*/
protected void init() {
newNode = new VertexFactory();
newEdge = new EdgeFactory();
Transformer<Node, Paint> vertexColor = new Transformer<Node, Paint>() {
public Paint transform(Node i) {
if (i.isSelected() == true) {
return Color.GREEN;
}
return Color.RED;
}
};
//ustawianie wyglau grafu
Layout<Node, Edge> layout = new CircleLayout<Node, Edge>(g);
layout.setSize(new Dimension(100, 100));
vv = new VisualizationViewer<Node, Edge>(layout);
vv.setPreferredSize(new Dimension(100, 100));
//kolorowanie wierzcholkow
vv.getRenderContext().setVertexFillPaintTransformer(vertexColor);
//koloroawnie wierzcho³kow
vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
//ustaweinie etykety na krawedz
// vv.getRenderContext().setEdgeLabelTransformer(n )
//edycja myszka
gm = new EditingModalGraphMouse(vv.getRenderContext(), newNode, newEdge);
vv.setGraphMouse(gm);
}
//funkcja ktora ustawia mozliwosc dodawania dodatkowych wiercho³kow
public void changeLayout(int nazwa) {
switch (nazwa) {
case 0: {
vv.setGraphLayout(new FRLayout2<Node, Edge>(g));
break;
}
case 1: {
vv.setGraphLayout(new KKLayout<Node, Edge>(g));
break;
}
case 2: {
vv.setGraphLayout(new CircleLayout<Node, Edge>(g));
break;
}
case 3: {
vv.setGraphLayout(new ISOMLayout<Node, Edge>(g));
break;
}
case 4: {
vv.setGraphLayout(new SpringLayout<Node, Edge>(g));
break;
}
case 5: {
vv.setGraphLayout(new SpringLayout2<Node, Edge>(g));
break;
}
default:
break;
}
}
//genertor grafu
public Graph generateGraph(int cliqueSize, int randomNode, int randomEdge) {
Graph<Node, Edge> newG = new UndirectedSparseGraph<Node, Edge>();
newEdge.clear();
newNode.clear();
Node[] tabNode = new Node[cliqueSize + randomNode];
//tworzenie kliki
if (cliqueSize != 0 || cliqueSize != 1) {
for (int i = 0; i < cliqueSize; i++) {
newG.addVertex(newNode.create());
}
newG.getVertices().toArray(tabNode);
for (int i = 1; i < cliqueSize; i++) {
for (int j = i; j < cliqueSize; j++) {
newG.addEdge(newEdge.create(), tabNode[i - 1], tabNode[j],
EdgeType.UNDIRECTED);
}
}
}
Random rand = new Random();
//dodaje wierzocholki oraz tworzy z nim losowa krawedz
for (int i = 0; i < randomNode; i++) {
newG.getVertices().toArray(tabNode);
Node node = newNode.create();
newG.addVertex(node);
//if ((cliqueSize==0 & (i!=0 & i!=1)))
newG.addEdge(newEdge.create(), node, tabNode[rand.nextInt(cliqueSize
+ i - 1)], EdgeType.UNDIRECTED);
}
//tworzenie losowych krawedzi
for (int i = 0; i < randomEdge; i++) {
newG.addEdge(newEdge.create(), tabNode[rand.nextInt(cliqueSize +
randomNode - 2)], tabNode[rand.nextInt(cliqueSize +
randomNode - 2)], EdgeType.UNDIRECTED);
}
return newG;
}
public Graph<Node, Edge> getG() {
return g;
}
public void setG(Graph<Node, Edge> g) {
this.g = g;
}
public EditingModalGraphMouse getGm() {
return gm;
}
public void setGm(EditingModalGraphMouse gm) {
this.gm = gm;
}
public EdgeFactory getNewEdge() {
return newEdge;
}
public void setNewEdge(EdgeFactory newEdge) {
this.newEdge = newEdge;
}
public VertexFactory getNewNode() {
return newNode;
}
public void setNewNode(VertexFactory newNode) {
this.newNode = newNode;
}
public VisualizationViewer<Node, Edge> getVv() {
return vv;
}
public void setVv(VisualizationViewer<Node, Edge> vv) {
this.vv = vv;
}
}
+225
View File
@@ -0,0 +1,225 @@
package genetic;
import java.util.LinkedList;
import java.util.Random;
public class Crossing
{
private int crossingType;
private int count;
private double crossingProb;
private int popSize;
public Crossing (int type, double prob, int size)
{
crossingType = type;
count=0;
crossingProb = prob;
popSize = size;
}
public void setCrossingType(int type)
{
crossingType = type;
}
public int getCount()
{
return count;
}
public void setCrossingProb(double prob)
{
crossingProb = prob;
}
public LinkedList<Indyvidual> crossing(LinkedList<Indyvidual> pop)
{
LinkedList<Indyvidual> newPop = null;
count=0;
switch (crossingType)
{
case 1:
{
newPop = onePointTwoChildren(pop);
break;
}
case 2:
{
newPop = onePointOneChild(pop);
break;
}
case 3:
{
newPop = manyPointsOneChild(pop);
break;
}
case 4:
{
newPop = manyPointsTwoChildren(pop);
break;
}
}
return newPop;
}
private LinkedList<Indyvidual> onePointTwoChildren(LinkedList<Indyvidual> pop)
{
int nodes = pop.get(0).getChromosome().length; //dlugosc tablicy chromosomow
Random r = new Random();
int div = r.nextInt(nodes); //punkt podzialu
int size = 0; //rozmiar aktualnej,nowej populacji
//System.out.println("Podzial - " + div);
LinkedList<Indyvidual> newPop = new LinkedList<Indyvidual>(); //lista na nowa populacje
while (size<popSize)
{
double prob = r.nextDouble();
if (prob<=crossingProb)
{
count++;
int par1 = r.nextInt(popSize);
int par2 = r.nextInt(popSize);
boolean[] chrom1 = new boolean[nodes];
boolean[] chrom2 = new boolean[nodes];
for (int i=0;i<div;i++)
chrom1[i]=pop.get(par1).getChromosome()[i];
for (int i=div;i<nodes;i++)
chrom1[i]=pop.get(par2).getChromosome()[i];
for (int i=0;i<div;i++)
chrom2[i]=pop.get(par2).getChromosome()[i];
for (int i=div;i<nodes;i++)
chrom2[i]=pop.get(par1).getChromosome()[i];
Indyvidual child1 = new Indyvidual(nodes);
child1.setChromosome(chrom1);
Indyvidual child2 = new Indyvidual(nodes);
child2.setChromosome(chrom2);
if (size<popSize)
{
newPop.add(child1);
size++;
}
if (size<popSize)
{
newPop.add(child2);
size++;
}
}
}
return newPop;
}
private LinkedList<Indyvidual> onePointOneChild(LinkedList<Indyvidual> pop)
{
int nodes = pop.get(0).getChromosome().length; //dlugosc tablicy chromosomow
Random r = new Random();
int div = r.nextInt(nodes); //punkt podzialu
int size = 0; //rozmiar aktualnej,nowej populacji
System.out.println("Podzial - " + div);
LinkedList<Indyvidual> newPop = new LinkedList<Indyvidual>(); //lista na nowa populacje
while (size<popSize)
{
double prob = r.nextDouble();
if (prob<=crossingProb)
{
count++;
int par1 = r.nextInt(popSize);
int par2 = r.nextInt(popSize);
boolean[] chrom = new boolean[nodes];
for (int i=0;i<div;i++)
chrom[i]=pop.get(par1).getChromosome()[i];
for (int i=div;i<nodes;i++)
chrom[i]=pop.get(par2).getChromosome()[i];
Indyvidual child = new Indyvidual(nodes);
child.setChromosome(chrom);
newPop.add(child);
size++;
}
}
return newPop;
}
private LinkedList<Indyvidual> manyPointsOneChild(LinkedList<Indyvidual> pop)
{
int nodes = pop.get(0).getChromosome().length; //dlugosc tablicy chromosomow
Random r = new Random();
int size = 0; //rozmiar aktualnej,nowej populacji
LinkedList<Indyvidual> newPop = new LinkedList<Indyvidual>(); //lista na nowa populacje
while (size<popSize)
{
double prob = r.nextDouble();
if (prob<=crossingProb)
{
count++;
int par1 = r.nextInt(popSize);
int par2 = r.nextInt(popSize);
boolean[] chrom = new boolean[nodes];
for (int i=0;i<nodes;i++)
{
boolean choice = r.nextBoolean();
if (choice==false)
chrom[i]=pop.get(par1).getChromosome()[i];
if (choice==true)
chrom[i]=pop.get(par2).getChromosome()[i];
}
Indyvidual child = new Indyvidual(nodes);
child.setChromosome(chrom);
newPop.add(child);
size++;
}
}
return newPop;
}
private LinkedList<Indyvidual> manyPointsTwoChildren(LinkedList<Indyvidual> pop)
{
int nodes = pop.get(0).getChromosome().length; //dlugosc tablicy chromosomow
Random r = new Random();
int size = 0; //rozmiar aktualnej,nowej populacji
LinkedList<Indyvidual> newPop = new LinkedList<Indyvidual>(); //lista na nowa populacje
while (size<popSize)
{
double prob = r.nextDouble();
if (prob<=crossingProb)
{
count++;
int par1 = r.nextInt(popSize);
int par2 = r.nextInt(popSize);
boolean[] chrom1 = new boolean[nodes];
boolean[] chrom2 = new boolean[nodes];
for (int i=0;i<nodes;i++)
{
boolean choice = r.nextBoolean();
if (choice==false)
{
chrom1[i]=pop.get(par1).getChromosome()[i];
chrom2[i]=pop.get(par2).getChromosome()[i];
}
if (choice==true)
{
chrom1[i]=pop.get(par2).getChromosome()[i];
chrom2[i]=pop.get(par1).getChromosome()[i];
}
}
Indyvidual child1 = new Indyvidual(nodes);
child1.setChromosome(chrom1);
Indyvidual child2 = new Indyvidual(nodes);
child2.setChromosome(chrom2);
if (size<popSize)
{
newPop.add(child1);
size++;
}
if (size<popSize)
{
newPop.add(child2);
size++;
}
}
}
return newPop;
}
}
+111
View File
@@ -0,0 +1,111 @@
package genetic;
import java.util.Collection;
import java.util.LinkedList;
import Graph.Edge;
import Graph.Node;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.UndirectedSparseGraph;
import edu.uci.ics.jung.graph.util.EdgeType;
import java.util.Collections;
import java.util.Comparator;
public class Fitness
{
private Graph<Node, Edge> graph;
public Fitness(Graph<Node, Edge> _graph)
{
graph=_graph;
}
public void fitness(LinkedList<Indyvidual> pop)
{
int popSize = pop.size();
for (int i=0;i<popSize;i++)
fitnessOne(pop.get(i));
}
private void fitnessOne(Indyvidual ind)
{
LinkedList<Integer> nodeList = new LinkedList<Integer>();
//lista indeksow wierzcholkow, ktore sa w podgrafie
int chromSize = ind.getChromosome().length; //dlugosc chromosomu
for (int i=0;i<chromSize;i++) //tworzenie listy numerow wierzcholkow, ktore maja byc w podgrafie
{
if (ind.getChromosome()[i]==true)
nodeList.add(i);
}
//jesli podgraf nie ma zadnych wierzcholkow
if (nodeList.size()==0)
ind.setFitness(0);
//jesli jednak jakies wierzcholki sa
if (nodeList.size()!=0)
{
//podgraf
Graph<Node, Edge> subGraph = new UndirectedSparseGraph<Node, Edge>();
//dodawanie wierzcholkow
int nodes = nodeList.size(); //ilosc wierzcholkow w podgrafie
for (int i=0;i<nodes;i++)
{
Node n = new Node(nodeList.get(i));
subGraph.addVertex(n);
}
//dodawanie krawedzi
Collection <Node> nodeCol = subGraph.getVertices(); //lista wierzcholkow w grafie
Object[] nodeTab = nodeCol.toArray(); //tablica wierzcholkow w grafie
for (int i=0;i<nodeCol.size();i++)
{
for (int j=i;j<nodeCol.size();j++)
{
Edge e = (Edge) graph.findEdge((Node)nodeTab[i], (Node)nodeTab[j]);
if (e!=null)
{
subGraph.addEdge(e, (Node)nodeTab[i], (Node)nodeTab[j], EdgeType.UNDIRECTED);
}
}
}
//obliczanie ilosci krawedzi
int edgeSubFullCount = nodes*(nodes-1)/2; //ilosc krawedzi w podgrafie, gdyby byl klika
int edgeSubCount = subGraph.getEdgeCount(); //ilosc krawedzi w podgrafie
int edgeCount = graph.getEdgeCount(); //ilosc krawedzi w grafie
int nodeCount = graph.getVertexCount(); //ilosc wierzcholkow w grafie
//nodes - ilosc wierzcholkow w podgrafie
//czy graf jest klika
int dif = edgeSubFullCount - edgeSubCount; //ilosc brakujacych krawedzi
double weight = 1;
if (dif==0)
weight = 5;
//if (dif!=0) weight = 1;
//wzor obliczajacy dostosowanie
double rating = edgeCount - dif + weight * nodeCount;
//dodanie obliczonego dopasowania
if (rating<0)
rating = 0;
ind.setFitness(rating);
//System.out.println("Dostosowanie - " + rating);
}
}
}
+100
View File
@@ -0,0 +1,100 @@
package genetic;
import java.util.LinkedList;
import Graph.Edge;
import Graph.Node;
import edu.uci.ics.jung.graph.Graph;
public class Genetic
{
private LinkedList<Indyvidual> oldPop;
private LinkedList<Indyvidual> tmpPop;
private LinkedList<Indyvidual> newPop;
private Graph<Node, Edge> graph;
int currGener;
//pola klas
private PreSelection preSelect;
private Crossing cross;
private Mutation mut;
private Fitness fit;
private Statistics stat;
private PostSelection postSelect;
//pola paramatrow dla klas
int popSize;
int nodes; //ilosc wierzcholkow=wielkosc tablicy
double mutProb;
double crossProb;
int preSelectType;
int crossType;
int postSelectType;
public Genetic(Graph<Node, Edge> _graph, int _popSize, double _mutProb, double _crosProb, int _preSelect,
int _crossTyp, int _postSelect)
{
graph = _graph;
nodes = graph.getVertexCount();
currGener = 0;
oldPop = new LinkedList<Indyvidual>();
popSize = _popSize;
mutProb = _mutProb;
crossProb = _crosProb;
preSelectType = _preSelect;
crossType = _crossTyp;
postSelectType = _postSelect;
preSelect = new PreSelection(preSelectType);
cross = new Crossing(crossType, crossProb, popSize);
mut = new Mutation(mutProb);
fit = new Fitness(graph);
stat = new Statistics();
postSelect = new PostSelection(postSelectType);
initPop();
}
private void initPop()
{
for (int i=0;i<popSize;i++)
{
Indyvidual osobnik = new Indyvidual(nodes);
osobnik.init();
oldPop.add(osobnik);
//osobnik.printTab();
fit.fitness(oldPop);
}
}
public void goAlgo()
{
tmpPop = preSelect.selection(oldPop);
if (tmpPop.size()==0)
System.out.println("NULL tmpPop");
newPop=cross.crossing(tmpPop);
mut.mutate(newPop);
fit.fitness(newPop);
stat.findStat(newPop);
oldPop=postSelect.postSelection(oldPop, newPop); //postselekcja
//oldPop = newPop;
}
public void printPop()
{
for (int i=0;i<popSize;i++)
{
newPop.get(i).printTab();
System.out.println(newPop.get(i).getFitness());
System.out.println();
}
}
}
+65
View File
@@ -0,0 +1,65 @@
package genetic;
import java.util.Random;
public class Indyvidual
{
private boolean chromosome[]; //chromosom
private double fitness; //dostosowanie osobnika
private int nodes; //dlugosc chromosomu
public Indyvidual(int _nodes)
{
nodes = _nodes;
chromosome = new boolean [nodes];
fitness = 0;
}
public void setChromosome(boolean chrom[])
{
chromosome = chrom;
}
public boolean[] getChromosome()
{
return chromosome;
}
public void setFitness(double fit)
{
fitness = fit;
}
public double getFitness()
{
return fitness;
}
public void init()
{
Random r = new Random();
for (int i=0;i<nodes;i++)
{
chromosome[i]=r.nextBoolean();
}
}
//testowa do wypisywania chromosomu
public void printTab()
{
for (int i=0;i<nodes;i++)
{
if (chromosome[i]==true)
System.out.print("1 ");
else
System.out.print("0 ");
}
System.out.println();
}
public void printFit()
{
System.out.println("Dopasowanie - " + fitness);
}
}
+48
View File
@@ -0,0 +1,48 @@
package genetic;
import java.util.LinkedList;
import java.util.Random;
public class Mutation
{
private double mutationProb;
private int count;
public Mutation(double prob)
{
mutationProb = prob;
count=0;
}
public void setMutationProb(double prob)
{
mutationProb = prob;
}
private void mutateOne(Indyvidual ind)
{
boolean[] chrom = ind.getChromosome();
int nodes = chrom.length;
Random r = new Random();
for (int i=0;i<nodes;i++)
{
double prob = r.nextDouble();
if (prob<=mutationProb)
{
chrom[i]=!chrom[i];
count++;
}
}
//System.out.println("Mutowan - " + count);
}
public void mutate(LinkedList<Indyvidual> pop)
{
int size = pop.size();
for (int i=0;i<size;i++)
mutateOne(pop.get(i));
}
}
+65
View File
@@ -0,0 +1,65 @@
package genetic;
import java.util.LinkedList;
public class PostSelection
{
private int postSelectType;
public PostSelection(int type)
{
postSelectType = type;
}
public LinkedList<Indyvidual> postSelection(LinkedList<Indyvidual> oldPop, LinkedList<Indyvidual> newPop)
{
LinkedList<Indyvidual> curPop = new LinkedList<Indyvidual>();
switch(postSelectType)
{
case 1:
{
curPop = fullReplace(newPop);
break;
}
case 2:
{
curPop = partialReplace(oldPop, newPop);
break;
}
case 3:
{
curPop = eliteReplace(oldPop, newPop);
break;
}
}
return curPop;
}
private LinkedList<Indyvidual> fullReplace(LinkedList<Indyvidual> pop)
{
LinkedList<Indyvidual> curPop = new LinkedList<Indyvidual>();
curPop = pop;
return curPop;
}
private LinkedList<Indyvidual> partialReplace(LinkedList<Indyvidual> oldPop, LinkedList<Indyvidual> newPop)
{
LinkedList<Indyvidual> curPop = new LinkedList<Indyvidual>();
return curPop;
}
private LinkedList<Indyvidual> eliteReplace(LinkedList<Indyvidual> oldPop, LinkedList<Indyvidual> newPop)
{
LinkedList<Indyvidual> curPop = new LinkedList<Indyvidual>();
return curPop;
}
}
+100
View File
@@ -0,0 +1,100 @@
package genetic;
import java.util.LinkedList;
import java.util.Random;
public class PreSelection
{
private int selectType;
public PreSelection(int type)
{
selectType = type;
}
public void setSelectType(int type)
{
selectType = type;
}
public LinkedList<Indyvidual> selection(LinkedList<Indyvidual> pop)
{
LinkedList<Indyvidual> newPop = new LinkedList<Indyvidual>();
switch (selectType)
{
case 1:
{
newPop = rouletteSelection(pop);
break;
}
case 2:
{
newPop = tournamentSelection(pop);
break;
}
}
return newPop;
}
private LinkedList<Indyvidual> rouletteSelection(LinkedList<Indyvidual> pop)
{
LinkedList<Indyvidual> newPop = new LinkedList<Indyvidual>();
int popSize = pop.size();
//sumowanie przystosowan
double sumFit = 0;
for (int i=0;i<popSize;i++)
{
sumFit+=pop.get(i).getFitness();
}
//System.out.println("Suma przystosowan - " + sumFit);
//usuniecie osobnikow o przystosowaniu 0
delZero(pop);
//losowanie kolejnych osobnikow do nowej populacji
Random r = new Random();
for (int i=0;i<popSize;i++)
{
double rand = r.nextDouble(); //losowanie liczby do pomnozenia przez sume przystosowan
double choice = rand * sumFit; //obliczanie miejsca, w ktorym bedzie osobnik do nowej populacji
double check = 0; //suma dostosowan osobnikow, ktore przeszly przez petle while
int ind=0;
while (check<choice && ind<pop.size()-1)
{
check+=pop.get(ind).getFitness();
ind++;
}
newPop.add(pop.get(ind));
}
return newPop;
}
private LinkedList<Indyvidual> tournamentSelection(LinkedList<Indyvidual> pop)
{
LinkedList<Indyvidual> newPop = new LinkedList<Indyvidual>();
return newPop;
}
private void delZero(LinkedList<Indyvidual> pop)
{
int j=0;
while (j<pop.size())
{
if (pop.get(j).getFitness()==0)
pop.remove(j);
else
j++;
}
}
}
+81
View File
@@ -0,0 +1,81 @@
package genetic;
import java.util.LinkedList;
public class Statistics
{
private LinkedList<Double> minList;
private LinkedList<Double> avgList;
private LinkedList<Double> maxList;
public Statistics()
{
minList = new LinkedList<Double>();
avgList = new LinkedList<Double>();
maxList = new LinkedList<Double>();
}
public LinkedList<Double> getMinList()
{
return minList;
}
public LinkedList<Double> getAvgList()
{
return avgList;
}
public LinkedList<Double> getMaxList()
{
return maxList;
}
public void findStat(LinkedList<Indyvidual> pop)
{
findMin(pop);
findAvg(pop);
findMax(pop);
}
private void findMin(LinkedList<Indyvidual> pop)
{
double min=pop.get(0).getFitness();
for (int i=1;i<pop.size();i++)
{
if (pop.get(i).getFitness()<min)
min=pop.get(i).getFitness();
}
System.out.println(min);
minList.add(min);
}
private void findAvg(LinkedList<Indyvidual> pop)
{
double sum=0;
for (int i=0;i<pop.size();i++)
{
sum+=pop.get(i).getFitness();
}
double avg = sum/pop.size();
System.out.println(avg);
avgList.add(avg);
}
private void findMax(LinkedList<Indyvidual> pop)
{
double max=pop.get(0).getFitness();
for (int i=1;i<pop.size();i++)
{
if (pop.get(i).getFitness()>max)
max=pop.get(i).getFitness();
}
System.out.println(max);
System.out.println();
maxList.add(max);
}
}
+133
View File
@@ -0,0 +1,133 @@
package genetic;
import java.util.LinkedList;
import Graph.Edge;
import Graph.Node;
import edu.uci.ics.jung.graph.Graph;
import gui.Jung;
import gui.Frame;
public class Tester
{
public static void main(String[] args)
{
genTest();
//preSelectTest();
}
private static void preSelectTest()
{
int selectType = 1;
int popSize = 20;
PreSelection preSel = new PreSelection(selectType);
Frame fr = new Frame();
Jung jung = fr.getJung();
Graph<Node, Edge> graph = jung.generateGraph(5, 10, 10);
LinkedList<Indyvidual> pop = new LinkedList<Indyvidual>();
for (int i=0;i<popSize;i++)
{
Indyvidual osobnik = new Indyvidual(20);
osobnik.init();
pop.add(osobnik);
}
Fitness fit = new Fitness(graph);
fit.fitness(pop);
for (int i=0;i<popSize;i++)
{
pop.get(i).printFit();
}
LinkedList<Indyvidual> newPop = preSel.selection(pop);
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println("Populcja po preselekcji");
for (int i=0;i<popSize;i++)
{
newPop.get(i).printFit();
}
}
private static void genTest()
{
int popSize=200;
double mutProb=0.05;
double crosProb=0.7;
int preSelect=1;
int crossTyp=1;
int postSelect=1;
Frame fr = new Frame();
Jung jung = fr.getJung();
Graph<Node, Edge> graph = jung.generateGraph(5, 10, 10);
Genetic gen = new Genetic(graph, popSize, mutProb, crosProb, preSelect, crossTyp, postSelect);
for (int i=0;i<100;i++)
gen.goAlgo();
//gen.printPop();
System.out.println("Done");
System.out.println("Wierzcholkow - " + graph.getVertexCount());
}
private static void mutTest()
{
int popSize = 2;
double mutationProb = 0.05;
Mutation mut = new Mutation(mutationProb);
LinkedList<Indyvidual> pop = new LinkedList<Indyvidual>();
for (int i=0;i<popSize;i++)
{
Indyvidual osobnik = new Indyvidual(20);
osobnik.init();
pop.add(osobnik);
osobnik.printTab();
}
mut.mutate(pop);
for (int i=0;i<popSize;i++)
pop.get(i).printTab();
}
private static void crosTest()
{
int popSize = 2;
double crossingProb = 0.8;
int crossingType = 4;
LinkedList<Indyvidual> pop = new LinkedList<Indyvidual>();
for (int i=0;i<popSize;i++)
{
Indyvidual osobnik = new Indyvidual(20);
osobnik.init();
pop.add(osobnik);
osobnik.printTab();
}
Crossing cros = new Crossing(crossingType,crossingProb,popSize);
LinkedList<Indyvidual> newPop = cros.crossing(pop);
System.out.println("Nowa populacja");
for (int i=0;i<popSize;i++)
newPop.get(i).printTab();
}
}