Question

J'ai une expression Mathematica générée par un autre programme, que je voudrais ouvrir dans un cahier, correctement mis en forme. Par exemple, l'autre programme génère ceci:

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"]]

Le texte est écrit dans un fichier, crûment suffixé « .nb », et a lancé, et l'expression s'ouvre dans un bloc-notes sans formatage. Pour obtenir le formatage, l'écriture d'un fichier manuellement avec BoxData semble peu pratique.

Le fichier est effectivement lancé à partir de .Net utilisant Process.Start ( « filename.nb »), mais le lancement de la ligne de commande semble tout aussi problématique.

Était-ce utile?

La solution 4

Voici la solution que j'adoptai. Merci pour toute l'aide.

La principale étape de la solution est de formater la commande via le noyau: -

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"]]]]]

Ensuite, les données formatées est encapsulé pour créer un bloc-notes: -

Notebook[{Cell[BoxData[

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

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

Il est écrit dans un fichier, suffixé « .nb ». Bien beau.

Cette approche fonctionne bien pour les blocs multi-états de code, mais un traitement supplémentaire a été inclus pour formater un seul appel de fonction de la forme Fonction [expression, options] pour ajouter une ligne-break avant chaque option. Voici le code C # utilisé pour produire les deux types de sorties: -

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();
    }
}

Autres conseils

Que diriez-vous ceci:

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

Je l'ai testé et il semble fonctionner (importer à partir du fichier ordinaire, l'exportation vers celui vous ouvrirez ensuite). Cela ne crée des boîtes explicites, mais avec un très peu d'effort du côté de l'utilisateur. Je n'ai pas testé, mais vous devriez être en mesure d'exécuter ce code dans le mode de script, de la ligne de commande.

EDIT

Pour tester à partir de Mathematica, vous pouvez utiliser par exemple.

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"]

avant d'exécuter le code ci-dessus.

Vous pouvez utiliser l'emballage suivant:

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"]]
     }]]

commande alors NotebookSave et NotebookClose peuvent être utilisés pour enregistrer et fermer la chose;)

Sauf si vous créez les expressions BoxData explicitement il n'y a aucun moyen de formater votre expression sans invoquer en fait au moins Mathematica frontend.

Le plus proche que je peux penser est que vous ajoutez ce qui suit:

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]; 

qui formate automatiquement la commande Plot lorsque la cellule est évaluée. (BTW:. Vous devriez probablement ajouter soit Evaluate devant la liste ou ajouter le (pas si bien documenté) option Evaluate->True

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top