如何创建具有正确格式表达式的笔记本

发布于 2024-12-02 20:56:40 字数 471 浏览 1 评论 0原文

我有一个由另一个程序生成的 Mathematica 表达式,我想在笔记本中打开该表达式,并且格式正确。例如,另一个程序生成以下内容:

Plot[{Exp[x],Interpolation[Table[{k/5,Exp[(k-1/2)/5]},{k,0,5}],
InterpolationOrder->0][x]},{x,0,1},Filling->{1->{{2},{Yellow,Orange}}},
PlotLabel->Style["Formatting",Blue,FontFamily->"Courier"]]

将文本写入文件中,粗略地添加后缀“.nb”,然后启动,并且表达式在笔记本中打开,而不进行格式化。要实现格式化,使用 BoxData 手动写入文件似乎不切实际。

该文件实际上是使用 Process.Start("filename.nb") 从 .Net 启动的,但命令行启动似乎同样存在问题。

I have a Mathematica expression generated by another program, which I would like to open in a notebook, properly formatted. For instance, the other program generates this:

Plot[{Exp[x],Interpolation[Table[{k/5,Exp[(k-1/2)/5]},{k,0,5}],
InterpolationOrder->0][x]},{x,0,1},Filling->{1->{{2},{Yellow,Orange}}},
PlotLabel->Style["Formatting",Blue,FontFamily->"Courier"]]

The text is written into a file, crudely suffixed ".nb", and launched, and the expression opens in a notebook without formatting. To achieve formatting, writing a file manually with BoxData seems impractical.

The file is actually being launched from .Net using Process.Start("filename.nb"), but a command line launch seems equally problematic.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

肥爪爪 2024-12-09 20:56:40

怎么样:

Export["C:\\Temp\\formatTest1.nb", 
   ToExpression[Import["C:\\Temp\\formatTest.nb", "Text"], InputForm, MakeBoxes]]

我测试了它,它似乎可以工作(从普通文件导入,导出到您将打开的文件)。这确实创建了显式框,但用户方面只需付出很少的努力。我没有测试,但您应该能够从命令行在脚本模式下运行此代码。

编辑

要在 Mathematica 中进行测试,您可以

Export["C:\\Temp\\formatTest.nb", 
  ToString@HoldForm@FullForm@
    Plot[{Exp[x],Interpolation[Table[{k/5, Exp[(k - 1/2)/5]}, {k, 0, 5}],
    InterpolationOrder -> 0][x]}, {x, 0, 1}, 
    Filling -> {1 -> {{2}, {Yellow, Orange}}},
    PlotLabel -> Style["Formatting", Blue, FontFamily -> "Courier"]], 
  "Text"]

在运行上面的代码之前使用 eg 。

How about this:

Export["C:\\Temp\\formatTest1.nb", 
   ToExpression[Import["C:\\Temp\\formatTest.nb", "Text"], InputForm, MakeBoxes]]

I tested it and it seems to work (importing from the plain file, exporting to the one you will then open). This does create explicit boxes, but with a very little effort on the user's side. I did not test, but you should be able to run this code in the script mode, from the command line.

EDIT

To test from within Mathematica, you can use e.g.

Export["C:\\Temp\\formatTest.nb", 
  ToString@HoldForm@FullForm@
    Plot[{Exp[x],Interpolation[Table[{k/5, Exp[(k - 1/2)/5]}, {k, 0, 5}],
    InterpolationOrder -> 0][x]}, {x, 0, 1}, 
    Filling -> {1 -> {{2}, {Yellow, Orange}}},
    PlotLabel -> Style["Formatting", Blue, FontFamily -> "Courier"]], 
  "Text"]

before running the code above.

最好是你 2024-12-09 20:56:40

您可以使用以下包装:

nb = CreateWindow[
     DocumentNotebook[{
       Plot[{Exp[x], 
       Interpolation[Table[{k/5, Exp[(k - 1/2)/5]}, {k, 0, 5}], 
       InterpolationOrder -> 0][x]}, {x, 0, 1}, 
       Filling -> {1 -> {{2}, {Yellow, Orange}}}, 
       PlotLabel -> 
       Style["Formatting", Blue, FontFamily -> "Courier"]]
     }]]

然后可以使用命令 NotebookSave 和 NotebookClose 来保存和关闭该内容;)

You can use the following wrapping:

nb = CreateWindow[
     DocumentNotebook[{
       Plot[{Exp[x], 
       Interpolation[Table[{k/5, Exp[(k - 1/2)/5]}, {k, 0, 5}], 
       InterpolationOrder -> 0][x]}, {x, 0, 1}, 
       Filling -> {1 -> {{2}, {Yellow, Orange}}}, 
       PlotLabel -> 
       Style["Formatting", Blue, FontFamily -> "Courier"]]
     }]]

then commands NotebookSave and NotebookClose can be used to save and close the thing ;)

左耳近心 2024-12-09 20:56:40

除非您显式创建 BoxData 表达式,否则无法在不实际调用 Mathematica 前端的情况下格式化您的表达式。

我能想到的最接近的是添加以下内容:

SelectionMove[EvaluationNotebook[], Next, EvaluationCell]; 
FrontEndExecute[{FrontEndToken[FrontEnd`InputNotebook[], 
                 "SelectionConvert", "StandardForm"]}]; 
Plot[{Exp[x], Interpolation[Table[{k/5, Exp[(1/5)*(k - 1/2)]}, {k, 0, 5}], 
                InterpolationOrder -> 0][x]}, {x, 0, 1}, 
  Filling -> {1 -> {{2}, {Yellow, Orange}}}, 
  PlotLabel -> Style["Formatting", Blue, FontFamily -> "Courier"], 
  Evaluated -> True]
SelectionMove[EvaluationNotebook[], After, GeneratedCell]; 

在计算单元格时自动格式化 Plot 命令。
(顺便说一句:您可能应该在列表前面添加 Evaluate 或添加(没有详细记录的)Evaluate->True 选项。

Unless you create the BoxData expressions explicitly there is no way to format your expression without actually invoking at least the Mathematica FrontEnd.

The closest I can think of is that you add the following:

SelectionMove[EvaluationNotebook[], Next, EvaluationCell]; 
FrontEndExecute[{FrontEndToken[FrontEnd`InputNotebook[], 
                 "SelectionConvert", "StandardForm"]}]; 
Plot[{Exp[x], Interpolation[Table[{k/5, Exp[(1/5)*(k - 1/2)]}, {k, 0, 5}], 
                InterpolationOrder -> 0][x]}, {x, 0, 1}, 
  Filling -> {1 -> {{2}, {Yellow, Orange}}}, 
  PlotLabel -> Style["Formatting", Blue, FontFamily -> "Courier"], 
  Evaluated -> True]
SelectionMove[EvaluationNotebook[], After, GeneratedCell]; 

which automatically formats the Plot command when the cell is evaluated.
(BTW: You probably should either add Evaluate in front of the list or add the (not-so-well documented) Evaluate->True option.

清浅ˋ旧时光 2024-12-09 20:56:40

这是我采用的解决方案。感谢您的所有帮助。

解决方案的主要步骤是通过内核格式化命令: -

FullForm[ToBoxes[
  Defer[Plot[{Exp[x], 
     Interpolation[Table[{k/5, Exp[(k - 1/2)/5]}, {k, 0, 5}], 
       InterpolationOrder -> 0][x]}, {x, 0, 1}, 
    Filling -> {1 -> {{2}, {Yellow, Orange}}}, 
    PlotLabel -> 
     Style["Formatting", Blue, FontFamily -> "Courier"]]]]]

然后将格式化的数据封装起来创建一个笔记本: -

Notebook[{Cell[BoxData[

... ( inserted box-formatted output ) ...

], "Input"]
},
WindowSize->{615, 750},
WindowMargins->{{328, Automatic}, {Automatic, 76}},
StyleDefinitions->"Default.nb"
]

将其写入一个文件,后缀为“.nb”。一切都很好,花花公子。

此方法适用于多语句代码块,但包含一些额外的处理来格式化 Function[表达式,选项] 形式的单个函数调用,以在每个选项之前添加换行符。以下是用于生成两种类型输出的 C# 代码:-

public static class MathematicaHelpers
{
    public static string CreateNotebook(string mathCommand, string fileLocation, MathKernel kernel, bool addNewLines)
    {
        if (addNewLines) {
            mathCommand = string.Format("{0}{1}{2}", "Module[{boxoutput,b2},boxoutput=FullForm[ToBoxes[Defer[", mathCommand, "]]];b2=boxoutput[[1,1,3,1]];boxoutput[[1,1,3,1]]=Join[Flatten[Riffle[Partition[b2,2],\"\\[IndentingNewLine]\"],1],{\"\\[IndentingNewLine]\",Last[b2]}];boxoutput]");
        } else {
            mathCommand = string.Format("{0}{1}{2}", "FullForm[ToBoxes[Defer[", mathCommand, "]]]");
        }
        fileLocation = Path.ChangeExtension(fileLocation, ".nb");

        mathCommand = ComputeMathCommand(mathCommand, kernel);
        mathCommand = string.Format("{0}{1}{2}", "Notebook[{Cell[BoxData[", mathCommand,
                                    "], \"Input\"]},WindowSize->{615, 750}, WindowMargins->{{328, Automatic}, {Automatic, 76}},StyleDefinitions->\"Default.nb\"]");

        File.WriteAllText(fileLocation, mathCommand);
        return fileLocation;
    }                             

    private static string ComputeMathCommand(string command, MathKernel kernel)
    {
        kernel.Compute(command);
        return kernel.Result.ToString();
    }
}

Here is the solution I adopted. Thanks for all the help.

The main step of the solution is to format the command via the kernel:-

FullForm[ToBoxes[
  Defer[Plot[{Exp[x], 
     Interpolation[Table[{k/5, Exp[(k - 1/2)/5]}, {k, 0, 5}], 
       InterpolationOrder -> 0][x]}, {x, 0, 1}, 
    Filling -> {1 -> {{2}, {Yellow, Orange}}}, 
    PlotLabel -> 
     Style["Formatting", Blue, FontFamily -> "Courier"]]]]]

Then the formatted data is encapsulated to create a notebook:-

Notebook[{Cell[BoxData[

... ( inserted box-formatted output ) ...

], "Input"]
},
WindowSize->{615, 750},
WindowMargins->{{328, Automatic}, {Automatic, 76}},
StyleDefinitions->"Default.nb"
]

This is written to a file, suffixed ".nb". All fine and dandy.

This approach works well for multi-statement blocks of code, but some additional processing was included to format a single function call of the form Function[expression, options] to add a line-break before each option. Here is the C# code used to produce both types of output:-

public static class MathematicaHelpers
{
    public static string CreateNotebook(string mathCommand, string fileLocation, MathKernel kernel, bool addNewLines)
    {
        if (addNewLines) {
            mathCommand = string.Format("{0}{1}{2}", "Module[{boxoutput,b2},boxoutput=FullForm[ToBoxes[Defer[", mathCommand, "]]];b2=boxoutput[[1,1,3,1]];boxoutput[[1,1,3,1]]=Join[Flatten[Riffle[Partition[b2,2],\"\\[IndentingNewLine]\"],1],{\"\\[IndentingNewLine]\",Last[b2]}];boxoutput]");
        } else {
            mathCommand = string.Format("{0}{1}{2}", "FullForm[ToBoxes[Defer[", mathCommand, "]]]");
        }
        fileLocation = Path.ChangeExtension(fileLocation, ".nb");

        mathCommand = ComputeMathCommand(mathCommand, kernel);
        mathCommand = string.Format("{0}{1}{2}", "Notebook[{Cell[BoxData[", mathCommand,
                                    "], \"Input\"]},WindowSize->{615, 750}, WindowMargins->{{328, Automatic}, {Automatic, 76}},StyleDefinitions->\"Default.nb\"]");

        File.WriteAllText(fileLocation, mathCommand);
        return fileLocation;
    }                             

    private static string ComputeMathCommand(string command, MathKernel kernel)
    {
        kernel.Compute(command);
        return kernel.Result.ToString();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文