
KDP_book
.pdf
Mathematica: Functional and procedural programming
Chapter 5: Organization of the user software
The Mathematica no possess comfortable enough tools for organization of the user libraries similarly to the case of Maple, creating certain difficulties at organization of the user software developed in its environment. For saving of definitions objects and results of calculations Mathematica uses files of different organization. At that, files of text format that not only are easily loaded into the current session, in general are most often used, but also are convenient enough for processing by other known means, for example, the word processors. Moreover, the text format provides the portability on other computing platforms. One of the main prerequisites of saving in files is possibility of use of definitions along with their usage for the Mathematica objects in the subsequent sessions of the system. At that, with questions of standard saving of objects (blocks, modules, functions etc.) the interested reader can familiarize in details in [1-15,17], some of them were considered in this book in the context of organization of packages while here we present simple tools of organization of the user libraries in the Mathematica system.
Meanwhile, here it is expedient to make a number of very essential remarks on use of the above system means. First, the mechanism of processing of erroneous and especial situations represents a rather powerful mean of programming practically of each quite complex algorithm. However, in the Mathematica such mechanism is characterized by essential shortcomings, for example, successfully using in the Input mode the mechanism of messages print concerning erroneous {Off, On} situations, in body of procedures such mechanism generally doesn't work as illustrates the following a rather simple fragment:
In[1117]:= Import["C:\\Mat\\A.m"]
… Import::nffil: File C:\Mat\A.m not found during Import. Out[17]= $Failed
In[1118]:= Off[Import::nffil] In[1119]:= Import["D:\\Mat\\A.m"]
Out[1119]= $Failed
341

V.Z. Aladjev, M.L. Shishakov, V.A. Vaganov
In[1123]:= On[Import::nffil]
In[24]:= F[x_] := Module[{a}, Off[Import::nffil];
a := Import[x]; On[Import::nffil]; a] In[1125]:= F["C:\\Mat\\A.m"]
… Import::nffil: File C:\Mat\A.m not found during Import. Out[1125]= $Failed
In a case of creation of rather complex procedures in which is required to solve questions of the suppressing of output of a number of erroneous messages, tools of Mathematica system are presented to us as insufficiently developed. The interested reader can familiarize with other peculiarities of the specified system tools in [1-15]. Now, we will present certain approaches concerning creation of the user libraries in Mathematica. Some of them can be useful in practical work with Mathematica.
In view of the scheme of organization of library considered in Maple [26] with organization different from the main library, we will present realization of the similar user library for a case of the Mathematica. On the first step in a directory, let us say, "c:/Lib" the txt–files with definitions of the user tools with their usage are placed. In principle, you can to place any number of definitions in the txt–files, in this case it is previously necessary to read a txt-file whose name coincides with name of the required tool, whereupon in the current session tools whose definitions are located in the file with usage are available. It is convenient in a case when in a single file are located the main tools along with tools accompanying them, excluding system tools. On the second step the tools together with their usage are created and debugged with their subsequent saving in the required file of a library subdirectory "C:\\Lib".
To save the definitions and usage in txt-files perhaps in two ways, namely: (1) by the function call Save, saving previously evaluated definitions and their usage in a txt–file given by its first argument; at that, saving is made in the append–mode, or (2) by creating txt–files with names of tools and usage whose contents are formed by means of a simple word processor, for example, Notepad. At that, by means of the Save function we
342

Mathematica: Functional and procedural programming
have possibility to create libraries of the user tools, located in an arbitrary directory of file system of the computer.
For operating with txt-files of such organization was created the procedure CallSave whose call CallSave[x,y,z] returns the result of a call y[z] of a tool y on the z list of factual arguments passed to y provided that the tool definition y with usage are located in a x txt–file that has been earlier created by means of Save function. If a tool with the given y name is absent in the x file, the procedure call returns $Failed. If a x data-file contains definitions of several tools of the same name y, the procedure call CallSave[x,y,z] is executed relative to their definition whose formal arguments correspond to a z list of actual arguments. If y determines the list, the call returns the names list of all tools located in the x file [1,16,24]. More detailed information on the capabilities of such organization of user libraries can be found in [5-10]. In our opinion, the represented approach quite can be used for the organization of simple and effective user libraries of traditional type.
As another an useful enough approach, based on the use of mx–format files to store tool definitions and their usage, we will introduce the CALLmx procedure whose the call serves to save means definitions in the library directory in files of mx–format with their subsequent uploading into the current session. The possibilities of the procedure can be found in [1,5,10,11,16]. It is possible to represent the UserLib procedure that supports some useful enough functions as one more rather simple example of maintaining the user libraries. The call UserLib[W, g] provides a number of important functions on maintaining of a simple user library located in a W file of txt–format. As the second actual g argument the 2–element list acts that defines such functions as: (1) return of the list of tools names, contained in W, (2) print to the screen of full contents of a library file W or a separate tool, (3) saving in the library file W in the append-mode of a tool with the given name, (4) loading into the current session of all tools whose definitions are in the W, (5) uploading into the current session of a tool with the given name whose definition is in the
343

V.Z. Aladjev, M.L. Shishakov, V.A. Vaganov
W library file. There is a rather good opportunity to extend the procedure with a number of useful enough functions such as deletion from a library of definitions of the specified means or their obsolete versions, etc. With the procedure the reader can familiarize more in details, for example, in [4-9,15,16].
The list structure of the Mathematica allows to rather easily simulate the operating with structures of a number of systems of computer mathematics, for example, Maple. So, in Maple the tabular structure as one of the most important structures is used that is rather widely used both for the organization of structures of data, and for organization of the libraries of software. Similar tabular organization is widely used for organization of package modules of Maple along with a number of tools of our UserLib library [42]. For simulation of main operations with the tabular organization similar to the Maple, in Mathematica the Table1 procedure can be used. On a basis of such tabular organization supported by the Table1 procedure it is rather simply possible to determine the user libraries. As one of such approaches we presented an example of the library LibBase whose structural organization has format of the ListList–type [14,16]. The main operations with the library organized thus are supported by the procedure TabLib whose source code with examples of its use are represented in [8-10,12,15,16].
The interested reader can develop own means of the library organization in Mathematica, using approaches offered by us along with others. However, the problem of organization of convenient help bases for the user libraries exists. A number of approaches in this direction can be found in [14]. In particular, on a basis of the list structure supported by Mathematica, it is rather simply to define help bases for the user libraries. On this basis as one of possible approaches an example of the BaseHelp procedure has been represented, whose structural organization has the list format [10,16]. Meanwhile, it is possible to create the help bases on a basis of packages containing usage on means of the user library which are saved in files of mx–format. At that, for complete library it is possible to create only one help mx-file,
344

Mathematica: Functional and procedural programming
uploading it as required into the current session by means of the Get function with receiving in the subsequent of access to all usage that are in the file. The Usage procedure can represent an quite certain interest for organization of a help database for the user libraries [8,9,12,16]. There too the interested reader can find and other useful tools for organizing user libraries.
5.1. MathToolBox package for Mathematica system
However, allowing the above approaches to organization of the user software, in our opinion the most convenient approach is the organization on the basis of packages. The packages are one of the main mechanisms of Mathematica extension which contain definitions of the new symbols with their usage that are intended for use both outside of package and in it. The symbols can correspond, in particular, to the definitions of new means defined in the package that extend the functional Mathematica possibilities. At that, according to the adopted system agreement all new symbols that entered in a certain package are placed in a context whose name is connected with name of the package.
At uploading of a package in the current session, the given context is added into the beginning of the list defined by global $ContextPath variable. As a rule, for ensuring of association of a package with context a construction BeginPackage["x'"] coded at its beginning is used. At uploading of package in the current session the "x'" context will update the current values of global variables $Context and $ContextPath. The closing bracket of the package is construction EndPackage[]. The package body itself, as a rule, consists of 2 parts – reference information (usage) for all symbols included in the package and definitions of symbols constituting the package. So, the N symbol help is framed in the form N::usage = "Description of N symbol". In turn, the symbols definitions are framed with constructs of the following format Begin["`N`"] and End[], for example, for the above symbol N. So, as a matter of experience works with Mathematica system, as a basis of the organization of the user software we offer a scheme.
345

V.Z. Aladjev, M.L. Shishakov, V.A. Vaganov
At the first stage, in a new nb–document a program object of the following organization is formed, namely:
General information on a package
BeginPackage["Context`"]
N1::usage = "Description of N1 tool"
============================
Np::usage = "Description of Np tool"
Begin["`N1`"]
Definition of N1 tool
End[]
=============================
Begin["`Np`"]
Definition of Np tool
End[]
EndPackage[]
Before the main body of the object the general information about the package is placed, followed by the opening bracket of the package with a context assigned to it. The opening bracket is followed by a set of the usage–sentences containing reference information for all package tools named N1, ..., Np. At the same time, it should be noted that each tool included in the package must have the appropriate usage–sentence; otherwise, if you upload the package into the current session, you will not have access to such tool. The definition of each tool to be included in the given package is then placed in special block, for example, Begin["`N1`"] ... End[], ending all such blocks with the closing bracket EndPackage[]. The definitions of means included in the package should be previously, whenever possible, are debugged including processing of the main special and error situations.
At the second stage by a chain of commands “Evaluation → Evaluation Notebook” of the graphic user interface (GUI) is made evaluation of the Notebook, i.e. actually the package with return of results of the following form:
346

Mathematica: Functional and procedural programming
In[3212]:= BeginPackage["Agn`"]
Name::usage = "Description of Name tool" Begin["`Name`"]
Name[x_] := x^2 End[] Begin["`Name1`"] Name1[x_] := x^3 End[] EndPackage[]
Out[3212]= "Agn`"
Out[3213]= "Description of Name tool"
Out[3214]= "Agn`Name`"
Out[3216]= "Agn`Name`"
Out[3217]= "Agn`Name1`"
Out[3219]= "Agn`Name1`"
In[3220]:= CNames["Agn`"]
Out[3220]= {"Name"}
The procedure call CNames["Agn`"] returns the name list in string format of all symbols whose definitions are located in the package with context "Agn`".
The evaluation of the above package with context "Agn`" in the current session activates all definitions and usage contained in the package. Therefore the following stage consists in saving of the package in files of formats {nb, mx}. The first saving is made by a chain of commands of GUI "File → Save", whereas by a call of the built-in system function DumpSave of the format
In[15]:= DumpSave["c:\\Math\\FileName.mx", "Agn`"]
Out[15]= {"Agn`"}
saving of this package in a file "FileName.mx" of the Math directory is provided (names of directory and file to the discretion of the user) with return of list of contexts ascribed to the package. All subsequent loadings of the mx–file with the package to the current session are made at any time, when demanding use of the tools that are contained in it, by a call of the built–in system function Get of the format Get["C:\\Math\\FileName.mx"].
347

V.Z. Aladjev, M.L. Shishakov, V.A. Vaganov
As noted above the built-in DumpSave function writes out definitions in a binary format that is optimized for input by the Mathematica. Meantime, at the call DumpSave[f, x] where f is a file of mx–format a symbol, list of symbols or a context can be used as the 2nd x argument. In order to enhance the call format of the DumpSave function some tools have been proposed [15].
In particular, the procedure call DumpSave1[x, y] returns the nested list whose first element defines the full path to a file x of mx–format (if necessary to the file is assigned the mx–extension) whereas the second element defines the list of objects and/or contexts from the list defined by argument y whose definitions were unloaded into the x file of mx–format.
Evaluation of definition of a symbol x in the current session it will associate with the context of "Global'" which remains at its unloading into a mx–file by the DumpSave function. While in some cases there is a need of saving of symbols in the files of mx–format with other contexts. This problem is solved by the procedure whose call DumpSave2[f, x, y] returns nothing, at the same time unloading into mx–file f the definition of symbol or the list of symbols x that have context "Global'", with context y. So, in the current session the x symbol receives the y context.
Finally, a simple DumpSave3 procedure allows an arbitrary expression to be used as the second argument of the procedure. Calling the DumpSave3[f, exp] procedure returns a variable in a string format while saving an exp expression in a mx-file f. Then the subsequent call Get[f] returns nothing with activating the variable returned by the previous call DumpSave3[f, exp] with the exp value assigned to it. The fragment below represent the source code of the procedure with an example of it application.
In[2267]:= DumpSave3[f_ /; StringQ[f], exp_] := Module[{a}, {ToString[a], a := exp, DumpSave[f, a]}[[1]]]
In[2268]:= DumpSave3["dump.mx", a*77 + b*78]
Out[2268]= "a$33218"
In[2269]:= Clear["a$33218"]
In[2270]:= Get["dump.mx"]; ToExpression["a$33218"]
Out[2270]= 77*a + 78*b
348

Mathematica: Functional and procedural programming
Fundamental differences between files of two formats mx and nb assume to save packages at least in files of these types, and that is why. Files of mx–format are optimized for input in Mathematica, each such file has a plain text header identifying its type and contexts ascribed to it. In turn, the rest of a mx–file containing definitions of tools is presented in the dump binary format that is not allowing to edit it. Files saved by DumpSave function can be load by Get function. Meantime, files of format mx can`t be exchanged between operating systems that differ in compliance with $SystemWordLength predefined variable.
Whereas files of the format nb (notebooks) are structured interactive documents that can contain calculations, text, typeset expressions, user interface elements, etc. Notebooks are typical method of interacting with Mathematica front end. Files of this format are automatically associated with the Mathematica on computers which have the Mathematica installed. In addition, mx–files contain only printable ASCII characters, are viewable and largely readable in any text editor. In addition, notebooks are cross–platform, meaning that a notebook created on any supported platform can be read by Mathematica on any other platform. Therefore to edit a package it is reasonable to do on the basis of the nb–file containing it while most effective to do the current work with the package on the basis of its mx–file.
It is this approach to software saving that we have chosen and implemented in the package MathToolBox. Our package MathToolBox [16] that is attached to the present book can as a bright example of the above organization of the user software. Package contains more than 1420 tools eliminating restrictions of a number of standard tools of the Mathematica, and expand its software with new tools. In this context, MathToolBox can serve as a certain additional tool of procedural programming, especially useful in the numerous applications where certain non–standard evaluations have to accompany programming. In addition, tools presented in MathToolBox have a direct relation to principal questions of procedural–functional programming in Mathematica, not only for the decision of applied problems,
349

V.Z. Aladjev, M.L. Shishakov, V.A. Vaganov
but, above all, for creation of software that extends frequently used facilities of the system and/or eliminating their defects or extending the system with new facilities. Software presented in this package contains a number of rather useful and effective receptions of programming in the Mathematica, and extends its software which allows in the system to programme the tasks of various purposes more simply and effectively. Additional tools composing the above package embrace the following sections of the Mathematica system, namely:
-additional tools in interactive mode of the system
-additional tools of processing of expressions
-additional tools of processing of symbols and strings
-additional tools of processing of sequences and lists
-additional tools expanding standard built-in functions or the system software as a whole (control structures branching and loop, etc.)
-determination of procedures in the Mathematica software
-determination of the user functions and pure functions
-means of testing of procedures and functions
-headings of procedures and function
-formal arguments of procedures and functions
-local variables of modules and blocks; means of their processing
-global variables of modules and blocks; means of their processing
-attributes, options and values by default for arguments of the user blocks, functions and modules; additional means of their processing
-useful additional means for processing of procedures and functions
-additional means of the processing of internal Mathematica files
-additional means of the processing of external Mathematica files
-additional tools of the processing of attributes of directories and files
-additional and special means of processing of directories and files
-additional tools of work with packages and contexts ascribed to them
-organization of the user software in the Mathematica system
Archive Archive76.ZIP with this package (Freeware license) can be freely downloaded here [16]. Archive contains 5 files of formats {nb, mx, cdf, m, txt}. Such approach allows to satisfy the user on different operating platforms. Memory size demanded
350