-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathSocketProvidedDescriptor.java
409 lines (357 loc) · 13.3 KB
/
SocketProvidedDescriptor.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
/*
* DENOPTIM
* Copyright (C) 2022 Marco Foscato <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package denoptim.fitness.descriptors;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import org.openscience.cdk.exception.CDKException;
import org.openscience.cdk.interfaces.IAtomContainer;
import org.openscience.cdk.qsar.AbstractMolecularDescriptor;
import org.openscience.cdk.qsar.DescriptorSpecification;
import org.openscience.cdk.qsar.DescriptorValue;
import org.openscience.cdk.qsar.IMolecularDescriptor;
import org.openscience.cdk.qsar.result.DoubleResult;
import org.openscience.cdk.qsar.result.DoubleResultType;
import org.openscience.cdk.qsar.result.IDescriptorResult;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import denoptim.fitness.IDenoptimDescriptor;
/**
* Sends the request to produce a numerical descriptor to a defined socket and
* receives back the response. JSON format is used for communicating information
* in both directions. This class follows this convention:
* <ul>
* <li>sends JSON string with member {@value #KEYJSONMEMBERSMILES} containing the
* SMILES of the candidate.</li>
* <li>expects to receive a JSON with either member {@value #KEYJSONMEMBERSCORE}
* containing one descriptor score as a float (double), or
* {@value KEYJSONMEMBERERR} containing any error occurred on the server side.
* </li>
* </ul>
*/
// WARNING: any change to the format convention for the communication to the
// socket server must be reflected in the RequestHandler of the unit test.
public class SocketProvidedDescriptor extends AbstractMolecularDescriptor
implements IMolecularDescriptor, IDenoptimDescriptor
{
/**
* Version identifier
*/
private final int version = 1;
/**
* The key of the JSON member defining the SMILES of the candidate for which
* the socket server should produce descriptor.
*/
public final static String KEYJSONMEMBERSMILES = "SMILES";
/**
* The key of the JSON member defining the score/s for the descriptor
* calculated
*/
public final static String KEYJSONMEMBERSCORE = "SCORE";
/**
* The key of the JSON member defining an error in the calculation of the
* score.
*/
public final static String KEYJSONMEMBERERR = "ERROR";
/**
* The name of the host or ID address used to communicate with the socket
* server.
*/
private String hostname;
/**
* The identifier of the port used to communicate with the socket server.
*/
private Integer port;
/**
* Name of the input parameters
*/
private static final String[] PARAMNAMES = new String[] {
"hostname","port"};
/**
* NAme of the descriptor produced by this class
*/
private static final String[] NAMES = {"SocketProvidedDescriptor"};
//------------------------------------------------------------------------------
/**
* Constructor for a SocketProvidedDescriptor object
*/
public SocketProvidedDescriptor() {}
//------------------------------------------------------------------------------
/**
* Get the specification attribute of socket-based descriptor provider.
* @return the specification of this descriptor.
*/
@Override
public DescriptorSpecification getSpecification()
{
String paramID = "";
if (hostname!=null && port!=null)
{
paramID = "" + hostname + port;
}
return new DescriptorSpecification("Denoptim source code",
this.getClass().getName(), paramID, "DENOPTIM project");
}
//------------------------------------------------------------------------------
/**
* Gets the parameterNames attribute of the TanimotoMolSimilarity object.
* @return the parameterNames value
*/
@Override
public String[] getParameterNames() {
return PARAMNAMES;
}
//------------------------------------------------------------------------------
/** {@inheritDoc} */
@Override
public Object getParameterType(String name)
{
if (name.equals(PARAMNAMES[1])) //port
{
return 0;
} else if (name.equals(PARAMNAMES[0])) // hostname
{
return "";
} else {
throw new IllegalArgumentException("No parameter for name: "+name);
}
}
//------------------------------------------------------------------------------
/**
* Set the parameters attributes.
* The descriptor takes two parameters: the host name and the port number.
* @param params the array of parameters
*/
@Override
public void setParameters(Object[] params) throws CDKException
{
if (params.length != 2)
{
throw new IllegalArgumentException("SocketProvidedDescriptor only "
+ "expects two parameter");
}
if (!(params[0] instanceof String))
{
throw new IllegalArgumentException("Parameter is not String ("
+ params[0].getClass().getName() + ").");
}
if (!(params[1] instanceof Integer))
{
throw new IllegalArgumentException("Parameter is not Integer ("
+ params[0].getClass().getName() + ").");
}
hostname = (String) params[0];
port = (Integer) params[1];
}
//------------------------------------------------------------------------------
/** {@inheritDoc} */
@Override
public Object[] getParameters()
{
Object[] params = new Object[2];
params[0] = hostname;
params[1] = port;
return params;
}
//------------------------------------------------------------------------------
/** {@inheritDoc} */
@Override
public String[] getDescriptorNames()
{
return NAMES;
}
//------------------------------------------------------------------------------
/** {@inheritDoc} */
@Override
public DescriptorValue calculate(IAtomContainer mol)
{
Socket socket;
try
{
socket = new Socket(hostname, port);
} catch (IOException e1)
{
throw new IllegalArgumentException("Could not connect to socket",e1);
}
Runtime.getRuntime().addShutdownHook(new Thread(){public void run(){
try {
socket.close();
} catch (IOException e) { /* failed */ }
}});
PrintWriter writerToSocket;
try
{
OutputStream outputSocket = socket.getOutputStream();
writerToSocket = new PrintWriter(outputSocket, true);
} catch (IOException e1)
{
try
{
socket.close();
} catch (IOException e)
{
e.printStackTrace();
}
throw new IllegalArgumentException("Could not connect to socket",e1);
}
BufferedReader readerFromSocket;
try
{
InputStream inputFromSocket = socket.getInputStream();
readerFromSocket = new BufferedReader(
new InputStreamReader(inputFromSocket));
} catch (IOException e1)
{
try
{
socket.close();
} catch (IOException e)
{
e.printStackTrace();
}
throw new IllegalArgumentException("Could not read from socket",e1);
}
JsonObject jsonObj = new JsonObject();
Object smilesProp = mol.getProperty("SMILES");
if (smilesProp==null)
{
try
{
socket.close();
} catch (IOException e)
{
e.printStackTrace();
}
throw new IllegalArgumentException("AtomContainers fed to "
+ this.getClass().getName() + " are expected to contain "
+ "property '" + KEYJSONMEMBERSMILES
+ "', but it was not found.");
}
jsonObj.addProperty("SMILES", smilesProp.toString());
jsonObj.addProperty("version", version);
// So far there is no need of DENOPTIM's customized Gson builder.
Gson jsonConverted = new GsonBuilder().create();
// Here we send the request to the socket
writerToSocket.println(jsonConverted.toJson(jsonObj));
try
{
socket.shutdownOutput();
} catch (IOException e1)
{
try
{
socket.close();
} catch (IOException e)
{
// At this point the socket is probably closed already...
}
throw new IllegalStateException("Could not half-close socket from "
+ this.getClass().getName(),e1);
}
JsonObject answer = null;
DoubleResult result;
try {
answer = jsonConverted.fromJson(readerFromSocket.readLine(),
JsonObject.class);
if (answer.has(KEYJSONMEMBERSCORE))
{
double value = Double.parseDouble(
answer.get(KEYJSONMEMBERSCORE).toString());
result = new DoubleResult(value);
} else if (answer.has(KEYJSONMEMBERERR)) {
//System.err.println(KEYJSONMEMBERERR + " from socket server.");
result = new DoubleResult(Double.NaN);
} else {
System.err.println("WARNING: Socket server replied without "
+ "providing either " + KEYJSONMEMBERSCORE + " or "
+ KEYJSONMEMBERERR + " member. Setting desctriptor "
+ "'" + NAMES[0] + "'to NaN.");
result = new DoubleResult(Double.NaN);
}
} catch (JsonSyntaxException | IOException e) {
e.printStackTrace();
result = new DoubleResult(Double.NaN);
}
try
{
socket.close();
} catch (IOException e)
{
e.printStackTrace();
}
return new DescriptorValue(getSpecification(),
getParameterNames(),
getParameters(),
result,
getDescriptorNames());
}
//------------------------------------------------------------------------------
/** {@inheritDoc} */
@Override
public IDescriptorResult getDescriptorResultType()
{
return new DoubleResultType();
}
//------------------------------------------------------------------------------
/** {@inheritDoc} */
@Override
public String getDictionaryTitle()
{
return "Socket-provided descriptor";
}
//------------------------------------------------------------------------------
/** {@inheritDoc} */
@Override
public String getDictionaryDefinition()
{
return "We ignore how the descriptor is calculated. We only know we "
+ "can ask a socket server for a score. The connection can be "
+ "parametrized so that we can define that a server is "
+ "reachable at host name <code>" + PARAMNAMES[0] + "</code>, "
+ "and port <code>" + PARAMNAMES[1] + "</code>. By convention, "
+ "the communication deploys a JSON string. "
+ "Such format is expected for both "
+ "the request for a score (the request generated by "
+ "DENOPTIM, i.e., the client) and for "
+ "the answer to such request (produced by the "
+ "server). The requst contains always the SMILES of the "
+ "candidate (e.g., "
+ "<code>{\"" + KEYJSONMEMBERSMILES + "\": \"CCO\"}</code>). "
+ "The answer may "
+ "contain a <code>" + KEYJSONMEMBERSCORE + "</code> "
+ "or an <code>" + KEYJSONMEMBERERR + "</code> "
+ "(e.g., <code>{\"" + KEYJSONMEMBERSCORE + "\": 1.23}</code>). "
+ "Failure in the "
+ "communication protocol will produce a <code>NaN</code> "
+ "score.";
}
//------------------------------------------------------------------------------
/** {@inheritDoc} */
@Override
public String[] getDictionaryClass()
{
return new String[] {"molecular"};
}
//------------------------------------------------------------------------------
}