How to create a Mathematica Notebook in Java?

和自甴很熟 提交于 2019-12-01 08:06:21
Chris Degnen

A method for creating a formatted notebook file is shown here:

How to create a notebook with a properly formatted expression

You can box format your Mathematica code (mathCommand) using a kernel call, e.g.

String mathCommand = "Plot[Sin[x], {x, 0, 6}]";
mathCommand = "FullForm[ToBoxes[Defer[" + mathCommand + "]]]";
MathKernel kernel = new MathKernel();
kernel.Compute(mathCommand);
mathCommand = kernel.Result.ToString();

Then encapsulate it like so, and save it with .nb extension.

Notebook[{Cell[BoxData[
... ( inserted box-formatted output ) ...
], "Input"]
},
WindowSize->{615, 750},
WindowMargins->{{328, Automatic}, {Automatic, 76}},
StyleDefinitions->"Default.nb"
]
Verbeia

Mathematica notebooks are plaintext files with structures like

Notebook[{Cell[],Cell[]}]

You can work out the required structure by viewing them with a text editor. Assuming you can get Java to create a text file, save it with a .nb file name ending, and invoke the command-line version of Mathematica, then what you want should be doable. You will probably want to set the input cells to initialization type.

It took some research but I managed to answer the question myself.

 package graphica;

 import com.wolfram.jlink.*;

 /**
  *
  * @author Nilo
  */
 public class MathematicaTester {

     public static void main(String[] args) {

         KernelLink ml = null; 
         String jLinkDir = "C:\\Program Files\\Wolfram Research\\Mathematica\\8.0\    \SystemFiles\\Links\\JLink";
         System.setProperty("com.wolfram.jlink.libdir", jLinkDir);

         try { 
             ml = MathLinkFactory.createKernelLink("-linkmode launch -linkname 'C:\\Program Files\\Wolfram Research\\Mathematica\\8.0\\MathKernel.exe'");
        //test-1
             ml.discardAnswer();
             String expr = "Sum[k,{k,1,11}]";
             ml.evaluate(expr);
             ml.waitForAnswer();
             String x = ml.getString();
             System.out.println("Result = " + x);
       //test-2
             expr = "UsingFrontEnd[nb=NotebookPut[Notebook[{Cell[\"Graphics3D[Cuboid[]]\", \"Input\"]}]]]";
             System.out.println("Result = " + ml.evaluateToOutputForm(expr, 40) );
             expr = "UsingFrontEnd[NotebookSave[nb,\"TERRANOVA1\"]]";
             System.out.println("Result = " + ml.evaluateToOutputForm(expr, 40) );

         } catch (MathLinkException e) { 
             System.out.println("Fatal error opening link: " + 
             e.getMessage()); 
             return; 
         }
     }
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!