List of usage examples for java.io File getAbsolutePath
public String getAbsolutePath()
From source file:mase.jbot.PresetCreator.java
public static void main(String[] args) throws Exception { if (args.length != 3) { System.out.println("PresetCreator [preset file] [controller file] [name tag]"); System.exit(1);/*ww w . jav a 2s. c o m*/ } File preset = new File(args[0]); File cont = new File(args[1]); File tag = new File(args[2]); PersistentSolution sol = SolutionPersistence.readSolution(new FileInputStream(cont)); GroupController contr = sol.getController(); if (contr instanceof HomogeneousGroupController) { AgentController ac = contr.getAgentControllers(1)[0]; File newFile = new File(preset.getAbsolutePath().replace(".conf", "") + "-" + tag + ".conf"); FileUtils.copyFile(preset, newFile); NEATAgentController nac = (NEATAgentController) ac; double[] w = NEATSerializer.serializeToArray(nac.getNetwork()); fillWeights(newFile, w); } else { AgentController[] acs = contr.getAgentControllers(0); for (int i = 0; i < acs.length; i++) { File newFile = new File( preset.getAbsolutePath().replace(".conf", "") + "-" + tag + "-" + i + ".conf"); FileUtils.copyFile(preset, newFile); NEATAgentController nac = (NEATAgentController) acs[i]; double[] w = NEATSerializer.serializeToArray(nac.getNetwork()); fillWeights(newFile, w); } } }
From source file:fr.inria.edelweiss.kgdqp.core.CentralizedInferrencing.java
public static void main(String args[]) throws ParseException, EngineException, InterruptedException, IOException { List<String> endpoints = new ArrayList<String>(); String queryPath = null;//ww w . ja va2 s. c o m boolean rulesSelection = false; File rulesDir = null; File ontDir = null; ///////////////// Graph graph = Graph.create(); QueryProcess exec = QueryProcess.create(graph); Options options = new Options(); Option helpOpt = new Option("h", "help", false, "print this message"); // Option queryOpt = new Option("q", "query", true, "specify the sparql query file"); // Option endpointOpt = new Option("e", "endpoint", true, "a federated sparql endpoint URL"); Option versionOpt = new Option("v", "version", false, "print the version information and exit"); Option rulesOpt = new Option("r", "rulesDir", true, "directory containing the inference rules"); Option ontOpt = new Option("o", "ontologiesDir", true, "directory containing the ontologies for rules selection"); // Option locOpt = new Option("c", "centralized", false, "performs centralized inferences"); Option dataOpt = new Option("l", "load", true, "data file or directory to be loaded"); // Option selOpt = new Option("s", "rulesSelection", false, "if set to true, only the applicable rules are run"); // options.addOption(queryOpt); // options.addOption(endpointOpt); options.addOption(helpOpt); options.addOption(versionOpt); options.addOption(rulesOpt); options.addOption(ontOpt); // options.addOption(selOpt); // options.addOption(locOpt); options.addOption(dataOpt); String header = "Corese/KGRAM rule engine experiment command line interface"; String footer = "\nPlease report any issue to alban.gaignard@cnrs.fr, olivier.corby@inria.fr"; CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("kgdqp", header, options, footer, true); System.exit(0); } if (cmd.hasOption("o")) { rulesSelection = true; String ontDirPath = cmd.getOptionValue("o"); ontDir = new File(ontDirPath); if (!ontDir.isDirectory()) { logger.warn(ontDirPath + " is not a valid directory path."); System.exit(0); } } if (!cmd.hasOption("r")) { logger.info("You must specify a path for inference rules directory !"); System.exit(0); } if (cmd.hasOption("l")) { String[] dataPaths = cmd.getOptionValues("l"); for (String path : dataPaths) { Load ld = Load.create(graph); ld.load(path); logger.info("Loaded " + path); } } if (cmd.hasOption("v")) { logger.info("version 3.0.4-SNAPSHOT"); System.exit(0); } String rulesDirPath = cmd.getOptionValue("r"); rulesDir = new File(rulesDirPath); if (!rulesDir.isDirectory()) { logger.warn(rulesDirPath + " is not a valid directory path."); System.exit(0); } // Local rules graph initialization Graph rulesG = Graph.create(); Load ld = Load.create(rulesG); if (rulesSelection) { // Ontology loading if (ontDir.isDirectory()) { for (File o : ontDir.listFiles()) { logger.info("Loading " + o.getAbsolutePath()); ld.load(o.getAbsolutePath()); } } } // Rules loading if (rulesDir.isDirectory()) { for (File r : rulesDir.listFiles()) { logger.info("Loading " + r.getAbsolutePath()); ld.load(r.getAbsolutePath()); } } // Rule engine initialization RuleEngine ruleEngine = RuleEngine.create(graph); ruleEngine.set(exec); ruleEngine.setOptimize(true); ruleEngine.setConstructResult(true); ruleEngine.setTrace(true); StopWatch sw = new StopWatch(); logger.info("Federated graph size : " + graph.size()); logger.info("Rules graph size : " + rulesG.size()); // Rule selection logger.info("Rules selection"); QueryProcess localKgram = QueryProcess.create(rulesG); ArrayList<String> applicableRules = new ArrayList<String>(); sw.start(); String rulesSelQuery = ""; if (rulesSelection) { rulesSelQuery = pertinentRulesQuery; } else { rulesSelQuery = allRulesQuery; } Mappings maps = localKgram.query(rulesSelQuery); logger.info("Rules selected in " + sw.getTime() + " ms"); logger.info("Applicable rules : " + maps.size()); // Selected rule loading for (Mapping map : maps) { IDatatype dt = (IDatatype) map.getValue("?res"); String rule = dt.getLabel(); //loading rule in the rule engine // logger.info("Adding rule : "); // System.out.println("-------"); // System.out.println(rule); // System.out.println(""); // if (! rule.toLowerCase().contains("sameas")) { applicableRules.add(rule); ruleEngine.addRule(rule); // } } // Rules application on distributed sparql endpoints logger.info("Rules application (" + applicableRules.size() + " rules)"); ExecutorService threadPool = Executors.newCachedThreadPool(); RuleEngineThread ruleThread = new RuleEngineThread(ruleEngine); sw.reset(); sw.start(); // ruleEngine.process(); threadPool.execute(ruleThread); threadPool.shutdown(); //monitoring loop while (!threadPool.isTerminated()) { // System.out.println("******************************"); // System.out.println(Util.jsonDqpCost(QueryProcessDQP.queryCounter, QueryProcessDQP.queryVolumeCounter, QueryProcessDQP.sourceCounter, QueryProcessDQP.sourceVolumeCounter)); // System.out.println("Rule engine running for " + sw.getTime() + " ms"); // System.out.println("Federated graph size : " + graph.size()); System.out.println(sw.getTime() + " , " + graph.size()); Thread.sleep(5000); } logger.info("Federated graph size : " + graph.size()); // logger.info(Util.jsonDqpCost(QueryProcessDQP.queryCounter, QueryProcessDQP.queryVolumeCounter, QueryProcessDQP.sourceCounter, QueryProcessDQP.sourceVolumeCounter)); // TripleFormat f = TripleFormat.create(graph, true); // f.write("/tmp/gAll.ttl"); }
From source file:act.installer.pubchem.PubchemSynonymFinder.java
public static void main(String[] args) throws Exception { org.apache.commons.cli.Options opts = new org.apache.commons.cli.Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());/* w ww . j a v a2 s . c o m*/ } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { System.err.format("Argument parsing failed: %s\n", e.getMessage()); HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } File rocksDBFile = new File(cl.getOptionValue(OPTION_INDEX_PATH)); if (!rocksDBFile.isDirectory()) { System.err.format("Index directory does not exist or is not a directory at '%s'", rocksDBFile.getAbsolutePath()); HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } List<String> compoundIds = null; if (cl.hasOption(OPTION_PUBCHEM_COMPOUND_ID)) { compoundIds = Collections.singletonList(cl.getOptionValue(OPTION_PUBCHEM_COMPOUND_ID)); } else if (cl.hasOption(OPTION_IDS_FILE)) { File idsFile = new File(cl.getOptionValue(OPTION_IDS_FILE)); if (!idsFile.exists()) { System.err.format("Cannot find Pubchem CIDs file at %s", idsFile.getAbsolutePath()); HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } compoundIds = getCIDsFromFile(idsFile); if (compoundIds.size() == 0) { System.err.format("Found zero Pubchem CIDs to process in file at '%s', exiting", idsFile.getAbsolutePath()); HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } } else { System.err.format("Must specify one of '%s' or '%s'; index is too big to print all synonyms.", OPTION_PUBCHEM_COMPOUND_ID, OPTION_IDS_FILE); HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } // Run a quick check to warn users of malformed ids. compoundIds.forEach(x -> { if (!PC_CID_PATTERN.matcher(x).matches()) { // Use matches() for complete matching. LOGGER.warn("Specified compound id does not match expected format: %s", x); } }); LOGGER.info("Opening DB and searching for %d Pubchem CIDs", compoundIds.size()); Pair<RocksDB, Map<PubchemTTLMerger.COLUMN_FAMILIES, ColumnFamilyHandle>> dbAndHandles = null; Map<String, PubchemSynonyms> results = new LinkedHashMap<>(compoundIds.size()); try { dbAndHandles = PubchemTTLMerger.openExistingRocksDB(rocksDBFile); RocksDB db = dbAndHandles.getLeft(); ColumnFamilyHandle cidToSynonymsCfh = dbAndHandles.getRight() .get(PubchemTTLMerger.COLUMN_FAMILIES.CID_TO_SYNONYMS); for (String cid : compoundIds) { PubchemSynonyms synonyms = null; byte[] val = db.get(cidToSynonymsCfh, cid.getBytes(UTF8)); if (val != null) { ObjectInputStream oi = new ObjectInputStream(new ByteArrayInputStream(val)); // We're relying on our use of a one-value-type per index model here so we can skip the instanceof check. synonyms = (PubchemSynonyms) oi.readObject(); } else { LOGGER.warn("No synonyms available for compound id '%s'", cid); } results.put(cid, synonyms); } } finally { if (dbAndHandles != null) { dbAndHandles.getLeft().close(); } } try (OutputStream outputStream = cl.hasOption(OPTION_OUTPUT) ? new FileOutputStream(cl.getOptionValue(OPTION_OUTPUT)) : System.out) { OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValue(outputStream, results); new OutputStreamWriter(outputStream).append('\n'); } LOGGER.info("Done searching for Pubchem synonyms"); }
From source file:Pathway2RDFv2.java
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, ServiceException, ClassNotFoundException, IDMapperException, ParseException { int softwareVersion = 0; int schemaVersion = 0; int latestRevision = 0; BioDataSource.init();/*from w w w.j ava 2 s .c o m*/ Class.forName("org.bridgedb.rdb.IDMapperRdb"); File dir = new File("/Users/andra/Downloads/bridge"); File[] bridgeDbFiles = dir.listFiles(); IDMapperStack mapper = new IDMapperStack(); for (File bridgeDbFile : bridgeDbFiles) { System.out.println(bridgeDbFile.getAbsolutePath()); mapper.addIDMapper("idmapper-pgdb:" + bridgeDbFile.getAbsolutePath()); } Model bridgeDbmodel = ModelFactory.createDefaultModel(); InputStream in = new FileInputStream("/tmp/BioDataSource.ttl"); bridgeDbmodel.read(in, "", "TURTLE"); WikiPathwaysClient client = new WikiPathwaysClient( new URL("http://www.wikipathways.org/wpi/webservice/webservice.php")); basicCalls.printMemoryStatus(); //Map wikipathway organisms to NCBI organisms HashMap<String, String> organismTaxonomy = wpRelatedCalls.getOrganismsTaxonomyMapping(); //HashMap<String, String> miriamSources = new HashMap<String, String>(); // HashMap<String, Str ing> miriamLinks = basicCalls.getMiriamUriBridgeDb(); //Document wikiPathwaysDom = basicCalls.openXmlFile(args[0]); Document wikiPathwaysDom = basicCalls.openXmlFile("/tmp/WpGPML.xml"); //initiate the Jena model to be populated Model model = ModelFactory.createDefaultModel(); Model voidModel = ModelFactory.createDefaultModel(); voidModel.setNsPrefix("xsd", XSD.getURI()); voidModel.setNsPrefix("void", Void.getURI()); voidModel.setNsPrefix("wprdf", "http://rdf.wikipathways.org/"); voidModel.setNsPrefix("pav", Pav.getURI()); voidModel.setNsPrefix("prov", Prov.getURI()); voidModel.setNsPrefix("dcterms", DCTerms.getURI()); voidModel.setNsPrefix("biopax", Biopax_level3.getURI()); voidModel.setNsPrefix("gpml", Gpml.getURI()); voidModel.setNsPrefix("wp", Wp.getURI()); voidModel.setNsPrefix("foaf", FOAF.getURI()); voidModel.setNsPrefix("hmdb", "http://identifiers.org/hmdb/"); voidModel.setNsPrefix("freq", Freq.getURI()); voidModel.setNsPrefix("dc", DC.getURI()); setModelPrefix(model); //Populate void.ttl Calendar now = Calendar.getInstance(); Literal nowLiteral = voidModel.createTypedLiteral(now); Literal titleLiteral = voidModel.createLiteral("WikiPathways-RDF VoID Description", "en"); Literal descriptionLiteral = voidModel .createLiteral("This is the VoID description for a WikiPathwyas-RDF dataset.", "en"); Resource voidBase = voidModel.createResource("http://rdf.wikipathways.org/"); Resource identifiersOrg = voidModel.createResource("http://identifiers.org"); Resource wpHomeBase = voidModel.createResource("http://www.wikipathways.org/"); Resource authorResource = voidModel .createResource("http://semantics.bigcat.unimaas.nl/figshare/search_author.php?author=waagmeester"); Resource apiResource = voidModel .createResource("http://www.wikipathways.org/wpi/webservice/webservice.php"); Resource mainDatadump = voidModel.createResource("http://rdf.wikipathways.org/wpContent.ttl.gz"); Resource license = voidModel.createResource("http://creativecommons.org/licenses/by/3.0/"); Resource instituteResource = voidModel.createResource("http://dbpedia.org/page/Maastricht_University"); voidBase.addProperty(RDF.type, Void.Dataset); voidBase.addProperty(DCTerms.title, titleLiteral); voidBase.addProperty(DCTerms.description, descriptionLiteral); voidBase.addProperty(FOAF.homepage, wpHomeBase); voidBase.addProperty(DCTerms.license, license); voidBase.addProperty(Void.uriSpace, voidBase); voidBase.addProperty(Void.uriSpace, identifiersOrg); voidBase.addProperty(Pav.importedBy, authorResource); voidBase.addProperty(Pav.importedFrom, apiResource); voidBase.addProperty(Pav.importedOn, nowLiteral); voidBase.addProperty(Void.dataDump, mainDatadump); voidBase.addProperty(Voag.frequencyOfChange, Freq.Irregular); voidBase.addProperty(Pav.createdBy, authorResource); voidBase.addProperty(Pav.createdAt, instituteResource); voidBase.addLiteral(Pav.createdOn, nowLiteral); voidBase.addProperty(DCTerms.subject, Biopax_level3.Pathway); voidBase.addProperty(Void.exampleResource, voidModel.createResource("http://identifiers.org/ncbigene/2678")); voidBase.addProperty(Void.exampleResource, voidModel.createResource("http://identifiers.org/pubmed/15215856")); voidBase.addProperty(Void.exampleResource, voidModel.createResource("http://identifiers.org/hmdb/HMDB02005")); voidBase.addProperty(Void.exampleResource, voidModel.createResource("http://rdf.wikipathways.org/WP15")); voidBase.addProperty(Void.exampleResource, voidModel.createResource("http://identifiers.org/obo.chebi/17242")); for (String organism : organismTaxonomy.values()) { voidBase.addProperty(DCTerms.subject, voidModel.createResource("http://dbpedia.org/page/" + organism.replace(" ", "_"))); } voidBase.addProperty(Void.vocabulary, Biopax_level3.NAMESPACE); voidBase.addProperty(Void.vocabulary, voidModel.createResource(Wp.getURI())); voidBase.addProperty(Void.vocabulary, voidModel.createResource(Gpml.getURI())); voidBase.addProperty(Void.vocabulary, FOAF.NAMESPACE); voidBase.addProperty(Void.vocabulary, Pav.NAMESPACE); //Custom Properties String baseUri = "http://rdf.wikipathways.org/"; NodeList pathwayElements = wikiPathwaysDom.getElementsByTagName("Pathway"); //BioDataSource.init(); for (int i = 0; i < pathwayElements.getLength(); i++) { Model pathwayModel = createPathwayModel(); String wpId = pathwayElements.item(i).getAttributes().getNamedItem("identifier").getTextContent(); String revision = pathwayElements.item(i).getAttributes().getNamedItem("revision").getTextContent(); String pathwayOrganism = ""; if (pathwayElements.item(i).getAttributes().getNamedItem("Organism") != null) pathwayOrganism = pathwayElements.item(i).getAttributes().getNamedItem("Organism").getTextContent() .trim(); if (Integer.valueOf(revision) > latestRevision) { latestRevision = Integer.valueOf(revision); } File f = new File("/tmp/" + args[0] + "/" + wpId + "_r" + revision + ".ttl"); System.out.println(f.getName()); if (!f.exists()) { Resource voidPwResource = wpRelatedCalls.addVoidTriples(voidModel, voidBase, pathwayElements.item(i), client); Resource pwResource = wpRelatedCalls.addPathwayLevelTriple(pathwayModel, pathwayElements.item(i), organismTaxonomy); // Get the comments NodeList commentElements = ((Element) pathwayElements.item(i)).getElementsByTagName("Comment"); wpRelatedCalls.addCommentTriples(pathwayModel, pwResource, commentElements, wpId, revision); // Get the Groups NodeList groupElements = ((Element) pathwayElements.item(i)).getElementsByTagName("Group"); for (int n = 0; n < groupElements.getLength(); n++) { wpRelatedCalls.addGroupTriples(pathwayModel, pwResource, groupElements.item(n), wpId, revision); } // Get all the Datanodes NodeList dataNodesElement = ((Element) pathwayElements.item(i)).getElementsByTagName("DataNode"); for (int j = 0; j < dataNodesElement.getLength(); j++) { wpRelatedCalls.addDataNodeTriples(pathwayModel, pwResource, dataNodesElement.item(j), wpId, revision, bridgeDbmodel, mapper); } // Get all the lines NodeList linesElement = ((Element) pathwayElements.item(i)).getElementsByTagName("Line"); for (int k = 0; k < linesElement.getLength(); k++) { wpRelatedCalls.addLineTriples(pathwayModel, pwResource, linesElement.item(k), wpId, revision); } //Get all the labels NodeList labelsElement = ((Element) pathwayElements.item(i)).getElementsByTagName("Label"); for (int l = 0; l < labelsElement.getLength(); l++) { wpRelatedCalls.addLabelTriples(pathwayModel, pwResource, labelsElement.item(l), wpId, revision); } NodeList referenceElements = ((Element) pathwayElements.item(i)) .getElementsByTagName("bp:PublicationXref"); for (int m = 0; m < referenceElements.getLength(); m++) { wpRelatedCalls.addReferenceTriples(pathwayModel, pwResource, referenceElements.item(m), wpId, revision); } NodeList referenceElements2 = ((Element) pathwayElements.item(i)) .getElementsByTagName("bp:publicationXref"); for (int m = 0; m < referenceElements2.getLength(); m++) { wpRelatedCalls.addReferenceTriples(pathwayModel, pwResource, referenceElements2.item(m), wpId, revision); } NodeList referenceElements3 = ((Element) pathwayElements.item(i)) .getElementsByTagName("bp:PublicationXRef"); for (int m = 0; m < referenceElements3.getLength(); m++) { wpRelatedCalls.addReferenceTriples(pathwayModel, pwResource, referenceElements3.item(m), wpId, revision); } NodeList ontologyElements = ((Element) pathwayElements.item(i)) .getElementsByTagName("bp:openControlledVocabulary"); for (int n = 0; n < ontologyElements.getLength(); n++) { wpRelatedCalls.addPathwayOntologyTriples(pathwayModel, pwResource, ontologyElements.item(n)); } System.out.println(wpId); basicCalls.saveRDF2File(pathwayModel, "/tmp/" + args[0] + "/" + wpId + "_r" + revision + ".ttl", "TURTLE"); model.add(pathwayModel); pathwayModel.removeAll(); } } Date myDate = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String myDateString = sdf.format(myDate); FileUtils.writeStringToFile(new File("latestVersion.txt"), "v" + schemaVersion + "." + softwareVersion + "." + latestRevision + "_" + myDateString); basicCalls.saveRDF2File(model, "/tmp/wpContent_v" + schemaVersion + "." + softwareVersion + "." + latestRevision + "_" + myDateString + ".ttl", "TURTLE"); basicCalls.saveRDF2File(voidModel, "/tmp/void.ttl", "TURTLE"); }
From source file:com.osrdata.etltoolbox.fileloader.Main.java
/** * Main entry point into the application. * @param args command line argunemtns//from w w w . j a va 2s . c om */ public static void main(String[] args) { Options options = new Options(); options.addOption(new Option("s", "spec", true, "Source-to-target specification file")); options.addOption(new Option("d", "directory", true, "Source directory to load")); options.addOption(new Option("f", "file", true, "File to perform operation on")); options.addOption(new Option("r", "replace", false, "Replace previously loaded data")); options.addOption(new Option("t", "trace", true, "Trace records processed at specified interval")); CommandLineParser parser = new BasicParser(); try { CommandLine line = parser.parse(options, args); if (line.hasOption("spec") && (line.hasOption("directory") || line.hasOption("file"))) { FileLoader loader = new FileLoader(line); loader.init(); if (line.hasOption("file")) { loader.load(new File(line.getOptionValue("file"))); } else if (line.hasOption("directory")) { File directory = new File(line.getOptionValue("directory")); if (directory.isDirectory()) { File[] files = directory.listFiles(); for (File file : files) { loader.load(file); } } else { log.fatal(directory.getAbsolutePath() + " does not appear to be a directory."); } } } else { usage(); } } catch (ParseException e) { usage(); } catch (IOException e) { e.printStackTrace(); } }
From source file:FaceRatios.java
@SuppressWarnings("serial") public static void main(String[] args) { int r = FSDK.ActivateLibrary(FACE_SDK_LICENSE); if (r == FSDK.FSDKE_OK) { FSDK.Initialize();/*ww w . jav a 2 s . co m*/ FSDK.SetFaceDetectionParameters(true, true, 384); Map<String, Map<String, ArrayList<Double>>> faceProperties = new HashMap<>(); for (String directory : new File(FACE_DIRECTORY).list()) { if (new File(FACE_DIRECTORY + directory).isDirectory()) { Map<String, ArrayList<Double>> properties = new HashMap<String, ArrayList<Double>>() { { for (String property : propertyNames) put(property, new ArrayList<Double>()); } }; File[] files = new File(FACE_DIRECTORY + directory).listFiles(); System.out.println("Analyzing " + directory + " with " + files.length + " files\n"); for (File file : files) { if (file.isFile()) { HImage imageHandle = new HImage(); FSDK.LoadImageFromFileW(imageHandle, file.getAbsolutePath()); FSDK.TFacePosition.ByReference facePosition = new FSDK.TFacePosition.ByReference(); if (FSDK.DetectFace(imageHandle, facePosition) == FSDK.FSDKE_OK) { FSDK_Features.ByReference facialFeatures = new FSDK_Features.ByReference(); FSDK.DetectFacialFeaturesInRegion(imageHandle, (FSDK.TFacePosition) facePosition, facialFeatures); Point[] featurePoints = new Point[FSDK.FSDK_FACIAL_FEATURE_COUNT]; for (int i = 0; i < FSDK.FSDK_FACIAL_FEATURE_COUNT; i++) { featurePoints[i] = new Point(0, 0); featurePoints[i].x = facialFeatures.features[i].x; featurePoints[i].y = facialFeatures.features[i].y; } double eyeDistance = featureDistance(featurePoints, FeatureID.LEFT_EYE, FeatureID.RIGHT_EYE); double rightEyeSize = featureDistance(featurePoints, FeatureID.RIGHT_EYE_INNER_CORNER, FeatureID.RIGHT_EYE_OUTER_CORNER); double leftEyeSize = featureDistance(featurePoints, FeatureID.LEFT_EYE_INNER_CORNER, FeatureID.LEFT_EYE_OUTER_CORNER); double averageEyeSize = (rightEyeSize + leftEyeSize) / 2; double mouthLength = featureDistance(featurePoints, FeatureID.MOUTH_RIGHT_CORNER, FeatureID.MOUTH_LEFT_CORNER); double mouthHeight = featureDistance(featurePoints, FeatureID.MOUTH_BOTTOM, FeatureID.MOUTH_TOP); double noseHeight = featureDistance(featurePoints, FeatureID.NOSE_BOTTOM, FeatureID.NOSE_BRIDGE); double chinHeight = featureDistance(featurePoints, FeatureID.CHIN_BOTTOM, FeatureID.MOUTH_BOTTOM); double chinToBridgeHeight = featureDistance(featurePoints, FeatureID.CHIN_BOTTOM, FeatureID.NOSE_BRIDGE); double faceContourLeft = (featurePoints[FeatureID.CHIN_BOTTOM.getIndex()].getY() - featurePoints[FeatureID.FACE_CONTOUR2.getIndex()].getY()) / (featurePoints[FeatureID.CHIN_BOTTOM.getIndex()].getX() - featurePoints[FeatureID.FACE_CONTOUR2.getIndex()].getX()); double faceContourRight = (featurePoints[FeatureID.CHIN_BOTTOM.getIndex()].getY() - featurePoints[FeatureID.FACE_CONTOUR12.getIndex()].getY()) / (featurePoints[FeatureID.CHIN_BOTTOM.getIndex()].getX() - featurePoints[FeatureID.FACE_CONTOUR12.getIndex()].getX()); double bridgeLeftEyeDistance = featureDistance(featurePoints, FeatureID.LEFT_EYE_INNER_CORNER, FeatureID.NOSE_BRIDGE); double bridgeRightEyeDistance = featureDistance(featurePoints, FeatureID.RIGHT_EYE_INNER_CORNER, FeatureID.NOSE_BRIDGE); properties.get("eyeSize/eyeDistance").add(averageEyeSize / eyeDistance); properties.get("eyeSizeDisparity") .add(Math.abs(leftEyeSize - rightEyeSize) / averageEyeSize); properties.get("bridgeToEyeDisparity") .add(Math.abs(bridgeLeftEyeDistance - bridgeRightEyeDistance) / ((bridgeLeftEyeDistance + bridgeRightEyeDistance) / 2)); properties.get("eyeDistance/mouthLength").add(eyeDistance / mouthLength); properties.get("eyeDistance/noseHeight").add(eyeDistance / noseHeight); properties.get("eyeSize/mouthLength").add(eyeDistance / mouthLength); properties.get("eyeSize/noseHeight").add(eyeDistance / noseHeight); properties.get("mouthLength/mouthHeight").add(mouthLength / mouthHeight); properties.get("chinHeight/noseHeight").add(chinHeight / noseHeight); properties.get("chinHeight/chinToBridgeHeight") .add(chinHeight / chinToBridgeHeight); properties.get("noseHeight/chinToBridgeHeight") .add(noseHeight / chinToBridgeHeight); properties.get("mouthHeight/chinToBridgeHeight") .add(mouthHeight / chinToBridgeHeight); properties.get("faceCountourAngle") .add(Math.toDegrees(Math.atan((faceContourLeft - faceContourRight) / (1 + faceContourLeft * faceContourRight)))); } FSDK.FreeImage(imageHandle); } } System.out.format("%32s\t%8s\t%8s\t%3s%n", "Property", "", "", "c"); System.out.println(new String(new char[76]).replace("\0", "-")); ArrayList<Entry<String, ArrayList<Double>>> propertyList = new ArrayList<>( properties.entrySet()); Collections.sort(propertyList, new Comparator<Entry<String, ArrayList<Double>>>() { @Override public int compare(Entry<String, ArrayList<Double>> arg0, Entry<String, ArrayList<Double>> arg1) { DescriptiveStatistics dStats0 = new DescriptiveStatistics(listToArray(arg0.getValue())); DescriptiveStatistics dStats1 = new DescriptiveStatistics(listToArray(arg1.getValue())); return new Double(dStats0.getStandardDeviation() / dStats0.getMean()) .compareTo(dStats1.getStandardDeviation() / dStats1.getMean()); } }); for (Entry<String, ArrayList<Double>> property : propertyList) { DescriptiveStatistics dStats = new DescriptiveStatistics(listToArray(property.getValue())); System.out.format("%32s\t%4f\t%4f\t%3s%n", property.getKey(), dStats.getMean(), dStats.getStandardDeviation(), Math.round(dStats.getStandardDeviation() / dStats.getMean() * 100) + "%"); } System.out.println("\n"); faceProperties.put(directory, properties); } } for (String propertyName : propertyNames) { DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset(); for (Entry<String, Map<String, ArrayList<Double>>> face : faceProperties.entrySet()) { dataset.add(face.getValue().get(propertyName), "Default Series", face.getKey()); } PropertyBoxWhisker plot = new PropertyBoxWhisker(propertyName, dataset); plot.pack(); plot.setVisible(true); } } }
From source file:com.norconex.collector.http.HttpCollector.java
/** * Invokes the HTTP Collector from the command line. * @param args Invoke it once without any arguments to get a * list of command-line options.//from w w w .ja va2 s .com */ public static void main(String[] args) { CommandLine cmd = parseCommandLineArguments(args); String action = cmd.getOptionValue(ARG_ACTION); File configFile = new File(cmd.getOptionValue(ARG_CONFIG)); File varFile = null; if (cmd.hasOption(ARG_VARIABLES)) { varFile = new File(cmd.getOptionValue(ARG_VARIABLES)); } try { HttpCollector conn = new HttpCollector(configFile, varFile); if (ARG_ACTION_START.equalsIgnoreCase(action)) { conn.crawl(false); } else if (ARG_ACTION_RESUME.equalsIgnoreCase(action)) { conn.crawl(true); } else if (ARG_ACTION_STOP.equalsIgnoreCase(action)) { conn.stop(); } } catch (Exception e) { File errorFile = new File("./error-" + System.currentTimeMillis() + ".log"); System.err.println("\n\nAn ERROR occured:\n\n" + e.getLocalizedMessage()); System.err.println( "\n\nDetails of the error has been stored at: " + errorFile.getAbsolutePath() + "\n\n"); try { PrintWriter w = new PrintWriter(errorFile); e.printStackTrace(w); w.flush(); w.close(); } catch (FileNotFoundException e1) { throw new HttpCollectorException("Cannot write error file.", e1); } } }
From source file:com.opendesign.utils.ThumbnailManager.java
public static void main(String[] args) { // //product ? // saveThumbDesignWorkMedium(thumbnailPath); //? ?? // saveThumbDesignWorkLarge(thumbnailPath); //? ?? // //from w ww .ja v a2 s. com // //project ? // saveThumbDesignWorkMedium(thumbnailPath); //? ?? // saveThumbProjectWorkMedium(thumbnailPath); //? ?? // // //work ? // saveThumbProjectWorkSmall(thumbnailPath); //? ?? // saveThumbProjectWorkLarge(thumbnailPath); //? ?? File productFolder = new File( "/Users/windfall/Desktop/00_working/02_?/02_01_OpenDesign/02_01_100_temp/km_upload/product"); int updated = 0; int total = 0; for (File image : productFolder.listFiles()) { if (image != null) { System.out.println("resizing " + image.getAbsolutePath()); saveThumbDesignWorkMedium(image.getAbsolutePath()); //? ?? saveThumbDesignWorkLarge(image.getAbsolutePath()); //? ?? updated++; } else { System.out.println("Fail=" + image); } total++; } System.out.println("Product Files=[" + total + "] updated=[" + updated + "]"); updated = 0; total = 0; File projectFolder = new File( "/Users/windfall/Desktop/00_working/02_?/02_01_OpenDesign/02_01_100_temp/km_upload/project"); for (File image : projectFolder.listFiles()) { if (image != null) { System.out.println("resizing " + image.getAbsolutePath()); saveThumbDesignWorkMedium(image.getAbsolutePath()); //? ?? saveThumbProjectWorkMedium(image.getAbsolutePath()); //? ?? updated++; } else { System.out.println("Fail=" + image); } total++; } System.out.println("Project Files=[" + total + "] updated=[" + updated + "]"); updated = 0; total = 0; File workFolder = new File( "/Users/windfall/Desktop/00_working/02_?/02_01_OpenDesign/02_01_100_temp/km_upload/project_work_file"); for (File image : workFolder.listFiles()) { if (image != null) { System.out.println("resizing " + image.getAbsolutePath()); saveThumbProjectWorkSmall(image.getAbsolutePath()); //? ?? saveThumbProjectWorkLarge(image.getAbsolutePath()); //? ?? updated++; } else { System.out.println("Fail=" + image); } total++; } System.out.println("Work Files=[" + total + "] updated=[" + updated + "]"); }
From source file:com.act.biointerpretation.l2expansion.L2ExpansionDriver.java
public static void main(String[] args) throws Exception { // Build command line parser. Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());//from w w w .j a va 2 s. c om } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { LOGGER.error("Argument parsing failed: %s", e.getMessage()); HELP_FORMATTER.printHelp(L2ExpansionDriver.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } // Print help. if (cl.hasOption(OPTION_HELP)) { HELP_FORMATTER.printHelp(L2ExpansionDriver.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } // Get output files. String outputPath = cl.getOptionValue(OPTION_OUTPUT_PATH); File outputFile = new File(outputPath); if (outputFile.isDirectory() || outputFile.exists()) { LOGGER.error("Supplied output file is a directory or already exists."); System.exit(1); } outputFile.createNewFile(); File inchiOutputFile = new File(outputPath + ".inchis"); if (inchiOutputFile.isDirectory() || inchiOutputFile.exists()) { LOGGER.error("Supplied inchi output file is a directory or already exists."); System.exit(1); } inchiOutputFile.createNewFile(); Optional<OutputStream> maybeProgressStream = Optional.empty(); if (cl.hasOption(OPTION_PROGRESS_PATH)) { String progressPath = cl.getOptionValue(OPTION_PROGRESS_PATH); File progressFile = new File(progressPath); LOGGER.info("Writing incremental results to file at %s", progressFile.getAbsolutePath()); if (progressFile.isDirectory() || progressFile.exists()) { LOGGER.error("Supplied progress file is a directory or already exists."); System.exit(1); } maybeProgressStream = Optional.of(new FileOutputStream(progressFile)); } // Get metabolite list L2InchiCorpus inchiCorpus = getInchiCorpus(cl, OPTION_METABOLITES); LOGGER.info("%d substrate inchis.", inchiCorpus.getInchiList().size()); Integer maxMass = NO_MASS_THRESHOLD; if (cl.hasOption(OPTION_MASS_THRESHOLD)) { maxMass = Integer.parseInt(cl.getOptionValue(OPTION_MASS_THRESHOLD)); LOGGER.info("Filtering out substrates with mass more than %d daltons.", maxMass); } inchiCorpus.filterByMass(maxMass); LOGGER.info("%d substrate inchis that are importable as molecules.", inchiCorpus.getInchiList().size()); PredictionGenerator generator = new AllPredictionsGenerator(new ReactionProjector()); L2Expander expander = buildExpander(cl, inchiCorpus, generator); L2PredictionCorpus predictionCorpus = expander.getPredictions(maybeProgressStream); LOGGER.info("Done with L2 expansion. Produced %d predictions.", predictionCorpus.getCorpus().size()); LOGGER.info("Writing corpus to file."); predictionCorpus.writePredictionsToJsonFile(outputFile); L2InchiCorpus productInchis = new L2InchiCorpus(predictionCorpus.getUniqueProductInchis()); productInchis.writeToFile(inchiOutputFile); LOGGER.info("L2ExpansionDriver complete!"); }
From source file:fr.inria.edelweiss.kgdqp.core.CentralizedInferrencingNoSpin.java
public static void main(String args[]) throws ParseException, EngineException, InterruptedException, IOException, LoadException { List<String> endpoints = new ArrayList<String>(); String queryPath = null;/*w w w . j ava2 s .co m*/ boolean rulesSelection = false; File rulesDir = null; File ontDir = null; ///////////////// Graph graph = Graph.create(); QueryProcess exec = QueryProcess.create(graph); Options options = new Options(); Option helpOpt = new Option("h", "help", false, "print this message"); // Option queryOpt = new Option("q", "query", true, "specify the sparql query file"); // Option endpointOpt = new Option("e", "endpoint", true, "a federated sparql endpoint URL"); Option versionOpt = new Option("v", "version", false, "print the version information and exit"); Option rulesOpt = new Option("r", "rulesDir", true, "directory containing the inference rules"); Option ontOpt = new Option("o", "ontologiesDir", true, "directory containing the ontologies for rules selection"); // Option locOpt = new Option("c", "centralized", false, "performs centralized inferences"); Option dataOpt = new Option("l", "load", true, "data file or directory to be loaded"); // Option selOpt = new Option("s", "rulesSelection", false, "if set to true, only the applicable rules are run"); // options.addOption(queryOpt); // options.addOption(endpointOpt); options.addOption(helpOpt); options.addOption(versionOpt); options.addOption(rulesOpt); options.addOption(ontOpt); // options.addOption(selOpt); // options.addOption(locOpt); options.addOption(dataOpt); String header = "Corese/KGRAM rule engine experiment command line interface"; String footer = "\nPlease report any issue to alban.gaignard@cnrs.fr, olivier.corby@inria.fr"; CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("kgdqp", header, options, footer, true); System.exit(0); } if (cmd.hasOption("o")) { rulesSelection = true; String ontDirPath = cmd.getOptionValue("o"); ontDir = new File(ontDirPath); if (!ontDir.isDirectory()) { logger.warn(ontDirPath + " is not a valid directory path."); System.exit(0); } } if (!cmd.hasOption("r")) { logger.info("You must specify a path for inference rules directory !"); System.exit(0); } if (cmd.hasOption("l")) { String[] dataPaths = cmd.getOptionValues("l"); for (String path : dataPaths) { Load ld = Load.create(graph); ld.load(path); logger.info("Loaded " + path); } } if (cmd.hasOption("v")) { logger.info("version 3.0.4-SNAPSHOT"); System.exit(0); } String rulesDirPath = cmd.getOptionValue("r"); rulesDir = new File(rulesDirPath); if (!rulesDir.isDirectory()) { logger.warn(rulesDirPath + " is not a valid directory path."); System.exit(0); } // Local rules graph initialization Graph rulesG = Graph.create(); Load ld = Load.create(rulesG); if (rulesSelection) { // Ontology loading if (ontDir.isDirectory()) { for (File o : ontDir.listFiles()) { logger.info("Loading " + o.getAbsolutePath()); ld.load(o.getAbsolutePath()); } } } // Rules loading if (rulesDir.isDirectory()) { for (File r : rulesDir.listFiles()) { if (r.getAbsolutePath().endsWith(".rq")) { logger.info("Loading " + r.getAbsolutePath()); // ld.load(r.getAbsolutePath()); // byte[] encoded = Files.readAllBytes(Paths.get(r.getAbsolutePath())); // String construct = new String(encoded, "UTF-8"); //StandardCharsets.UTF_8); FileInputStream f = new FileInputStream(r); QueryLoad ql = QueryLoad.create(); String construct = ql.read(f); f.close(); SPINProcess sp = SPINProcess.create(); String spinConstruct = sp.toSpin(construct); ld.load(new ByteArrayInputStream(spinConstruct.getBytes()), Load.TURTLE_FORMAT); logger.info("Rules graph size : " + rulesG.size()); } } } // Rule engine initialization RuleEngine ruleEngine = RuleEngine.create(graph); ruleEngine.set(exec); ruleEngine.setOptimize(true); ruleEngine.setConstructResult(true); ruleEngine.setTrace(true); StopWatch sw = new StopWatch(); logger.info("Federated graph size : " + graph.size()); logger.info("Rules graph size : " + rulesG.size()); // Rule selection logger.info("Rules selection"); QueryProcess localKgram = QueryProcess.create(rulesG); ArrayList<String> applicableRules = new ArrayList<String>(); sw.start(); String rulesSelQuery = ""; if (rulesSelection) { rulesSelQuery = pertinentRulesQuery; } else { rulesSelQuery = allRulesQuery; } Mappings maps = localKgram.query(rulesSelQuery); logger.info("Rules selected in " + sw.getTime() + " ms"); logger.info("Applicable rules : " + maps.size()); // Selected rule loading for (Mapping map : maps) { IDatatype dt = (IDatatype) map.getValue("?res"); String rule = dt.getLabel(); //loading rule in the rule engine // logger.info("Adding rule : "); // System.out.println("-------"); // System.out.println(rule); // System.out.println(""); // if (! rule.toLowerCase().contains("sameas")) { applicableRules.add(rule); ruleEngine.addRule(rule); // } } // Rules application on distributed sparql endpoints logger.info("Rules application (" + applicableRules.size() + " rules)"); ExecutorService threadPool = Executors.newCachedThreadPool(); RuleEngineThread ruleThread = new RuleEngineThread(ruleEngine); sw.reset(); sw.start(); // ruleEngine.process(); threadPool.execute(ruleThread); threadPool.shutdown(); //monitoring loop while (!threadPool.isTerminated()) { // System.out.println("******************************"); // System.out.println(Util.jsonDqpCost(QueryProcessDQP.queryCounter, QueryProcessDQP.queryVolumeCounter, QueryProcessDQP.sourceCounter, QueryProcessDQP.sourceVolumeCounter)); // System.out.println("Rule engine running for " + sw.getTime() + " ms"); // System.out.println("Federated graph size : " + graph.size()); System.out.println(sw.getTime() + " , " + graph.size()); Thread.sleep(5000); } logger.info("Federated graph size : " + graph.size()); // logger.info(Util.jsonDqpCost(QueryProcessDQP.queryCounter, QueryProcessDQP.queryVolumeCounter, QueryProcessDQP.sourceCounter, QueryProcessDQP.sourceVolumeCounter)); // TripleFormat f = TripleFormat.create(graph, true); // f.write("/tmp/gAll.ttl"); }