📄 rmodel.java
字号:
/** * Get the instance of the <code>Rengine</code>. * <p/> * In case the R engine has not been initialized, it is initialized before * returning the object. * * @return The Rengine object */ public static Rengine getRengine() { return rengine; } /** * Get the actual model object. * * @return An <code>RList</code> object representation of the model. */ public RList getModelObject() { return modelObject; } /** * Get a unique String value. * <p/> * This method can be used to get unique variable names for use in an R session. The * String is generated from a combination of the prefix, the system time and a random * portion. * * @param prefix Any value. If empty or null, <code>"var"</code> is used. * @return A unique String value */ public String getUniqueVariableName(String prefix) { if (prefix == null || prefix.equals("")) prefix = "var"; Random rnd = new Random(); long uid = ((System.currentTimeMillis() >>> 16) << 16) + rnd.nextLong(); return prefix + String.valueOf(Math.abs(uid)).trim(); } /** * Loads the parameters for a model into a <code>list</code> object in the R session. * <p/> * The method assigns the list to a (relatively) unique variable name and returns * the variable name to the caller so that the list can be accessed later on. * * @return * @throws QSARModelException if there are any problems within the R session. */ protected String loadParametersIntoRSession() throws QSARModelException { REXP result; Set keys = params.keySet(); String paramVariableName = getUniqueVariableName("param"); for (Iterator iterator = keys.iterator(); iterator.hasNext();) { String name = (String) iterator.next(); Object value = params.get(name); if (value instanceof Integer) { logger.debug("Assigning a Integer"); Integer tmp1 = (Integer) value; int[] tmp2 = new int[]{tmp1.intValue()}; rengine.assign(name, tmp2); } else if (value instanceof String) { logger.debug("Assigning a String"); rengine.assign(name, (String) value); } else if (value instanceof Boolean) { logger.debug("Assigning a Boolean"); Boolean tmp1 = (Boolean) value; if (tmp1.booleanValue()) result = rengine.eval(name + "<- TRUE"); else result = rengine.eval(name + "<- FALSE"); if (result == null) throw new QSARModelException("Error assigning a boolean"); } else if (value instanceof Double) { logger.debug("Assigning a Double"); Double tmp1 = (Double) value; double[] tmp2 = new double[]{tmp1.doubleValue()}; rengine.assign(name, tmp2); } else if (value instanceof Integer[]) { logger.debug("Assigning a Integer[]"); Integer[] tmp1 = (Integer[]) value; int[] tmp2 = new int[tmp1.length]; for (int i = 0; i < tmp1.length; i++) tmp2[i] = tmp1[i].intValue(); rengine.assign(name, tmp2); } else if (value instanceof Double[]) { logger.debug("Assigning a Double[]"); Double[] tmp1 = (Double[]) value; double[] tmp2 = new double[tmp1.length]; for (int i = 0; i < tmp1.length; i++) tmp2[i] = tmp1[i].doubleValue(); rengine.assign(name, tmp2); } else if (value instanceof Integer[][]) { logger.debug("Assigning a Integer[][]"); Integer[][] tmp1 = (Integer[][]) value; int nrow = tmp1.length; int ncol = tmp1[0].length; int[] tmp2 = new int[nrow * ncol]; for (int i = 0; i < ncol; i++) { for (int j = 0; j < nrow; j++) { tmp2[i * nrow + j] = (tmp1[j][i]).intValue(); } } rengine.assign(name, tmp2); result = rengine.eval(name + "<- matrix(" + name + ", nrow=" + nrow + ")"); if (result == null) throw new QSARModelException("Error assigning a int[][]"); } else if (value instanceof Double[][]) { logger.debug("Assigning a Double[][]"); Double[][] tmp1 = (Double[][]) value; int nrow = tmp1.length; int ncol = tmp1[0].length; double[] tmp2 = new double[nrow * ncol]; for (int i = 0; i < ncol; i++) { for (int j = 0; j < nrow; j++) { tmp2[i * nrow + j] = (tmp1[j][i]).doubleValue(); } } rengine.assign(name, tmp2); result = rengine.eval(name + "<- matrix(" + name + ", nrow=" + nrow + ")"); if (result == null) throw new QSARModelException("Error assigning a double[][]"); } } // make the list command String cmd = paramVariableName + " <- list("; for (Iterator iterator = keys.iterator(); iterator.hasNext();) { String name = (String) iterator.next(); cmd = cmd + name + " = " + name + ", "; } cmd = cmd + ")"; // now eval the command result = rengine.eval(cmd); if (result == null) throw new QSARModelException("Error making the parameter list"); // now lets remove all the variables we had assigned for (Iterator iterator = keys.iterator(); iterator.hasNext();) { String name = (String) iterator.next(); rengine.eval("rm(" + name + ")"); } return paramVariableName; } /** * Checks whether the class of a named object is of the specified class. * <p/> * * @param objectName The name of the R variable holding the object to check * @param objectClass The class to check for * @return true if the object is of the specified class, false if the object is not * of the specified class or the R command to obtain the class failed */ public boolean isOfClass(String objectName, String objectClass) { REXP klass = rengine.eval("class(" + objectName + ")"); if (klass == null) { return false; } return klass.asString().equals(objectClass); } /** * Removes an object from the R session. * * @param objectName The name of the R variable to remove * @throws QSARModelException if the <code>'rm'</code> command failed */ public void removeObject(String objectName) throws QSARModelException { REXP ret = rengine.eval("rm(\"" + objectName + "\")"); if (ret == null) throw new QSARModelException("Error removing \'" + objectName + "\'"); } /** * Abstract method to handle loading R models. * <p/> * This method can be used to load a previously saved R model object. Since * the user can save any arbitrary R object, checks must be made that the * object being returned is an instance of one of the current modeling classes. * <p/> * This is best achieved by forcing each modeling class to write its own loader. * * @param fileName The file containing the R object to load * @throws org.openscience.cdk.qsar.model.QSARModelException * if the R session could not load the object or if the loaded model * does not correspond to the class that it was loaded from * @see #saveModel */ abstract public void loadModel(String fileName) throws QSARModelException; /** * Abstract method to handle loading R models that were previously serialized. * <p/> * This method can be used to load a previously serialized R model object (usinging * serialize()). Since * the user can save any arbitrary R object, checks must be made that the * object being returned is an instance of one of the current modeling classes. * This is best achieved by forcing each modeling class to write its own loader. * <p/> * In addition * objects saved using serialize() do not have a name. As a result a name for the object must * be specified when using this method. * * @param serializedModel A String containing the ASCII sreialized R object * @param modelName The name of the model. (Within the R session, the model will be assigned to * a variable of this name) * @throws QSARModelException if the R session could not load the object or if the loaded model * does not correspond to the class that it was loaded from * @see #saveModel */ abstract public void loadModel(String serializedModel, String modelName) throws QSARModelException; /** * Specifies the parameters value. * * @param key A String representing the name of the parameter (corresponding to the * name described in the R manpages) * @param obj The value of the parameter * @throws QSARModelException if the parameters are of the wrong type for the given modeling function */ abstract public void setParameters(String key, Object obj) throws QSARModelException; abstract public void build() throws QSARModelException; abstract public void predict() throws QSARModelException; protected void finalize() { rengine.eval("rm(\"" + getModelName() + "\",pos=1)"); } ; class TextConsole implements RMainLoopCallbacks { public void rWriteConsole(Rengine re, String text) { System.out.print(text); } public void rBusy(Rengine re, int which) { System.out.println("rBusy(" + which + ")"); } public String rReadConsole(Rengine re, String prompt, int addToHistory) { System.out.print(prompt); try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); return (s == null || s.length() == 0) ? s : s + "\n"; } catch (Exception e) { System.out.println("jriReadConsole exception: " + e.getMessage()); } return null; } public void rShowMessage(Rengine re, String message) { System.out.println("rShowMessage \"" + message + "\""); } public String rChooseFile(Rengine re, int newFile) { FileDialog fd = new FileDialog(new Frame(), (newFile == 0) ? "Select a file" : "Select a new file", (newFile == 0) ? FileDialog.LOAD : FileDialog.SAVE); fd.pack(); fd.setVisible(true); String res = null; if (fd.getDirectory() != null) res = fd.getDirectory(); if (fd.getFile() != null) res = (res == null) ? fd.getFile() : (res + fd.getFile()); return res; } public void rFlushConsole(Rengine re) { } public void rLoadHistory(Rengine re, String filename) { } public void rSaveHistory(Rengine re, String filename) { } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -