tutorial.txt 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320
  1. MESCHACH VERSION 1.2A
  2. ---------------------
  3. TUTORIAL
  4. ========
  5. In this manual the basic data structures are introduced, and some of the
  6. more basic operations are illustrated. Then some examples of how to use
  7. the data structures and procedures to solve some simple problems are given.
  8. The first example program is a simple 4th order Runge-Kutta solver for
  9. ordinary differential equations. The second is a general least squares
  10. equation solver for over-determined equations. The third example
  11. illustrates how to solve a problem involving sparse matrices. These
  12. examples illustrate the use of matrices, matrix factorisations and solving
  13. systems of linear equations. The examples described in this manual are
  14. implemented in tutorial.c.
  15. While the description of each aspect of the system is brief and far from
  16. comprehensive, the aim is to show the different aspects of how to set up
  17. programs and routines and how these work in practice, which includes I/O
  18. and error-handling issues.
  19. 1. THE DATA STRUCTURES AND SOME BASIC OPERATIONS
  20. The three main data structures are those describing vectors, matrices
  21. and permutations. These have been used to create data structures for
  22. simplex tableaus for linear programming, and used with data structures for
  23. sparse matrices etc. To use the system reliably, you should always use
  24. pointers to these data structures and use library routines to do all the
  25. necessary initialisation.
  26. In fact, for the operations that involve memory management (creation,
  27. destruction and resizing), it is essential that you use the routines
  28. provided.
  29. For example, to create a matrix A of size 34 , a vector x of dimension
  30. 10, and a permutation p of size 10, use the following code:
  31. #include "matrix.h"
  32. ..............
  33. main()
  34. {
  35. MAT *A;
  36. VEC *x;
  37. PERM *p;
  38. ..........
  39. A = m_get(3,4);
  40. x = v_get(10);
  41. p = px_get(10);
  42. ..........
  43. }
  44. This initialises these data structures to have the given size. The
  45. matrix A and the vector x are initially all zero, while p is initially the
  46. identity permutation.
  47. They can be disposed of by calling M_FREE(A), V_FREE(x) and PX_FREE(p)
  48. respectively if you need to re-use the memory for something else. The
  49. elements of each data structure can be accessed directly using the members
  50. (or fields) of the corresponding structures. For example the (i,j)
  51. component of A is accessed by A->me[i][j], x_i by x->ve[i] and p_i by
  52. p->pe[i].
  53. Their sizes are also directly accessible: A->m and A->n are the number
  54. of rows and columns of A respectively, x->dim is the dimension of x , and
  55. size of p is p->size.
  56. Note that the indexes are zero relative just as they are in ordinary C,
  57. so that the index i in x->ve[i] can range from 0 to x->dim -1 . Thus the
  58. total number of entries of a vector is exactly x->dim.
  59. While this alone is sufficient to allow a programmer to do any desired
  60. operation with vectors and matrices it is neither convenient for the
  61. programmer, nor efficient use of the CPU. A whole library has been
  62. implemented to reduce the burden on the programmer in implementing
  63. algorithms with vectors and matrices. For instance, to copy a vector from
  64. x to y it is sufficient to write y = v_copy(x,VNULL). The VNULL is the
  65. NULL vector, and usually tells the routine called to create a vector for
  66. output.
  67. Thus, the v_copy function will create a vector which has the same size
  68. as x and all the components are equal to those of x. If y has already
  69. been created then you can write y = v_copy(x,y); in general, writing
  70. ``v_copy(x,y);'' is not enough! If y is NULL, then it is created (to have
  71. the correct size, i.e. the same size as x), and if it is the wrong size,
  72. then it is resized to have the correct size (i.e. same size as x). Note
  73. that for all the following functions, the output value is returned, even if
  74. you have a non-NULL value as the output argument. This is the standard
  75. across the entire library.
  76. Addition, subtraction and scalar multiples of vectors can be computed by
  77. calls to library routines: v_add(x,y,out), v_sub(x,y,out), sv_mlt(s,x,out)
  78. where x and y are input vectors (with data type VEC *), out is the output
  79. vector (same data type) and s is a double precision number (data type
  80. double). There is also a special combination routine, which computes
  81. out=v_1+s,v_2 in a single routine: v_mltadd(v1,v2,s,out). This is not only
  82. extremely useful, it is also more efficient than using the scalar-vector
  83. multiply and vector addition routines separately.
  84. Inner products can be computed directly: in_prod(x,y) returns the inner
  85. product of x and y. Note that extended precision evaluation is not
  86. guaranteed. The standard installation options uses double precision
  87. operations throughout the library.
  88. Equivalent operations can be performed on matrices: m_add(A,B,C) which
  89. returns C=A+B , and sm_mlt(s,A,C) which returns C=sA . The data types of
  90. A, B and C are all MAT *, while that of s is type double as before. The
  91. matrix NULL is called MNULL.
  92. Multiplying matrices and vectors can be done by a single function call:
  93. mv_mlt(A,x,out) returns out=A*x while vm_mlt(A,x,out) returns out=A^T*x , or
  94. equivalently, out^T=x^T*A . Note that there is no distinction between row
  95. and column vectors unlike certain interactive environments such as MATLAB
  96. or MATCALC.
  97. Permutations are also an essential part of the package. Vectors can be
  98. permuted by using px_vec(p,x,p_x), rows and columns of matrices can be
  99. permuted by using px_rows(p,A,p_A), px_cols(p,A,A_p), and permutations can
  100. be multiplied using px_mlt(p1,p2,p1_p2) and inverted using px_inv(p,p_inv).
  101. The NULL permutation is called PXNULL.
  102. There are also utility routines to initialise or re-initialise these
  103. data structures: v_zero(x), m_zero(A), m_ident(A) (which sets A=I of the
  104. correct size), v_rand(x), m_rand(A) which sets the entries of x and A
  105. respectively to be randomly and uniformly selected between zero and one,
  106. and px_ident(p) which sets p to be an identity permutation.
  107. Input and output are accomplished by library routines v_input(x),
  108. m_input(A), and px_input(p). If a null object is passed to any of these
  109. input routines, all data will be obtained from the input file, which is
  110. stdin. If input is taken from a keyboard then the user will be prompted
  111. for all the data items needed; if input is taken from a file, then the
  112. input will have to be of the same format as that produced by the output
  113. routines, which are: v_output(x), m_output(A) and px_output(p). This
  114. output is both human and machine readable!
  115. If you wish to send the data to a file other than the standard output
  116. device stdout, or receive input from a file or device other than the
  117. standard input device stdin, take the appropriate routine above, use the
  118. ``foutpout'' suffix instead of just ``output'', and add a file pointer as
  119. the first argument. For example, to send a matrix A to a file called
  120. ``fred'', use the following:
  121. #include "matrix.h"
  122. .............
  123. main()
  124. {
  125. FILE *fp;
  126. MAT *A;
  127. .............
  128. fp = fopen("fred","w");
  129. m_foutput(fp,A);
  130. .............
  131. }
  132. These input routines allow for the presence of comments in the data. A
  133. comment in the input starts with a ``hash'' character ``#'', and continues
  134. to the end of the line. For example, the following is valid input for a
  135. 3-dimensional vector:
  136. # The initial vector must not be zero
  137. # x =
  138. Vector: dim: 3
  139. -7 0 3
  140. For general input/output which conforms to this format, allowing
  141. comments in the input files, use the input() and finput() macros. These
  142. are used to print out a prompt message if stdin is a terminal (or ``tty''
  143. in Unix jargon), and to skip over any comments if input is from a
  144. non-interactive device. An example of the usage of these macros is:
  145. input("Input number of steps: ","%d",&steps);
  146. fp = stdin;
  147. finput(fp,"Input number of steps: ","%d",&steps);
  148. fp = fopen("fred","r");
  149. finput(fp,"Input number of steps: ","%d",&steps);
  150. The "%d" is one of the format specifiers which are used in fscanf(); the
  151. last argument is the pointer to the variable (unless the variable is a
  152. string) just as for scanf() and fscanf(). The first two macro calls read
  153. input from stdin, the last from the file fred. If, in the first two calls,
  154. stdin is a keyboard (a ``tty'' in Unix jargon) then the prompt string
  155. "Input number of steps: "
  156. is printed out on the terminal.
  157. The second part of the library contains routines for various
  158. factorisation methods. To use it put
  159. #include "matrix2.h"
  160. at the beginning of your program. It contains factorisation and solution
  161. routines for LU, Cholesky and QR-factorisation methods, as well as update
  162. routines for Cholesky and QR factorisations. Supporting these are a number
  163. of Householder transformation and Givens' rotation routines. Also there is
  164. a routine for generating the Q matrix for a QR-factorisation, if it is
  165. needed explicitly, as it often is.
  166. There are routines for band factorisation and solution for LU and LDL^T
  167. factorisations.
  168. For using complex numbers, vectors and matrices include
  169. #include "zmatrix.h"
  170. for using the basic routines, and
  171. #include "zmatrix2.h"
  172. for the complex matrix factorisation routines. The zmatrix2.h file
  173. includes matrix.h and zmatrix.h so you don't need these files included
  174. together.
  175. For using the sparse matrix routines in the library you need to put
  176. #include "sparse.h"
  177. or, if you use any sparse factorisation routines,
  178. #include "sparse2.h"
  179. at the beginning of your file. The routines contained in the library
  180. include routines for creating, destroying, initialising and updating sparse
  181. matrices, and also routines for sparse matrix-dense vector multiplication,
  182. sparse LU factorisation and sparse Cholesky factorisation.
  183. For using the iterative routines you need to use
  184. #include "iter.h"
  185. This includes the sparse.h and matrix.h file.
  186. There are also routines for applying iterative methods such as
  187. pre-conditioned conjugate gradient methods to sparse matrices.
  188. And if you use the standard maths library (sin(), cos(), tan(), exp(),
  189. log(), sqrt(), acos() etc.) don't forget to include the standard
  190. mathematics header:
  191. #include <math.h>
  192. This file is not automatically included by any of the Meschach
  193. header files.
  194. 2. HOW TO MANAGE MEMORY
  195. Unlike many other numerical libraries, Meschach allows you to allocate,
  196. deallocate and resize the vectors, matrices and permutations that you are
  197. using. To gain maximum benefit from this it is sometimes necessary to
  198. think a little about where memory is allocated and deallocated. There are
  199. two reasons for this.
  200. Memory allocation, deallocation and resizing takes a significant amount
  201. of time compared with (say) vector operations, so it should not be done too
  202. frequently. Allocating memory but not deallocating it means that it cannot
  203. be used by any other data structure. Data structures that are no longer
  204. needed should be explicitly deallocated, or kept as static variables for
  205. later use. Unlike other interpreted systems (such as Lisp) there is no
  206. implicit ``garbage collection'' of no-longer-used memory.
  207. There are three main strategies that are recommended for deciding how to
  208. allocate, deallocate and resize objects. These are ``no deallocation''
  209. which is really only useful for demonstration programs, ``allocate and
  210. deallocate'' which minimises overall memory requirements at the expense of
  211. speed, and ``resize on demand'' which is useful for routines that are
  212. called repeatedly. A new technique for static workspace arrays is to
  213. ``register workspace variables''.
  214. 2.1 NO DEALLOCATION
  215. This is the strategy of allocating but never deallocating data
  216. structures. This is only useful for demonstration programs run with small
  217. to medium size data structures. For example, there could be a line
  218. QR = m_copy(A,MNULL); /* allocate memory for QR */
  219. to allocate the memory, but without the call M_FREE(QR); in it. This can
  220. be acceptable if QR = m_copy(A,MNULL) is only executed once, and so the
  221. allocated memory never needs to be explicitly deallocated.
  222. This would not be acceptable if QR = m_copy(A,MNULL) occurred inside a
  223. for loop. If this were so, then memory would be ``lost'' as far as the
  224. program is concerned until there was insufficient space for allocating the
  225. next matrix for QR. The next subsection shows how to avoid this.
  226. 2.2 ALLOCATE AND DEALLOCATE
  227. This is the most straightforward way of ensuring that memory is not
  228. lost. With the example of allocating QR it would work like this:
  229. for ( ... ; ... ; ... )
  230. {
  231. QR = m_copy(A,MNULL); /* allocate memory for QR */
  232. /* could have been allocated by m_get() */
  233. /* use QR */
  234. ......
  235. ......
  236. /* no longer need QR for this cycle */
  237. M_FREE(QR); /* deallocate QR so memory can be reused */
  238. }
  239. The allocate and deallocate statements could also have come at the
  240. beginning and end of a function or procedure, so that when the function
  241. returns, all the memory that the function has allocated has been
  242. deallocated.
  243. This is most suitable for functions or sections of code that are called
  244. repeatedly but involve fairly extensive calculations (at least a
  245. matrix-matrix multiply, or solving a system of equations).
  246. 2.3 RESIZE ON DEMAND
  247. This technique reduces the time involved in memory allocation for code
  248. that is repeatedly called or used, especially where the same size matrix or
  249. vector is needed. For example, the vectors v1, v2, etc. in the
  250. Runge-Kutta routine rk4() are allocated according to this strategy:
  251. rk4(...,x,...)
  252. {
  253. static VEC *v1=VNULL, *v2=VNULL, *v3=VNULL, *v4=VNULL, *temp=VNULL;
  254. .......
  255. v1 = v_resize(v1,x->dim);
  256. v2 = v_resize(v2,x->dim);
  257. v3 = v_resize(v3,x->dim);
  258. v4 = v_resize(v4,x->dim);
  259. temp = v_resize(temp,x->dim);
  260. .......
  261. }
  262. The intention is that the rk4() routine is called repeatedly with the
  263. same size x vector. It then doesn't make as much sense to allocate v1, v2
  264. etc. whenever the function is called. Instead, v_resize() only performs
  265. memory allocation if the memory already allocated to v1, v2 etc. is smaller
  266. than x->dim.
  267. The vectors v1, v2 etc. are declared to be static to ensure that their
  268. values are not lost between function calls. Variables that are declared
  269. static are set to NULL or zero by default. So the declaration of v1, v2,
  270. etc., could be
  271. static VEC *v1, *v2, *v3, *v4, *temp;
  272. This strategy of resizing static workspace variables is not so useful if
  273. the object being allocated is extremely large. The previous ``allocate and
  274. deallocate'' strategy is much more efficient for memory in those
  275. circumstances. However, the following section shows how to get the best of
  276. both worlds.
  277. 2.4 REGISTRATION OF WORKSPACE
  278. From version 1.2 onwards, workspace variables can be registered so that
  279. the memory they reference can be freed up on demand. To do this, the
  280. function containing the static workspace variables has to include calls to
  281. MEM_STAT_REG(var,type) where var is a pointer to a Meschach data type (such
  282. as VEC or MAT). This call should be placed after the call to the
  283. appropriate resize function. The type parameter should be a TYPE_... macro
  284. where the ``...'' is the name of a Meschach type such as VEC or MAT. For
  285. example,
  286. rk4(...,x,...)
  287. {
  288. static VEC *v1, *v2, *v3, *v4, *temp;
  289. .......
  290. v1 = v_resize(v1,x->dim);
  291. MEM_STAT_REG(v1,TYPE_VEC);
  292. v2 = v_resize(v2,x->dim);
  293. MEM_STAT_REG(v2,TYPE_VEC);
  294. ......
  295. }
  296. Normally, these registered workspace variables remain allocated. However,
  297. to implement the ``deallocate on exit'' approach, use the following code:
  298. ......
  299. mem_stat_mark(1);
  300. rk4(...,x,...)
  301. mem_stat_free(1);
  302. ......
  303. To keep the workspace vectors allocated for the duration of a loop, but
  304. then deallocated, use
  305. ......
  306. mem_stat_mark(1);
  307. for (i = 0; i < N; i++ )
  308. rk4(...,x,...);
  309. mem_stat_free(1);
  310. ......
  311. The number used in the mem_stat_mark() and mem_stat_free() calls is the
  312. workspace group number. The call mem_stat_mark(1) designates 1 as the
  313. current workspace group number; the call mem_stat_free(1) deallocates (and
  314. sets to NULL) all static workspace variables registered as belonging to
  315. workspace group 1.
  316. 3. SIMPLE VECTOR OPERATIONS: AN RK4 ROUTINE
  317. The main purpose of this example is to show how to deal with vectors and
  318. to compute linear combinations.
  319. The problem here is to implement the standard 4th order Runge-Kutta
  320. method for the ODE
  321. x'=f(t,x), x(t_0)=x_0
  322. for x(t_i), i=1,2,3, where t_i=t_0+i*h and h is the step size.
  323. The formulae for the 4th order Runge-Kutta method are:
  324. x_i+1 = x_i+ h/6*(v_1+2*v_2+2*v_3+v_4),
  325. where
  326. v_1 = f(t_i,x_i)
  327. v_2 = f(t_i+h, x_i+h*v_1)
  328. v_3 = f(t_i+h, x_i+h*v_2)
  329. v_4 = f(t_i+h, x_i+h*v_3)
  330. where the v_i are vectors.
  331. The procedure for implementing this method (rk4()) will be passed (a
  332. pointer to) the function f. The implementation of f could, in this system,
  333. create a vector to hold the return value each time it is called. However,
  334. such a scheme is memory intensive and the calls to the memory allocation
  335. functions could easily dominate the time performed doing numerical
  336. computations. So, the implementation of f will also be passed an already
  337. allocated vector to be filled in with the appropriate values.
  338. The procedure rk4() will also be passed the current time t, the step
  339. size h, and the current value for x. The time after the step will be
  340. returned by rk4().
  341. The code that does this follows.
  342. #include "matrix.h"
  343. /* rk4 - 4th order Runge-Kutta method */
  344. double rk4(f,t,x,h)
  345. double t, h;
  346. VEC *(*f)(), *x;
  347. {
  348. static VEC *v1=VNULL, *v2=VNULL, *v3=VNULL, *v4=VNULL;
  349. static VEC *temp=VNULL;
  350. /* do not work with NULL initial vector */
  351. if ( x == VNULL )
  352. error(E_NULL,"rk4");
  353. /* ensure that v1, ..., v4, temp are of the correct size */
  354. v1 = v_resize(v1,x->dim);
  355. v2 = v_resize(v2,x->dim);
  356. v3 = v_resize(v3,x->dim);
  357. v4 = v_resize(v4,x->dim);
  358. temp = v_resize(temp,x->dim);
  359. /* register workspace variables */
  360. MEM_STAT_REG(v1,TYPE_VEC);
  361. MEM_STAT_REG(v2,TYPE_VEC);
  362. MEM_STAT_REG(v3,TYPE_VEC);
  363. MEM_STAT_REG(v4,TYPE_VEC);
  364. MEM_STAT_REG(temp,TYPE_VEC);
  365. /* end of memory allocation */
  366. (*f)(t,x,v1); /* most compilers allow: f(t,x,v1); */
  367. v_mltadd(x,v1,0.5*h,temp); /* temp = x+.5*h*v1 */
  368. (*f)(t+0.5*h,temp,v2);
  369. v_mltadd(x,v2,0.5*h,temp); /* temp = x+.5*h*v2 */
  370. (*f)(t+0.5*h,temp,v3);
  371. v_mltadd(x,v3,h,temp); /* temp = x+h*v3 */
  372. (*f)(t+h,temp,v4);
  373. /* now add: v1+2*v2+2*v3+v4 */
  374. v_copy(v1,temp); /* temp = v1 */
  375. v_mltadd(temp,v2,2.0,temp); /* temp = v1+2*v2 */
  376. v_mltadd(temp,v3,2.0,temp); /* temp = v1+2*v2+2*v3 */
  377. v_add(temp,v4,temp); /* temp = v1+2*v2+2*v3+v4 */
  378. /* adjust x */
  379. v_mltadd(x,temp,h/6.0,x); /* x = x+(h/6)*temp */
  380. return t+h; /* return the new time */
  381. }
  382. Note that the last parameter of f() is where the output is placed.
  383. Often this can be NULL in which case the appropriate data structure is
  384. allocated and initialised. Note also that this routine can be used for
  385. problems of arbitrary size, and the dimension of the problem is determined
  386. directly from the data given. The vectors v_1,...,v_4 are created to have
  387. the correct size in the lines
  388. ....
  389. v1 = v_resize(v1,x->dim);
  390. v2 = v_resize(v2,x->dim);
  391. ....
  392. Here v_resize(v,dim) resizes the VEC structure v to hold a vector of
  393. length dim. If v is initially NULL, then this creates a new vector of
  394. dimension dim, just as v_get(dim) would do. For the above piece of code to
  395. work correctly, v1, v2 etc., must be initialised to be NULL vectors. This
  396. is done by the declaration
  397. static VEC *v1=VNULL, *v2=VNULL, *v3=VNULL, *v4=VNULL;
  398. or
  399. static VEC *v1, *v2, *v3, *v4;
  400. The operations of vector addition and scalar addition are really the only
  401. vector operations that need to be performed in rk4. Vector addition is
  402. done by v_add(v1,v2,out), where out=v1+v2, and scalar multiplication by
  403. sv_mlt(scale,v,out), where out=scale*v.
  404. These can be combined into a single operation v_mltadd(v1,v2,scale,out),
  405. where out=v1+scale*v2. As many operations in numerical mathematics involve
  406. accumulating scalar multiples, this is an extremely useful operation, as we
  407. can see above. For example:
  408. v_mltadd(x,v1,0.5*h,temp); /* temp = x+0.5*h*v1 */
  409. We also need a number of ``utility'' operations. For example v_copy(in,
  410. out) copies the vector in to out. There is also v_zero(v) to zero a vector
  411. v.
  412. Here is an implementation of the function f for simple harmonic motion:
  413. /* f - right-hand side of ODE solver */
  414. VEC *f(t,x,out)
  415. VEC *x, *out;
  416. double t;
  417. {
  418. if ( x == VNULL || out == VNULL )
  419. error(E_NULL,"f");
  420. if ( x->dim != 2 || out->dim != 2 )
  421. error(E_SIZES,"f");
  422. out->ve[0] = x->ve[1];
  423. out->ve[1] = - x->ve[0];
  424. return out;
  425. }
  426. As can be seen, most of this code is error checking code, which, of
  427. course, makes the routine safer but a little slower. For a procedure like
  428. f() it is probably not necessary, although then the main program would have
  429. to perform checking to ensure that the vectors involved have the correct
  430. size etc. The ith component of a vector x is x->ve[i], and indexing is
  431. zero-relative (i.e., the ``first'' component is component 0). The ODE
  432. described above is for simple harmonic motion:
  433. x_0'=x_1 , x_1'=-x_0 , or equivalently, x_0''+ x_0 = 0 .
  434. Here is the main program:
  435. #include <stdio.h>
  436. #include "matrix.h"
  437. main()
  438. {
  439. VEC *x;
  440. VEC *f();
  441. double h, t, t_fin;
  442. double rk4();
  443. input("Input initial time: ", "%lf", &t);
  444. input("Input final time: ", "%lf", &t_fin);
  445. x = v_get(2); /* this is the size needed by f() */
  446. prompter("Input initial state:\n"); x = v_input(VNULL);
  447. input("Input step size: ", "%lf", &h);
  448. printf("# At time %g, the state is\n",t);
  449. v_output(x);
  450. while ( t < t_fin )
  451. {
  452. t = rk4(f,t,x,min(h,t_fin-t)); /* new t is returned */
  453. printf("# At time %g, the state is\n",t);
  454. v_output(x);
  455. t += h;
  456. }
  457. }
  458. The initial values are entered as a vector by v_input(). If v_input()
  459. is passed a vector, then this vector will be used to store the input, and
  460. this vector has the size that x had on entry to v_input(). The original
  461. values of x are also used as a prompt on input from a tty. If a NULL is
  462. passed to v_input() then v_input() will return a vector of whatever size
  463. the user inputs. So, to ensure that only a two-dimensional vector is used
  464. for the initial conditions (which is what f() is expecting) we use
  465. x = v_get(2); x = v_input(x);
  466. To compile the program under Unix, if it is in a file tutorial.c:
  467. cc -o tutorial tutorial.c meschach.a
  468. or, if you have an ANSI compiler,
  469. cc -DANSI_C -o tutorial tutorial.c meschach.a
  470. Here is a sample session with the above program:
  471. tutorial
  472. Input initial time: 0
  473. Input final time: 1
  474. Input initial state:
  475. Vector: dim: 2
  476. entry 0: -1
  477. entry 1: b
  478. entry 0: old -1 new: 1
  479. entry 1: old 0 new: 0
  480. Input step size: 0.1
  481. At time 0, the state is
  482. Vector: dim: 2
  483. 1 0
  484. At time 0.1, the state is
  485. Vector: dim: 2
  486. 0.995004167 -0.0998333333
  487. .................
  488. At time 1, the state is
  489. Vector: dim: 2
  490. 0.540302967 -0.841470478
  491. By way of comparison, the state at t=1 for the true solution is
  492. x_0(1)=0.5403023058 , x_1(1)=-0.8414709848 .
  493. The ``b'' that is typed in entering the x vector allows the user to alter
  494. previously entered components. In this case once this is done, the user is
  495. prompted with the old values when entering the new values. The user can
  496. also type in ``f'' for skipping over the vector's components, which are
  497. then unchanged. If an incorrectly sized initial value vector x is given,
  498. the error handler comes into action:
  499. Input initial time: 0
  500. Input final time: 1
  501. Input initial state:
  502. Vector: dim: 3
  503. entry 0: 3
  504. entry 1: 2
  505. entry 2: -1
  506. Input step size: 0.1
  507. At time 0, the state is
  508. Vector: dim: 3
  509. 3 2 -1
  510. "tutorial.c", line 79: sizes of objects don't match in function f()
  511. Sorry, aborting program
  512. The error handler prints out the error message giving the source code
  513. file and line number as well as the function name where the error was
  514. raised. The relevant section of f() in file tutorial.c is:
  515. if ( x->dim != 2 || out->dim != 2 )
  516. error(E_SIZES,"f"); /* line 79 */
  517. The standard routines in this system perform error checking of this
  518. type, and also checking for undefined results such as division by zero in
  519. the routines for solving systems of linear equations. There are also error
  520. messages for incorrectly formatted input and end-of-file conditions.
  521. To round off the discussion of this program, note that we have seen
  522. interactive input of vectors. If the input file or stream is not a tty
  523. (e.g., a file, a pipeline or a device) then it expects the input to have
  524. the same form as the output for each of the data structures. Each of the
  525. input routines (v_input(), m_input(), px_input()) skips over ``comments''
  526. in the input data, as do the macros input() and finput(). Anything from a
  527. `#' to the end of the line (or EOF) is considered to be a comment. For
  528. example, the initial value problem could be set up in a file ivp.dat as:
  529. # Initial time
  530. 0
  531. # Final time
  532. 1
  533. # Solution is x(t) = (cos(t),-sin(t))
  534. # x(0) =
  535. Vector: dim: 2
  536. 1 0
  537. # Step size
  538. 0.1
  539. The output of the above program with the above input (from a file) gives
  540. essentially the same output as shown above, except that no prompts are sent
  541. to the screen.
  542. 4. USING ROUTINES FOR LISTS OF ARGUMENTS
  543. Some of the most common routines have variants that take a variable
  544. number of arguments. These are the routines .._get_vars(), .._resize_vars()
  545. and .._free_vars(). These correspond to the the basic routines .._get(),
  546. .._resize() and .._free() respectively. Also there is the
  547. mem_stat_reg_vars() routine which registers a list of static workspace
  548. variables. This corresponds to mem_stat_reg_list() for a single variable.
  549. Here is an example of how to use these functions. This example also
  550. uses the routine v_linlist() to compute a linear combination of vectors.
  551. Note that the code is much more compact, but don't forget that these
  552. ``..._vars()'' routines usually need the address-of operator ``&'' and NULL
  553. termination of the arguments to work correctly.
  554. #include "matrix.h"
  555. /* rk4 - 4th order Runge-Kutta method */
  556. double rk4(f,t,x,h)
  557. double t, h;
  558. VEC *(*f)(), *x;
  559. {
  560. static VEC *v1, *v2, *v3, *v4, *temp;
  561. /* do not work with NULL initial vector */
  562. if ( x == VNULL )
  563. error(E_NULL,"rk4");
  564. /* ensure that v1, ..., v4, temp are of the correct size */
  565. v_resize_vars(x->dim, &v1, &v2, &v3, &v4, &temp, NULL);
  566. /* register workspace variables */
  567. mem_stat_reg_vars(0, TYPE_VEC, &v1, &v2, &v3, &v4, &temp, NULL);
  568. /* end of memory allocation */
  569. (*f)(t,x,v1); v_mltadd(x,v1,0.5*h,temp);
  570. (*f)(t+0.5*h,temp,v2); v_mltadd(x,v2,0.5*h,temp);
  571. (*f)(t+0.5*h,temp,v3); v_mltadd(x,v3,h,temp);
  572. (*f)(t+h,temp,v4);
  573. /* now add: temp = v1+2*v2+2*v3+v4 */
  574. v_linlist(temp, v1, 1.0, v2, 2.0, v3, 2.0, v4, 1.0, VNULL);
  575. /* adjust x */
  576. v_mltadd(x,temp,h/6.0,x); /* x = x+(h/6)*temp */
  577. return t+h; /* return the new time */
  578. }
  579. 5. A LEAST SQUARES PROBLEM
  580. Here we need to use matrices and matrix factorisations (in particular, a
  581. QR factorisation) in order to find the best linear least squares solution
  582. to some data. Thus in order to solve the (approximate) equations
  583. A*x = b,
  584. where A is an m x n matrix (m > n) we really need to solve the optimisation
  585. problem
  586. min_x ||Ax-b||^2.
  587. If we write A=QR where Q is an orthogonal m x m matrix and R is an upper
  588. triangular m x n matrix then (we use 2-norm)
  589. ||A*x-b||^2 = ||R*x-Q^T*b||^2 = || R_1*x - Q_1^T*b||^2 + ||Q_2^T*b||^2
  590. where R_1 is an n x n upper triangular matrix. If A has full rank then R_1
  591. will be an invertible matrix, and the best least squares solution of A*x=b
  592. is x= R_1^{-1}*Q_1^T*b .
  593. These calculations can be be done quite easily as there is a QRfactor()
  594. function available with the system. QRfactor() is declared to have the
  595. prototype
  596. MAT *QRfactor(MAT *A, VEC *diag);
  597. The matrix A is overwritten with the factorisation of A ``in compact
  598. form''; that is, while the upper triangular part of A is indeed the R
  599. matrix described above, the Q matrix is stored as a collection of
  600. Householder vectors in the strictly lower triangular part of A and in the
  601. diag vector. The QRsolve() function knows and uses this compact form and
  602. solves Q*R*x=b with the call QRsolve(A,diag,b,x), which also returns x.
  603. Here is the code to obtain the matrix A, perform the QR factorisation,
  604. obtain the data vector b, solve for x, and determine what the norm of the
  605. errors ( ||Ax-b||_2 ) is.
  606. #include "matrix2.h"
  607. main()
  608. {
  609. MAT *A, *QR;
  610. VEC *b, *x, *diag;
  611. /* read in A matrix */
  612. printf("Input A matrix:");
  613. A = m_input(MNULL); /* A has whatever size is input */
  614. if ( A->m < A->n )
  615. {
  616. printf("Need m >= n to obtain least squares fit");
  617. exit(0);
  618. }
  619. printf("# A ="); m_output(A);
  620. diag = v_get(A->m);
  621. /* QR is to be the QR factorisation of A */
  622. QR = m_copy(A,MNULL);
  623. QRfactor(QR,diag);
  624. /* read in b vector */
  625. printf("Input b vector:");
  626. b = v_get(A->m);
  627. b = v_input(b);
  628. printf("# b ="); v_output(b);
  629. /* solve for x */
  630. x = QRsolve(QR,diag,b,VNULL);
  631. printf("Vector of best fit parameters is");
  632. v_output(x);
  633. /* ... and work out norm of errors... */
  634. printf("||A*x-b|| = %g\n",
  635. v_norm2(v_sub(mv_mlt(A,x,VNULL),b,VNULL)));
  636. }
  637. Note that as well as the usual memory allocation functions like m_get(),
  638. the I/O functions like m_input() and m_output(), and the
  639. factorise-and-solve functions QRfactor() and QRsolve(), there are also
  640. functions for matrix-vector multiplication:
  641. mv_mlt(MAT *A, VEC *x, VEC *out)
  642. and also vector-matrix multiplication (with the vector on the left):
  643. vm_mlt(MAT *A, VEC *x, VEC *out),
  644. with out=x^T A. There are also functions to perform matrix arithmetic -
  645. matrix addition m_add(), matrix-scalar multiplication sm_mlt(),
  646. matrix-matrix multiplication m_mlt().
  647. Several different sorts of matrix factorisation are supported: LU
  648. factorisation (also known as Gaussian elimination) with partial pivoting,
  649. by LUfactor() and LUsolve(). Other factorisation methods include Cholesky
  650. factorisation CHfactor() and CHsolve(), and QR factorisation with column
  651. pivoting QRCPfactor().
  652. Pivoting involve permutations which have their own PERM data structure.
  653. Permutations can be created by px_get(), read and written by px_input() and
  654. px_output(), multiplied by px_mlt(), inverted by px_inv() and applied to
  655. vectors by px_vec().
  656. The above program can be put into a file leastsq.c and compiled under Unix
  657. using
  658. cc -o leastsq leastsq.c meschach.a -lm
  659. A sample session using leastsq follows:
  660. Input A matrix:
  661. Matrix: rows cols:5 3
  662. row 0:
  663. entry (0,0): 3
  664. entry (0,1): -1
  665. entry (0,2): 2
  666. Continue:
  667. row 1:
  668. entry (1,0): 2
  669. entry (1,1): -1
  670. entry (1,2): 1
  671. Continue: n
  672. row 1:
  673. entry (1,0): old 2 new: 2
  674. entry (1,1): old -1 new: -1
  675. entry (1,2): old 1 new: 1.2
  676. Continue:
  677. row 2:
  678. entry (2,0): old 0 new: 2.5
  679. ....
  680. .... (Data entry)
  681. ....
  682. # A =
  683. Matrix: 5 by 3
  684. row 0: 3 -1 2
  685. row 1: 2 -1 1.2
  686. row 2: 2.5 1 -1.5
  687. row 3: 3 1 1
  688. row 4: -1 1 -2.2
  689. Input b vector:
  690. entry 0: old 0 new: 5
  691. entry 1: old 0 new: 3
  692. entry 2: old 0 new: 2
  693. entry 3: old 0 new: 4
  694. entry 4: old 0 new: 6
  695. # b =
  696. Vector: dim: 5
  697. 5 3 2 4 6
  698. Vector of best fit parameters is
  699. Vector: dim: 3
  700. 1.47241555 -0.402817858 -1.14411815
  701. ||A*x-b|| = 6.78938
  702. The Q matrix can be obtained explicitly by the routine makeQ(). The Q
  703. matrix can then be used to obtain an orthogonal basis for the range of A .
  704. An orthogonal basis for the null space of A can be obtained by finding the
  705. QR-factorisation of A^T .
  706. 6. A SPARSE MATRIX EXAMPLE
  707. To illustrate the sparse matrix routines, consider the problem of
  708. solving Poisson's equation on a square using finite differences, and
  709. incomplete Cholesky factorisation. The actual equations to solve are
  710. u_{i,j+1} + u_{i,j-1} + u_{i+1,j} + u_{i-1,j} - 4*u_{i,j} =
  711. h^2*f(x_i,y_j), for i,j=1,...,N
  712. where u_{0,j} = u_{i,0} = u_{N+1,j} = u_{i,N+1} = 0 for i,j=1,...,N and h
  713. is the common distance between grid points.
  714. The first task is to set up the matrix describing this system of linear
  715. equations. The next is to set up the right-hand side. The third is to
  716. form the incomplete Cholesky factorisation of this matrix, and finally to
  717. use the sparse matrix conjugate gradient routine with the incomplete
  718. Cholesky factorisation as preconditioner.
  719. Setting up the matrix and right-hand side can be done by the following
  720. code:
  721. #define N 100
  722. #define index(i,j) (N*((i)-1)+(j)-1)
  723. ......
  724. A = sp_get(N*N,N*N,5);
  725. b = v_get(N*N);
  726. h = 1.0/(N+1); /* for a unit square */
  727. ......
  728. for ( i = 1; i <= N; i++ )
  729. for ( j = 1; j <= N; j++ )
  730. {
  731. if ( i < N )
  732. sp_set_val(A,index(i,j),index(i+1,j),-1.0);
  733. if ( i > 1 )
  734. sp_set_val(A,index(i,j),index(i-1,j),-1.0);
  735. if ( j < N )
  736. sp_set_val(A,index(i,j),index(i,j+1),-1.0);
  737. if ( j > 1 )
  738. sp_set_val(A,index(i,j),index(i,j-1),-1.0);
  739. sp_set_val(A,index(i,j),index(i,j),4.0);
  740. b->ve[index(i,j)] = -h*h*f(h*i,h*j);
  741. }
  742. Once the matrix and right-hand side are set up, the next task is to
  743. compute the sparse incomplete Cholesky factorisation of A. This must be
  744. done in a different matrix, so A must be copied.
  745. LLT = sp_copy(A);
  746. spICHfactor(LLT);
  747. Now when that is done, the remainder is easy:
  748. out = v_get(A->m);
  749. ......
  750. iter_spcg(A,LLT,b,1e-6,out,1000,&num_steps);
  751. printf("Number of iterations = %d\n",num_steps);
  752. ......
  753. and the output can be used in whatever way desired.
  754. For graphical output of the results, the solution vector can be copied
  755. into a square matrix, which is then saved in MATLAB format using m_save(),
  756. and graphical output can be produced by MATLAB.
  757. 7. HOW DO I ....?
  758. For the convenience of the user, here a number of common tasks that
  759. people need to perform frequently, and how to perform the computations
  760. using Meschach.
  761. 7.1 .... SOLVE A SYSTEM OF LINEAR EQUATIONS ?
  762. If you wish to solve Ax=b for x given A and b (without destroying A),
  763. then the following code will do this:
  764. VEC *x, *b;
  765. MAT *A, *LU;
  766. PERM *pivot;
  767. ......
  768. LU = m_get(A->m,A->n);
  769. LU = m_copy(A,LU);
  770. pivot = px_get(A->m);
  771. LUfactor(LU,pivot);
  772. /* set values of b here */
  773. x = LUsolve(LU,pivot,b,VNULL);
  774. 7.2 .... SOLVE A LEAST-SQUARES PROBLEM ?
  775. To minimise ||Ax-b||_2^2 = sum_i ((Ax)_i-b_i)^2, the most reliable
  776. method is based on the QR-factorisation. The following code performs this
  777. calculation assuming that A is m x n with m > n :
  778. MAT *A, *QR;
  779. VEC *diag, *b, *x;
  780. ......
  781. QR = m_get(A->m,A->n);
  782. QR = m_copy(A,QR);
  783. diag = v_get(A->n);
  784. QRfactor(QR,diag);
  785. /* set values of b here */
  786. x = QRsolve(QR,diag,b,x);
  787. 7.3 .... FIND ALL THE EIGENVALUES (AND EIGENVECTORS) OF A GENERAL MATRIX ?
  788. The best method is based on the Schur decomposition. For symmetric
  789. matrices, the eigenvalues and eigenvectors can be computed by a single call
  790. to symmeig(). For non-symmetric matrices, the situation is more complex
  791. and the problem of finding eigenvalues and eigenvectors can become quite
  792. ill-conditioned. Provided the problem is not too ill-conditioned, the
  793. following code should give accurate results:
  794. /* A is the matrix whose eigenvalues and eigenvectors are sought */
  795. MAT *A, *T, *Q, *X_re, *X_im;
  796. VEC *evals_re, *evals_im;
  797. ......
  798. Q = m_get(A->m,A->n);
  799. T = m_copy(A,MNULL);
  800. /* compute Schur form: A = Q*T*Q^T */
  801. schur(T,Q);
  802. /* extract eigenvalues */
  803. evals_re = v_get(A->m);
  804. evals_im = v_get(A->m);
  805. schur_evals(T,evals_re,evals_im);
  806. /* Q not needed for eiegenvalues */
  807. X_re = m_get(A->m,A->n);
  808. X_im = m_get(A->m,A->n);
  809. schur_vecs(T,Q,X_re,X_im);
  810. /* k'th eigenvector is k'th column of (X_re + i*X_im) */
  811. 7.4 .... SOLVE A LARGE, SPARSE, POSITIVE DEFINITE SYSTEM OF EQUATIONS ?
  812. An example of a large, sparse, positive definite matrix is the matrix
  813. obtained from a finite-difference approximation of the Laplacian operator.
  814. If an explicit representation of such a matrix is available, then the
  815. following code is suggested as a reasonable way of computing solutions:
  816. /* A*x == b is the system to be solved */
  817. SPMAT *A, *LLT;
  818. VEC *x, *b;
  819. int num_steps;
  820. ......
  821. /* set up A and b */
  822. ......
  823. x = m_get(A->m);
  824. LLT = sp_copy(A);
  825. /* preconditioning using the incomplete Cholesky factorisation */
  826. spICHfactor(LLT);
  827. /* now use pre-conditioned conjugate gradients */
  828. x = iter_spcg(A,LLT,b,1e-7,x,1000,&num_steps);
  829. /* solution computed to give a relative residual of 10^-7 */
  830. If explicitly storing such a matrix takes up too much memory, then if
  831. you can write a routine to perform the calculation of A*x for any given x ,
  832. the following code may be more suitable (if slower):
  833. VEC *mult_routine(user_def,x,out)
  834. void *user_def;
  835. VEC *x, *out;
  836. {
  837. /* compute out = A*x */
  838. ......
  839. return out;
  840. }
  841. main()
  842. {
  843. ITER *ip;
  844. VEC *x, *b;
  845. ......
  846. b = v_get(BIG_DIM); /* right-hand side */
  847. x = v_get(BIG_DIM); /* solution */
  848. /* set up b */
  849. ......
  850. ip = iter_get(b->dim, x->dim);
  851. ip->b = v_copy(b,ip->b);
  852. ip->info = NULL; /* if you don't want information
  853. about solution process */
  854. v_zero(ip->x); /* initial guess is zero */
  855. iter_Ax(ip,mult_routine,user_def);
  856. iter_cg(ip);
  857. printf("# Solution is:\n"); v_output(ip->x);
  858. ......
  859. ITER_FREE(ip); /* destroy ip */
  860. }
  861. The user_def argument is for a pointer to a user-defined structure
  862. (possibly NULL, if you don't need this) so that you can write a common
  863. function for handling a large number of different circumstances.
  864. 8. MORE ADVANCED TOPICS
  865. Read this if you are interested in using Meschach library as a base for
  866. applications. As an example we show how to implement a new type for 3
  867. dimensional matrices and incorporate this new type into the Meschach
  868. system. Usually this part of Meschach is transparent to a user. But a more
  869. advanced user can take advantage of these routines. We do not describe
  870. the routines in detail here, but we want to give a rather broad picture of
  871. what can be done. By the system we mainly mean the system of delivering
  872. information on the number of bytes of allocated memory and routines for
  873. deallocating static variables by mem_stat_... routines.
  874. First we introduce a concept of a list of types. By a list of types we
  875. mean a set of different types with corresponding routines for creating
  876. these types, destroying and resizing them. Each type list has a number.
  877. The list 0 is a list of standard Meschach types such as MAT or VEC. Other
  878. lists can be defined by a user or a application (based on Meschach). The
  879. user can attach his/her own list to the system by the routine
  880. mem_attach_list(). Sometimes it is worth checking if a list number is
  881. already used by another application. It can be done by
  882. mem_is_list_attached(ls_num), which returns TRUE if the number ls_num
  883. is used. And such a list can be removed from the system by
  884. mem_free_list(ls_num) if necessary.
  885. We describe arguments required by mem_attach_list(). The prototype of
  886. this function is as follow
  887. int mem_attach_list(int ls_num, int ntypes, char *type_names[],
  888. int (*free_funcs[])(), MEM_ARRAY sum[]);
  889. where the structure MEM_ARRAY has two members: "bytes" of type long and
  890. "numvar" of type int. The frst argument is the list number. Note that you
  891. cannot overwrite another list. To do this remove first the old list (by
  892. mem_free_list()) or choose another number. The next argument is the number
  893. of types which are on the list. This number cannot be changed during
  894. running a program. The third argument is an array containing the names of
  895. types (these are character strings). The fourth one is an array of
  896. functions deallocating variables of the corresponding type. And the last
  897. argument is the local array where information about the number of bytes of
  898. allocated/deallocated memory (member bytes) and the number of allocated
  899. variables (member numvar) are gathered. The functions which send
  900. information to this array are mem_bytes_list() and mem_numvar_list().
  901. Example: The routines described here are in the file tutadv.c.
  902. Firstly we define some macros and a type for 3 dimensional matrices.
  903. #include "matrix.h"
  904. #define M3D_LIST 3 /* list number */
  905. #define TYPE_MAT3D 0 /* the number of a type */
  906. /* type for 3 dimensional matrices */
  907. typedef struct {
  908. int l,m,n; /* actual dimensions */
  909. int max_l, max_m, max_n; /* maximal dimensions */
  910. Real ***me; /* pointer to matrix elements */
  911. /* we do not consider segmented memory */
  912. Real *base, **me2d; /* me and me2d are additional pointers
  913. to base */
  914. } MAT3D;
  915. Now we need two routines: one for allocating memory for 3 dimensional
  916. matrices and the other for deallocating it. It can be useful to have a
  917. routine for resizing 3 dimensional matrices but we do not use it here.
  918. Note the use of mem_bytes_list() and mem_numvar_list() to notify the change
  919. in the number of structures and bytes in use.
  920. /* function for creating a variable of MAT3D type */
  921. MAT3D *m3d_get(l,m,n)
  922. int l,m,n;
  923. {
  924. MAT3D *mat;
  925. ....
  926. /* alocate memory for structure */
  927. if ((mat = NEW(MAT3D)) == (MAT3D *)NULL)
  928. error(E_MEM,"m3d_get");
  929. else if (mem_info_is_on()) {
  930. /* record how many bytes are allocated to structure */
  931. mem_bytes_list(TYPE_MAT3D,0,sizeof(MAT3D),M3D_LIST);
  932. /* record a new allocated variable */
  933. mem_numvar_list(TYPE_MAT3D,1,M3D_LIST);
  934. }
  935. ....
  936. /* allocate memory for 3D array */
  937. if ((mat->base = NEW_A(l*m*n,Real)) == (Real *)NULL)
  938. error(E_MEM,"m3d_get");
  939. else if (mem_info_is_on())
  940. mem_bytes_list(TYPE_MAT3D,0,l*m*n*sizeof(Real),M3D_LIST);
  941. ....
  942. return mat;
  943. }
  944. /* deallocate a variable of type MAT3D */
  945. int m3d_free(mat)
  946. MAT3D *mat;
  947. {
  948. /* do not try to deallocate the NULL pointer */
  949. if (mat == (MAT3D *)NULL)
  950. return -1;
  951. ....
  952. /* first deallocate base */
  953. if (mat->base != (Real *)NULL) {
  954. if (mem_info_is_on())
  955. /* record how many bytes is deallocated */
  956. mem_bytes_list(TYPE_MAT3D,mat->max_l*mat->max_m*mat->max_n*sizeof(Real),
  957. 0,M3D_LIST);
  958. free((char *)mat->base);
  959. }
  960. ....
  961. /* deallocate MAT3D structure */
  962. if (mem_info_is_on()) {
  963. mem_bytes_list(TYPE_MAT3D,sizeof(MAT3D),0,M3D_LIST);
  964. mem_numvar_list(TYPE_MAT3D,-1,M3D_LIST);
  965. }
  966. free((char *)mat);
  967. ....
  968. free((char *)mat);
  969. return 0;
  970. }
  971. We can now create the arrays necessary for mem_attach_list(). Note that
  972. m3d_sum can be static if it is in the same file as main(), where
  973. mem_attach_list is called. Otherwise it must be global.
  974. char *m3d_names[] = {
  975. "MAT3D"
  976. };
  977. #define M3D_NUM (sizeof(m3d_names)/sizeof(*m3d_names))
  978. int (*m3d_free_funcs[M3D_NUM])() = {
  979. m3d_free
  980. }
  981. static MEM_ARRAY m3d_sum[M3D_NUM];
  982. The last thing is to attach the list to the system.
  983. void main()
  984. {
  985. MAT3D *M;
  986. ....
  987. mem_info_on(TRUE); /* switch memory info on */
  988. /* attach the new list */
  989. mem_attach_list(M3D_LIST,M3D_NUM,m3d_names,m3d_free_funcs,m3d_sum);
  990. ....
  991. M = m3d_get(3,4,5);
  992. ....
  993. /* making use of M->me[i][j][k], where i,j,k are non-negative and
  994. i < 3, j < 4, k < 5 */
  995. ....
  996. mem_info_file(stdout,M3D_LIST); /* info on the number of allocated
  997. bytes of memory for types
  998. on the list M3D_LIST */
  999. ....
  1000. m3d_free(M); /* if M is not necessary */
  1001. ....
  1002. }
  1003. We can now use the function mem_info_file() for getting information about
  1004. the number of bytes of allocated memory and number of allocated variables
  1005. of type MAT3D; mem_stat_reg_list() for registering variables of this type
  1006. and mem_stat_mark() and mem_stat_free_list() for deallocating static
  1007. variables of this type.
  1008. In the similar way you can create you own list of errors and attach it to
  1009. the system. See the functions:
  1010. int err_list_attach(int list_num, int list_len, char **err_ptr,
  1011. int warn); /* for attaching a list of errors */
  1012. int err_is_list_attached(int list_num); /* checking if a list
  1013. is attached */
  1014. extern int err_list_free(int list_num); /* freeing a list of errors */
  1015. where list_num is the number of the error list, list_len is the number of
  1016. errors on the list, err_ptr is the character string explaining the error
  1017. and warn can be TRUE if this is only a warning (the program continues to
  1018. run) or it can be FALSE if it is an error (the program stops).
  1019. The examples are the standard errors (error list 0) and warnings
  1020. (error list 1) which are in the file err.c
  1021. David Stewart and Zbigniew Leyk, 1993