使用 rjava 的 jar 中 java 方法的 R 包装器

R wrapper for a java method in a jar using rjava

我正在尝试使用 rjava 包在 R 中访问 java 程序 MELTING 5

我可以使用 system 函数,如下所示,使用批处理文件。

path <- "path/to/melting.bat"
sequence = "GTCGTATCCAGTGCAGGGTCCGAGGTATTCGCACTGGATACGACTTCCAC"
hybridisation.type = "dnadna"
OligomerConc = 5e-8
Sodium = 0.05

command=paste("-S", sequence,
              "-H", hybridisation.type,
              "-P", OligomerConc,
              "-E", paste("Na=", Sodium, sep = ""))

system(paste("melting.bat", command))

我正在按照 hellowjavaworld 中的步骤尝试使用包装器做同样的事情,但没有成功。

.jaddClassPath('path/to/melting5.jar')
main <- .jnew("melting/Main")
out <- .jcall(obj = main, returnSig = "V", method = "main", .jarray(list(), "java/lang/String"),
              argument = command)

我试图访问的melting5.jar中melting/Main.java中的java代码如下。

package melting;

import java.text.NumberFormat;

import melting.configuration.OptionManagement;
import melting.configuration.RegisterMethods;
import melting.methodInterfaces.MeltingComputationMethod;
import melting.nearestNeighborModel.NearestNeighborMode;

/**
 * The Melting main class which contains the public static void main(String[] args) method.
 */
public class Main {

    // private static methods

    /**
     * Compute the entropy, enthalpy and the melting temperature and display the results. 
     * @param args : contains the options entered by the user.
     * @param OptionManagement optionManager : the OptionManegement which allows to manage
     * the different options entered by the user.
     */
    private static ThermoResult runMelting(String [] args, OptionManagement optionManager){
        try {
                        ThermoResult results = 
                                        getMeltingResults(args, optionManager);
            displaysMeltingResults(results);
                        return results;

        } catch (Exception e) {
            OptionManagement.logError(e.getMessage());
                        return null;
        }
    }

        /**
         * Compute the entropy, enthalpy and melting temperature, and return 
         * these results.
         * @param args options (entered by the user) that determine the
         *             sequence, hybridization type and other features of the
         *             environment.
         * @param optionManager the {@link 
         *                           melting.configuration.OptionManagement 
         *                           <code>OptionManagement</code>} which
         *                      allows the program to manage the different
         *                      options entered by the user.  
         * @return The results of the Melting computation.
         */
        public static ThermoResult getMeltingResults(String[] args,
                                                OptionManagement optionManager)
        {
            NumberFormat format = NumberFormat.getInstance();
            format.setMaximumFractionDigits(2);

            // Set up the environment from the supplied arguments and get the 
            // results.
            Environment environment = optionManager.createEnvironment(args);
            RegisterMethods register = new RegisterMethods();
            MeltingComputationMethod calculMethod = 
                register.getMeltingComputationMethod(environment.getOptions());
            ThermoResult results = calculMethod.computesThermodynamics();
            results.setCalculMethod(calculMethod);
            environment.setResult(results);

            // Apply corrections to the results.
            results = calculMethod.getRegister().
                                   computeOtherMeltingCorrections(environment);
            environment.setResult(results);
            return environment.getResult();
        }

    /**
     * displays the results of Melting : the computed enthalpy and entropy (in cal/mol and J/mol), and the computed 
     * melting temperature (in degrees).
     * @param results : the ThermoResult containing the computed enthalpy, entropy and
     * melting temperature
     * @param MeltingComputationMethod calculMethod : the melting computation method (Approximative or nearest neighbor computation)
     */
    private static void displaysMeltingResults(ThermoResult results)
        {
        NumberFormat format = NumberFormat.getInstance(); 
        format.setMaximumFractionDigits(2);
                MeltingComputationMethod calculMethod = 
                                                     results.getCalculMethod();

        double enthalpy = results.getEnthalpy();
        double entropy = results.getEntropy();

        OptionManagement.logInfo("\n The MELTING results are : ");
        if (calculMethod instanceof NearestNeighborMode){
            OptionManagement.logInfo("Enthalpy : " + format.format(enthalpy) + " cal/mol ( " + format.format(results.getEnergyValueInJ(enthalpy)) + " J /mol)");
            OptionManagement.logInfo("Entropy : " + format.format(entropy) + " cal/mol-K ( " + format.format(results.getEnergyValueInJ(entropy)) + " J /mol-K)");
        }
        OptionManagement.logInfo("Melting temperature : " + format.format(results.getTm()) + " degrees C.\n");
    }

    // public static main method

    /**
     * @param args : contains the options entered by the user.
     */
    public static void main(String[] args) {

        OptionManagement optionManager = new OptionManagement();

        if (args.length == 0){
            optionManager.initialiseLogger();
            optionManager.readMeltingHelp();
        }
        else if (optionManager.isMeltingInformationOption(args)){
            try {
                optionManager.readOptions(args);

            } catch (Exception e) {
                OptionManagement.logError(e.getMessage());
            }
        }
        else {
            runMelting(args, optionManager);
        }
    }
}

如何将 command 中的参数传递给 java jar 中的 public static void main

https://github.com/hrbrmstr/melting5jars 我为 MELTING 5 jar (melting5.jar) 制作了一个 pkg 包装器,并将 Data/ 目录放入其中,这样你就不必处理jar文件管理。它可以通过 devtools::install_github("hrbrmstr/melting5jars"),

安装

在加载该库之前,您需要设置 NN_PATH,因为 Data/ 目录不是默认情况下 jar 期望的目录,您可能 运行 遇到问题之后设置它 (YMMV)。

注意:我不使用这个 Java 库,也不在你的领域,所以请用你习惯的命令行仔细检查结果 运行ning!

所以,要让它发挥作用,首先要做的是:

Sys.setenv("NN_PATH"=system.file("extdata", "Data", package="melting5jars"))

library(melting5jars) # devtools::install_github("hrbrmstr/melting5jars")

现在,rJava 最酷的部分之一是,如果您想与 Java(代码)相比,您可以在 R(代码)中工作。我们可以在 R 中重新创建 Main class 的核心部分。

首先,获取一个新的 melting.Main 对象和一个新的 OptionManagement 对象,就像 Java 代码所做的那样:

melting <- new(J("melting.Main"))
optionManager <- new(J("melting.configuration.OptionManagement"))

接下来,我们设置您的选项。我离开 Sodium 的方式只是为了确保我没有搞砸任何事情。

Sodium <- 0.05

opts <- c(
  "-S", "GTCGTATCCAGTGCAGGGTCCGAGGTATTCGCACTGGATACGACTTCCAC",
  "-H", "dnadna",
  "-P", 5e-8,
  "-E", paste("Na=", Sodium, sep = "")
)

现在,我们可以直接从 Main class 调用 getMeltingResults()

results <- melting$getMeltingResults(opts, optionManager)

然后对这些结果执行相同的调用:

calculMethod <- results$getCalculMethod()

enthalpy <- results$getEnthalpy()
entropy <- results$getEntropy()

if (.jinstanceof(calculMethod, J("melting.nearestNeighborModel.NearestNeighborMode"))) {
  enthalpy <- results$getEnergyValueInJ(enthalpy)
  entropy <- results$getEnergyValueInJ(entropy)
}

melting_temperature <- results$getTm()

enthalpy
## [1] -1705440

entropy
## [1] -4566.232

melting_temperature
## [1] 72.04301

我们可以将所有这些打包成一个函数,以便将来更容易调用:

get_melting_results <- function(opts = c()) {

  stopifnot(length(opts) > 2) # a sanity check that could be improved

  Sys.setenv("NN_PATH"=system.file("extdata", "Data", package="melting5jars"))

  require(melting5jars)

  melting <- new(J("melting.Main"))
  optionManager <- new(J("melting.configuration.OptionManagement"))

  results <- melting$getMeltingResults(opts, optionManager)

  calculMethod <- results$getCalculMethod()

  enthalpy_cal <- results$getEnthalpy()
  entropy_cal <- results$getEntropy()

  enthalpy_J <- entropy_J <- NULL

  if (.jinstanceof(calculMethod, J("melting.nearestNeighborModel.NearestNeighborMode"))) {
    enthalpy_J <- results$getEnergyValueInJ(enthalpy_cal)
    entropy_J <- results$getEnergyValueInJ(entropy_cal)
  }

  melting_temp_C <- results$getTm()

  list(
    enthalpy_cal = enthalpy_cal,
    entropy_cal = entropy_cal,
    enthalpy_J = enthalpy_J,
    entropy_J = entropy_J,
    melting_temp_C = melting_temp_C
  ) -> out

  class(out) <- c("melting_res")

  out

}

根据方法结果,这也有单独的焓值和熵值。

我们还可以创建打印辅助函数,因为我们 classed list() 我们要返回:

print.melting_res <- function(x, ...) {

  cat(
    "The MELTING results are:\n\n",
    "  - Enthalpy: ", prettyNum(x$enthalpy_cal), " cal/mol",
    {if (!is.null(x$enthalpy_J)) paste0(" (", prettyNum(x$enthalpy_J), " J /mol)", collapse="") else ""}, "\n",
    "  - Entropy: ", prettyNum(x$entropy_cal), " cal/mol-K",
    {if (!is.null(x$entropy_J)) paste0(" (", prettyNum(x$entropy_J), " J /mol-K)", collapse="") else ""}, "\n",
    "  - Meltng temperature: ", prettyNum(x$melting_temp_C), " degress C\n",
    sep=""
  )

}

(我假设您习惯于看到 MELTING 5 命令行输出)

最后,重新运行计算:

Sodium <- 0.05

opts <- c(
  "-S", "GTCGTATCCAGTGCAGGGTCCGAGGTATTCGCACTGGATACGACTTCCAC",
  "-H", "dnadna",
  "-P", 5e-8,
  "-E", paste("Na=", Sodium, sep = "")
)

res <- get_melting_results(opts)

res
## The MELTING results are:
## 
##   - Enthalpy: -408000 cal/mol (-1705440 J /mol)
##   - Entropy: -1092.4 cal/mol-K (-4566.232 J /mol-K)
##   - Meltng temperature: 72.04301 degress C

str(res)
## List of 5
##  $ enthalpy_cal  : num -408000
##  $ entropy_cal   : num -1092
##  $ enthalpy_J    : num -1705440
##  $ entropy_J     : num -4566
##  $ melting_temp_C: num 72
##  - attr(*, "class")= chr "melting_res"

您应该能够使用上述方法将其他组件(如果有)包装在 MELTING 库中。