【问题标题】:R wrapper for a java method in a jar using rjava使用 rjava 的 jar 中的 java 方法的 R 包装器
【发布时间】:2018-01-06 13:52:42
【问题描述】:

我正在尝试使用 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

【问题讨论】:

    标签: java r jar rjava


    【解决方案1】:

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

    在加载该库之前,您需要设置 NN_PATH,因为 Data/ 目录不是 jar 所期望的默认位置,并且您之后可能会遇到设置问题 (YMMV)。

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

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

    Sys.setenv("NN_PATH"=system.file("extdata", "Data", package="melting5jars"))
    
    library(melting5jars) # devtools::install_github("hrbrmstr/melting5jars")
    

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

    首先,获取一个新的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 类中调用 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
    
    }
    

    根据方法结果,焓和熵也有不同的值。

    我们还可以创建一个打印辅助函数,因为我们将返回的 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 库中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多