use of ambit2.smarts.processors.SMIRKSProcessor in project ambit-mirror by ideaconsult.
the class StdzBatchProcessor method process.
@Override
public IStructureRecord process(IStructureRecord record) throws Exception {
IAtomContainer mol;
IAtomContainer processed = null;
try {
mol = molReader.process(record);
if (mol != null) {
for (Property p : record.getRecordProperties()) {
Object v = record.getRecordProperty(p);
// already parsed
if (tags_to_keep != null && Arrays.binarySearch(tags_to_keep, p.getName()) < 0)
continue;
if (p.getName().startsWith("http://www.opentox.org/api/1.1#"))
continue;
else
mol.setProperty(p, v);
}
if (tags_to_keep != null) {
List<String> toRemove = null;
Iterator pi = mol.getProperties().keySet().iterator();
while (pi.hasNext()) {
Object p = pi.next();
if (Arrays.binarySearch(tags_to_keep, p.toString()) < 0) {
if (toRemove == null)
toRemove = new ArrayList<String>();
toRemove.add(p.toString());
}
}
if (toRemove != null)
for (String propertyToRemove : toRemove) mol.removeProperty(propertyToRemove);
}
} else {
logger.log(Level.SEVERE, "MSG_STANDARDIZE", new Object[] { "Empty molecule See the ERROR tag in the output file", getIds(record) });
return record;
}
} catch (Exception x) {
x.printStackTrace();
logger.log(Level.SEVERE, "MSG_ERR_MOLREAD", new Object[] { getIds(record), x.toString() });
return record;
} finally {
}
processed = mol;
// CDK adds these for the first MOL line
if (!writesdf) {
// mol.removeProperty(CDKConstants.TITLE);
if (mol.getProperty(CDKConstants.REMARK) != null)
mol.removeProperty(CDKConstants.REMARK);
}
if ((smirksProcessor != null) && smirksProcessor.isEnabled()) {
processed = smirksProcessor.process(processed);
}
try {
processed = standardprocessor.process(processed);
} catch (Exception x) {
String err = processed.getProperty(StructureStandardizer.ERROR_TAG);
logger.log(Level.SEVERE, x.getMessage(), x);
if (processed != null) {
err = processed.getProperty(StructureStandardizer.ERROR_TAG);
processed.setProperty(StructureStandardizer.ERROR_TAG, String.format("%s %s %s", err == null ? "" : err, x.getClass().getName(), x.getMessage()));
}
} finally {
if (processed != null) {
Iterator<Entry<Object, Object>> p = mol.getProperties().entrySet().iterator();
// molecule
while (p.hasNext()) {
Entry<Object, Object> entry = p.next();
Object value = processed.getProperty(entry.getKey());
if (value == null || "".equals(value.toString().trim()))
processed.setProperty(entry.getKey(), entry.getValue());
}
}
}
if (processed != null)
try {
if (writesdf && sdf_title != null) {
for (Entry<Object, Object> p : processed.getProperties().entrySet()) if (sdf_title.equals(p.getKey().toString().toLowerCase())) {
processed.setProperty(CDKConstants.TITLE, p.getValue());
break;
}
}
if (debugatomtypes) {
Object debug = (processed == null) ? null : processed.getProperty("AtomTypes");
if (debug != null && !"".equals(debug))
writer.write(processed);
} else
writer.write(processed);
} catch (Exception x) {
logger.log(Level.SEVERE, x.getMessage());
}
return record;
}
use of ambit2.smarts.processors.SMIRKSProcessor in project ambit-mirror by ideaconsult.
the class SmirksProcessorTest method test.
@Test
public void test() throws Exception {
URL config = this.getClass().getClassLoader().getResource("ambit2/smirks/smirks.json");
SMIRKSProcessor p = new SMIRKSProcessor(logger);
p.setLoadExamples(true);
p.loadReactionsFromJSON(new File(config.getFile()));
p.setTransformationasproperties(true);
Assert.assertEquals(51, p.getTransformations().size());
Assert.assertFalse(p.isAtomtypeasproperties());
p.setAtomtypeasproperties(true);
SMIRKSManager m = new SMIRKSManager(SilentChemObjectBuilder.getInstance());
SmilesParser parser = new SmilesParser(SilentChemObjectBuilder.getInstance());
for (SMIRKSTransformation t : p.getTransformations()) {
if (t.getExample() != null) {
IAtomContainer mol = parser.parseSmiles(t.getExample());
Assert.assertNotNull(mol);
AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(mol);
mol = p.process(mol);
logger.log(Level.INFO, String.format("%s\t%s", t.getName(), mol.getProperties()));
Assert.assertNotNull(String.format("%s\t%s", t.getName(), t.getExample()), mol.getProperty("Transformed"));
Assert.assertTrue((int) mol.getProperty("Transformed") > 0);
Assert.assertEquals(1, (int) mol.getProperty("T." + t.getName()));
Object atomsadded = mol.getProperty("AtomTypes.added");
if (atomsadded != null)
Assert.assertEquals("[]", mol.getProperty("AtomTypes.added").toString());
}
}
}
use of ambit2.smarts.processors.SMIRKSProcessor in project ambit-mirror by ideaconsult.
the class AmbitPipeline method parseCommandStandardize.
public void parseCommandStandardize(String subcommand, long now) throws Exception {
int page = parsePageParam();
int pagesize = parsePageSizeParam();
Object tmpTag = parseSdfTitleParam();
String smiles_header = parseInputTag_Param("smiles", IteratingDelimitedFileReader.defaultSMILESHeader);
String inchi_header = parseInputTag_Param("inchi", "InChI");
String inchikey_header = parseInputTag_Param("inchikey", "InChIKey");
final String sdf_title = tmpTag == null ? null : tmpTag.toString().toLowerCase();
final StructureStandardizer standardprocessor = new StructureStandardizer(logger_cli);
standardprocessor.setGenerate2D(parseBooleanParam(":generate2D", false));
standardprocessor.setGenerateTautomers(parseBooleanParam(":tautomers", false));
SMIRKSProcessor tmp = null;
try {
Object o = options.getParam(":smirks");
if (o != null) {
File smirksConfig = new File(o.toString());
if (smirksConfig.exists()) {
tmp = new SMIRKSProcessor(smirksConfig, logger_cli);
tmp.setEnabled(true);
} else
logger_cli.log(Level.WARNING, "SMIRKS transformation file not found");
}
} catch (Exception x) {
logger_cli.log(Level.SEVERE, x.getMessage());
tmp = null;
}
final SMIRKSProcessor smirksProcessor = tmp;
standardprocessor.setSplitFragments(parseBooleanParam(":splitfragments", false));
standardprocessor.setImplicitHydrogens(parseBooleanParam(":implicith", false));
standardprocessor.setNeutralise(parseBooleanParam(":neutralise", false));
final String[] tags_to_keep = parsetags_to_keep();
standardprocessor.setRankTag(parseStringParam(":tag_rank", "RANK"));
standardprocessor.setInchiTag(parseStringParam(":tag_inchi", "InChI"));
standardprocessor.setInchiKeyTag(parseStringParam(":tag_inchikey", "InChIKey"));
standardprocessor.setSMILESTag(parseStringParam(":tag_smiles", "SMILES"));
standardprocessor.setGenerateInChI(parseBooleanParam(":inchi", true));
standardprocessor.setGenerateSMILES(parseBooleanParam(":smiles", true));
standardprocessor.setGenerateSMILES_Canonical(parseBooleanParam(":smilescanonical", false));
standardprocessor.setGenerateSMILES_Aromatic(parseBooleanParam(":smilesaromatic", false));
standardprocessor.setGenerateStereofrom2D(parseBooleanParam(":generatestereofrom2d", false));
standardprocessor.setClearIsotopes(parseBooleanParam(":setClearIsotopes", false));
final boolean debugatomtypes = parseBooleanParam(":debugatomtypes", false);
final int startRecord = pagesize > 0 ? (page * pagesize + 1) : 1;
final int maxRecord = pagesize > 0 ? ((page + 1) * pagesize + 1) : pagesize;
final File file = getInputFile();
FileInputState in = new FileInputState(file);
in.setOptionalInChIHeader(inchi_header);
in.setOptionalInChIKeyHeader(inchikey_header);
in.setOptionalSMILESHeader(smiles_header);
if (options.output == null)
throw new FileNotFoundException("Output file not specified. Please use -o {file}");
final File outfile = new File(options.output);
logger_cli.log(Level.INFO, "MSG_INFO_READINGWRITING", new Object[] { file.getAbsoluteFile(), outfile.getAbsolutePath() });
FileOutputState out = new FileOutputState(outfile);
final IChemObjectWriter writer = out.getWriter();
if (writer instanceof FilesWithHeaderWriter)
((FilesWithHeaderWriter) writer).setAddSMILEScolumn(false);
final BatchDBProcessor<IStructureRecord> batch = new BatchDBProcessor<IStructureRecord>() {
@Override
public void onItemRead(IStructureRecord input, IBatchStatistics stats) {
super.onItemRead(input, stats);
if ((maxRecord > 0) && stats.getRecords(RECORDS_STATS.RECORDS_READ) >= (maxRecord))
cancel();
}
@Override
public boolean skip(IStructureRecord input, IBatchStatistics stats) {
return (stats.getRecords(RECORDS_STATS.RECORDS_READ) < startRecord) || ((maxRecord > 0) && (stats.getRecords(RECORDS_STATS.RECORDS_READ) >= maxRecord));
}
@Override
public void onItemSkipped(IStructureRecord input, IBatchStatistics stats) {
super.onItemSkipped(input, stats);
if (stats.isTimeToPrint(getSilentInterval() * 2))
propertyChangeSupport.firePropertyChange(PROPERTY_BATCHSTATS, null, stats);
}
@Override
public void onItemProcessing(IStructureRecord input, Object output, IBatchStatistics stats) {
}
@Override
public void onError(IStructureRecord input, Object output, IBatchStatistics stats, Exception x) {
super.onError(input, output, stats, x);
logger_cli.log(Level.SEVERE, x.getMessage());
}
@Override
public long getSilentInterval() {
return 30000L;
}
@Override
public void close() throws Exception {
try {
writer.close();
} catch (Exception x) {
} finally {
}
super.close();
}
};
batch.setProcessorChain(new ProcessorsChain<IStructureRecord, IBatchStatistics, IProcessor>());
batch.getProcessorChain().add(new StdzBatchProcessor(standardprocessor, smirksProcessor, tags_to_keep, logger_cli, writer, sdf_title, debugatomtypes));
batch.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (AbstractBatchProcessor.PROPERTY_BATCHSTATS.equals(evt.getPropertyName()))
logger_cli.log(Level.INFO, evt.getNewValue().toString());
}
});
/*
* standardprocessor.setCallback(new
* DefaultAmbitProcessor<IAtomContainer, IAtomContainer>() {
*
* @Override public IAtomContainer process(IAtomContainer target) throws
* Exception { try { //writer.write(target); } catch (Exception x) {
* logger.log(Level.SEVERE, x.getMessage()); } return target; } });
*/
IBatchStatistics stats = null;
try {
stats = batch.process(in);
} catch (Exception x) {
StringWriter w = new StringWriter();
x.printStackTrace(new PrintWriter(w));
logger_cli.log(Level.WARNING, "MSG_ERR", new Object[] { x.getMessage() });
logger_cli.log(Level.FINE, "MSG_ERR_DEBUG", new Object[] { x.getMessage(), w.toString() });
} finally {
try {
if (batch != null)
batch.close();
} catch (Exception x) {
logger_cli.log(Level.WARNING, "MSG_ERR", new Object[] { x.getMessage() });
}
if (stats != null)
logger_cli.log(Level.INFO, "MSG_INFO", new Object[] { stats.toString() });
}
}
Aggregations