forked from pyphs/pyphs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.py
1360 lines (1077 loc) · 41.9 KB
/
core.py
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 22 18:26:56 2016
@author: Falaize
"""
from __future__ import absolute_import, division, print_function
import sympy
import copy
import shelve
from ..misc.tools import geteval
from ..config import VERBOSE
# Structure methods
from .structure.R import reduce_z
from .structure.splits import linear_nonlinear
from .structure.output import output_function as output
from .structure.moves import move_stor, move_diss, move_port, move_connector
from .structure.connectors import port2connector
from .maths import gradient, jacobian, inverse, hessian, matvecprod
from .structure.dimensions import Dimensions
from .structure.indices import Indices
from .tools import (types, free_symbols, sympify,
substitute_core, subsinverse_core, simplify_core)
from ..misc.latex import texdocument, core2tex
from collections import OrderedDict
import os
class Core:
"""
This is the base class for the core *Port-Hamiltonian Systems* structure
in PyPHS.
"""
# =====================================================================
# Retrieve structure methods
reduce_z = reduce_z
linear_nonlinear = linear_nonlinear
output = output
move_storage = move_stor
move_dissipative = move_diss
move_port = move_port
move_connector = move_connector
# =====================================================================
# Constructor
def __init__(self, label=None):
"""
Constructor for the Core Port-Hamiltonian structure object of pyphs.
Parameter
----------
label: None or string
An optional label string (default is None).
Returns
-------
core : Core
A Core Port-Hamiltonian structure object.
"""
# =====================================================================
# Label
# Init label
if label is None:
label = 'phs'
self.label = label
# =====================================================================
# Symbols
# assertions for sympy symbols
self.assertions = {'real': True}
# =====================================================================
# Arguments
# Ordered list of variables considered as the systems's arguments
self.args_names = ('x', 'dx', 'w', 'u', 'p', 'o')
self.attrstocopy = {('dims', '_xl'), ('dims', '_wl'),
'connectors', 'force_wnl', 'subs', 'M', '_dxH',
'symbs_names', 'exprs_names', 'observers'}
# Names for structure matrices
self.struc_names = ['M', 'J', 'R']
# =====================================================================
# Returned by core.dxH(). If None, returns gradient(core.H, core.x).
self._dxH = None
# names for lists of symbols (x, w, ...)
self.symbs_names = set()
# Expressions names
self.exprs_names = set()
# Init structure
self.M = types.matrix_types[0](sympy.zeros(0))
# List of connectors
self.connectors = list()
# UNORDERED Dictionary of substitution {symbol: value}
self.subs = OrderedDict()
# ORDERED Dictionary of observers {symbol: expr}
self.observers = OrderedDict()
# List of dissipative variable symbols to be ignored in self.reduce_z
self.force_wnl = list()
# set Dimensions object
self.dims = Dimensions(self)
# set Indices object
self.inds = Indices(self)
# init lists of symbols
for name in {'x', 'w', 'u', 'y', 'cu', 'cy', 'p'}:
self.setsymb(name, types.vector_types[0]())
# init functions
self.setexpr('H', sympify(0))
self.setexpr('z', types.vector_types[0]())
# Coefficient matrices for linear parts
self.setexpr('Q', types.matrix_types[0](sympy.zeros(0, 0)))
self.setexpr('Zl', types.matrix_types[0](sympy.zeros(0, 0)))
self.setexpr('bl', types.matrix_types[0](sympy.zeros(0, 0)))
# init tools
self.dims = Dimensions(self)
self.inds = Indices(self)
# =====================================================================
# Accessors and mutators
# get() and set() for structure matrices
names = ('x', 'w', 'y', 'cy', 'xl', 'xnl', 'wl', 'wnl')
self._struc_getset(names)
# build accessors for nonlinear and linear parts
for name in {'x', 'dx', 'dxH'}:
lnl_accessors = self._gen_lnl_accessors(name, 'x')
setattr(self, name+'l', lnl_accessors[0])
setattr(self, name+'nl', lnl_accessors[1])
for name in {'w', 'z'}:
lnl_accessors = self._gen_lnl_accessors(name, 'w')
setattr(self, name+'l', lnl_accessors[0])
setattr(self, name+'nl', lnl_accessors[1])
# =========================================================================
# =========================================================================
# Save and Load
def save(self, folder=None, label=None):
"""
save
====
Save Core object to disk. The path is `folder/label.phs`.
Notice the data appears on disk as `folder/label.phs.db`.
Parameters
----------
folder : string (optional)
Folder where to save the object (default is current working
directory).
label : string (optional)
label of the object to save (default is current object label).
"""
if folder is None:
folder = os.getcwd()
if label is None:
label = self.label
folder = os.path.join(folder, label)
if not os.path.exists(folder):
os.mkdir(folder)
filename = '{0}.{1}'.format(label, 'phs')
path = os.path.join(folder, filename)
dico = {}
dico['label'] = label
for name in (list(set().union(
self.attrstocopy,
self.exprs_names,
self.symbs_names))):
if isinstance(name, str):
source = self
attr_name = name
else:
source = getattr(self, name[0])
attr_name = name[1]
obj = getattr(source, attr_name)
dico[attr_name] = obj
with shelve.open(path) as database:
database['core'] = dico
if VERBOSE > 0:
print('Core {0} saved in {1}'.format(self.label, path))
def load(self, folder=None, label=None):
"""
load
====
Load Core object content from disk. The path is
* folder/label.phs
Notice the data appears on disk as
* folder/label.phs.db
Parameters
----------
folder : string (optional)
Folder where to load the object (default is current working
directory).
label : string (optional)
label of the object to load (default is current object label).
"""
if folder is None:
folder = os.getcwd()
if label is None:
label = self.label
filename = '{0}.{1}'.format(label, 'phs')
path = os.path.join(folder, label, filename)
with shelve.open(path) as database:
dico = database['core']
self.label = copy.copy(dico['label'])
for name in (list(set().union(
self.attrstocopy,
self.exprs_names,
self.symbs_names))):
if isinstance(name, str):
target = self
attr_name = name
else:
target = getattr(self, name[0])
attr_name = name[1]
attr = dico[attr_name]
try:
setattr(target, attr_name, attr.copy())
except AttributeError:
setattr(target, attr_name, copy.copy(attr))
if VERBOSE > 0:
print('Read Core from {0}'.format(path))
# =========================================================================
# Copy
def __copy__(self):
core = Core(label=None)
for name in (list(set().union(
self.attrstocopy,
self.exprs_names,
self.symbs_names))):
if isinstance(name, str):
source = self
target = core
attr_name = name
else:
source = geteval(self, name[0])
target = geteval(core, name[0])
attr_name = name[1]
attr = geteval(source, attr_name)
try:
setattr(target, attr_name, attr.copy())
except AttributeError:
setattr(target, attr_name, copy.copy(attr))
core.label = copy.copy(self.label)
return core
# =========================================================================
def __add__(core1, core2):
"""
Add core1 and core2 and return a new core.
Every vectors are concatenated and structure matrices with same labels
are diagonally stacked into a big (square) structure matrix.
"""
assert set(core1.symbs_names) == set(core2.symbs_names)
core = Core(label=core1.label)
# Concatenate lists of symbols
for name in core1.symbs_names:
attr1 = getattr(core1, name)
attr2 = getattr(core2, name)
core.setsymb(name, attr1 + attr2)
for vari in core.dims.names:
for varj in core.dims.names:
Mij1 = getattr(core1, 'M'+vari+varj)()
Mij2 = getattr(core2, 'M'+vari+varj)()
Mij = types.matrix_types[0](sympy.diag(Mij1, Mij2))
if all(dim > 0 for dim in Mij.shape):
set_func = getattr(core, 'set_M'+vari+varj)
set_func(Mij)
# Concatenate lists of symbols
for name in core1.symbs_names:
attr1 = getattr(core1, name)
attr2 = getattr(core2, name)
core.setsymb(name, attr1 + attr2)
# Update subs disctionary
core.subs = {}
core.subs.update(core1.subs)
core.subs.update(core2.subs)
# Update observers dictionary
core.observers.update(core1.observers)
core.observers.update(core2.observers)
# Set Hamiltonian expression
core.setexpr('H', core1.H + core2.H)
# Concatenate lists of expressions
core.setexpr('z', core1.z + core2.z)
core.connectors = core1.connectors + core2.connectors
core.force_wnl = core1.force_wnl + core2.force_wnl
for vari in core.dims.names:
for varj in core.dims.names:
Mij = getattr(core, 'M'+vari+varj)()
if all(dim > 0 for dim in Mij.shape):
set_func = getattr(core, 'set_M'+vari+varj)
set_func(Mij)
return core
# =========================================================================
# SYMBOLS
def dx(self):
"""
dx
==
Returns the symbols "dxi" associated with the differentials of the
state with symbol "xi" for each "xi" in state vector 'Core.x'. It
is used in the numerical methods as the state increment
:code:`x[n+1]=x[n]+dx[n]`.
"""
return [self.symbols('d'+str(x)) for x in self.x]
def dtx(self):
return [self.symbols('dt'+str(x)) for x in self.x]
def b(self):
return self.dtx() + self.w + self.y
def a(self):
return geteval(self, 'dxH') + self.z + self.u
def pd(self):
output = sympify(0)
for w, z in zip(self.w, self.z):
output += w*z
output += sympy.SparseMatrix(self.a()).dot(matvecprod(self.R(),
self.a()))
return output
def z_symbols(self):
"""
z_symbols
=========
Returns the symbols "zi" associated with the dissipation function
"(zi, wi)" for each "wi" in dissipation variables vector
'Core.w'.
"""
return self.symbols(['z'+str(w)[1:] for w in self.w])
def g(self):
"""
g
=
Returns the symbols "gxi" associated with the gradient of the storage
function w.r.t the state "xi" for each "xi" in state vector
'Core.x'. It is used in the numerical methods as replacement symbols
for the discrete evaluation of Hamiltonian's gradient in the structure
matrix and dissipation function z.
"""
return [self.symbols('g'+str(x)) for x in self.x]
def o(self):
"""
o
=
Returns the symbols "oi" associated with the i-th keyof dictionary
'Core.observers'. It is used in the numerical methods as replacement
symbols for the discrete evaluation of observers in the structure
matrix and dissipation function z.
"""
return list(self.observers.keys())
def setsymb(self, name, symbs):
"""
If name attribute does not exist, it is created with contents symbs
and name is added to symbs_names. Else, attribute name is overwritten
by symbs.
"""
if name not in self.symbs_names:
self.symbs_names.add(name)
setattr(self, name, symbs)
def allsymbs(self):
"""
Returns all the symbols in the lists with names from
'Core.symbs_names'.
"""
symbs = set()
for name in self.symbs_names:
this_name_symbs = getattr(self, name)
for symb in this_name_symbs:
symbs.add(symb)
for k in self.subs:
for s in free_symbols(k):
symbs.add(s)
for s in free_symbols(self.subs[k]):
symbs.add(s)
return symbs
def index(self, name, symb):
"""
index
=====
Return the index of symb in attribute name.
Parameters
----------
name : str
Name of attribute in self where to search for symb.
symb : symbol or str
Item to search in attribute 'name'.
"""
attr = getattr(self, name)
if not isinstance(symb, sympy.Symbol):
symb = self.symbols(symb)
i = attr.index(symb)
return i
# try:
# print('try:')
# i = attr.get_index(symb)
# print(i)
# except AttributeError:
# # name and attribute type
# text = 'Attribute {} is not a list, it is a {}.'.format(name,
# type(attr))
# raise AttributeError(text)
#
# except ValueError:
# # name and attribute type
# text = 'Attribute {} does not contain {}.'.format(name, symb)
# raise AttributeError(text)
# except:
# print('error')
# finally:
# return i
# =========================================================================
# EXPRESSIONS
def setexpr(self, name, expr):
"""
setexpr
*******
Add the sympy expression 'expr' to the object under argument 'name',
and add 'name' to the set of expressions names 'core.exprs_names'.
"""
if name not in self.exprs_names:
self.exprs_names.add(name)
setattr(self, name, expr)
def freesymbols(self):
"""
freesymbols
***********
Retrun a set of freesymbols in all exprs referenced in
'Core.exprs_names'.
"""
symbs = set()
for name in self.exprs_names:
expr = geteval(self, name)
symbs.union(free_symbols(expr))
symbs.union(free_symbols(self.M))
return symbs
def dxH(self):
"""
dxH
***
Gradient of storage function
:math:`\\mathtt{dxH}_i = \\frac{\\partial \\mathrm H}{\\partial x_i}`.
Return
------
dxH: list of sympy expressions
If core._dxH is None, this is a shortcut for
:code:`[core.H.diff(xi) for xi in core.x]`. Else, returns
:code:`core._dxH` (as an example, :code:`Method.dxH()`
returns the discrete gradient expression).
See also
---------
:code:`pyphs.core.calculus.gradient`
"""
if self._dxH is None:
return gradient(self.H, self.x)
else:
return self._dxH
def Hx(self, x):
"""
Return the part of H associated with x, i.e. int_x (dH(x)/dx) dx
Parameter
---------
x : core symbol
Symbol for which the contribution to energy is returned
Output
------
Hx : expression
The contribution to total energy associated with x
"""
def jacz(self):
"""
jacz
***
Return the jacobian of dissipative function
:math:`\left[\\mathcal{J}_{\\mathbf z}\right]_{i,j}(\\mathbf w)=\\frac{\partial z_i}{\partial w_j}(\\mathbf w)`.
"""
return jacobian(self.z, self.w)
def hessH(self):
"""
hessH
***
Return the hessian matrix of the storage function
:math:`\left[\\mathcal{J}_{\\mathbf z}\right]_{i,j}(\\mathbf w)=\\frac{\partial z_i}{\partial w_j}(\\mathbf w)`.
"""
return hessian(self.H, self.x)
# =========================================================================
# STRUCTURE
def init_M(self):
"""
init_M
******
Initialize the structure matrix M with appropriate number of zeros.
"""
self.M = types.matrix_types[0](sympy.zeros(self.dims.tot()))
def J(self):
"""
J
*
Return the skew-symetric part of structure matrix
:math:`\\mathbf{M} = \\mathbf{J} - \\mathbf{R}` associated with the
conservative interconnection.
Return
------
J: sympy SparseMatrix
:math:`\\mathbf{J} = \\frac{1}{2}(\\mathbf{M} - \\mathbf{M}^\intercal)`
"""
return (self.M - self.M.T)/2.
def R(self):
"""
*
R
*
Return the symetric part of structure matrix
:math:`\\mathbf{M} = \\mathbf{J} - \\mathbf{R}` associated with the
resistive interconnection.
Return
------
R: sympy SparseMatrix
:math:`\\mathbf{R} = -\\frac{1}{2}(\\mathbf{M} + \\mathbf{M}^\intercal)`
"""
return -(self.M + self.M.T)/2.
# =========================================================================
# LABELS
def labels(self, i=None):
"""
Return a list of the system's equations labels wich are by convention
:code:`(x, w, y, cy)`. Every symbols (:code:`core.x`, ...) are
converted to strings.
Parameter
---------
i : None or int
If None, every symbols are returned, else the label with index i is
returned (default is None).
"""
labels = self.x + self.w + self.y + self.cy
if i is None:
return [str(el) for el in labels]
else:
return str(labels[i])
# =========================================================================
def simplify(self):
"""
simplify
**********
Apply simplifications to every expressions.
"""
simplify_core(self)
# =========================================================================
@property
def subsexprs(self):
exprs_dic = {}
for k in self.subs.keys():
if not isinstance(self.subs[k], (int, float)):
exprs_dic[k] = self.subs[k]
return exprs_dic
def substitute(self, **kwargs):
"""
substitute
**********
Apply substitutions to every expressions.
Keyword arguments
-----------------
subs : dictionary or None
A dictionary with entries in the format :code:`{s: v}` with
:code:`s` the sympy symbol to substitute by value :code:`v`, which
value can be a numerical value (:code:`float, int`), a new sympy
symbol or a sympy expression. Default is None.
selfall : bool
If True, every substitutions in the dictionary :code:`Core.subs`
are applied and the dictionary is reinitialized to :code:`{}`.
Default is False.
selfexprs : bool
If True, only substitutions in the dictionary :code:`Core.subs`
that are not numerical values are applied.
simplify : bool
If True, every expressions are simplified after substitution.
The default is True
subsofsubs : bool
If True, the substitution dictionary substitutes itself
recursively. Default is True.
"""
substitute_core(self, **kwargs)
# =========================================================================
def subsinverse(self):
"""
subsinverse
***********
Remove every occurence of inverse of symbols in core.subs. they are
replaced by the same symbols with prefix 'inv', which is appended to
the dictionary core.subs.
"""
if VERBOSE >= 1:
print("Remove Inverse of Parameters...")
subsinverse_core(self)
# =========================================================================
# Connectors
def add_connector(self, indices, alpha=None):
"""
add_connector
*************
Add a connector which describes the connection of two ports from a
unique core.
Usage
------
core.add_connector(indices, alpha)
Parameters
----------
indices: tuple of int
The indices of the two ports to be connected.
alpha: scalar quantity
Coefficient of the connection.
Description
-----------
The resulting connection reads:
* :code:`core.u[indices[0]] = alpha * core.y[indices[1]]`,
* :code:`core.u[indices[1]] = -alpha * core.y[indices[0]]`.
Notice this method only stores a description of the connection in the
:code:`core.connectors` argument. The connection will be effective only
after calling the method :code:`core.connect()`.
"""
if alpha is None:
alpha = sympify(1.)
assert indices[0] != indices[1], 'Can not connect a port to itself: \
indices={}.'.format(indices)
u = list()
y = list()
for i in indices:
assert i < self.dims.y(), 'Port index {} is not known. Can not \
add the connector'.format(i)
u.append(self.u[i])
y.append(self.y[i])
connector = {'u': u,
'y': y,
'alpha': alpha}
self.connectors += [connector, ]
sorted_indices = list(copy.deepcopy(indices))
sorted_indices.sort()
sorted_indices.reverse()
for i in sorted_indices:
port2connector(self, i)
def connect(self):
"""
Effectively connect inputs and outputs defined in core.connectors.
See also
--------
See help of method :code:`core.add_connector` for details.
"""
all_alpha = list()
# recover connectors and sort cy and cu
for i, c in enumerate(self.connectors):
all_alpha.append(c['alpha'])
i_primal = getattr(self, 'cy').index(c['y'][0])
self.move_connector(i_primal, 2*i)
i_dual = getattr(self, 'cy').index(c['y'][1])
self.move_connector(i_dual, 2*i+1)
Mswitch_list = [alpha * sympy.Matrix([[0, -1],
[1, 0]])
for alpha in all_alpha]
Mswitch = types.matrix_types[0](sympy.diag(*Mswitch_list))
nxwy = self.dims.x() + self.dims.w() + self.dims.y()
# Gain matrix
G_connectors = self.M[:nxwy, nxwy:]
# Observation matrix
O_connectors = self.M[nxwy:, :nxwy]
N_connectors = types.matrix_types[0](sympy.eye(self.dims.cy()) -
self.Mcycy() * Mswitch)
try:
iN_connectors = inverse(N_connectors, dosimplify=False)
# Interconnection Matrix due to the connectors
M_connectors = G_connectors*Mswitch*iN_connectors*O_connectors
# Store new structure
self.M = types.matrix_types[0](self.M[:nxwy, :nxwy] + M_connectors)
# clean
setattr(self, 'cy', list())
setattr(self, 'cu', list())
setattr(self, 'connectors', list())
except ValueError:
raise Exception('Can not resolve the connection.\n\nABORD')
# =========================================================================
# ADD COMPONENTS
def add_storages(self, x, H):
"""
Add storage components with state :math:`\\mathbf{x}` and energy
:math:`\\mathrm{H}(\\mathbf{x}) \geq 0`.
* State :math:`\\mathbf{x}` is appended to the current list of
states symbols :code:`core.x`,
* Expression :math:`\\mathrm{H}` is added to the current expression
of the Hamiltonian :code:`core.H`.
Parameters
----------
x: one or several pyphs.symbols
State symbols. Can be a single symbol or a list of symbols.
H: sympy.Expr
Must be a valid storage function with respect to the state
:math:`\\mathbf{x}` with :math:`\\nabla^2\\mahtrm H(\\mathbf{x}) \\succeq 0`.
"""
if isinstance(x, types.scalar_types):
x = [x, ]
elif isinstance(x, types.vector_types):
pass
else:
x_types = types.scalar_types+types.vector_types
raise TypeError('Type of x should be one of {}'.format(x_types))
types.scalar_test(H)
self.x += x
self.H += H
def add_dissipations(self, w, z):
"""
Add dissipative components with variable :math:`\\mathbf{w}` and
dissipative function :math:`\\mathrm{z}(\\mathbf{w})`.
* Variable :math:`\\mathbf{w}` is appended to the current list of
variables symbols :code:`core.w`,
* Expression :math:`\\mathrm{z}` is appended to the current list of
dissipative functions :code:`core.z`.
Parameters
----------
w: one or several pyphs.symbols
Variable symbols. Can be a single symbol or a list of symbols.
z: one or several sympy.Expr
Must be a valid dissipative function with respect to the variable
:math:`\\mathbf{w}` with :math:`\\nabla\\mahtrm z(\\mathbf{w}) \succeq 0`.
"""
if isinstance(w, types.vector_types):
types.vector_test(z)
elif isinstance(w, types.scalar_types):
types.scalar_test(z)
w = [w, ]
z = [z, ]
w_types = types.scalar_types+types.vector_types
else:
text = 'Type of w and z should be one of {}'.format(w_types)
raise TypeError(text)
if not len(w) == len(z):
raise TypeError('w and z should have same dimension.')
self.w += w
self.z += z
def add_ports(self, u, y):
"""
Add one or several ports with input :math:`{\\mathbf{u}}` and output
:math:`{\\mathbf{y}}`.
* Input :math:`\\mathbf{y}` is appended to the current list of input
symbols :code:`core.u`,
* ouput {\\mathbf{y}} is appended to the current list of ouputs
:code:`core.y`.
Parameters
----------
u : one or several pyphs.symbols
Inputs symbols. Can be a single symbol or a list of symbols.
y : one or several sympy.Expr
Outputs symbols. Can be a single symbol or a list of symbols.
"""
if isinstance(u, types.vector_types):
types.vector_test(y)
elif isinstance(u, types.scalar_types):
types.scalar_test(y)
u = [u, ]
y = [y, ]
y_types = types.scalar_types+types.vector_types
else:
text = 'Type of u and y should be one of {}'.format(y_types)
raise TypeError(text)
if not len(u) == len(y):
raise TypeError('u and y should have same dimension.')
self.u += u
self.y += y
def add_parameters(self, p):
"""
Add one or several parameters :math:`{\\mathbf{p}}`, which is
appended to the current list of parameters symbols :code:`core.p`.
Also, the parameters symbols are removed from the sustitution
dictionary.
Parameter
----------
p : one or several pyphs.symbols
Parameters symbols. Can be a single symbol or a list of symbols.
"""
if isinstance(p, types.vector_types):
pass
elif isinstance(p, types.scalar_types):
p = [p, ]
self.p += p
for par in p:
if par in self.subs:
self.subs.pop(par)
def add_observer(self, obs):
"""
add_observer
*************
Add a dictionary of observers
Parameter
---------
obs: dict
Observers are couple {symb: expr}. They are evaluated during
simulation at the begining of each time step.
"""
self.observers.update(obs)
# =========================================================================
# Latex
def texwrite(self, path=None, title=None):
"""
Write the port Hamiltonian Structure to a LaTeX file.
Parameters
----------
path : str
Path to the file to write. If file does not exist, it is create,