• R/O
  • SSH
  • HTTPS

opengion: Commit


Commit MetaInfo

Revisão1413 (tree)
Hora2017-03-28 10:31:51
Autortakahashi_m

Mensagem de Log

(mensagem de log vazia)

Mudança Sumário

Diff

--- trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/HybsGAObject.java (revision 1412)
+++ trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/HybsGAObject.java (nonexistent)
@@ -1,26 +0,0 @@
1-
2-package org.opengion.penguin.math;
3-
4-/**
5- * HybsGeneticAlgorithmで取り扱うデータ用の共通インターフェースです。
6- *
7- * GAではこのインタフェイスを継承したオブジェクトを遺伝情報として利用します。
8- *
9- */
10-public interface HybsGAObject {
11- /**
12- * fitness計算時に利用する値。
13- * 実クラスでは、例えば内部の値を元にDBから検索した値でもよい。
14- *
15- * @return fitness用の値
16- */
17- double getFitness();
18-
19- /**
20- * 自身を表す文字列。
21- *
22- * @return 自身を表す文字列
23- */
24- @Override
25- String toString() ;
26-}
--- trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/HybsGAObjectImpl.java (revision 1412)
+++ trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/HybsGAObjectImpl.java (nonexistent)
@@ -1,193 +0,0 @@
1-package org.opengion.penguin.math;
2-
3-/**
4- * HybsGeneticAlgorithmで取り扱うデータ用の実装クラスです。
5- *
6- * ある程度標準的に利用できるようにで、名称、属性値(実数)、属性値(文字列)、属性値配列(実数)、属性値配列(文字列)を持ちます。
7- *
8- */
9-public class HybsGAObjectImpl implements HybsGAObject {
10- private String name; // 名称
11- private double attr; // 属性値(実数)
12- private String attrStr; // 属性値(文字列)
13- private double[] attrArray; // 属性値配列(実数)
14- private String[] attrStrArray; // 属性値配列(文字列)
15-
16- /**
17- * コンストラクタ。
18- *
19- * @param name 名称
20- * @param attr 属性値(実数)
21- */
22- public HybsGAObjectImpl (final String name, final double attr){
23- this( name, attr, null, null,null);
24- }
25-
26- /**
27- * コンストラクタ。
28- *
29- * @param name 名称
30- * @param attr 属性値(実数)
31- * @param attrArray 属性値配列(実数)
32- */
33- public HybsGAObjectImpl (final String name, final double attr, final double[] attrArray){
34- this( name, attr, null, attrArray, null);
35- }
36-
37- /**
38- * コンストラクタ。
39- *
40- * @param name 名称
41- * @param attr 属性値(実数)
42- * @param attrStr 属性値(文字)
43- * @param attrArray 属性値配列(実数)
44- */
45- public HybsGAObjectImpl (final String name, final double attr, final String attrStr, final double[] attrArray){
46-// this( name, attr, null, attrArray, null);
47- this( name, attr, attrStr, attrArray, null);
48- }
49-
50- /**
51- * コンストラクタ。
52- *
53- * @param name 名称
54- * @param attr 属性値(実数)
55- * @param attrStr 属性値(文字)
56- * @param attrStrArray 属性値配列(文字)
57- */
58- public HybsGAObjectImpl (final String name, final double attr, final String attrStr, final String[] attrStrArray){
59-// this( name, attr, null, null, attrStrArray);
60- this( name, attr, attrStr, null, attrStrArray);
61- }
62-
63- /**
64- * コンストラクタ。
65- *
66- * @param name 名称
67- * @param attr 属性値(実数)
68- * @param attrStr 属性値(文字)
69- * @param attrArray 属性値配列(実数)
70- * @param attrStrArray 属性値配列(文字)
71- */
72- public HybsGAObjectImpl (final String name, final double attr, final String attrStr, final double[] attrArray, final String[] attrStrArray){
73- this.name = name;
74- this.attr = attr;
75- this.attrStr = attrStr;
76- this.attrArray = attrArray;
77- this.attrStrArray = attrStrArray;
78- }
79-
80- // インタフェイスによる必須メソッド。
81- /**
82- * フィットネス用に利用する値。
83- *
84- * 属性値(実数)を返す
85- *
86- * @return フィットネス用に利用する値
87- */
88- public double getFitness(){
89- return attr;
90- }
91-
92- /**
93- * 文字列表現。
94- *
95- * [名称]([属性値(実数)])
96- *
97- * @return 文字列表現
98- */
99- @Override
100- public String toString(){
101- return name + "(" + attr + ")";
102- }
103-
104- /**
105- * 名称セット。
106- *
107- * @param name 名称
108- */
109- public void setName (final String name ){
110- this.name = name;
111- }
112-
113- /**
114- * 名称取得。
115- *
116- * @return 名称
117- */
118- public String getName (){
119- return this.name;
120- }
121-
122- /**
123- * 属性値セット。
124- *
125- * @param attr 属性値
126- */
127- public void setAttr (final double attr ){
128- this.attr = attr;
129- }
130-
131- /**
132- * 属性値取得。
133- *
134- * @return 属性値(数値)
135- */
136- public double getAttr (){
137- return this.attr;
138- }
139-
140- /**
141- * 属性値(文字)セット。
142- *
143- * @param attrStr 属性値(文字)
144- */
145- public void setAttrStr (final String attrStr ){
146- this.attrStr = attrStr;
147- }
148-
149- /**
150- * 属性値(文字)取得。
151- *
152- * @return 属性値(文字)
153- */
154- public String getAttrStr (){
155- return this.attrStr;
156- }
157-
158- /**
159- * 属性値配列セット。
160- *
161- * @param attrArray 属性値配列
162- */
163- public void setAttrArray (final double[] attrArray ){
164- this.attrArray = attrArray;
165- }
166-
167- /**
168- * 属性値配列取得。
169- *
170- * @return 属性値配列
171- */
172- public double[] getAttrArray (){
173- return this.attrArray;
174- }
175-
176- /**
177- * 属性値配列(文字)セット。
178- *
179- * @param attrStrArray 属性値配列(文字)
180- */
181- public void setAttrStrArray (final String[] attrStrArray ){
182- this.attrStrArray = attrStrArray;
183- }
184-
185- /**
186- * 属性値配列(文字)取得。
187- *
188- * @return 属性値配列(文字)
189- */
190- public String[] getAttrStrArray (){
191- return this.attrStrArray;
192- }
193-}
--- trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/HybsScheduleChromosome.java (revision 1412)
+++ trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/HybsScheduleChromosome.java (nonexistent)
@@ -1,133 +0,0 @@
1-package org.opengion.penguin.math;
2-
3-import java.util.ArrayList;
4-import java.util.List;
5-import java.util.Map;
6-import java.util.HashMap;
7-import org.apache.commons.math3.genetics.InvalidRepresentationException;
8-
9-/**
10- * AbstractHybsGAChromosomeのサンプル実装クラスです。
11- * HybsGAObjectImplを利用しています。
12- * 属性値配列(文字列)にタスクの割当先(機械や人)候補
13- * 属性値(実数)にこのタスクにかかる時間
14- * 属性値配列(実数)[0]にこのタスクの納期(開始からの経過時間)
15- * を持たせているという想定です。
16- * このクラスでは次のようにスケジュールを決めます。
17- * 1.候補のうち、一番タスクが積まれていないものに前から積む
18- * 2.同じであればリストの先頭の方に割り当てられる
19- * 3.納期オーバーの場合は評価関数の値が小さくなるようにする
20- *
21- */
22-public class HybsScheduleChromosome extends AbstractHybsGAChromosome {
23-
24- /**
25- * コンストラクタ。
26- */
27- public HybsScheduleChromosome() {
28- super();
29- }
30-
31- /**
32- * コンストラクタ。
33- *
34- * @param representation 染色体表現
35- */
36- public HybsScheduleChromosome(final List<HybsGAObject> representation) {
37- super(representation);
38- }
39-
40- /**
41- * 適合度計算。
42- *
43- * @return 適合度計算の結果
44- */
45- public double fitness() {
46- final List<HybsGAObject> representation = getRepresentation();
47- double nokisum = 0.0;
48-// final HashMap<String,Double> machineList = new HashMap<String, Double>(); //名前は機械リストだが、人でも良い
49-// final HashMap<String, ArrayList<String>> taskSchedule = new HashMap<String, ArrayList<String>>();
50- final Map<String,Double> machineList = new HashMap<String,Double>(); //名前は機械リストだが、人でも良い
51- final Map<String, List<String>> taskSchedule = new HashMap<String, List<String>>();
52-
53- // 実際にスケジュールの積み上げを行い、納期遅れの合計を出します
54- nokisum = makeSchedule( representation, machineList, taskSchedule );
55-
56- // リストから最大値を取得する(出てくる順番は問わない)
57- double maxWork=0;
58- for( final String mw : machineList.keySet() ){
59- maxWork = ( machineList.get(mw) > maxWork ) ? machineList.get(mw) :maxWork;
60- }
61-
62- return 1 / ( maxWork + nokisum*nokisum); //納期遅れが多くなるとどんどん値が小さくなるように評価する
63- }
64-
65- /**
66- * HybsGAObjectImplを利用して前からスケジュールを積み上げていきます。
67- *
68- * @param representation 染色体表現
69- * @param machineList マシンに対する積み上げ工数のリスト。(書き込まれるのでfinalにしない)
70- * @param taskSchedule マシンに対して、前からタスクをセットするリスト。(書き込まれるのでfinalにしない)
71- * @return 納期遅れの累計
72- */
73-// public double makeSchedule( final List<HybsGAObject> representation , final HashMap<String,Double> machineList, final HashMap<String, ArrayList<String>> taskSchedule){
74- public double makeSchedule( final List<HybsGAObject> representation , final Map<String,Double> machineList, final Map<String, List<String>> taskSchedule){
75- HybsGAObjectImpl chrom;
76- double nokisum = 0.0;
77-
78- for ( int i=0; i<representation.size(); i++){
79- chrom = (HybsGAObjectImpl)representation.get(i);
80-
81- final String[] machines = chrom.getAttrStrArray();
82- // ここでスケジュールを当てはめていく
83- final double noki = chrom.getAttrArray()[0];
84- String hitMachine = null;
85- double work=999999999;
86- for( int j=0; j<machines.length; j++ ){
87- if(!machineList.containsKey( machines[j] )){
88- machineList.put( machines[j], new Double(0) );
89- taskSchedule.put( machines[j], new ArrayList<String>() );
90- }
91-
92- if( machineList.get(machines[j]) < work){
93- work = machineList.get(machines[j]);
94- hitMachine = machines[j];
95- }
96- }
97-
98- machineList.put( hitMachine, new Double(work + chrom.getAttr()) ); // 総工数
99- taskSchedule.get( hitMachine ).add( chrom.getName() ); // 割りついたタスクリスト
100-
101- if( work + chrom.getAttr() > noki ){
102- nokisum += ( noki - (work + chrom.getAttr()) );
103- }
104- }
105- return nokisum;
106- }
107-
108- /**
109- * 自身のクラスを新たに作成するメソッド。
110- *
111- * ここではオプションデータはクローンせずに参照で渡しています。
112- * (計算では利用していません)
113- *
114- * @param repr 染色体表現
115- * @return 作成された自分自身のクラス
116- */
117- @Override
118- public AbstractHybsGAChromosome newFixedLengthChromosome(final List<HybsGAObject> repr) {
119- final HybsScheduleChromosome rtn = new HybsScheduleChromosome(repr);
120- rtn .setOptionData( optionData );
121- return rtn;
122- }
123-
124- /**
125- * 染色体表現のチェック。
126- *
127- * @param repr HybsGAObjectのリスト
128- */
129- @Override
130- protected void checkValidity(final List<HybsGAObject> repr) throws InvalidRepresentationException {
131- // Listの中身のチェックをする箇所。必要であれば記述する
132- }
133-}
--- trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/HybsGeneticAlgorithm.java (revision 1412)
+++ trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/HybsGeneticAlgorithm.java (nonexistent)
@@ -1,254 +0,0 @@
1-package org.opengion.penguin.math;
2-
3-import java.util.Collections;
4-import java.util.List;
5-import java.util.Arrays;
6-import java.util.LinkedList;
7-import java.util.ArrayList;
8-import org.apache.commons.math3.genetics.MutationPolicy;
9-import org.apache.commons.math3.genetics.Chromosome;
10-import org.apache.commons.math3.genetics.ElitisticListPopulation;
11-import org.apache.commons.math3.genetics.FixedGenerationCount;
12-import org.apache.commons.math3.genetics.GeneticAlgorithm;
13-import org.apache.commons.math3.genetics.OrderedCrossover;
14-import org.apache.commons.math3.genetics.Population;
15-import org.apache.commons.math3.genetics.StoppingCondition;
16-import org.apache.commons.math3.genetics.TournamentSelection;
17-import org.opengion.penguin.common.SystemUtil;
18-
19-/**
20- * apache.commons.mathを利用した遺伝的アルゴリズム実行クラスです。
21- * 0/1ではなくリスト形式の染色体をある程度手軽に利用できるようにしています。
22- * 利用する場合は上記パッケージをjava\jre\lib\ext等に配置してください。
23- *
24- * 交叉率等はsetterで与えられるようにしています。
25- * スケジューリング等を考慮して、交叉方法はOrderedCrossover(順序交叉)としています。
26- * 選択方式はトーナメントです。突然変異は遺伝子ランダム入れ替えです。
27- *
28- * 染色体として与えるものはhybsGAObjectインタフェイスを継承したクラスです。
29- * AbstractListChromosomeを継承したAbstracthybsChromosomeを利用して染色体を作成します。
30- *
31- *
32- * mainメソッドではサンプルとして、巡回セールスマン問題を行います。
33- */
34-public class HybsGeneticAlgorithm {
35- // 標準設定
36- private int populationSize = 100; // 個数
37- private double crossoverRate = 0.8; // 交叉率
38- private double mutationRate = 0.05; // 突然変異率
39- private double elitismRate = 0.1; // 残すエリートの割合
40- private int tournamentArity = 2; // トーナメント個体数:2が一般的
41- private String chromosomeClazz = "org.opengion.fukurou.math.HybsScheduleChromosome"; // 利用する染色体
42- private Object optionData; // 作成する染色体クラスに自由にオプション情報を渡せるようにしておく
43-
44- private HybsGAObject [] gaList;
45-
46- /**
47- * 内部クラス。
48- *
49- * 突然変異はランダム入れ替え方式とします
50- */
51-// private static class RandomMutation implements MutationPolicy {
52- private static final class RandomMutation implements MutationPolicy {
53- /**
54- * コンストラクタ。
55- *
56- * @param original オリジナル染色体
57- * @return 突然変異染色体
58- */
59- public Chromosome mutate(final Chromosome original) {
60- final AbstractHybsGAChromosome strChromosome = (AbstractHybsGAChromosome) original;
61- final List<HybsGAObject> lists = strChromosome.getThisRepresentation();
62- final int mutationIndex1 = GeneticAlgorithm.getRandomGenerator().nextInt(lists.size());
63- final int mutationIndex2 = GeneticAlgorithm.getRandomGenerator().nextInt(lists.size());
64- final List<HybsGAObject> mutatedChromosome = new ArrayList<HybsGAObject>(lists);
65- final HybsGAObject mi1 = lists.get(mutationIndex1);
66- final HybsGAObject mi2 = lists.get(mutationIndex2);
67- mutatedChromosome.set(mutationIndex2, mi1);
68- mutatedChromosome.set(mutationIndex1, mi2);
69- return strChromosome.newFixedLengthChromosome(mutatedChromosome);
70- }
71- }
72-
73- /**
74- * 計算の実行。
75- *
76- * @return 最適染色体
77- */
78- public AbstractHybsGAChromosome execute() {
79- // initialize a new genetic algorithm
80- final GeneticAlgorithm ga = new GeneticAlgorithm(
81- new OrderedCrossover<HybsGAObject>(), //CrossoverPolicy:順序交叉を利用する
82- crossoverRate, //crossoverRate
83- new RandomMutation(), //MutationPolicy
84- mutationRate, //mutationRate
85- new TournamentSelection(tournamentArity) //SelectionPolicy
86- );
87-
88- // initial population
89- final Population initial = getInitialPopulation();
90-
91- // stopping condition
92- final StoppingCondition stopCond = new FixedGenerationCount(100);
93-
94- // run the algorithm
95- final Population finalPopulation = ga.evolve(initial, stopCond);
96-
97- // best chromosome from the final population
98- final Chromosome bestFinal = finalPopulation.getFittestChromosome();
99-
100- return (AbstractHybsGAChromosome)bestFinal;
101- }
102-
103- /**
104- * 初期遺伝子の作成。シャッフルする。
105- *
106- * クラスの読み込み部分をfukurouに依存
107- *
108- * @return 初期遺伝子
109- */
110- private Population getInitialPopulation() {
111- final List<Chromosome> popList = new LinkedList<Chromosome>();
112- final List<HybsGAObject> gal = Arrays.asList(gaList);
113-// AbstractHybsGAChromosome chr = (AbstractHybsGAChromosome)newInstance( chromosomeClazz );
114- final AbstractHybsGAChromosome chr = (AbstractHybsGAChromosome)SystemUtil.newInstance( chromosomeClazz );
115- chr.setOptionData( optionData );
116- for (int i = 0; i < populationSize; i++) {
117- Collections.shuffle(gal);
118- popList.add( chr.clone(gal) );
119- }
120- return new ElitisticListPopulation(popList, 2 * popList.size(), elitismRate);
121- }
122-
123- /**
124- * 染色体配列のセット。
125- *
126- * @param gal 染色体とする配列
127- * @return クラス自身
128- */
129- public HybsGeneticAlgorithm setGAList(final HybsGAObject[] gal ) {
130- this.gaList = gal;
131- return this;
132- }
133-
134- /**
135- * 交叉率のセット。
136- * 交叉率+突然変異率 < 1.0 となるようにする
137- * 初期値は0.8
138- *
139- * @param cr 交叉率
140- * @return クラス自身
141- */
142- public HybsGeneticAlgorithm setCrossoverRate(final double cr ){
143- this.crossoverRate = cr;
144- return this;
145- }
146-
147- /**
148- * 突然変異率のセット。
149- * 交叉率+突然変異率 < 1.0 となるようにする
150- * 初期値は0.05
151- *
152- * @param mr 突然変異率
153- * @return クラス自身
154- */
155- public HybsGeneticAlgorithm setMutationRate(final double mr ){
156- this.mutationRate = mr;
157- return this;
158- }
159-
160- /**
161- * エリート主義の割合。
162- * 初期値は0.2
163- *
164- * @param er エリート主義の率
165- * @return クラス自身
166- */
167- public HybsGeneticAlgorithm setElitismRate(final double er ){
168- this.elitismRate = er;
169- return this;
170- }
171-
172- /**
173- * トーナメントサイズ。
174- * 初期値は2
175- *
176- * @param ta トーナメントサイズ
177- * @return クラス自身
178- */
179- public HybsGeneticAlgorithm setTournamentArity(final int ta ){
180- this.tournamentArity = ta;
181- return this;
182- }
183-
184- /**
185- * 集団サイズ。
186- * 染色体のサイズ等によって適度な値を取るべきだが、初期値は100としている。
187- *
188- *
189- * @param ps 集団サイズ
190- * @return クラス自身
191- */
192- public HybsGeneticAlgorithm setPopulationSize(final int ps ){
193- this.populationSize = ps;
194- return this;
195- }
196-
197- /**
198- * 利用する染色体クラスを指定します。
199- * 初期値はorg.opengion.fukurou.math.HybsScheduleChromosome
200- *
201- * @param cc 染色体のクラス名
202- * @return クラス自身
203- */
204- public HybsGeneticAlgorithm setChromosomeClazz(final String cc ){
205- this.chromosomeClazz = cc;
206- return this;
207- }
208-
209- /**
210- * 染色体クラスにオプションをセットします。
211- *
212- * @param obj オプションデータ
213- * @return クラス自身
214- */
215- public HybsGeneticAlgorithm setOptionData(final Object obj ){
216- this.optionData = obj;
217- return this;
218- }
219-
220- /*** ここまでがGA本体 ***/
221- /**
222- * ここからテスト用mainメソッド。
223- *
224- * @param args ****************************************
225- */
226- public static void main(final String [] args) {
227-
228- final AbstractHybsGAChromosome rtn1 = new HybsGeneticAlgorithm()
229- .setChromosomeClazz("org.opengion.penguin.math.HybsTSPChromosome")
230- .setGAList(new HybsGAObject[] {
231- new HybsGAObjectImpl("1",1,new double[] {1,1})
232- ,new HybsGAObjectImpl("2",2,new double[] {1,10})
233- ,new HybsGAObjectImpl("3",3,new double[] {11,20})
234- ,new HybsGAObjectImpl("4",4,new double[] {22,50})
235- ,new HybsGAObjectImpl("5",5,new double[] {25,70})
236- ,new HybsGAObjectImpl("6",6,new double[] {33,5})
237- ,new HybsGAObjectImpl("7",7,new double[] {54,20})
238- ,new HybsGAObjectImpl("8",8,new double[] {75,80})
239- ,new HybsGAObjectImpl("9",9,new double[] {86,55})
240- ,new HybsGAObjectImpl("10",10,new double[] {97,90})
241- ,new HybsGAObjectImpl("11",11,new double[] {18,50})
242- ,new HybsGAObjectImpl("12",12,new double[] {39,10})
243- ,new HybsGAObjectImpl("13",13,new double[] {40,90})
244- ,new HybsGAObjectImpl("14",14,new double[] {51,10})
245- ,new HybsGAObjectImpl("15",15,new double[] {62,55})
246- ,new HybsGAObjectImpl("16",16,new double[] {73,70})
247- ,new HybsGAObjectImpl("17",17,new double[] {84,10})
248- ,new HybsGAObjectImpl("18",18,new double[] {95,45})
249- }).execute();
250-
251- System.out.println(rtn1.toString());
252- System.out.println( 1/rtn1.getFitness() +"\n");
253- }
254-}
--- trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/HybsTSPChromosome.java (revision 1412)
+++ trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/HybsTSPChromosome.java (nonexistent)
@@ -1,79 +0,0 @@
1-package org.opengion.penguin.math;
2-
3-import java.util.List;
4-import org.apache.commons.math3.genetics.InvalidRepresentationException;
5-
6-/**
7- * AbstractHybsGAChromosomeのサンプル実装クラスです.
8- * HybsGAObjectImplを利用してます。
9- * Implの配列に各都市の座標が入っており、座標間の距離を元にして
10- * 単純な巡回セールスマン問題を解きます。
11- * (ルートが交差するかどうかは問いません)
12- *
13- */
14-public class HybsTSPChromosome extends AbstractHybsGAChromosome {
15-
16- /**
17- * コンストラクタ。
18- */
19- public HybsTSPChromosome() {
20- super();
21- }
22-
23- /**
24- * コンストラクタ。
25- *
26- * @param representation 染色体表現
27- */
28- public HybsTSPChromosome(final List<HybsGAObject> representation) {
29- super(representation);
30- }
31-
32- /**
33- * 適合度計算。
34- *
35- * @return 適合度計算の結果
36- */
37- public double fitness() {
38- double fitness = 0.0;
39- // int idx = 0;
40- final List<HybsGAObject> representation = getRepresentation();
41-
42- // implをここでは利用する。attrArrayを座標として距離から求めることとする
43- double[] bfr = ((HybsGAObjectImpl)( representation.get( representation.size()-1 ) )).getAttrArray();
44- double[] now = {0,0};
45- for ( final HybsGAObject chrom : representation ) {
46- // 一つ前との距離をプラス
47- now = ((HybsGAObjectImpl)chrom).getAttrArray();
48- fitness += Math.sqrt( (bfr[0]-now[0])*(bfr[0]-now[0]) + (bfr[1]-now[1])*(bfr[1]-now[1]) );
49-
50- bfr=now;
51- // idx++;
52- }
53-
54- // fitnessが最小になると適合度が最大になる
55- // 交差等は特に考えず、単純に計算
56- return 1 / fitness;
57- }
58-
59- /**
60- * 自身のクラスを新たに作成するメソッド。
61- *
62- * @param repr 染色体表現
63- * @return 作成された自分自身のクラス
64- */
65- @Override
66- public AbstractHybsGAChromosome newFixedLengthChromosome(final List<HybsGAObject> repr) {
67- return new HybsTSPChromosome(repr);
68- }
69-
70- /**
71- * 染色体表現のチェック。
72- *
73- * @param repr 染色体表現リスト
74- */
75- @Override
76- protected void checkValidity(final List<HybsGAObject> repr) throws InvalidRepresentationException {
77- // Listの中身のチェックをする箇所。必要であれば記述する
78- }
79-}
--- trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/AbstractHybsGAChromosome.java (revision 1412)
+++ trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/AbstractHybsGAChromosome.java (nonexistent)
@@ -1,95 +0,0 @@
1-package org.opengion.penguin.math;
2-
3-import java.util.ArrayList;
4-import java.util.List;
5-import org.apache.commons.math3.genetics.AbstractListChromosome;
6-import org.apache.commons.math3.genetics.InvalidRepresentationException;
7-
8-/**
9- * HybsGeneticAlgorithmで利用するChromosomeインターフェースです。
10- *
11- * AbstractListChromosomeだと少し使いにくいので、AbstractListChromosomeを継承して
12- * 独自にAbstractクラスを作成しています。
13- * (大半はAbstractListChromosomeそのものです)
14- *
15- */
16-public abstract class AbstractHybsGAChromosome extends AbstractListChromosome<HybsGAObject> {
17-
18- protected Object optionData; // 染色体に何らかのオプション情報を持たせる場合に利用
19-
20- /**
21- * デフォルトコンストラクタ。
22- *
23- * 空の染色体配列を持つインスタンスを作成する。
24- * newInstanceメソッドでインスタンスを作成するために、若干トリッキーな事をする。
25- * このコンストラクタを利用する場合はcloneで染色体セットし、増殖させて利用する。
26- *
27- * @throws InvalidRepresentationException 染色体の表現が無効であることを示す例外
28- */
29- public AbstractHybsGAChromosome() throws InvalidRepresentationException {
30- super( new HybsGAObject[] {} );
31- }
32-
33- /**
34- * 染色体のリストを引数に持つコンストラクタ。
35- *
36- * @param representation 染色体表現のリスト
37- * @throws InvalidRepresentationException 染色体の表現が無効であることを示す例外
38- */
39- public AbstractHybsGAChromosome(final List<HybsGAObject> representation) throws InvalidRepresentationException {
40- super(representation);
41- }
42-
43- /**
44- * 初期化用のsetter。
45- * 通常、copyListにはtrueをセットして染色体表現のインスタンスを新たに作成する。
46- *
47- * @param chromosomeRepresentation 染色体表現
48- * @param copyList newを利用してクローンするかどうか
49- * @return クローン
50- */
51- public AbstractListChromosome<HybsGAObject> clone(final List<HybsGAObject> chromosomeRepresentation, final boolean copyList) {
52- checkValidity(chromosomeRepresentation);
53- return newFixedLengthChromosome(copyList ? new ArrayList<HybsGAObject>(chromosomeRepresentation) : chromosomeRepresentation);
54- }
55-
56- /**
57- * 初期化用のsetter。
58- *
59- * @param chromosomeRepresentation 染色体表現
60- * @return クローン
61- * @throws InvalidRepresentationException 染色体の表現が無効であることを示す例外
62- */
63- public AbstractListChromosome<HybsGAObject> clone(final List<HybsGAObject> chromosomeRepresentation) throws InvalidRepresentationException {
64- return clone( chromosomeRepresentation, true );
65- }
66-
67- /**
68- * 自分と同じクラスを作成するメソッド。
69- * 各クラスで実装する。
70- * 必要に応じてoptionDataをセットすること。
71- *
72- * @param repr 作成する際に渡す染色体
73- * @return 作成されたクラス
74- */
75- @Override
76- abstract public AbstractHybsGAChromosome newFixedLengthChromosome(final List<HybsGAObject> repr);
77-
78- /**
79- * 染色体配列を返す。
80- *
81- * @return 染色体配列
82- */
83- public List<HybsGAObject> getThisRepresentation() {
84- return getRepresentation();
85- }
86-
87- /**
88- * オプション情報を渡す場合に利用。
89- *
90- * @param option オプション情報
91- */
92- public void setOptionData( final Object option ) {
93- this.optionData = option;
94- }
95-}
--- trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/HybsCorrelation.java (revision 1412)
+++ trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/HybsCorrelation.java (nonexistent)
@@ -1,132 +0,0 @@
1-package org.opengion.penguin.math;
2-
3-import org.apache.commons.math3.linear.MatrixUtils;
4-import org.apache.commons.math3.linear.RealMatrix;
5-import org.apache.commons.math3.stat.correlation.PearsonsCorrelation;
6-import org.opengion.penguin.common.SystemUtil;
7-
8-/**
9- * apache.commons.mathを利用した相関計算及びその周辺機能を利用するためのクラスです。
10- *
11- * とりあえず通常のピアソン積率相関のみを利用可能としておきます。
12- *
13- */
14-public class HybsCorrelation {
15- private String[] names;
16- private double[][] pearsonsMatrix;
17- private RealMatrix corrMatrix;
18-
19-
20- /**
21- * コンストラクタ。
22- * 与えたデータマトリクスを元にピアソン積率相関を計算します。
23- * 名称 = { "数学" , "英語", "国語" }
24- * データ = { { 90 ,60 ,70 }, {70, 90, 80 } }
25- * のような形としてデータを与えます。
26- * @param name
27- * @param matrix
28- */
29- public HybsCorrelation(String[] name, double[][] matrix){
30- // 一応元データをセットしておく
31- this.names = name;
32- this.pearsonsMatrix = matrix;
33-
34- // ここで相関係数行列を作成してしまう
35- corrMatrix = (new PearsonsCorrelation()).computeCorrelationMatrix(pearsonsMatrix);
36- }
37-
38- /**
39- * コンストラクタ。
40- * 計算後の相関係数行列をdouble[][]型で直接与えられるようにしておきます。
41- * 以前に計算した行列を使って行列の積を算出する場合に利用します。
42- *
43- * @param matrix
44- */
45- public HybsCorrelation( double[][] matrix){
46- corrMatrix = MatrixUtils.createRealMatrix( matrix );
47- }
48-
49- /**
50- * コンストラクタで算出した相関値行列に対して与えた行列を掛け算します。
51- * 例えば以下のような算出を行う事が可能です。
52- * 各商品を何回購入したかというデータを人数分用意し、相関係数行列を作成し、
53- *  それに対してある人の今まで購入した履歴を掛け算する事で相関の高い商品を導出します。
54- *  つまり、購入した事のないもので有意な相関係数を持つものは購入可能性が高いと言えます。
55- * @param data 掛け算する行列
56- * @return 行列積の結果マトリクス
57- */
58- public double[][] multiply(double[][] data){
59- RealMatrix dataMatrix = MatrixUtils.createRealMatrix(data);
60- RealMatrix scores = dataMatrix.multiply(corrMatrix);
61-
62- return scores.getData();
63- }
64-
65- /**
66- * 相関値行列取得。
67- * @return 相関マトリクス
68- */
69- public double[][] getCorrMatrix(){
70- return corrMatrix.getData();
71- }
72-
73- /**
74- * 指定行の相関値配列取得。
75- * @param x ROW番号
76- * @return 行方向の相関ベクトル
77- */
78- public double[] getCorrMatrixRow(int x){
79- return corrMatrix.getRow(x);
80- }
81-
82- /**
83- * 指定列の相関値配列取得。
84- * @param x COL番号
85- * @return 列方向の相関ベクトル
86- */
87- public double[] getCorrMatrixCol(int x){
88- return corrMatrix.getColumn(x);
89- }
90-
91- /**
92- * 名称配列の取得。
93- * @return 名称配列
94- */
95- public String[] getNames(){
96- return names;
97- }
98-
99- /**
100- * 名称配列のセット。
101- * @param name 名称配列
102- */
103- public void setNames( String[] name){
104- this.names = name;
105- }
106-
107- /*** ここまでが本体 ***/
108- /*** ここからテスト用mainメソッド ***/
109- /**
110- * @param args *****************************************/
111- public static void main(final String [] args) {
112- String[] name = {"A", "B", "C", "D","E"};
113- double[][] data = {
114- {3, 1, 0, 0 , 1},
115- {1, 0, 0, 0 , 1},
116- {0, 0, 2, 2 , 2},
117- {2, 2, 1, 0 , 0},
118- {1, 0, 2, 4 , 1},
119- };
120-
121- HybsCorrelation rtn = new HybsCorrelation(name,data);
122-
123- for( int i = 0; i< rtn.getCorrMatrix().length; i++ ){
124- System.out.println(java.util.Arrays.toString(rtn.getCorrMatrix()[i]));
125- }
126-
127- // オススメ度計算
128- System.out.println(java.util.Arrays.toString(rtn.multiply( new double[][] { {0, 1, 0, 0 , 0}})[0]));
129-
130- }
131-}
132-
--- trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/ga/AbstractHybsGAChromosome.java (nonexistent)
+++ trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/ga/AbstractHybsGAChromosome.java (revision 1413)
@@ -0,0 +1,95 @@
1+package org.opengion.penguin.math.ga;
2+
3+import java.util.ArrayList;
4+import java.util.List;
5+import org.apache.commons.math3.genetics.AbstractListChromosome;
6+import org.apache.commons.math3.genetics.InvalidRepresentationException;
7+
8+/**
9+ * HybsGeneticAlgorithmで利用するChromosomeインターフェースです。
10+ *
11+ * AbstractListChromosomeだと少し使いにくいので、AbstractListChromosomeを継承して
12+ * 独自にAbstractクラスを作成しています。
13+ * (大半はAbstractListChromosomeそのものです)
14+ *
15+ */
16+public abstract class AbstractHybsGAChromosome extends AbstractListChromosome<HybsGAObject> {
17+
18+ protected Object optionData; // 染色体に何らかのオプション情報を持たせる場合に利用
19+
20+ /**
21+ * デフォルトコンストラクタ。
22+ *
23+ * 空の染色体配列を持つインスタンスを作成する。
24+ * newInstanceメソッドでインスタンスを作成するために、若干トリッキーな事をする。
25+ * このコンストラクタを利用する場合はcloneで染色体セットし、増殖させて利用する。
26+ *
27+ * @throws InvalidRepresentationException 染色体の表現が無効であることを示す例外
28+ */
29+ public AbstractHybsGAChromosome() throws InvalidRepresentationException {
30+ super( new HybsGAObject[] {} );
31+ }
32+
33+ /**
34+ * 染色体のリストを引数に持つコンストラクタ。
35+ *
36+ * @param representation 染色体表現のリスト
37+ * @throws InvalidRepresentationException 染色体の表現が無効であることを示す例外
38+ */
39+ public AbstractHybsGAChromosome(final List<HybsGAObject> representation) throws InvalidRepresentationException {
40+ super(representation);
41+ }
42+
43+ /**
44+ * 初期化用のsetter。
45+ * 通常、copyListにはtrueをセットして染色体表現のインスタンスを新たに作成する。
46+ *
47+ * @param chromosomeRepresentation 染色体表現
48+ * @param copyList newを利用してクローンするかどうか
49+ * @return クローン
50+ */
51+ public AbstractListChromosome<HybsGAObject> clone(final List<HybsGAObject> chromosomeRepresentation, final boolean copyList) {
52+ checkValidity(chromosomeRepresentation);
53+ return newFixedLengthChromosome(copyList ? new ArrayList<HybsGAObject>(chromosomeRepresentation) : chromosomeRepresentation);
54+ }
55+
56+ /**
57+ * 初期化用のsetter。
58+ *
59+ * @param chromosomeRepresentation 染色体表現
60+ * @return クローン
61+ * @throws InvalidRepresentationException 染色体の表現が無効であることを示す例外
62+ */
63+ public AbstractListChromosome<HybsGAObject> clone(final List<HybsGAObject> chromosomeRepresentation) throws InvalidRepresentationException {
64+ return clone( chromosomeRepresentation, true );
65+ }
66+
67+ /**
68+ * 自分と同じクラスを作成するメソッド。
69+ * 各クラスで実装する。
70+ * 必要に応じてoptionDataをセットすること。
71+ *
72+ * @param repr 作成する際に渡す染色体
73+ * @return 作成されたクラス
74+ */
75+ @Override
76+ abstract public AbstractHybsGAChromosome newFixedLengthChromosome(final List<HybsGAObject> repr);
77+
78+ /**
79+ * 染色体配列を返す。
80+ *
81+ * @return 染色体配列
82+ */
83+ public List<HybsGAObject> getThisRepresentation() {
84+ return getRepresentation();
85+ }
86+
87+ /**
88+ * オプション情報を渡す場合に利用。
89+ *
90+ * @param option オプション情報
91+ */
92+ public void setOptionData( final Object option ) {
93+ this.optionData = option;
94+ }
95+}
--- trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/ga/HybsGAObject.java (nonexistent)
+++ trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/ga/HybsGAObject.java (revision 1413)
@@ -0,0 +1,26 @@
1+
2+package org.opengion.penguin.math.ga;
3+
4+/**
5+ * HybsGeneticAlgorithmで取り扱うデータ用の共通インターフェースです。
6+ *
7+ * GAではこのインタフェイスを継承したオブジェクトを遺伝情報として利用します。
8+ *
9+ */
10+public interface HybsGAObject {
11+ /**
12+ * fitness計算時に利用する値。
13+ * 実クラスでは、例えば内部の値を元にDBから検索した値でもよい。
14+ *
15+ * @return fitness用の値
16+ */
17+ double getFitness();
18+
19+ /**
20+ * 自身を表す文字列。
21+ *
22+ * @return 自身を表す文字列
23+ */
24+ @Override
25+ String toString() ;
26+}
--- trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/ga/HybsGAObjectImpl.java (nonexistent)
+++ trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/ga/HybsGAObjectImpl.java (revision 1413)
@@ -0,0 +1,193 @@
1+package org.opengion.penguin.math.ga;
2+
3+/**
4+ * HybsGeneticAlgorithmで取り扱うデータ用の実装クラスです。
5+ *
6+ * ある程度標準的に利用できるようにで、名称、属性値(実数)、属性値(文字列)、属性値配列(実数)、属性値配列(文字列)を持ちます。
7+ *
8+ */
9+public class HybsGAObjectImpl implements HybsGAObject {
10+ private String name; // 名称
11+ private double attr; // 属性値(実数)
12+ private String attrStr; // 属性値(文字列)
13+ private double[] attrArray; // 属性値配列(実数)
14+ private String[] attrStrArray; // 属性値配列(文字列)
15+
16+ /**
17+ * コンストラクタ。
18+ *
19+ * @param name 名称
20+ * @param attr 属性値(実数)
21+ */
22+ public HybsGAObjectImpl (final String name, final double attr){
23+ this( name, attr, null, null,null);
24+ }
25+
26+ /**
27+ * コンストラクタ。
28+ *
29+ * @param name 名称
30+ * @param attr 属性値(実数)
31+ * @param attrArray 属性値配列(実数)
32+ */
33+ public HybsGAObjectImpl (final String name, final double attr, final double[] attrArray){
34+ this( name, attr, null, attrArray, null);
35+ }
36+
37+ /**
38+ * コンストラクタ。
39+ *
40+ * @param name 名称
41+ * @param attr 属性値(実数)
42+ * @param attrStr 属性値(文字)
43+ * @param attrArray 属性値配列(実数)
44+ */
45+ public HybsGAObjectImpl (final String name, final double attr, final String attrStr, final double[] attrArray){
46+// this( name, attr, null, attrArray, null);
47+ this( name, attr, attrStr, attrArray, null);
48+ }
49+
50+ /**
51+ * コンストラクタ。
52+ *
53+ * @param name 名称
54+ * @param attr 属性値(実数)
55+ * @param attrStr 属性値(文字)
56+ * @param attrStrArray 属性値配列(文字)
57+ */
58+ public HybsGAObjectImpl (final String name, final double attr, final String attrStr, final String[] attrStrArray){
59+// this( name, attr, null, null, attrStrArray);
60+ this( name, attr, attrStr, null, attrStrArray);
61+ }
62+
63+ /**
64+ * コンストラクタ。
65+ *
66+ * @param name 名称
67+ * @param attr 属性値(実数)
68+ * @param attrStr 属性値(文字)
69+ * @param attrArray 属性値配列(実数)
70+ * @param attrStrArray 属性値配列(文字)
71+ */
72+ public HybsGAObjectImpl (final String name, final double attr, final String attrStr, final double[] attrArray, final String[] attrStrArray){
73+ this.name = name;
74+ this.attr = attr;
75+ this.attrStr = attrStr;
76+ this.attrArray = attrArray;
77+ this.attrStrArray = attrStrArray;
78+ }
79+
80+ // インタフェイスによる必須メソッド。
81+ /**
82+ * フィットネス用に利用する値。
83+ *
84+ * 属性値(実数)を返す
85+ *
86+ * @return フィットネス用に利用する値
87+ */
88+ public double getFitness(){
89+ return attr;
90+ }
91+
92+ /**
93+ * 文字列表現。
94+ *
95+ * [名称]([属性値(実数)])
96+ *
97+ * @return 文字列表現
98+ */
99+ @Override
100+ public String toString(){
101+ return name + "(" + attr + ")";
102+ }
103+
104+ /**
105+ * 名称セット。
106+ *
107+ * @param name 名称
108+ */
109+ public void setName (final String name ){
110+ this.name = name;
111+ }
112+
113+ /**
114+ * 名称取得。
115+ *
116+ * @return 名称
117+ */
118+ public String getName (){
119+ return this.name;
120+ }
121+
122+ /**
123+ * 属性値セット。
124+ *
125+ * @param attr 属性値
126+ */
127+ public void setAttr (final double attr ){
128+ this.attr = attr;
129+ }
130+
131+ /**
132+ * 属性値取得。
133+ *
134+ * @return 属性値(数値)
135+ */
136+ public double getAttr (){
137+ return this.attr;
138+ }
139+
140+ /**
141+ * 属性値(文字)セット。
142+ *
143+ * @param attrStr 属性値(文字)
144+ */
145+ public void setAttrStr (final String attrStr ){
146+ this.attrStr = attrStr;
147+ }
148+
149+ /**
150+ * 属性値(文字)取得。
151+ *
152+ * @return 属性値(文字)
153+ */
154+ public String getAttrStr (){
155+ return this.attrStr;
156+ }
157+
158+ /**
159+ * 属性値配列セット。
160+ *
161+ * @param attrArray 属性値配列
162+ */
163+ public void setAttrArray (final double[] attrArray ){
164+ this.attrArray = attrArray;
165+ }
166+
167+ /**
168+ * 属性値配列取得。
169+ *
170+ * @return 属性値配列
171+ */
172+ public double[] getAttrArray (){
173+ return this.attrArray;
174+ }
175+
176+ /**
177+ * 属性値配列(文字)セット。
178+ *
179+ * @param attrStrArray 属性値配列(文字)
180+ */
181+ public void setAttrStrArray (final String[] attrStrArray ){
182+ this.attrStrArray = attrStrArray;
183+ }
184+
185+ /**
186+ * 属性値配列(文字)取得。
187+ *
188+ * @return 属性値配列(文字)
189+ */
190+ public String[] getAttrStrArray (){
191+ return this.attrStrArray;
192+ }
193+}
--- trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/ga/HybsGeneticAlgorithm.java (nonexistent)
+++ trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/ga/HybsGeneticAlgorithm.java (revision 1413)
@@ -0,0 +1,254 @@
1+package org.opengion.penguin.math.ga;
2+
3+import java.util.Collections;
4+import java.util.List;
5+import java.util.Arrays;
6+import java.util.LinkedList;
7+import java.util.ArrayList;
8+import org.apache.commons.math3.genetics.MutationPolicy;
9+import org.apache.commons.math3.genetics.Chromosome;
10+import org.apache.commons.math3.genetics.ElitisticListPopulation;
11+import org.apache.commons.math3.genetics.FixedGenerationCount;
12+import org.apache.commons.math3.genetics.GeneticAlgorithm;
13+import org.apache.commons.math3.genetics.OrderedCrossover;
14+import org.apache.commons.math3.genetics.Population;
15+import org.apache.commons.math3.genetics.StoppingCondition;
16+import org.apache.commons.math3.genetics.TournamentSelection;
17+import org.opengion.penguin.common.SystemUtil;
18+
19+/**
20+ * apache.commons.mathを利用した遺伝的アルゴリズム実行クラスです。
21+ * 0/1ではなくリスト形式の染色体をある程度手軽に利用できるようにしています。
22+ * 利用する場合は上記パッケージをjava\jre\lib\ext等に配置してください。
23+ *
24+ * 交叉率等はsetterで与えられるようにしています。
25+ * スケジューリング等を考慮して、交叉方法はOrderedCrossover(順序交叉)としています。
26+ * 選択方式はトーナメントです。突然変異は遺伝子ランダム入れ替えです。
27+ *
28+ * 染色体として与えるものはhybsGAObjectインタフェイスを継承したクラスです。
29+ * AbstractListChromosomeを継承したAbstracthybsChromosomeを利用して染色体を作成します。
30+ *
31+ *
32+ * mainメソッドではサンプルとして、巡回セールスマン問題を行います。
33+ */
34+public class HybsGeneticAlgorithm {
35+ // 標準設定
36+ private int populationSize = 100; // 個数
37+ private double crossoverRate = 0.8; // 交叉率
38+ private double mutationRate = 0.05; // 突然変異率
39+ private double elitismRate = 0.1; // 残すエリートの割合
40+ private int tournamentArity = 2; // トーナメント個体数:2が一般的
41+ private String chromosomeClazz = "org.opengion.fukurou.math.HybsScheduleChromosome"; // 利用する染色体
42+ private Object optionData; // 作成する染色体クラスに自由にオプション情報を渡せるようにしておく
43+
44+ private HybsGAObject [] gaList;
45+
46+ /**
47+ * 内部クラス。
48+ *
49+ * 突然変異はランダム入れ替え方式とします
50+ */
51+// private static class RandomMutation implements MutationPolicy {
52+ private static final class RandomMutation implements MutationPolicy {
53+ /**
54+ * コンストラクタ。
55+ *
56+ * @param original オリジナル染色体
57+ * @return 突然変異染色体
58+ */
59+ public Chromosome mutate(final Chromosome original) {
60+ final AbstractHybsGAChromosome strChromosome = (AbstractHybsGAChromosome) original;
61+ final List<HybsGAObject> lists = strChromosome.getThisRepresentation();
62+ final int mutationIndex1 = GeneticAlgorithm.getRandomGenerator().nextInt(lists.size());
63+ final int mutationIndex2 = GeneticAlgorithm.getRandomGenerator().nextInt(lists.size());
64+ final List<HybsGAObject> mutatedChromosome = new ArrayList<HybsGAObject>(lists);
65+ final HybsGAObject mi1 = lists.get(mutationIndex1);
66+ final HybsGAObject mi2 = lists.get(mutationIndex2);
67+ mutatedChromosome.set(mutationIndex2, mi1);
68+ mutatedChromosome.set(mutationIndex1, mi2);
69+ return strChromosome.newFixedLengthChromosome(mutatedChromosome);
70+ }
71+ }
72+
73+ /**
74+ * 計算の実行。
75+ *
76+ * @return 最適染色体
77+ */
78+ public AbstractHybsGAChromosome execute() {
79+ // initialize a new genetic algorithm
80+ final GeneticAlgorithm ga = new GeneticAlgorithm(
81+ new OrderedCrossover<HybsGAObject>(), //CrossoverPolicy:順序交叉を利用する
82+ crossoverRate, //crossoverRate
83+ new RandomMutation(), //MutationPolicy
84+ mutationRate, //mutationRate
85+ new TournamentSelection(tournamentArity) //SelectionPolicy
86+ );
87+
88+ // initial population
89+ final Population initial = getInitialPopulation();
90+
91+ // stopping condition
92+ final StoppingCondition stopCond = new FixedGenerationCount(100);
93+
94+ // run the algorithm
95+ final Population finalPopulation = ga.evolve(initial, stopCond);
96+
97+ // best chromosome from the final population
98+ final Chromosome bestFinal = finalPopulation.getFittestChromosome();
99+
100+ return (AbstractHybsGAChromosome)bestFinal;
101+ }
102+
103+ /**
104+ * 初期遺伝子の作成。シャッフルする。
105+ *
106+ * クラスの読み込み部分をfukurouに依存
107+ *
108+ * @return 初期遺伝子
109+ */
110+ private Population getInitialPopulation() {
111+ final List<Chromosome> popList = new LinkedList<Chromosome>();
112+ final List<HybsGAObject> gal = Arrays.asList(gaList);
113+// AbstractHybsGAChromosome chr = (AbstractHybsGAChromosome)newInstance( chromosomeClazz );
114+ final AbstractHybsGAChromosome chr = (AbstractHybsGAChromosome)SystemUtil.newInstance( chromosomeClazz );
115+ chr.setOptionData( optionData );
116+ for (int i = 0; i < populationSize; i++) {
117+ Collections.shuffle(gal);
118+ popList.add( chr.clone(gal) );
119+ }
120+ return new ElitisticListPopulation(popList, 2 * popList.size(), elitismRate);
121+ }
122+
123+ /**
124+ * 染色体配列のセット。
125+ *
126+ * @param gal 染色体とする配列
127+ * @return クラス自身
128+ */
129+ public HybsGeneticAlgorithm setGAList(final HybsGAObject[] gal ) {
130+ this.gaList = gal;
131+ return this;
132+ }
133+
134+ /**
135+ * 交叉率のセット。
136+ * 交叉率+突然変異率 < 1.0 となるようにする
137+ * 初期値は0.8
138+ *
139+ * @param cr 交叉率
140+ * @return クラス自身
141+ */
142+ public HybsGeneticAlgorithm setCrossoverRate(final double cr ){
143+ this.crossoverRate = cr;
144+ return this;
145+ }
146+
147+ /**
148+ * 突然変異率のセット。
149+ * 交叉率+突然変異率 < 1.0 となるようにする
150+ * 初期値は0.05
151+ *
152+ * @param mr 突然変異率
153+ * @return クラス自身
154+ */
155+ public HybsGeneticAlgorithm setMutationRate(final double mr ){
156+ this.mutationRate = mr;
157+ return this;
158+ }
159+
160+ /**
161+ * エリート主義の割合。
162+ * 初期値は0.2
163+ *
164+ * @param er エリート主義の率
165+ * @return クラス自身
166+ */
167+ public HybsGeneticAlgorithm setElitismRate(final double er ){
168+ this.elitismRate = er;
169+ return this;
170+ }
171+
172+ /**
173+ * トーナメントサイズ。
174+ * 初期値は2
175+ *
176+ * @param ta トーナメントサイズ
177+ * @return クラス自身
178+ */
179+ public HybsGeneticAlgorithm setTournamentArity(final int ta ){
180+ this.tournamentArity = ta;
181+ return this;
182+ }
183+
184+ /**
185+ * 集団サイズ。
186+ * 染色体のサイズ等によって適度な値を取るべきだが、初期値は100としている。
187+ *
188+ *
189+ * @param ps 集団サイズ
190+ * @return クラス自身
191+ */
192+ public HybsGeneticAlgorithm setPopulationSize(final int ps ){
193+ this.populationSize = ps;
194+ return this;
195+ }
196+
197+ /**
198+ * 利用する染色体クラスを指定します。
199+ * 初期値はorg.opengion.fukurou.math.HybsScheduleChromosome
200+ *
201+ * @param cc 染色体のクラス名
202+ * @return クラス自身
203+ */
204+ public HybsGeneticAlgorithm setChromosomeClazz(final String cc ){
205+ this.chromosomeClazz = cc;
206+ return this;
207+ }
208+
209+ /**
210+ * 染色体クラスにオプションをセットします。
211+ *
212+ * @param obj オプションデータ
213+ * @return クラス自身
214+ */
215+ public HybsGeneticAlgorithm setOptionData(final Object obj ){
216+ this.optionData = obj;
217+ return this;
218+ }
219+
220+ /*** ここまでがGA本体 ***/
221+ /**
222+ * ここからテスト用mainメソッド。
223+ *
224+ * @param args ****************************************
225+ */
226+ public static void main(final String [] args) {
227+
228+ final AbstractHybsGAChromosome rtn1 = new HybsGeneticAlgorithm()
229+ .setChromosomeClazz("org.opengion.penguin.math.HybsTSPChromosome")
230+ .setGAList(new HybsGAObject[] {
231+ new HybsGAObjectImpl("1",1,new double[] {1,1})
232+ ,new HybsGAObjectImpl("2",2,new double[] {1,10})
233+ ,new HybsGAObjectImpl("3",3,new double[] {11,20})
234+ ,new HybsGAObjectImpl("4",4,new double[] {22,50})
235+ ,new HybsGAObjectImpl("5",5,new double[] {25,70})
236+ ,new HybsGAObjectImpl("6",6,new double[] {33,5})
237+ ,new HybsGAObjectImpl("7",7,new double[] {54,20})
238+ ,new HybsGAObjectImpl("8",8,new double[] {75,80})
239+ ,new HybsGAObjectImpl("9",9,new double[] {86,55})
240+ ,new HybsGAObjectImpl("10",10,new double[] {97,90})
241+ ,new HybsGAObjectImpl("11",11,new double[] {18,50})
242+ ,new HybsGAObjectImpl("12",12,new double[] {39,10})
243+ ,new HybsGAObjectImpl("13",13,new double[] {40,90})
244+ ,new HybsGAObjectImpl("14",14,new double[] {51,10})
245+ ,new HybsGAObjectImpl("15",15,new double[] {62,55})
246+ ,new HybsGAObjectImpl("16",16,new double[] {73,70})
247+ ,new HybsGAObjectImpl("17",17,new double[] {84,10})
248+ ,new HybsGAObjectImpl("18",18,new double[] {95,45})
249+ }).execute();
250+
251+ System.out.println(rtn1.toString());
252+ System.out.println( 1/rtn1.getFitness() +"\n");
253+ }
254+}
--- trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/ga/HybsScheduleChromosome.java (nonexistent)
+++ trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/ga/HybsScheduleChromosome.java (revision 1413)
@@ -0,0 +1,133 @@
1+package org.opengion.penguin.math.ga;
2+
3+import java.util.ArrayList;
4+import java.util.List;
5+import java.util.Map;
6+import java.util.HashMap;
7+import org.apache.commons.math3.genetics.InvalidRepresentationException;
8+
9+/**
10+ * AbstractHybsGAChromosomeのサンプル実装クラスです。
11+ * HybsGAObjectImplを利用しています。
12+ * 属性値配列(文字列)にタスクの割当先(機械や人)候補
13+ * 属性値(実数)にこのタスクにかかる時間
14+ * 属性値配列(実数)[0]にこのタスクの納期(開始からの経過時間)
15+ * を持たせているという想定です。
16+ * このクラスでは次のようにスケジュールを決めます。
17+ * 1.候補のうち、一番タスクが積まれていないものに前から積む
18+ * 2.同じであればリストの先頭の方に割り当てられる
19+ * 3.納期オーバーの場合は評価関数の値が小さくなるようにする
20+ *
21+ */
22+public class HybsScheduleChromosome extends AbstractHybsGAChromosome {
23+
24+ /**
25+ * コンストラクタ。
26+ */
27+ public HybsScheduleChromosome() {
28+ super();
29+ }
30+
31+ /**
32+ * コンストラクタ。
33+ *
34+ * @param representation 染色体表現
35+ */
36+ public HybsScheduleChromosome(final List<HybsGAObject> representation) {
37+ super(representation);
38+ }
39+
40+ /**
41+ * 適合度計算。
42+ *
43+ * @return 適合度計算の結果
44+ */
45+ public double fitness() {
46+ final List<HybsGAObject> representation = getRepresentation();
47+ double nokisum = 0.0;
48+// final HashMap<String,Double> machineList = new HashMap<String, Double>(); //名前は機械リストだが、人でも良い
49+// final HashMap<String, ArrayList<String>> taskSchedule = new HashMap<String, ArrayList<String>>();
50+ final Map<String,Double> machineList = new HashMap<String,Double>(); //名前は機械リストだが、人でも良い
51+ final Map<String, List<String>> taskSchedule = new HashMap<String, List<String>>();
52+
53+ // 実際にスケジュールの積み上げを行い、納期遅れの合計を出します
54+ nokisum = makeSchedule( representation, machineList, taskSchedule );
55+
56+ // リストから最大値を取得する(出てくる順番は問わない)
57+ double maxWork=0;
58+ for( final String mw : machineList.keySet() ){
59+ maxWork = ( machineList.get(mw) > maxWork ) ? machineList.get(mw) :maxWork;
60+ }
61+
62+ return 1 / ( maxWork + nokisum*nokisum); //納期遅れが多くなるとどんどん値が小さくなるように評価する
63+ }
64+
65+ /**
66+ * HybsGAObjectImplを利用して前からスケジュールを積み上げていきます。
67+ *
68+ * @param representation 染色体表現
69+ * @param machineList マシンに対する積み上げ工数のリスト。(書き込まれるのでfinalにしない)
70+ * @param taskSchedule マシンに対して、前からタスクをセットするリスト。(書き込まれるのでfinalにしない)
71+ * @return 納期遅れの累計
72+ */
73+// public double makeSchedule( final List<HybsGAObject> representation , final HashMap<String,Double> machineList, final HashMap<String, ArrayList<String>> taskSchedule){
74+ public double makeSchedule( final List<HybsGAObject> representation , final Map<String,Double> machineList, final Map<String, List<String>> taskSchedule){
75+ HybsGAObjectImpl chrom;
76+ double nokisum = 0.0;
77+
78+ for ( int i=0; i<representation.size(); i++){
79+ chrom = (HybsGAObjectImpl)representation.get(i);
80+
81+ final String[] machines = chrom.getAttrStrArray();
82+ // ここでスケジュールを当てはめていく
83+ final double noki = chrom.getAttrArray()[0];
84+ String hitMachine = null;
85+ double work=999999999;
86+ for( int j=0; j<machines.length; j++ ){
87+ if(!machineList.containsKey( machines[j] )){
88+ machineList.put( machines[j], new Double(0) );
89+ taskSchedule.put( machines[j], new ArrayList<String>() );
90+ }
91+
92+ if( machineList.get(machines[j]) < work){
93+ work = machineList.get(machines[j]);
94+ hitMachine = machines[j];
95+ }
96+ }
97+
98+ machineList.put( hitMachine, new Double(work + chrom.getAttr()) ); // 総工数
99+ taskSchedule.get( hitMachine ).add( chrom.getName() ); // 割りついたタスクリスト
100+
101+ if( work + chrom.getAttr() > noki ){
102+ nokisum += ( noki - (work + chrom.getAttr()) );
103+ }
104+ }
105+ return nokisum;
106+ }
107+
108+ /**
109+ * 自身のクラスを新たに作成するメソッド。
110+ *
111+ * ここではオプションデータはクローンせずに参照で渡しています。
112+ * (計算では利用していません)
113+ *
114+ * @param repr 染色体表現
115+ * @return 作成された自分自身のクラス
116+ */
117+ @Override
118+ public AbstractHybsGAChromosome newFixedLengthChromosome(final List<HybsGAObject> repr) {
119+ final HybsScheduleChromosome rtn = new HybsScheduleChromosome(repr);
120+ rtn .setOptionData( optionData );
121+ return rtn;
122+ }
123+
124+ /**
125+ * 染色体表現のチェック。
126+ *
127+ * @param repr HybsGAObjectのリスト
128+ */
129+ @Override
130+ protected void checkValidity(final List<HybsGAObject> repr) throws InvalidRepresentationException {
131+ // Listの中身のチェックをする箇所。必要であれば記述する
132+ }
133+}
--- trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/ga/HybsTSPChromosome.java (nonexistent)
+++ trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/ga/HybsTSPChromosome.java (revision 1413)
@@ -0,0 +1,79 @@
1+package org.opengion.penguin.math.ga;
2+
3+import java.util.List;
4+import org.apache.commons.math3.genetics.InvalidRepresentationException;
5+
6+/**
7+ * AbstractHybsGAChromosomeのサンプル実装クラスです.
8+ * HybsGAObjectImplを利用してます。
9+ * Implの配列に各都市の座標が入っており、座標間の距離を元にして
10+ * 単純な巡回セールスマン問題を解きます。
11+ * (ルートが交差するかどうかは問いません)
12+ *
13+ */
14+public class HybsTSPChromosome extends AbstractHybsGAChromosome {
15+
16+ /**
17+ * コンストラクタ。
18+ */
19+ public HybsTSPChromosome() {
20+ super();
21+ }
22+
23+ /**
24+ * コンストラクタ。
25+ *
26+ * @param representation 染色体表現
27+ */
28+ public HybsTSPChromosome(final List<HybsGAObject> representation) {
29+ super(representation);
30+ }
31+
32+ /**
33+ * 適合度計算。
34+ *
35+ * @return 適合度計算の結果
36+ */
37+ public double fitness() {
38+ double fitness = 0.0;
39+ // int idx = 0;
40+ final List<HybsGAObject> representation = getRepresentation();
41+
42+ // implをここでは利用する。attrArrayを座標として距離から求めることとする
43+ double[] bfr = ((HybsGAObjectImpl)( representation.get( representation.size()-1 ) )).getAttrArray();
44+ double[] now = {0,0};
45+ for ( final HybsGAObject chrom : representation ) {
46+ // 一つ前との距離をプラス
47+ now = ((HybsGAObjectImpl)chrom).getAttrArray();
48+ fitness += Math.sqrt( (bfr[0]-now[0])*(bfr[0]-now[0]) + (bfr[1]-now[1])*(bfr[1]-now[1]) );
49+
50+ bfr=now;
51+ // idx++;
52+ }
53+
54+ // fitnessが最小になると適合度が最大になる
55+ // 交差等は特に考えず、単純に計算
56+ return 1 / fitness;
57+ }
58+
59+ /**
60+ * 自身のクラスを新たに作成するメソッド。
61+ *
62+ * @param repr 染色体表現
63+ * @return 作成された自分自身のクラス
64+ */
65+ @Override
66+ public AbstractHybsGAChromosome newFixedLengthChromosome(final List<HybsGAObject> repr) {
67+ return new HybsTSPChromosome(repr);
68+ }
69+
70+ /**
71+ * 染色体表現のチェック。
72+ *
73+ * @param repr 染色体表現リスト
74+ */
75+ @Override
76+ protected void checkValidity(final List<HybsGAObject> repr) throws InvalidRepresentationException {
77+ // Listの中身のチェックをする箇所。必要であれば記述する
78+ }
79+}
--- trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/package.html (revision 1412)
+++ trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/package.html (revision 1413)
@@ -1,6 +1,6 @@
11 <body>
22 数学的処理をするためのクラスを提供します。
33
4-単純な数値計算ではなく、遺伝的アルゴリズム等を利用するためのクラスです。<br />
4+遺伝的アルゴリズムや統計計算のためのクラスです。<br />
55
66 </body>
--- trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/statistics/HybsCorrelation.java (nonexistent)
+++ trunk/opengionV5/uap/webapps/gf/src/org/opengion/penguin/math/statistics/HybsCorrelation.java (revision 1413)
@@ -0,0 +1,131 @@
1+package org.opengion.penguin.math.statistics;
2+
3+import org.apache.commons.math3.linear.MatrixUtils;
4+import org.apache.commons.math3.linear.RealMatrix;
5+import org.apache.commons.math3.stat.correlation.PearsonsCorrelation;
6+
7+/**
8+ * apache.commons.mathを利用した相関計算及びその周辺機能を利用するためのクラスです。
9+ *
10+ * とりあえず通常のピアソン積率相関のみを利用可能としておきます。
11+ *
12+ */
13+public class HybsCorrelation {
14+ private String[] names;
15+ private double[][] pearsonsMatrix;
16+ private RealMatrix corrMatrix;
17+
18+
19+ /**
20+ * コンストラクタ。
21+ * 与えたデータマトリクスを元にピアソン積率相関を計算します。
22+ * 名称 = { "数学" , "英語", "国語" }
23+ * データ = { { 90 ,60 ,70 }, {70, 90, 80 } }
24+ * のような形としてデータを与えます。
25+ * @param name
26+ * @param matrix
27+ */
28+ public HybsCorrelation(String[] name, double[][] matrix){
29+ // 一応元データをセットしておく
30+ this.names = name;
31+ this.pearsonsMatrix = matrix;
32+
33+ // ここで相関係数行列を作成してしまう
34+ corrMatrix = (new PearsonsCorrelation()).computeCorrelationMatrix(pearsonsMatrix);
35+ }
36+
37+ /**
38+ * コンストラクタ。
39+ * 計算後の相関係数行列をdouble[][]型で直接与えられるようにしておきます。
40+ * 以前に計算した行列を使って行列の積を算出する場合に利用します。
41+ *
42+ * @param matrix
43+ */
44+ public HybsCorrelation( double[][] matrix){
45+ corrMatrix = MatrixUtils.createRealMatrix( matrix );
46+ }
47+
48+ /**
49+ * コンストラクタで算出した相関値行列に対して与えた行列を掛け算します。
50+ * 例えば以下のような算出を行う事が可能です。
51+ * 各商品を何回購入したかというデータを人数分用意し、相関係数行列を作成し、
52+ *  それに対してある人の今まで購入した履歴を掛け算する事で相関の高い商品を導出します。
53+ *  つまり、購入した事のないもので有意な相関係数を持つものは購入可能性が高いと言えます。
54+ * @param data 掛け算する行列
55+ * @return 行列積の結果マトリクス
56+ */
57+ public double[][] multiply(double[][] data){
58+ RealMatrix dataMatrix = MatrixUtils.createRealMatrix(data);
59+ RealMatrix scores = dataMatrix.multiply(corrMatrix);
60+
61+ return scores.getData();
62+ }
63+
64+ /**
65+ * 相関値行列取得。
66+ * @return 相関マトリクス
67+ */
68+ public double[][] getCorrMatrix(){
69+ return corrMatrix.getData();
70+ }
71+
72+ /**
73+ * 指定行の相関値配列取得。
74+ * @param x ROW番号
75+ * @return 行方向の相関ベクトル
76+ */
77+ public double[] getCorrMatrixRow(int x){
78+ return corrMatrix.getRow(x);
79+ }
80+
81+ /**
82+ * 指定列の相関値配列取得。
83+ * @param x COL番号
84+ * @return 列方向の相関ベクトル
85+ */
86+ public double[] getCorrMatrixCol(int x){
87+ return corrMatrix.getColumn(x);
88+ }
89+
90+ /**
91+ * 名称配列の取得。
92+ * @return 名称配列
93+ */
94+ public String[] getNames(){
95+ return names;
96+ }
97+
98+ /**
99+ * 名称配列のセット。
100+ * @param name 名称配列
101+ */
102+ public void setNames( String[] name){
103+ this.names = name;
104+ }
105+
106+ /*** ここまでが本体 ***/
107+ /*** ここからテスト用mainメソッド ***/
108+ /**
109+ * @param args *****************************************/
110+ public static void main(final String [] args) {
111+ String[] name = {"A", "B", "C", "D","E"};
112+ double[][] data = {
113+ {3, 1, 0, 0 , 1},
114+ {1, 0, 0, 0 , 1},
115+ {0, 0, 2, 2 , 2},
116+ {2, 2, 1, 0 , 0},
117+ {1, 0, 2, 4 , 1},
118+ };
119+
120+ HybsCorrelation rtn = new HybsCorrelation(name,data);
121+
122+ for( int i = 0; i< rtn.getCorrMatrix().length; i++ ){
123+ System.out.println(java.util.Arrays.toString(rtn.getCorrMatrix()[i]));
124+ }
125+
126+ // オススメ度計算
127+ System.out.println(java.util.Arrays.toString(rtn.multiply( new double[][] { {0, 1, 0, 0 , 0}})[0]));
128+
129+ }
130+}
131+
Show on old repository browser