KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jgap > distr > grid > JGAPClient


1 /*
2  * This file is part of JGAP.
3  *
4  * JGAP offers a dual license model containing the LGPL as well as the MPL.
5  *
6  * For licencing information please see the file license.txt included with JGAP
7  * or have a look at the top of class org.jgap.Chromosome which representatively
8  * includes the JGAP license policy applicable for any file delivered with JGAP.
9  */

10 package org.jgap.distr.grid;
11
12 import org.apache.log4j.*;
13 import org.homedns.dade.jcgrid.client.*;
14 import org.jgap.*;
15 import org.homedns.dade.jcgrid.message.*;
16 import org.homedns.dade.jcgrid.cmd.*;
17 import org.apache.commons.cli.*;
18
19 /**
20  * A client defines work for the grid and sends it to the JGAPServer.
21  * Use this class as base class for your grid client implementations.
22  *
23  * @author Klaus Meffert
24  * @since 3.01
25  */

26 public class JGAPClient
27     extends Thread JavaDoc {
28   /** String containing the CVS revision. Read out via reflection!*/
29   private final static String JavaDoc CVS_REVISION = "$Revision: 1.9 $";
30
31   private final static String JavaDoc className = JGAPClient.class.getName();
32
33   private static Logger log = Logger.getLogger(className);
34
35   protected GridNodeClientConfig m_gridconfig;
36
37   protected JGAPRequest m_workReq;
38
39   private GridClient m_gc;
40
41   private IGridConfiguration m_gridConfig;
42
43   public JGAPClient(GridNodeClientConfig a_gridconfig, String JavaDoc a_clientClassName)
44       throws Exception JavaDoc {
45     m_gridconfig = a_gridconfig;
46     Class JavaDoc client = Class.forName(a_clientClassName);
47     m_gridConfig = (IGridConfiguration) client.getConstructor(new
48         Class JavaDoc[] {}).newInstance(new Object JavaDoc[] {});
49     m_gridConfig.initialize(m_gridconfig);
50     // Setup work request.
51
// -------------------
52
JGAPRequest req = new JGAPRequest(m_gridconfig.getSessionName(), 0,
53                                   m_gridConfig.getConfiguration());
54     req.setWorkerReturnStrategy(m_gridConfig.getWorkerReturnStrategy());
55     req.setGenotypeInitializer(m_gridConfig.getGenotypeInitializer());
56     req.setEvolveStrategy(m_gridConfig.getWorkerEvolveStrategy());
57     // Evolution takes place on client only!
58
// -------------------------------------
59
req.setEvolveStrategy(null);
60     setWorkRequest(req);
61     // Start the threaded process.
62
// ---------------------------
63
start();
64     join();
65   }
66
67   public void setWorkRequest(JGAPRequest a_request) {
68     m_workReq = a_request;
69   }
70
71   protected GridClient startClient()
72       throws Exception JavaDoc {
73     GridClient gc = new GridClient();
74     gc.setNodeConfig(m_gridconfig);
75     gc.start();
76     return gc;
77   }
78
79   /**
80    * Threaded: Splits work, sends it to workers and receives computed solutions.
81    *
82    * @author Klaus Meffert
83    * @since 3.01
84    */

85   public void run() {
86     try {
87       // Start client.
88
// -------------
89
m_gc = startClient();
90       try {
91         // Initialize evolution.
92
// ---------------------
93
IClientEvolveStrategy clientEvolver = m_gridConfig.getClientEvolveStrategy();
94         if (clientEvolver != null) {
95           clientEvolver.initialize(m_gc, getConfiguration(),
96                                     m_gridConfig.getClientFeedback());
97         }
98         // Do the evolution.
99
// -----------------
100
evolve(m_gc);
101       } finally {
102         try {
103           m_gc.stop();
104         } catch (Exception JavaDoc ex) {}
105       }
106     } catch (Exception JavaDoc ex) {
107       ex.printStackTrace();
108       m_gridConfig.getClientFeedback().error("Error while doing the work", ex);
109     }
110   }
111
112   protected void sendWorkRequests(JGAPRequest[] a_workList)
113       throws Exception JavaDoc {
114     // Send work requests.
115
// -------------------
116
for (int i = 0; i < a_workList.length; i++) {
117       JGAPRequest req = a_workList[i];
118       m_gridConfig.getClientFeedback().sendingFragmentRequest(req);
119       m_gc.send(new GridMessageWorkRequest(req));
120       if (this.isInterrupted()) {
121         break;
122       }
123     }
124   }
125
126   protected void receiveWorkResults(JGAPRequest[] workList)
127       throws Exception JavaDoc {
128     IClientFeedback feedback = m_gridConfig.getClientFeedback();
129     // Receive work results.
130
// ---------------------
131
int idx = -1;
132     for (int i = 0; i < workList.length; i++) {
133       feedback.setProgressValue(i + workList.length);
134       m_gc.getGridMessageChannel();
135       GridMessageWorkResult gmwr = (GridMessageWorkResult) m_gc.recv(i);
136       JGAPResult workResult = (JGAPResult) gmwr.getWorkResult();
137       m_gridConfig.getClientEvolveStrategy().resultReceived(workResult);
138       idx = workResult.getRID();
139       // Fire listener.
140
// --------------
141
feedback.receivedFragmentResult(workList[idx], workResult,
142                                       idx);
143       if (this.isInterrupted()) {
144         break;
145       }
146     }
147   }
148
149   /**
150    * If necessary: override to implement your evolution cycle individually.
151    *
152    * @param gc GridClient
153    * @throws Exception
154    */

155   protected void evolve(GridClient gc)
156       throws Exception JavaDoc {
157     // Do the complete evolution cycle until end.
158
// ------------------------------------------
159
IClientFeedback feedback = m_gridConfig.getClientFeedback();
160     feedback.beginWork();
161     IClientEvolveStrategy evolver = m_gridConfig.getClientEvolveStrategy();
162     IRequestSplitStrategy splitter = m_gridConfig.getRequestSplitStrategy();
163     int evolutionIndex = 0;
164     do {
165 // m_clientEvolveStrategy.beforeGenerateWorkResults();
166
JGAPRequest[] workRequests = evolver.generateWorkRequests(
167           m_workReq, splitter, null);
168       feedback.setProgressMaximum(0);
169       feedback.setProgressMaximum(workRequests.length - 1);
170       sendWorkRequests(workRequests);
171       if (this.isInterrupted()) {
172         break;
173       }
174       evolver.afterWorkRequestsSent();
175       receiveWorkResults(workRequests);
176       evolver.evolve();
177       // Fire listener that one evolution cycle is complete.
178
// ---------------------------------------------------
179
feedback.completeFrame(evolutionIndex);
180       evolutionIndex++;
181       // Check if evolution is finished.
182
// -------------------------------
183
if (evolver.isEvolutionFinished(evolutionIndex)) {
184         evolver.onFinished();
185         break;
186       }
187     } while (true);
188     m_gridConfig.getClientFeedback().endWork();
189   }
190
191   public void start() {
192     try {
193       m_gridConfig.validate();
194     } catch (Exception JavaDoc ex) {
195       throw new RuntimeException JavaDoc(ex);
196     }
197     super.start();
198   }
199
200   public Configuration getConfiguration() {
201     return m_gridConfig.getConfiguration();
202   }
203
204   /**
205    * Starts a client (first parameter: name of specific setup class).
206    *
207    * @param args String[]
208    *
209    * @author Klaus Meffert
210    * @since 3.01
211    */

212   public static void main(String JavaDoc[] args) {
213     if (args.length < 1) {
214       System.out.println(
215           "Please provide a name of the grid configuration class to use");
216       System.out.println("An example class would be "
217                          + "examples.grid.fitnessDistributed.GridConfiguration");
218       System.exit(1);
219     }
220     try {
221       // Setup logging.
222
// --------------
223
MainCmd.setUpLog4J("client", true);
224       // Command line options.
225
// ---------------------
226
GridNodeClientConfig config = new GridNodeClientConfig();
227       Options options = new Options();
228       CommandLine cmd = MainCmd.parseCommonOptions(options, config, args);
229       // Setup and start client.
230
// -----------------------
231
new JGAPClient(config, args[0]);
232     } catch (Exception JavaDoc ex) {
233       ex.printStackTrace();
234       System.exit(1);
235     }
236   }
237 }
238
Popular Tags