File: solve.py

package info (click to toggle)
pyx3 0.17-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,328 kB
  • sloc: python: 27,656; makefile: 225; ansic: 130; sh: 17
file content (613 lines) | stat: -rw-r--r-- 19,536 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
#!/usr/bin/env python
# -*- coding: ISO-8859-1 -*-
#
#
# Copyright (C) 2004 Andr Wobst <wobsta@users.sourceforge.net>
#
# This file is part of PyX (https://pyx-project.org/).
#
# PyX is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# PyX is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyX; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


import numpy


def sum(list):
    # we can assume len(list) != 0 here (and do not start from the scalar 0)
    sum = list[0]
    for item in list[1:]:
        sum += item
    return sum

def product(list):
    # we can assume len(list) != 0 here (and do not start from the scalar 1)
    product = list[0]
    for item in list[1:]:
        product *= item
    return product


class scalar:
    # represents a scalar variable or constant

    def __init__(self, value=None, name="unnamed_scalar"):
        self._scalar = None
        if value is not None:
            self.set(value)
        self.name = name

    def scalar(self):
        return self

    def addend(self):
        return addend([self])

    def polynom(self):
        return self.addend().polynom()

    def __neg__(self):
        return -self.addend()

    def __add__(self, other):
        return self.polynom() + other

    __radd__ = __add__

    def __sub__(self, other):
        return self.polynom() - other

    def __rsub__(self, other):
        return -self.polynom() + other

    def __mul__(self, other):
        return self.addend()*other

    __rmul__ = __mul__

    def __div__(self, other):
        return self.addend()/other

    def is_set(self):
        return self._scalar is not None

    def set(self, value):
        if self.is_set():
            raise RuntimeError("scalar already defined")
        try:
            self._scalar = float(value)
        except Exception:
            raise RuntimeError("float expected")

    def get(self):
        if not self.is_set():
            raise RuntimeError("scalar not yet defined")
        return self._scalar

    def __float__(self):
        return self.get()

    def __str__(self):
        if self.is_set():
            return "%s{=%s}" % (self.name, self._scalar)
        else:
            return self.name


class addend:
    # represents a addend, i.e. list of scalars to be multiplied by each other

    def __init__(self, scalars):
        self._scalars = [scalar.scalar() for scalar in scalars]
        if not len(self._scalars):
            raise RuntimeError("empty scalars not allowed")

    def addend(self):
        return self

    def polynom(self):
        return polynom([self])

    def __neg__(self):
        return addend([scalar(-1)] + self._scalars)

    def __add__(self, other):
        return self.polynom() + other

    __radd__ = __add__

    def __sub__(self, other):
        return self.polynom() - other

    def __rsub__(self, other):
        return -self.polynom() + other

    def __mul__(self, other):
        try:
            other = other.addend()
        except (TypeError, AttributeError):
            try:
                other = scalar(other)
            except RuntimeError:
                return other * self
            else:
                return addend(self._scalars + [other])
        else:
            return addend(self._scalars + other._scalars)

    __rmul__ = __mul__

    def __div__(self, other):
        return addend([scalar(1/other)] + self._scalars)

    def __float__(self):
        return product([float(scalar) for scalar in self._scalars])

    def is_linear(self):
        return len([scalar for scalar in self._scalars if not scalar.is_set()]) < 2

    def prefactor(self):
        assert self.is_linear()
        setscalars = [scalar for scalar in self._scalars if scalar.is_set()]
        if len(setscalars):
            return float(addend(setscalars))
        else:
            return 1

    def variable(self):
        assert self.is_linear()
        unsetscalars = [scalar for scalar in self._scalars if not scalar.is_set()]
        if len(unsetscalars):
            assert len(unsetscalars) == 1
            return unsetscalars[0]
        else:
            return None

    def __str__(self):
        return " * ".join([str(scalar) for scalar in self._scalars])


class polynom:
    # represents a polynom, i.e. a list of addends to be summed up

    def __init__(self, polynom):
        self._addends = [addend.addend() for addend in polynom]
        if not len(self._addends):
            raise RuntimeError("empty polynom not allowed")

    def polynom(self):
        return self

    def __neg__(self):
        return polynom([-addend for addend in self._addends])

    def __add__(self, other):
        try:
            other = other.polynom()
        except (TypeError, AttributeError):
            other = scalar(other).polynom()
        return polynom(self._addends + other._addends)

    __radd__ = __add__

    def __sub__(self, other):
        return -other + self

    def __rsub__(self, other):
        return -self + other

    def __mul__(self, other):
        return sum([addend*other for addend in self._addends])

    __rmul__ = __mul__

    def __div__(self, other):
        return polynom([addend/other for addend in self._addends])

    def __float__(self):
        return sum([float(addend) for addend in self._addends])

    def is_linear(self):
        is_linear = 1
        for addend in self._addends:
            is_linear = is_linear and addend.is_linear()
        return is_linear

    def __str__(self):
        return "  +  ".join([str(addend) for addend in self._addends])

    def solve(self, solver):
        solver.addequation(self)


class vector:
    # represents a vector, i.e. a list of scalars (or polynoms)

    def __init__(self, dimension_or_values, name="unnamed_vector"):
        try:
            name + ""
        except Exception:
            raise RuntimeError("a vectors name should be a string (you probably wanted to write vector([x, y]) instead of vector(x, y))")
        try:
            for value in dimension_or_values:
                pass
        except Exception:
            # dimension
            self._items = [scalar(name="%s[%i]" % (name, i))
                           for i in range(dimension_or_values)]
        else:
            # values
            self._items = []
            for value in dimension_or_values:
                try:
                    value.polynom()
                except (TypeError, AttributeError):
                    self._items.append(scalar(value=value, name="%s[%i]" % (name, len(self._items))))
                else:
                    self._items.append(value)
        if not len(self._items):
            raise RuntimeError("empty vector not allowed")
        self.name = name

    def __len__(self):
        return len(self._items)

    def __getitem__(self, i):
        return self._items[i]

    def __getattr__(self, attr):
        if attr == "x":
            return self[0]
        if attr == "y":
            return self[1]
        if attr == "z":
            return self[2]
        else:
            raise AttributeError(attr)

    def vector(self):
        return self

    def __neg__(self):
        return vector([-item for item in self._items])

    def __add__(self, other):
        other = other.vector()
        if len(self) != len(other):
            raise RuntimeError("vector length mismatch in add")
        return vector([selfitem + otheritem for selfitem, otheritem in zip(self._items, other._items)])

    __radd__ = __add__

    def __sub__(self, other):
        return -other + self

    def __rsub__(self, other):
        return -self + other

    def __mul__(self, other):
        try:
            other = other.vector()
        except (TypeError, AttributeError):
            return vector([item*other for item in self._items])
        else:
            # scalar product
            if len(self) != len(other):
                raise RuntimeError("vector length mismatch in scalar product")
            return sum([selfitem*otheritem for selfitem, otheritem in zip(self._items, other._items)])

    def __rmul__(self, other):
        return vector([other*item for item in self._items])
        # We do not allow for vector * <matrix-like-object> here (i.e. a
        # simulating the behaviour of a dual vector). In principle we could do
        # that, but for transformations it would lead to (a*X)*c != a*(X*c).
        # Hence we disallow vector*X for X being something else that a scalar.

    def __div__(self, other):
        return vector([item/other for item in self._items])

    def __str__(self):
        return "%s{=(%s)}" % (self.name, ", ".join([str(item) for item in self._items]))

    def solve(self, solver):
        for item in self._items:
            solver.addequation(item)


class zerovector(vector):

    def __init__(self, dimension, name="0"):
        vector.__init__(self, [0 for i in range(dimension)], name)


class matrix:
    # represents a matrix, i.e. a 2d list of scalars (or polynoms)

    def __init__(self, dimensions_or_values, name="unnamed_matrix"):
        try:
            name + ""
        except Exception:
            raise RuntimeError("a matrix name should be a string (you probably wanted to write matrix([x, y]) instead of matrix(x, y))")
        try:
            for row in dimensions_or_values:
                for col in row:
                    pass
        except Exception:
            # dimension
            self._numberofrows, self._numberofcols = [int(x) for x in dimensions_or_values]
            self._rows = [[scalar(name="%s[%i, %i]" % (name, row, col))
                           for col in range(self._numberofcols)]
                          for row in range(self._numberofrows)]
        else:
            # values
            self._rows = []
            self._numberofcols = None
            for row in dimensions_or_values:
                _cols = []
                for col in row:
                    try:
                        col.polynom()
                    except (TypeError, AttributeError):
                        _cols.append(scalar(value=col, name="%s[%i, %i]" % (name, len(self._rows), len(_cols))))
                    else:
                        _cols.append(col)
                self._rows.append(_cols)
                if self._numberofcols is None:
                    self._numberofcols = len(_cols)
                elif self._numberofcols != len(_cols):
                    raise RuntimeError("column length mismatch")
            self._numberofrows = len(self._rows)
        if not self._numberofrows or not self._numberofcols:
            raise RuntimeError("empty matrix not allowed")
        self.name = name

    # instead of __len__ two methods to fetch the matrix dimensions
    def getnumberofrows(self):
        return self._numberofrows

    def getnumberofcols(self):
        return self._numberofcols

    def __getitem__(self, xxx_todo_changeme):
        (row, col) = xxx_todo_changeme
        return self._rows[row][col]

    def matrix(self):
        return self

    def __neg__(self):
        return matrix([[-col for col in row] for row in self._rows])

    def __add__(self, other):
        other = other.matrix()
        if self._numberofrows != other._numberofrows or self._numberofcols != other._numberofcols:
            raise RuntimeError("matrix geometry mismatch in add")
        return matrix([[selfcol + othercol
                        for selfcol, othercol in zip(selfrow, otherrow)]
                       for selfrow, otherrow in zip(self._rows, other._rows)])

    __radd__ = __add__

    def __sub__(self, other):
        return -other + self

    def __rsub__(self, other):
        return -self + other

    def __mul__(self, other):
        try:
            other = other.matrix()
        except (TypeError, AttributeError):
            try:
                other = other.vector()
            except (TypeError, AttributeError):
                return matrix([[col*other for col in row] for row in self._rows])
            else:
                if self._numberofcols != len(other):
                    raise RuntimeError("size mismatch in matrix vector product")
                return vector([sum([col*otheritem
                                    for col, otheritem in zip(row, other)])
                               for row in self._rows])
        else:
            if self._numberofcols != other._numberofrows:
                raise RuntimeError("size mismatch in matrix product")
            return matrix([[sum([self._rows[row][i]*other._rows[i][col]
                                 for i in range(self._numberofcols)])
                            for col in range(other._numberofcols)]
                           for row in range(self._numberofrows)])

    def __rmul__(self, other):
        try:
            other = other.vector()
        except (TypeError, AttributeError):
            return matrix([[other*col for col in row] for row in self._rows])
        else:
            if self._numberofrows != len(other):
                raise RuntimeError("size mismatch in matrix vector product")
            return vector([sum([other[i]*self._rows[i][col]
                                for i in range(self._numberofrows)])
                           for col in range(self._numberofcols)])

    def __div__(self, other):
        return matrix([[col/other for col in row] for row in self._rows])

    def __str__(self):
        return "%s{=(%s)}" % (self.name, ", ".join(["(" + ", ".join([str(col) for col in row]) + ")" for row in self._rows]))

    def solve(self, solver):
        for row in self._rows:
            for col in row:
                solver.addequation(col)


class identitymatrix(matrix):

    def __init__(self, dimension, name="I"):
        def eq(row, col):
            if row == col:
                return 1
            else:
                return 0
        matrix.__init__(self, [[eq(row, col) for col in range(dimension)] for row in range(dimension)], name)


class trafo:
    # represents a transformation, i.e. matrix and a constant vector

    def __init__(self, dimensions_or_values, name="unnamed_trafo"):
        try:
            name + ""
        except Exception:
            raise RuntimeError("a trafo name should be a string (you probably wanted to write trafo([x, y]) instead of trafo(x, y))")
        if len(dimensions_or_values) != 2:
            raise RuntimeError("first parameter of a trafo must contain two elements: either two dimensions or a matrix and a vector")
        try:
            numberofrows, numberofcols = [int(x) for x in dimensions_or_values]
        except Exception:
            self._matrix = dimensions_or_values[0].matrix()
            self._vector = dimensions_or_values[1].vector()
            if self._matrix.getnumberofrows() != len(self._vector):
                raise RuntimeError("size mismatch between matrix and vector")
        else:
            self._matrix = matrix((numberofrows, numberofcols), name=name + "_matrix")
            self._vector = vector(numberofrows, name=name + "_vector")
        self.name = name

    def trafo(self):
        return self

    def getmatrix(self):
        return self._matrix

    def getvector(self):
        return self._vector

    def __neg__(self):
        return trafo((-self._matrix, -self._vector))

    def __add__(self, other):
        other = other.trafo()
        return trafo((self._matrix + other._matrix, self._vector + other._vector))

    __radd__ = __add__

    def __sub__(self, other):
        return -other + self

    def __rsub__(self, other):
        return -self + other

    def __mul__(self, other):
        try:
            other = other.trafo()
        except (TypeError, AttributeError):
            try:
                other = other.vector()
            except (TypeError, AttributeError):
                return trafo((self._matrix * other, self._vector * other))
            else:
                return self._matrix * other + self._vector
        else:
            return trafo((self._matrix * other._matrix, self._vector + self._matrix * other._vector))

    def __rmul__(self, other):
        return trafo((other * self._matrix, other * self._vector))

    def __div__(self, other):
        return trafo((self._matrix/other, self._vector/other))

    def __str__(self):
        return "%s{=(matrix: %s, vector: %s)}" % (self.name, self._matrix, self._vector)

    def solve(self, solver):
        self._matrix.solve(solver)
        self._vector.solve(solver)


class identitytrafo(trafo):

    def __init__(self, dimension, name="I"):
        trafo.__init__(self, (identitymatrix(dimension, name=name),
                              zerovector(dimension, name=name)), name)


class Solver:
    # linear equation solver

    def __init__(self):
        self.eqs = [] # scalar equations not yet solved (a equation is a polynom to be zero)

    def eq(self, lhs, rhs=None):
        if rhs is None:
            eq = lhs
        else:
            eq = lhs - rhs
        eq.solve(self)

    def addequation(self, equation):
        # the equation is just a polynom which should be zero
        self.eqs.append(equation.polynom())

        # try to solve some combinations of linear equations
        while 1:
            for eqs in self.combine(self.eqs):
                if self.solve(eqs):
                    break # restart for loop
            else:
                break # quit while loop

    def combine(self, eqs):
        # create combinations of linear equations
        if not len(eqs):
            yield []
        else:
            for x in self.combine(eqs[1:]):
                yield x
            if eqs[0].is_linear():
                for x in self.combine(eqs[1:]):
                    yield [eqs[0]] + x

    def solve(self, eqs):
        # try to solve a set of linear equations
        l = len(eqs)
        if l:
            vars = []
            for eq in eqs:
                for addend in eq._addends:
                    var = addend.variable()
                    if var is not None and var not in vars:
                        vars.append(var)
            if len(vars) == l:
                a = numpy.zeros((l, l), numpy.float)
                b = numpy.zeros((l, ), numpy.float)
                for i, eq in enumerate(eqs):
                    for addend in eq._addends:
                        var = addend.variable()
                        if var is not None:
                            a[i, vars.index(var)] += addend.prefactor()
                        else:
                            b[i] -= addend.prefactor()
                for i, value in enumerate(numpy.linalg.solve(a, b)):
                    vars[i].set(value)
                for eq in eqs:
                    i, = [i for i, selfeq in enumerate(self.eqs) if selfeq == eq]
                    del self.eqs[i]
                return 1
            elif len(vars) < l:
                raise RuntimeError("equations are overdetermined")
        return 0

solver = Solver()