]> www.ginac.de Git - ginac.git/blob - ginac/archive.cpp
- Lewis-Wester tests D and E now benchmark the time to expand the
[ginac.git] / ginac / archive.cpp
1 /** @file archive.cpp
2  *
3  *  Archiving of GiNaC expressions. */
4
5 /*
6  *  GiNaC Copyright (C) 1999-2001 Johannes Gutenberg University Mainz, Germany
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 #include <iostream>
24 #include <stdexcept>
25
26 #include "archive.h"
27 #include "registrar.h"
28 #include "ex.h"
29 #include "config.h"
30 #include "utils.h"
31
32 #ifndef NO_NAMESPACE_GINAC
33 namespace GiNaC {
34 #endif // ndef NO_NAMESPACE_GINAC
35
36
37 /** Archive an expression.
38  *  @param ex  the expression to be archived
39  *  @param name  name under which the expression is stored */
40 void archive::archive_ex(const ex &e, const char *name)
41 {
42         // Create root node (which recursively archives the whole expression tree)
43         // and add it to the archive
44         archive_node_id id = add_node(archive_node(*this, e));
45
46         // Add root node ID to list of archived expressions
47         archived_ex ae = archived_ex(atomize(name), id);
48         exprs.push_back(ae);
49 }
50
51
52 /** Add archive_node to archive if the corresponding expression is
53  *  not already archived.
54  *  @return ID of archived node */
55 archive_node_id archive::add_node(const archive_node &n)
56 {
57         // Search for node in nodes vector
58         std::vector<archive_node>::const_iterator i = nodes.begin(), iend = nodes.end();
59         archive_node_id id = 0;
60         while (i != iend) {
61                 if (i->has_same_ex_as(n))
62                         return id;
63                 i++; id++;
64         }
65
66         // Not found, add archive_node to nodes vector
67         nodes.push_back(n);
68         return id;
69 }
70
71
72 /** Retrieve archive_node by ID. */
73 archive_node &archive::get_node(archive_node_id id)
74 {
75         if (id >= nodes.size())
76                 throw (std::range_error("archive::get_node(): archive node ID out of range"));
77
78         return nodes[id];
79 }
80
81
82 /** Retrieve expression from archive by name.
83  *  @param sym_lst  list of pre-defined symbols */
84 ex archive::unarchive_ex(const lst &sym_lst, const char *name) const
85 {
86         // Find root node
87         std::string name_string = name;
88         archive_atom id = atomize(name_string);
89         std::vector<archived_ex>::const_iterator i = exprs.begin(), iend = exprs.end();
90         while (i != iend) {
91                 if (i->name == id)
92                         goto found;
93                 i++;
94         }
95         throw (std::logic_error("expression with name '" + name_string + "' not found in archive"));
96
97 found:
98         // Recursively unarchive all nodes, starting at the root node
99         return nodes[i->root].unarchive(sym_lst);
100 }
101
102 /** Retrieve expression from archive by index.
103  *  @param sym_lst  list of pre-defined symbols */
104 ex archive::unarchive_ex(const lst &sym_lst, unsigned int index) const
105 {
106         if (index >= exprs.size())
107                 throw (std::range_error("index of archived expression out of range"));
108
109         // Recursively unarchive all nodes, starting at the root node
110         return nodes[exprs[index].root].unarchive(sym_lst);
111 }
112
113 /** Retrieve expression and its name from archive by index.
114  *  @param sym_lst  list of pre-defined symbols */
115 ex archive::unarchive_ex(const lst &sym_lst, std::string &name, unsigned int index) const
116 {
117         if (index >= exprs.size())
118                 throw (std::range_error("index of archived expression out of range"));
119
120         // Return expression name
121         name = unatomize(exprs[index].name);
122
123         // Recursively unarchive all nodes, starting at the root node
124         return nodes[exprs[index].root].unarchive(sym_lst);
125 }
126
127
128 /** Return number of archived expressions. */
129 unsigned int archive::num_expressions(void) const
130 {
131         return exprs.size();
132 }
133
134
135 /*
136  *  Archive file format
137  *
138  *   - 4 bytes signature 'GARC'
139  *   - unsigned version number
140  *   - unsigned number of atoms
141  *      - atom strings (each zero-terminated)
142  *   - unsigned number of expressions
143  *      - unsigned name atom
144  *      - unsigned root node ID
145  *   - unsigned number of nodes
146  *      - unsigned number of properties
147  *        - unsigned containing type (PTYPE_*) in its lower 3 bits and
148  *          name atom in the upper bits
149  *        - unsigned property value
150  *
151  *  Unsigned quantities are stored in a compressed format:
152  *   - numbers in the range 0x00..0x7f are stored verbatim (1 byte)
153  *   - numbers larger than 0x7f are stored in 7-bit packets (1 byte per
154  *     packet), starting with the LSBs; all bytes except the last one have
155  *     their upper bit set
156  *
157  *  Examples:
158  *   0x00           =   0x00
159  *    ..                 ..
160  *   0x7f           =   0x7f
161  *   0x80 0x01      =   0x80
162  *    ..   ..            ..
163  *   0xff 0x01      =   0xff
164  *   0x80 0x02      =  0x100
165  *    ..   ..            ..
166  *   0xff 0x02      =  0x17f
167  *   0x80 0x03      =  0x180
168  *    ..   ..            ..
169  *   0xff 0x7f      = 0x3fff
170  *   0x80 0x80 0x01 = 0x4000
171  *    ..   ..   ..       ..
172  */
173
174 /** Write unsigned integer quantity to stream. */
175 static void write_unsigned(std::ostream &os, unsigned int val)
176 {
177         while (val > 0x80) {
178                 os.put((val & 0x7f) | 0x80);
179                 val >>= 7;
180         }
181         os.put(val);
182 }
183
184 /** Read unsigned integer quantity from stream. */
185 static unsigned int read_unsigned(std::istream &is)
186 {
187         unsigned char b;
188         unsigned int ret = 0;
189         unsigned int shift = 0;
190         do {
191         char b2;
192                 is.get(b2);
193         b = b2;
194                 ret |= (b & 0x7f) << shift;
195                 shift += 7;
196         } while (b & 0x80);
197         return ret;
198 }
199
200 /** Write archive_node to binary data stream. */
201 std::ostream &operator<<(std::ostream &os, const archive_node &n)
202 {
203         // Write properties
204         unsigned int num_props = n.props.size();
205         write_unsigned(os, num_props);
206         for (unsigned int i=0; i<num_props; i++) {
207                 write_unsigned(os, n.props[i].type | (n.props[i].name << 3));
208                 write_unsigned(os, n.props[i].value);
209         }
210         return os;
211 }
212
213 /** Write archive to binary data stream. */
214 std::ostream &operator<<(std::ostream &os, const archive &ar)
215 {
216         // Write header
217         os.put('G');    // Signature
218         os.put('A');
219         os.put('R');
220         os.put('C');
221         write_unsigned(os, ARCHIVE_VERSION);
222
223         // Write atoms
224         unsigned int num_atoms = ar.atoms.size();
225         write_unsigned(os, num_atoms);
226         for (unsigned int i=0; i<num_atoms; i++)
227                 os << ar.atoms[i] << std::ends;
228
229         // Write expressions
230         unsigned int num_exprs = ar.exprs.size();
231         write_unsigned(os, num_exprs);
232         for (unsigned int i=0; i<num_exprs; i++) {
233                 write_unsigned(os, ar.exprs[i].name);
234                 write_unsigned(os, ar.exprs[i].root);
235         }
236
237         // Write nodes
238         unsigned int num_nodes = ar.nodes.size();
239         write_unsigned(os, num_nodes);
240         for (unsigned int i=0; i<num_nodes; i++)
241                 os << ar.nodes[i];
242         return os;
243 }
244
245 /** Read archive_node from binary data stream. */
246 std::istream &operator>>(std::istream &is, archive_node &n)
247 {
248         // Read properties
249         unsigned int num_props = read_unsigned(is);
250         n.props.resize(num_props);
251         for (unsigned int i=0; i<num_props; i++) {
252                 unsigned int name_type = read_unsigned(is);
253                 n.props[i].type = (archive_node::property_type)(name_type & 7);
254                 n.props[i].name = name_type >> 3;
255                 n.props[i].value = read_unsigned(is);
256         }
257         return is;
258 }
259
260 /** Read archive from binary data stream. */
261 std::istream &operator>>(std::istream &is, archive &ar)
262 {
263         // Read header
264         char c1, c2, c3, c4;
265         is.get(c1); is.get(c2); is.get(c3); is.get(c4);
266         if (c1 != 'G' || c2 != 'A' || c3 != 'R' || c4 != 'C')
267                 throw (std::runtime_error("not a GiNaC archive (signature not found)"));
268         unsigned int version = read_unsigned(is);
269         if (version > ARCHIVE_VERSION || version < ARCHIVE_VERSION - ARCHIVE_AGE)
270                 throw (std::runtime_error("archive version " + ToString(version) + " cannot be read by this GiNaC library (which supports versions " + ToString(ARCHIVE_VERSION-ARCHIVE_AGE) + " thru " + ToString(ARCHIVE_VERSION)));
271
272         // Read atoms
273         unsigned int num_atoms = read_unsigned(is);
274         ar.atoms.resize(num_atoms);
275         for (unsigned int i=0; i<num_atoms; i++)
276                 getline(is, ar.atoms[i], '\0');
277
278         // Read expressions
279         unsigned int num_exprs = read_unsigned(is);
280         ar.exprs.resize(num_exprs);
281         for (unsigned int i=0; i<num_exprs; i++) {
282                 archive_atom name = read_unsigned(is);
283                 archive_node_id root = read_unsigned(is);
284                 ar.exprs[i] = archive::archived_ex(name, root);
285         }
286
287         // Read nodes
288         unsigned int num_nodes = read_unsigned(is);
289         ar.nodes.resize(num_nodes, ar);
290         for (unsigned int i=0; i<num_nodes; i++)
291                 is >> ar.nodes[i];
292         return is;
293 }
294
295
296 /** Atomize a string (i.e. convert it into an ID number that uniquely
297  *  represents the string). */
298 archive_atom archive::atomize(const std::string &s) const
299 {
300         // Search for string in atoms vector
301         std::vector<std::string>::const_iterator i = atoms.begin(), iend = atoms.end();
302         archive_atom id = 0;
303         while (i != iend) {
304                 if (*i == s)
305                         return id;
306                 i++; id++;
307         }
308
309         // Not found, add to atoms vector
310         atoms.push_back(s);
311         return id;
312 }
313
314 /** Unatomize a string (i.e. convert the ID number back to the string). */
315 const std::string &archive::unatomize(archive_atom id) const
316 {
317         if (id >= atoms.size())
318                 throw (std::range_error("archive::unatomizee(): atom ID out of range"));
319
320         return atoms[id];
321 }
322
323
324 /** Copy constructor of archive_node. */
325 archive_node::archive_node(const archive_node &other)
326   : a(other.a), props(other.props), has_expression(other.has_expression), e(other.e)
327 {
328 }
329
330
331 /** Assignment operator of archive_node. */
332 const archive_node &archive_node::operator=(const archive_node &other)
333 {
334         if (this != &other) {
335                 a = other.a;
336                 props = other.props;
337                 has_expression = other.has_expression;
338                 e = other.e;
339         }
340         return *this;
341 }
342
343
344 /** Recursively construct archive node from expression. */
345 archive_node::archive_node(archive &ar, const ex &expr)
346   : a(ar), has_expression(true), e(expr)
347 {
348         expr.bp->archive(*this);
349 }
350
351
352 /** Check if the archive_node stores the same expression as another
353  *  archive_node.
354  *  @return "true" if expressions are the same */
355 bool archive_node::has_same_ex_as(const archive_node &other) const
356 {
357         if (!has_expression || !other.has_expression)
358                 return false;
359         return e.bp == other.e.bp;
360 }
361
362
363 /** Add property of type "bool" to node. */
364 void archive_node::add_bool(const std::string &name, bool value)
365 {
366         props.push_back(property(a.atomize(name), PTYPE_BOOL, value));
367 }
368
369 /** Add property of type "unsigned int" to node. */
370 void archive_node::add_unsigned(const std::string &name, unsigned int value)
371 {
372         props.push_back(property(a.atomize(name), PTYPE_UNSIGNED, value));
373 }
374
375 /** Add property of type "string" to node. */
376 void archive_node::add_string(const std::string &name, const std::string &value)
377 {
378         props.push_back(property(a.atomize(name), PTYPE_STRING, a.atomize(value)));
379 }
380
381 /** Add property of type "ex" to node. */
382 void archive_node::add_ex(const std::string &name, const ex &value)
383 {
384         // Recursively create an archive_node and add its ID to the properties of this node
385         archive_node_id id = a.add_node(archive_node(a, value));
386         props.push_back(property(a.atomize(name), PTYPE_NODE, id));
387 }
388
389
390 /** Retrieve property of type "bool" from node.
391  *  @return "true" if property was found, "false" otherwise */
392 bool archive_node::find_bool(const std::string &name, bool &ret) const
393 {
394         archive_atom name_atom = a.atomize(name);
395         std::vector<property>::const_iterator i = props.begin(), iend = props.end();
396         while (i != iend) {
397                 if (i->type == PTYPE_BOOL && i->name == name_atom) {
398                         ret = i->value;
399                         return true;
400                 }
401                 i++;
402         }
403         return false;
404 }
405
406 /** Retrieve property of type "unsigned" from node.
407  *  @return "true" if property was found, "false" otherwise */
408 bool archive_node::find_unsigned(const std::string &name, unsigned int &ret) const
409 {
410         archive_atom name_atom = a.atomize(name);
411         std::vector<property>::const_iterator i = props.begin(), iend = props.end();
412         while (i != iend) {
413                 if (i->type == PTYPE_UNSIGNED && i->name == name_atom) {
414                         ret = i->value;
415                         return true;
416                 }
417                 i++;
418         }
419         return false;
420 }
421
422 /** Retrieve property of type "string" from node.
423  *  @return "true" if property was found, "false" otherwise */
424 bool archive_node::find_string(const std::string &name, std::string &ret) const
425 {
426         archive_atom name_atom = a.atomize(name);
427         std::vector<property>::const_iterator i = props.begin(), iend = props.end();
428         while (i != iend) {
429                 if (i->type == PTYPE_STRING && i->name == name_atom) {
430                         ret = a.unatomize(i->value);
431                         return true;
432                 }
433                 i++;
434         }
435         return false;
436 }
437
438 /** Retrieve property of type "ex" from node.
439  *  @return "true" if property was found, "false" otherwise */
440 bool archive_node::find_ex(const std::string &name, ex &ret, const lst &sym_lst, unsigned int index) const
441 {
442         archive_atom name_atom = a.atomize(name);
443         std::vector<property>::const_iterator i = props.begin(), iend = props.end();
444         unsigned int found_index = 0;
445         while (i != iend) {
446                 if (i->type == PTYPE_NODE && i->name == name_atom) {
447                         if (found_index == index)
448                                 goto found;
449                         found_index++;
450                 }
451                 i++;
452         }
453         return false;
454
455 found:
456         ret = a.get_node(i->value).unarchive(sym_lst);
457         return true;
458 }
459
460
461 /** Convert archive node to GiNaC expression. */
462 ex archive_node::unarchive(const lst &sym_lst) const
463 {
464         // Already unarchived? Then return cached unarchived expression.
465         if (has_expression)
466                 return e;
467
468         // Find instantiation function for class specified in node
469         std::string class_name;
470         if (!find_string("class", class_name))
471                 throw (std::runtime_error("archive node contains no class name"));
472         unarch_func f = find_unarch_func(class_name);
473
474         // Call instantiation function
475         e = f(*this, sym_lst);
476         has_expression = true;
477         return e;
478 }
479
480
481 /** Assignment operator of property. */
482 const archive_node::property &archive_node::property::operator=(const property &other)
483 {
484         if (this != &other) {
485                 type = other.type;
486                 name = other.name;
487                 value = other.value;
488         }
489         return *this;
490 }
491
492
493 /** Clear all archived expressions. */
494 void archive::clear(void)
495 {
496         atoms.clear();
497         exprs.clear();
498         nodes.clear();
499 }
500
501
502 /** Delete cached unarchived expressions in all archive_nodes (mainly for debugging). */
503 void archive::forget(void)
504 {
505         std::vector<archive_node>::iterator i = nodes.begin(), iend = nodes.end();
506         while (i != iend) {
507                 i->forget();
508                 i++;
509         }
510 }
511
512 /** Delete cached unarchived expressions from node (for debugging). */
513 void archive_node::forget(void)
514 {
515         has_expression = false;
516         e = 0;
517 }
518
519
520 /** Print archive to stream in ugly raw format (for debugging). */
521 void archive::printraw(std::ostream &os) const
522 {
523         // Dump atoms
524         os << "Atoms:\n";
525         {
526                 std::vector<std::string>::const_iterator i = atoms.begin(), iend = atoms.end();
527                 archive_atom id = 0;
528                 while (i != iend) {
529                         os << " " << id << " " << *i << std::endl;
530                         i++; id++;
531                 }
532         }
533         os << std::endl;
534
535         // Dump expressions
536         os << "Expressions:\n";
537         {
538                 std::vector<archived_ex>::const_iterator i = exprs.begin(), iend = exprs.end();
539                 unsigned int index = 0;
540                 while (i != iend) {
541                         os << " " << index << " \"" << unatomize(i->name) << "\" root node " << i->root << std::endl;
542                         i++; index++;
543                 }
544         }
545         os << std::endl;
546
547         // Dump nodes
548         os << "Nodes:\n";
549         {
550                 std::vector<archive_node>::const_iterator i = nodes.begin(), iend = nodes.end();
551                 archive_node_id id = 0;
552                 while (i != iend) {
553                         os << " " << id << " ";
554                         i->printraw(os);
555                         i++; id++;
556                 }
557         }
558 }
559
560 /** Output archive_node to stream in ugly raw format (for debugging). */
561 void archive_node::printraw(std::ostream &os) const
562 {
563         // Dump cached unarchived expression
564         if (has_expression)
565                 os << "(basic * " << e.bp << " = " << e << ")\n";
566         else
567                 os << "\n";
568
569         // Dump properties
570         std::vector<property>::const_iterator i = props.begin(), iend = props.end();
571         while (i != iend) {
572                 os << "  ";
573                 switch (i->type) {
574                         case PTYPE_BOOL: os << "bool"; break;
575                         case PTYPE_UNSIGNED: os << "unsigned"; break;
576                         case PTYPE_STRING: os << "string"; break;
577                         case PTYPE_NODE: os << "node"; break;
578                         default: os << "<unknown>"; break;
579                 }
580                 os << " \"" << a.unatomize(i->name) << "\" " << i->value << std::endl;
581                 i++;
582         }
583 }
584
585 /** Create a dummy archive.  The intention is to fill archive_node's default
586  *  ctor, which is currently a Cint-requirement. */
587 archive* archive_node::dummy_ar_creator(void)
588 {
589         static archive* some_ar = new archive;
590         return some_ar;
591 }
592
593
594 #ifndef NO_NAMESPACE_GINAC
595 } // namespace GiNaC
596 #endif // ndef NO_NAMESPACE_GINAC