tensor.py 177 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265
  1. """
  2. This module defines tensors with abstract index notation.
  3. The abstract index notation has been first formalized by Penrose.
  4. Tensor indices are formal objects, with a tensor type; there is no
  5. notion of index range, it is only possible to assign the dimension,
  6. used to trace the Kronecker delta; the dimension can be a Symbol.
  7. The Einstein summation convention is used.
  8. The covariant indices are indicated with a minus sign in front of the index.
  9. For instance the tensor ``t = p(a)*A(b,c)*q(-c)`` has the index ``c``
  10. contracted.
  11. A tensor expression ``t`` can be called; called with its
  12. indices in sorted order it is equal to itself:
  13. in the above example ``t(a, b) == t``;
  14. one can call ``t`` with different indices; ``t(c, d) == p(c)*A(d,a)*q(-a)``.
  15. The contracted indices are dummy indices, internally they have no name,
  16. the indices being represented by a graph-like structure.
  17. Tensors are put in canonical form using ``canon_bp``, which uses
  18. the Butler-Portugal algorithm for canonicalization using the monoterm
  19. symmetries of the tensors.
  20. If there is a (anti)symmetric metric, the indices can be raised and
  21. lowered when the tensor is put in canonical form.
  22. """
  23. from __future__ import annotations
  24. from typing import Any
  25. from functools import reduce
  26. from math import prod
  27. from abc import abstractmethod, ABC
  28. from collections import defaultdict
  29. import operator
  30. import itertools
  31. from sympy.core.numbers import (Integer, Rational)
  32. from sympy.combinatorics import Permutation
  33. from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, \
  34. bsgs_direct_product, canonicalize, riemann_bsgs
  35. from sympy.core import Basic, Expr, sympify, Add, Mul, S
  36. from sympy.core.cache import clear_cache
  37. from sympy.core.containers import Tuple, Dict
  38. from sympy.core.function import WildFunction
  39. from sympy.core.sorting import default_sort_key
  40. from sympy.core.symbol import Symbol, symbols, Wild
  41. from sympy.core.sympify import CantSympify, _sympify
  42. from sympy.core.operations import AssocOp
  43. from sympy.external.gmpy import SYMPY_INTS
  44. from sympy.matrices import eye
  45. from sympy.utilities.exceptions import (sympy_deprecation_warning,
  46. SymPyDeprecationWarning,
  47. ignore_warnings)
  48. from sympy.utilities.decorator import memoize_property, deprecated
  49. from sympy.utilities.iterables import sift
  50. def deprecate_data():
  51. sympy_deprecation_warning(
  52. """
  53. The data attribute of TensorIndexType is deprecated. Use The
  54. replace_with_arrays() method instead.
  55. """,
  56. deprecated_since_version="1.4",
  57. active_deprecations_target="deprecated-tensorindextype-attrs",
  58. stacklevel=4,
  59. )
  60. def deprecate_fun_eval():
  61. sympy_deprecation_warning(
  62. """
  63. The Tensor.fun_eval() method is deprecated. Use
  64. Tensor.substitute_indices() instead.
  65. """,
  66. deprecated_since_version="1.5",
  67. active_deprecations_target="deprecated-tensor-fun-eval",
  68. stacklevel=4,
  69. )
  70. def deprecate_call():
  71. sympy_deprecation_warning(
  72. """
  73. Calling a tensor like Tensor(*indices) is deprecated. Use
  74. Tensor.substitute_indices() instead.
  75. """,
  76. deprecated_since_version="1.5",
  77. active_deprecations_target="deprecated-tensor-fun-eval",
  78. stacklevel=4,
  79. )
  80. class _IndexStructure(CantSympify):
  81. """
  82. This class handles the indices (free and dummy ones). It contains the
  83. algorithms to manage the dummy indices replacements and contractions of
  84. free indices under multiplications of tensor expressions, as well as stuff
  85. related to canonicalization sorting, getting the permutation of the
  86. expression and so on. It also includes tools to get the ``TensorIndex``
  87. objects corresponding to the given index structure.
  88. """
  89. def __init__(self, free, dum, index_types, indices, canon_bp=False):
  90. self.free = free
  91. self.dum = dum
  92. self.index_types = index_types
  93. self.indices = indices
  94. self._ext_rank = len(self.free) + 2*len(self.dum)
  95. self.dum.sort(key=lambda x: x[0])
  96. @staticmethod
  97. def from_indices(*indices):
  98. """
  99. Create a new ``_IndexStructure`` object from a list of ``indices``.
  100. Explanation
  101. ===========
  102. ``indices`` ``TensorIndex`` objects, the indices. Contractions are
  103. detected upon construction.
  104. Examples
  105. ========
  106. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, _IndexStructure
  107. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  108. >>> m0, m1, m2, m3 = tensor_indices('m0,m1,m2,m3', Lorentz)
  109. >>> _IndexStructure.from_indices(m0, m1, -m1, m3)
  110. _IndexStructure([(m0, 0), (m3, 3)], [(1, 2)], [Lorentz, Lorentz, Lorentz, Lorentz])
  111. """
  112. free, dum = _IndexStructure._free_dum_from_indices(*indices)
  113. index_types = [i.tensor_index_type for i in indices]
  114. indices = _IndexStructure._replace_dummy_names(indices, free, dum)
  115. return _IndexStructure(free, dum, index_types, indices)
  116. @staticmethod
  117. def from_components_free_dum(components, free, dum):
  118. index_types = []
  119. for component in components:
  120. index_types.extend(component.index_types)
  121. indices = _IndexStructure.generate_indices_from_free_dum_index_types(free, dum, index_types)
  122. return _IndexStructure(free, dum, index_types, indices)
  123. @staticmethod
  124. def _free_dum_from_indices(*indices):
  125. """
  126. Convert ``indices`` into ``free``, ``dum`` for single component tensor.
  127. Explanation
  128. ===========
  129. ``free`` list of tuples ``(index, pos, 0)``,
  130. where ``pos`` is the position of index in
  131. the list of indices formed by the component tensors
  132. ``dum`` list of tuples ``(pos_contr, pos_cov, 0, 0)``
  133. Examples
  134. ========
  135. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, \
  136. _IndexStructure
  137. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  138. >>> m0, m1, m2, m3 = tensor_indices('m0,m1,m2,m3', Lorentz)
  139. >>> _IndexStructure._free_dum_from_indices(m0, m1, -m1, m3)
  140. ([(m0, 0), (m3, 3)], [(1, 2)])
  141. """
  142. n = len(indices)
  143. if n == 1:
  144. return [(indices[0], 0)], []
  145. # find the positions of the free indices and of the dummy indices
  146. free = [True]*len(indices)
  147. index_dict = {}
  148. dum = []
  149. for i, index in enumerate(indices):
  150. name = index.name
  151. typ = index.tensor_index_type
  152. contr = index.is_up
  153. if (name, typ) in index_dict:
  154. # found a pair of dummy indices
  155. is_contr, pos = index_dict[(name, typ)]
  156. # check consistency and update free
  157. if is_contr:
  158. if contr:
  159. raise ValueError('two equal contravariant indices in slots %d and %d' %(pos, i))
  160. else:
  161. free[pos] = False
  162. free[i] = False
  163. else:
  164. if contr:
  165. free[pos] = False
  166. free[i] = False
  167. else:
  168. raise ValueError('two equal covariant indices in slots %d and %d' %(pos, i))
  169. if contr:
  170. dum.append((i, pos))
  171. else:
  172. dum.append((pos, i))
  173. else:
  174. index_dict[(name, typ)] = index.is_up, i
  175. free = [(index, i) for i, index in enumerate(indices) if free[i]]
  176. free.sort()
  177. return free, dum
  178. def get_indices(self):
  179. """
  180. Get a list of indices, creating new tensor indices to complete dummy indices.
  181. """
  182. return self.indices[:]
  183. @staticmethod
  184. def generate_indices_from_free_dum_index_types(free, dum, index_types):
  185. indices = [None]*(len(free)+2*len(dum))
  186. for idx, pos in free:
  187. indices[pos] = idx
  188. generate_dummy_name = _IndexStructure._get_generator_for_dummy_indices(free)
  189. for pos1, pos2 in dum:
  190. typ1 = index_types[pos1]
  191. indname = generate_dummy_name(typ1)
  192. indices[pos1] = TensorIndex(indname, typ1, True)
  193. indices[pos2] = TensorIndex(indname, typ1, False)
  194. return _IndexStructure._replace_dummy_names(indices, free, dum)
  195. @staticmethod
  196. def _get_generator_for_dummy_indices(free):
  197. cdt = defaultdict(int)
  198. # if the free indices have names with dummy_name, start with an
  199. # index higher than those for the dummy indices
  200. # to avoid name collisions
  201. for indx, ipos in free:
  202. if indx.name.split('_')[0] == indx.tensor_index_type.dummy_name:
  203. cdt[indx.tensor_index_type] = max(cdt[indx.tensor_index_type], int(indx.name.split('_')[1]) + 1)
  204. def dummy_name_gen(tensor_index_type):
  205. nd = str(cdt[tensor_index_type])
  206. cdt[tensor_index_type] += 1
  207. return tensor_index_type.dummy_name + '_' + nd
  208. return dummy_name_gen
  209. @staticmethod
  210. def _replace_dummy_names(indices, free, dum):
  211. dum.sort(key=lambda x: x[0])
  212. new_indices = list(indices)
  213. assert len(indices) == len(free) + 2*len(dum)
  214. generate_dummy_name = _IndexStructure._get_generator_for_dummy_indices(free)
  215. for ipos1, ipos2 in dum:
  216. typ1 = new_indices[ipos1].tensor_index_type
  217. indname = generate_dummy_name(typ1)
  218. new_indices[ipos1] = TensorIndex(indname, typ1, True)
  219. new_indices[ipos2] = TensorIndex(indname, typ1, False)
  220. return new_indices
  221. def get_free_indices(self) -> list[TensorIndex]:
  222. """
  223. Get a list of free indices.
  224. """
  225. # get sorted indices according to their position:
  226. free = sorted(self.free, key=lambda x: x[1])
  227. return [i[0] for i in free]
  228. def __str__(self):
  229. return "_IndexStructure({}, {}, {})".format(self.free, self.dum, self.index_types)
  230. def __repr__(self):
  231. return self.__str__()
  232. def _get_sorted_free_indices_for_canon(self):
  233. sorted_free = self.free[:]
  234. sorted_free.sort(key=lambda x: x[0])
  235. return sorted_free
  236. def _get_sorted_dum_indices_for_canon(self):
  237. return sorted(self.dum, key=lambda x: x[0])
  238. def _get_lexicographically_sorted_index_types(self):
  239. permutation = self.indices_canon_args()[0]
  240. index_types = [None]*self._ext_rank
  241. for i, it in enumerate(self.index_types):
  242. index_types[permutation(i)] = it
  243. return index_types
  244. def _get_lexicographically_sorted_indices(self):
  245. permutation = self.indices_canon_args()[0]
  246. indices = [None]*self._ext_rank
  247. for i, it in enumerate(self.indices):
  248. indices[permutation(i)] = it
  249. return indices
  250. def perm2tensor(self, g, is_canon_bp=False):
  251. """
  252. Returns a ``_IndexStructure`` instance corresponding to the permutation ``g``.
  253. Explanation
  254. ===========
  255. ``g`` permutation corresponding to the tensor in the representation
  256. used in canonicalization
  257. ``is_canon_bp`` if True, then ``g`` is the permutation
  258. corresponding to the canonical form of the tensor
  259. """
  260. sorted_free = [i[0] for i in self._get_sorted_free_indices_for_canon()]
  261. lex_index_types = self._get_lexicographically_sorted_index_types()
  262. lex_indices = self._get_lexicographically_sorted_indices()
  263. nfree = len(sorted_free)
  264. rank = self._ext_rank
  265. dum = [[None]*2 for i in range((rank - nfree)//2)]
  266. free = []
  267. index_types = [None]*rank
  268. indices = [None]*rank
  269. for i in range(rank):
  270. gi = g[i]
  271. index_types[i] = lex_index_types[gi]
  272. indices[i] = lex_indices[gi]
  273. if gi < nfree:
  274. ind = sorted_free[gi]
  275. assert index_types[i] == sorted_free[gi].tensor_index_type
  276. free.append((ind, i))
  277. else:
  278. j = gi - nfree
  279. idum, cov = divmod(j, 2)
  280. if cov:
  281. dum[idum][1] = i
  282. else:
  283. dum[idum][0] = i
  284. dum = [tuple(x) for x in dum]
  285. return _IndexStructure(free, dum, index_types, indices)
  286. def indices_canon_args(self):
  287. """
  288. Returns ``(g, dummies, msym, v)``, the entries of ``canonicalize``
  289. See ``canonicalize`` in ``tensor_can.py`` in combinatorics module.
  290. """
  291. # to be called after sorted_components
  292. from sympy.combinatorics.permutations import _af_new
  293. n = self._ext_rank
  294. g = [None]*n + [n, n+1]
  295. # Converts the symmetry of the metric into msym from .canonicalize()
  296. # method in the combinatorics module
  297. def metric_symmetry_to_msym(metric):
  298. if metric is None:
  299. return None
  300. sym = metric.symmetry
  301. if sym == TensorSymmetry.fully_symmetric(2):
  302. return 0
  303. if sym == TensorSymmetry.fully_symmetric(-2):
  304. return 1
  305. return None
  306. # ordered indices: first the free indices, ordered by types
  307. # then the dummy indices, ordered by types and contravariant before
  308. # covariant
  309. # g[position in tensor] = position in ordered indices
  310. for i, (indx, ipos) in enumerate(self._get_sorted_free_indices_for_canon()):
  311. g[ipos] = i
  312. pos = len(self.free)
  313. j = len(self.free)
  314. dummies = []
  315. prev = None
  316. a = []
  317. msym = []
  318. for ipos1, ipos2 in self._get_sorted_dum_indices_for_canon():
  319. g[ipos1] = j
  320. g[ipos2] = j + 1
  321. j += 2
  322. typ = self.index_types[ipos1]
  323. if typ != prev:
  324. if a:
  325. dummies.append(a)
  326. a = [pos, pos + 1]
  327. prev = typ
  328. msym.append(metric_symmetry_to_msym(typ.metric))
  329. else:
  330. a.extend([pos, pos + 1])
  331. pos += 2
  332. if a:
  333. dummies.append(a)
  334. return _af_new(g), dummies, msym
  335. def components_canon_args(components):
  336. numtyp = []
  337. prev = None
  338. for t in components:
  339. if t == prev:
  340. numtyp[-1][1] += 1
  341. else:
  342. prev = t
  343. numtyp.append([prev, 1])
  344. v = []
  345. for h, n in numtyp:
  346. if h.comm in (0, 1):
  347. comm = h.comm
  348. else:
  349. comm = TensorManager.get_comm(h.comm, h.comm)
  350. v.append((h.symmetry.base, h.symmetry.generators, n, comm))
  351. return v
  352. class _TensorDataLazyEvaluator(CantSympify):
  353. """
  354. EXPERIMENTAL: do not rely on this class, it may change without deprecation
  355. warnings in future versions of SymPy.
  356. Explanation
  357. ===========
  358. This object contains the logic to associate components data to a tensor
  359. expression. Components data are set via the ``.data`` property of tensor
  360. expressions, is stored inside this class as a mapping between the tensor
  361. expression and the ``ndarray``.
  362. Computations are executed lazily: whereas the tensor expressions can have
  363. contractions, tensor products, and additions, components data are not
  364. computed until they are accessed by reading the ``.data`` property
  365. associated to the tensor expression.
  366. """
  367. _substitutions_dict: dict[Any, Any] = {}
  368. _substitutions_dict_tensmul: dict[Any, Any] = {}
  369. def __getitem__(self, key):
  370. dat = self._get(key)
  371. if dat is None:
  372. return None
  373. from .array import NDimArray
  374. if not isinstance(dat, NDimArray):
  375. return dat
  376. if dat.rank() == 0:
  377. return dat[()]
  378. elif dat.rank() == 1 and len(dat) == 1:
  379. return dat[0]
  380. return dat
  381. def _get(self, key):
  382. """
  383. Retrieve ``data`` associated with ``key``.
  384. Explanation
  385. ===========
  386. This algorithm looks into ``self._substitutions_dict`` for all
  387. ``TensorHead`` in the ``TensExpr`` (or just ``TensorHead`` if key is a
  388. TensorHead instance). It reconstructs the components data that the
  389. tensor expression should have by performing on components data the
  390. operations that correspond to the abstract tensor operations applied.
  391. Metric tensor is handled in a different manner: it is pre-computed in
  392. ``self._substitutions_dict_tensmul``.
  393. """
  394. if key in self._substitutions_dict:
  395. return self._substitutions_dict[key]
  396. if isinstance(key, TensorHead):
  397. return None
  398. if isinstance(key, Tensor):
  399. # special case to handle metrics. Metric tensors cannot be
  400. # constructed through contraction by the metric, their
  401. # components show if they are a matrix or its inverse.
  402. signature = tuple([i.is_up for i in key.get_indices()])
  403. srch = (key.component,) + signature
  404. if srch in self._substitutions_dict_tensmul:
  405. return self._substitutions_dict_tensmul[srch]
  406. array_list = [self.data_from_tensor(key)]
  407. return self.data_contract_dum(array_list, key.dum, key.ext_rank)
  408. if isinstance(key, TensMul):
  409. tensmul_args = key.args
  410. if len(tensmul_args) == 1 and len(tensmul_args[0].components) == 1:
  411. # special case to handle metrics. Metric tensors cannot be
  412. # constructed through contraction by the metric, their
  413. # components show if they are a matrix or its inverse.
  414. signature = tuple([i.is_up for i in tensmul_args[0].get_indices()])
  415. srch = (tensmul_args[0].components[0],) + signature
  416. if srch in self._substitutions_dict_tensmul:
  417. return self._substitutions_dict_tensmul[srch]
  418. #data_list = [self.data_from_tensor(i) for i in tensmul_args if isinstance(i, TensExpr)]
  419. data_list = [self.data_from_tensor(i) if isinstance(i, Tensor) else i.data for i in tensmul_args if isinstance(i, TensExpr)]
  420. coeff = prod([i for i in tensmul_args if not isinstance(i, TensExpr)])
  421. if all(i is None for i in data_list):
  422. return None
  423. if any(i is None for i in data_list):
  424. raise ValueError("Mixing tensors with associated components "\
  425. "data with tensors without components data")
  426. data_result = self.data_contract_dum(data_list, key.dum, key.ext_rank)
  427. return coeff*data_result
  428. if isinstance(key, TensAdd):
  429. data_list = []
  430. free_args_list = []
  431. for arg in key.args:
  432. if isinstance(arg, TensExpr):
  433. data_list.append(arg.data)
  434. free_args_list.append([x[0] for x in arg.free])
  435. else:
  436. data_list.append(arg)
  437. free_args_list.append([])
  438. if all(i is None for i in data_list):
  439. return None
  440. if any(i is None for i in data_list):
  441. raise ValueError("Mixing tensors with associated components "\
  442. "data with tensors without components data")
  443. sum_list = []
  444. from .array import permutedims
  445. for data, free_args in zip(data_list, free_args_list):
  446. if len(free_args) < 2:
  447. sum_list.append(data)
  448. else:
  449. free_args_pos = {y: x for x, y in enumerate(free_args)}
  450. axes = [free_args_pos[arg] for arg in key.free_args]
  451. sum_list.append(permutedims(data, axes))
  452. return reduce(lambda x, y: x+y, sum_list)
  453. return None
  454. @staticmethod
  455. def data_contract_dum(ndarray_list, dum, ext_rank):
  456. from .array import tensorproduct, tensorcontraction, MutableDenseNDimArray
  457. arrays = list(map(MutableDenseNDimArray, ndarray_list))
  458. prodarr = tensorproduct(*arrays)
  459. return tensorcontraction(prodarr, *dum)
  460. def data_tensorhead_from_tensmul(self, data, tensmul, tensorhead):
  461. """
  462. This method is used when assigning components data to a ``TensMul``
  463. object, it converts components data to a fully contravariant ndarray,
  464. which is then stored according to the ``TensorHead`` key.
  465. """
  466. if data is None:
  467. return None
  468. return self._correct_signature_from_indices(
  469. data,
  470. tensmul.get_indices(),
  471. tensmul.free,
  472. tensmul.dum,
  473. True)
  474. def data_from_tensor(self, tensor):
  475. """
  476. This method corrects the components data to the right signature
  477. (covariant/contravariant) using the metric associated with each
  478. ``TensorIndexType``.
  479. """
  480. tensorhead = tensor.component
  481. if tensorhead.data is None:
  482. return None
  483. return self._correct_signature_from_indices(
  484. tensorhead.data,
  485. tensor.get_indices(),
  486. tensor.free,
  487. tensor.dum)
  488. def _assign_data_to_tensor_expr(self, key, data):
  489. if isinstance(key, TensAdd):
  490. raise ValueError('cannot assign data to TensAdd')
  491. # here it is assumed that `key` is a `TensMul` instance.
  492. if len(key.components) != 1:
  493. raise ValueError('cannot assign data to TensMul with multiple components')
  494. tensorhead = key.components[0]
  495. newdata = self.data_tensorhead_from_tensmul(data, key, tensorhead)
  496. return tensorhead, newdata
  497. def _check_permutations_on_data(self, tens, data):
  498. from .array import permutedims
  499. from .array.arrayop import Flatten
  500. if isinstance(tens, TensorHead):
  501. rank = tens.rank
  502. generators = tens.symmetry.generators
  503. elif isinstance(tens, Tensor):
  504. rank = tens.rank
  505. generators = tens.components[0].symmetry.generators
  506. elif isinstance(tens, TensorIndexType):
  507. rank = tens.metric.rank
  508. generators = tens.metric.symmetry.generators
  509. # Every generator is a permutation, check that by permuting the array
  510. # by that permutation, the array will be the same, except for a
  511. # possible sign change if the permutation admits it.
  512. for gener in generators:
  513. sign_change = +1 if (gener(rank) == rank) else -1
  514. data_swapped = data
  515. last_data = data
  516. permute_axes = list(map(gener, range(rank)))
  517. # the order of a permutation is the number of times to get the
  518. # identity by applying that permutation.
  519. for i in range(gener.order()-1):
  520. data_swapped = permutedims(data_swapped, permute_axes)
  521. # if any value in the difference array is non-zero, raise an error:
  522. if any(Flatten(last_data - sign_change*data_swapped)):
  523. raise ValueError("Component data symmetry structure error")
  524. last_data = data_swapped
  525. def __setitem__(self, key, value):
  526. """
  527. Set the components data of a tensor object/expression.
  528. Explanation
  529. ===========
  530. Components data are transformed to the all-contravariant form and stored
  531. with the corresponding ``TensorHead`` object. If a ``TensorHead`` object
  532. cannot be uniquely identified, it will raise an error.
  533. """
  534. data = _TensorDataLazyEvaluator.parse_data(value)
  535. self._check_permutations_on_data(key, data)
  536. # TensorHead and TensorIndexType can be assigned data directly, while
  537. # TensMul must first convert data to a fully contravariant form, and
  538. # assign it to its corresponding TensorHead single component.
  539. if not isinstance(key, (TensorHead, TensorIndexType)):
  540. key, data = self._assign_data_to_tensor_expr(key, data)
  541. if isinstance(key, TensorHead):
  542. for dim, indextype in zip(data.shape, key.index_types):
  543. if indextype.data is None:
  544. raise ValueError("index type {} has no components data"\
  545. " associated (needed to raise/lower index)".format(indextype))
  546. if not indextype.dim.is_number:
  547. continue
  548. if dim != indextype.dim:
  549. raise ValueError("wrong dimension of ndarray")
  550. self._substitutions_dict[key] = data
  551. def __delitem__(self, key):
  552. del self._substitutions_dict[key]
  553. def __contains__(self, key):
  554. return key in self._substitutions_dict
  555. def add_metric_data(self, metric, data):
  556. """
  557. Assign data to the ``metric`` tensor. The metric tensor behaves in an
  558. anomalous way when raising and lowering indices.
  559. Explanation
  560. ===========
  561. A fully covariant metric is the inverse transpose of the fully
  562. contravariant metric (it is meant matrix inverse). If the metric is
  563. symmetric, the transpose is not necessary and mixed
  564. covariant/contravariant metrics are Kronecker deltas.
  565. """
  566. # hard assignment, data should not be added to `TensorHead` for metric:
  567. # the problem with `TensorHead` is that the metric is anomalous, i.e.
  568. # raising and lowering the index means considering the metric or its
  569. # inverse, this is not the case for other tensors.
  570. self._substitutions_dict_tensmul[metric, True, True] = data
  571. inverse_transpose = self.inverse_transpose_matrix(data)
  572. # in symmetric spaces, the transpose is the same as the original matrix,
  573. # the full covariant metric tensor is the inverse transpose, so this
  574. # code will be able to handle non-symmetric metrics.
  575. self._substitutions_dict_tensmul[metric, False, False] = inverse_transpose
  576. # now mixed cases, these are identical to the unit matrix if the metric
  577. # is symmetric.
  578. m = data.tomatrix()
  579. invt = inverse_transpose.tomatrix()
  580. self._substitutions_dict_tensmul[metric, True, False] = m * invt
  581. self._substitutions_dict_tensmul[metric, False, True] = invt * m
  582. @staticmethod
  583. def _flip_index_by_metric(data, metric, pos):
  584. from .array import tensorproduct, tensorcontraction
  585. mdim = metric.rank()
  586. ddim = data.rank()
  587. if pos == 0:
  588. data = tensorcontraction(
  589. tensorproduct(
  590. metric,
  591. data
  592. ),
  593. (1, mdim+pos)
  594. )
  595. else:
  596. data = tensorcontraction(
  597. tensorproduct(
  598. data,
  599. metric
  600. ),
  601. (pos, ddim)
  602. )
  603. return data
  604. @staticmethod
  605. def inverse_matrix(ndarray):
  606. m = ndarray.tomatrix().inv()
  607. return _TensorDataLazyEvaluator.parse_data(m)
  608. @staticmethod
  609. def inverse_transpose_matrix(ndarray):
  610. m = ndarray.tomatrix().inv().T
  611. return _TensorDataLazyEvaluator.parse_data(m)
  612. @staticmethod
  613. def _correct_signature_from_indices(data, indices, free, dum, inverse=False):
  614. """
  615. Utility function to correct the values inside the components data
  616. ndarray according to whether indices are covariant or contravariant.
  617. It uses the metric matrix to lower values of covariant indices.
  618. """
  619. # change the ndarray values according covariantness/contravariantness of the indices
  620. # use the metric
  621. for i, indx in enumerate(indices):
  622. if not indx.is_up and not inverse:
  623. data = _TensorDataLazyEvaluator._flip_index_by_metric(data, indx.tensor_index_type.data, i)
  624. elif not indx.is_up and inverse:
  625. data = _TensorDataLazyEvaluator._flip_index_by_metric(
  626. data,
  627. _TensorDataLazyEvaluator.inverse_matrix(indx.tensor_index_type.data),
  628. i
  629. )
  630. return data
  631. @staticmethod
  632. def _sort_data_axes(old, new):
  633. from .array import permutedims
  634. new_data = old.data.copy()
  635. old_free = [i[0] for i in old.free]
  636. new_free = [i[0] for i in new.free]
  637. for i in range(len(new_free)):
  638. for j in range(i, len(old_free)):
  639. if old_free[j] == new_free[i]:
  640. old_free[i], old_free[j] = old_free[j], old_free[i]
  641. new_data = permutedims(new_data, (i, j))
  642. break
  643. return new_data
  644. @staticmethod
  645. def add_rearrange_tensmul_parts(new_tensmul, old_tensmul):
  646. def sorted_compo():
  647. return _TensorDataLazyEvaluator._sort_data_axes(old_tensmul, new_tensmul)
  648. _TensorDataLazyEvaluator._substitutions_dict[new_tensmul] = sorted_compo()
  649. @staticmethod
  650. def parse_data(data):
  651. """
  652. Transform ``data`` to array. The parameter ``data`` may
  653. contain data in various formats, e.g. nested lists, SymPy ``Matrix``,
  654. and so on.
  655. Examples
  656. ========
  657. >>> from sympy.tensor.tensor import _TensorDataLazyEvaluator
  658. >>> _TensorDataLazyEvaluator.parse_data([1, 3, -6, 12])
  659. [1, 3, -6, 12]
  660. >>> _TensorDataLazyEvaluator.parse_data([[1, 2], [4, 7]])
  661. [[1, 2], [4, 7]]
  662. """
  663. from .array import MutableDenseNDimArray
  664. if not isinstance(data, MutableDenseNDimArray):
  665. if len(data) == 2 and hasattr(data[0], '__call__'):
  666. data = MutableDenseNDimArray(data[0], data[1])
  667. else:
  668. data = MutableDenseNDimArray(data)
  669. return data
  670. _tensor_data_substitution_dict = _TensorDataLazyEvaluator()
  671. class _TensorManager:
  672. """
  673. Class to manage tensor properties.
  674. Notes
  675. =====
  676. Tensors belong to tensor commutation groups; each group has a label
  677. ``comm``; there are predefined labels:
  678. ``0`` tensors commuting with any other tensor
  679. ``1`` tensors anticommuting among themselves
  680. ``2`` tensors not commuting, apart with those with ``comm=0``
  681. Other groups can be defined using ``set_comm``; tensors in those
  682. groups commute with those with ``comm=0``; by default they
  683. do not commute with any other group.
  684. """
  685. def __init__(self):
  686. self._comm_init()
  687. def _comm_init(self):
  688. self._comm = [{} for i in range(3)]
  689. for i in range(3):
  690. self._comm[0][i] = 0
  691. self._comm[i][0] = 0
  692. self._comm[1][1] = 1
  693. self._comm[2][1] = None
  694. self._comm[1][2] = None
  695. self._comm_symbols2i = {0:0, 1:1, 2:2}
  696. self._comm_i2symbol = {0:0, 1:1, 2:2}
  697. @property
  698. def comm(self):
  699. return self._comm
  700. def comm_symbols2i(self, i):
  701. """
  702. Get the commutation group number corresponding to ``i``.
  703. ``i`` can be a symbol or a number or a string.
  704. If ``i`` is not already defined its commutation group number
  705. is set.
  706. """
  707. if i not in self._comm_symbols2i:
  708. n = len(self._comm)
  709. self._comm.append({})
  710. self._comm[n][0] = 0
  711. self._comm[0][n] = 0
  712. self._comm_symbols2i[i] = n
  713. self._comm_i2symbol[n] = i
  714. return n
  715. return self._comm_symbols2i[i]
  716. def comm_i2symbol(self, i):
  717. """
  718. Returns the symbol corresponding to the commutation group number.
  719. """
  720. return self._comm_i2symbol[i]
  721. def set_comm(self, i, j, c):
  722. """
  723. Set the commutation parameter ``c`` for commutation groups ``i, j``.
  724. Parameters
  725. ==========
  726. i, j : symbols representing commutation groups
  727. c : group commutation number
  728. Notes
  729. =====
  730. ``i, j`` can be symbols, strings or numbers,
  731. apart from ``0, 1`` and ``2`` which are reserved respectively
  732. for commuting, anticommuting tensors and tensors not commuting
  733. with any other group apart with the commuting tensors.
  734. For the remaining cases, use this method to set the commutation rules;
  735. by default ``c=None``.
  736. The group commutation number ``c`` is assigned in correspondence
  737. to the group commutation symbols; it can be
  738. 0 commuting
  739. 1 anticommuting
  740. None no commutation property
  741. Examples
  742. ========
  743. ``G`` and ``GH`` do not commute with themselves and commute with
  744. each other; A is commuting.
  745. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, TensorManager, TensorSymmetry
  746. >>> Lorentz = TensorIndexType('Lorentz')
  747. >>> i0,i1,i2,i3,i4 = tensor_indices('i0:5', Lorentz)
  748. >>> A = TensorHead('A', [Lorentz])
  749. >>> G = TensorHead('G', [Lorentz], TensorSymmetry.no_symmetry(1), 'Gcomm')
  750. >>> GH = TensorHead('GH', [Lorentz], TensorSymmetry.no_symmetry(1), 'GHcomm')
  751. >>> TensorManager.set_comm('Gcomm', 'GHcomm', 0)
  752. >>> (GH(i1)*G(i0)).canon_bp()
  753. G(i0)*GH(i1)
  754. >>> (G(i1)*G(i0)).canon_bp()
  755. G(i1)*G(i0)
  756. >>> (G(i1)*A(i0)).canon_bp()
  757. A(i0)*G(i1)
  758. """
  759. if c not in (0, 1, None):
  760. raise ValueError('`c` can assume only the values 0, 1 or None')
  761. i = sympify(i)
  762. j = sympify(j)
  763. if i not in self._comm_symbols2i:
  764. n = len(self._comm)
  765. self._comm.append({})
  766. self._comm[n][0] = 0
  767. self._comm[0][n] = 0
  768. self._comm_symbols2i[i] = n
  769. self._comm_i2symbol[n] = i
  770. if j not in self._comm_symbols2i:
  771. n = len(self._comm)
  772. self._comm.append({})
  773. self._comm[0][n] = 0
  774. self._comm[n][0] = 0
  775. self._comm_symbols2i[j] = n
  776. self._comm_i2symbol[n] = j
  777. ni = self._comm_symbols2i[i]
  778. nj = self._comm_symbols2i[j]
  779. self._comm[ni][nj] = c
  780. self._comm[nj][ni] = c
  781. """
  782. Cached sympy functions (e.g. expand) may have cached the results of
  783. expressions involving tensors, but those results may not be valid after
  784. changing the commutation properties. To stay on the safe side, we clear
  785. the cache of all functions.
  786. """
  787. clear_cache()
  788. def set_comms(self, *args):
  789. """
  790. Set the commutation group numbers ``c`` for symbols ``i, j``.
  791. Parameters
  792. ==========
  793. args : sequence of ``(i, j, c)``
  794. """
  795. for i, j, c in args:
  796. self.set_comm(i, j, c)
  797. def get_comm(self, i, j):
  798. """
  799. Return the commutation parameter for commutation group numbers ``i, j``
  800. see ``_TensorManager.set_comm``
  801. """
  802. return self._comm[i].get(j, 0 if i == 0 or j == 0 else None)
  803. def clear(self):
  804. """
  805. Clear the TensorManager.
  806. """
  807. self._comm_init()
  808. TensorManager = _TensorManager()
  809. class TensorIndexType(Basic):
  810. """
  811. A TensorIndexType is characterized by its name and its metric.
  812. Parameters
  813. ==========
  814. name : name of the tensor type
  815. dummy_name : name of the head of dummy indices
  816. dim : dimension, it can be a symbol or an integer or ``None``
  817. eps_dim : dimension of the epsilon tensor
  818. metric_symmetry : integer that denotes metric symmetry or ``None`` for no metric
  819. metric_name : string with the name of the metric tensor
  820. Attributes
  821. ==========
  822. ``metric`` : the metric tensor
  823. ``delta`` : ``Kronecker delta``
  824. ``epsilon`` : the ``Levi-Civita epsilon`` tensor
  825. ``data`` : (deprecated) a property to add ``ndarray`` values, to work in a specified basis.
  826. Notes
  827. =====
  828. The possible values of the ``metric_symmetry`` parameter are:
  829. ``1`` : metric tensor is fully symmetric
  830. ``0`` : metric tensor possesses no index symmetry
  831. ``-1`` : metric tensor is fully antisymmetric
  832. ``None``: there is no metric tensor (metric equals to ``None``)
  833. The metric is assumed to be symmetric by default. It can also be set
  834. to a custom tensor by the ``.set_metric()`` method.
  835. If there is a metric the metric is used to raise and lower indices.
  836. In the case of non-symmetric metric, the following raising and
  837. lowering conventions will be adopted:
  838. ``psi(a) = g(a, b)*psi(-b); chi(-a) = chi(b)*g(-b, -a)``
  839. From these it is easy to find:
  840. ``g(-a, b) = delta(-a, b)``
  841. where ``delta(-a, b) = delta(b, -a)`` is the ``Kronecker delta``
  842. (see ``TensorIndex`` for the conventions on indices).
  843. For antisymmetric metrics there is also the following equality:
  844. ``g(a, -b) = -delta(a, -b)``
  845. If there is no metric it is not possible to raise or lower indices;
  846. e.g. the index of the defining representation of ``SU(N)``
  847. is 'covariant' and the conjugate representation is
  848. 'contravariant'; for ``N > 2`` they are linearly independent.
  849. ``eps_dim`` is by default equal to ``dim``, if the latter is an integer;
  850. else it can be assigned (for use in naive dimensional regularization);
  851. if ``eps_dim`` is not an integer ``epsilon`` is ``None``.
  852. Examples
  853. ========
  854. >>> from sympy.tensor.tensor import TensorIndexType
  855. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  856. >>> Lorentz.metric
  857. metric(Lorentz,Lorentz)
  858. """
  859. def __new__(cls, name, dummy_name=None, dim=None, eps_dim=None,
  860. metric_symmetry=1, metric_name='metric', **kwargs):
  861. if 'dummy_fmt' in kwargs:
  862. dummy_fmt = kwargs['dummy_fmt']
  863. sympy_deprecation_warning(
  864. f"""
  865. The dummy_fmt keyword to TensorIndexType is deprecated. Use
  866. dummy_name={dummy_fmt} instead.
  867. """,
  868. deprecated_since_version="1.5",
  869. active_deprecations_target="deprecated-tensorindextype-dummy-fmt",
  870. )
  871. dummy_name = dummy_fmt
  872. if isinstance(name, str):
  873. name = Symbol(name)
  874. if dummy_name is None:
  875. dummy_name = str(name)[0]
  876. if isinstance(dummy_name, str):
  877. dummy_name = Symbol(dummy_name)
  878. if dim is None:
  879. dim = Symbol("dim_" + dummy_name.name)
  880. else:
  881. dim = sympify(dim)
  882. if eps_dim is None:
  883. eps_dim = dim
  884. else:
  885. eps_dim = sympify(eps_dim)
  886. metric_symmetry = sympify(metric_symmetry)
  887. if isinstance(metric_name, str):
  888. metric_name = Symbol(metric_name)
  889. if 'metric' in kwargs:
  890. SymPyDeprecationWarning(
  891. """
  892. The 'metric' keyword argument to TensorIndexType is
  893. deprecated. Use the 'metric_symmetry' keyword argument or the
  894. TensorIndexType.set_metric() method instead.
  895. """,
  896. deprecated_since_version="1.5",
  897. active_deprecations_target="deprecated-tensorindextype-metric",
  898. )
  899. metric = kwargs.get('metric')
  900. if metric is not None:
  901. if metric in (True, False, 0, 1):
  902. metric_name = 'metric'
  903. #metric_antisym = metric
  904. else:
  905. metric_name = metric.name
  906. #metric_antisym = metric.antisym
  907. if metric:
  908. metric_symmetry = -1
  909. else:
  910. metric_symmetry = 1
  911. obj = Basic.__new__(cls, name, dummy_name, dim, eps_dim,
  912. metric_symmetry, metric_name)
  913. obj._autogenerated = []
  914. return obj
  915. @property
  916. def name(self):
  917. return self.args[0].name
  918. @property
  919. def dummy_name(self):
  920. return self.args[1].name
  921. @property
  922. def dim(self):
  923. return self.args[2]
  924. @property
  925. def eps_dim(self):
  926. return self.args[3]
  927. @memoize_property
  928. def metric(self):
  929. metric_symmetry = self.args[4]
  930. metric_name = self.args[5]
  931. if metric_symmetry is None:
  932. return None
  933. if metric_symmetry == 0:
  934. symmetry = TensorSymmetry.no_symmetry(2)
  935. elif metric_symmetry == 1:
  936. symmetry = TensorSymmetry.fully_symmetric(2)
  937. elif metric_symmetry == -1:
  938. symmetry = TensorSymmetry.fully_symmetric(-2)
  939. return TensorHead(metric_name, [self]*2, symmetry)
  940. @memoize_property
  941. def delta(self):
  942. return TensorHead('KD', [self]*2, TensorSymmetry.fully_symmetric(2))
  943. @memoize_property
  944. def epsilon(self):
  945. if not isinstance(self.eps_dim, (SYMPY_INTS, Integer)):
  946. return None
  947. symmetry = TensorSymmetry.fully_symmetric(-self.eps_dim)
  948. return TensorHead('Eps', [self]*self.eps_dim, symmetry)
  949. def set_metric(self, tensor):
  950. self._metric = tensor
  951. def __lt__(self, other):
  952. return self.name < other.name
  953. def __str__(self):
  954. return self.name
  955. __repr__ = __str__
  956. # Everything below this line is deprecated
  957. @property
  958. def data(self):
  959. deprecate_data()
  960. with ignore_warnings(SymPyDeprecationWarning):
  961. return _tensor_data_substitution_dict[self]
  962. @data.setter
  963. def data(self, data):
  964. deprecate_data()
  965. # This assignment is a bit controversial, should metric components be assigned
  966. # to the metric only or also to the TensorIndexType object? The advantage here
  967. # is the ability to assign a 1D array and transform it to a 2D diagonal array.
  968. from .array import MutableDenseNDimArray
  969. data = _TensorDataLazyEvaluator.parse_data(data)
  970. if data.rank() > 2:
  971. raise ValueError("data have to be of rank 1 (diagonal metric) or 2.")
  972. if data.rank() == 1:
  973. if self.dim.is_number:
  974. nda_dim = data.shape[0]
  975. if nda_dim != self.dim:
  976. raise ValueError("Dimension mismatch")
  977. dim = data.shape[0]
  978. newndarray = MutableDenseNDimArray.zeros(dim, dim)
  979. for i, val in enumerate(data):
  980. newndarray[i, i] = val
  981. data = newndarray
  982. dim1, dim2 = data.shape
  983. if dim1 != dim2:
  984. raise ValueError("Non-square matrix tensor.")
  985. if self.dim.is_number:
  986. if self.dim != dim1:
  987. raise ValueError("Dimension mismatch")
  988. _tensor_data_substitution_dict[self] = data
  989. _tensor_data_substitution_dict.add_metric_data(self.metric, data)
  990. with ignore_warnings(SymPyDeprecationWarning):
  991. delta = self.get_kronecker_delta()
  992. i1 = TensorIndex('i1', self)
  993. i2 = TensorIndex('i2', self)
  994. with ignore_warnings(SymPyDeprecationWarning):
  995. delta(i1, -i2).data = _TensorDataLazyEvaluator.parse_data(eye(dim1))
  996. @data.deleter
  997. def data(self):
  998. deprecate_data()
  999. with ignore_warnings(SymPyDeprecationWarning):
  1000. if self in _tensor_data_substitution_dict:
  1001. del _tensor_data_substitution_dict[self]
  1002. if self.metric in _tensor_data_substitution_dict:
  1003. del _tensor_data_substitution_dict[self.metric]
  1004. @deprecated(
  1005. """
  1006. The TensorIndexType.get_kronecker_delta() method is deprecated. Use
  1007. the TensorIndexType.delta attribute instead.
  1008. """,
  1009. deprecated_since_version="1.5",
  1010. active_deprecations_target="deprecated-tensorindextype-methods",
  1011. )
  1012. def get_kronecker_delta(self):
  1013. sym2 = TensorSymmetry(get_symmetric_group_sgs(2))
  1014. delta = TensorHead('KD', [self]*2, sym2)
  1015. return delta
  1016. @deprecated(
  1017. """
  1018. The TensorIndexType.get_epsilon() method is deprecated. Use
  1019. the TensorIndexType.epsilon attribute instead.
  1020. """,
  1021. deprecated_since_version="1.5",
  1022. active_deprecations_target="deprecated-tensorindextype-methods",
  1023. )
  1024. def get_epsilon(self):
  1025. if not isinstance(self._eps_dim, (SYMPY_INTS, Integer)):
  1026. return None
  1027. sym = TensorSymmetry(get_symmetric_group_sgs(self._eps_dim, 1))
  1028. epsilon = TensorHead('Eps', [self]*self._eps_dim, sym)
  1029. return epsilon
  1030. def _components_data_full_destroy(self):
  1031. """
  1032. EXPERIMENTAL: do not rely on this API method.
  1033. This destroys components data associated to the ``TensorIndexType``, if
  1034. any, specifically:
  1035. * metric tensor data
  1036. * Kronecker tensor data
  1037. """
  1038. if self in _tensor_data_substitution_dict:
  1039. del _tensor_data_substitution_dict[self]
  1040. def delete_tensmul_data(key):
  1041. if key in _tensor_data_substitution_dict._substitutions_dict_tensmul:
  1042. del _tensor_data_substitution_dict._substitutions_dict_tensmul[key]
  1043. # delete metric data:
  1044. delete_tensmul_data((self.metric, True, True))
  1045. delete_tensmul_data((self.metric, True, False))
  1046. delete_tensmul_data((self.metric, False, True))
  1047. delete_tensmul_data((self.metric, False, False))
  1048. # delete delta tensor data:
  1049. delta = self.get_kronecker_delta()
  1050. if delta in _tensor_data_substitution_dict:
  1051. del _tensor_data_substitution_dict[delta]
  1052. class TensorIndex(Basic):
  1053. """
  1054. Represents a tensor index
  1055. Parameters
  1056. ==========
  1057. name : name of the index, or ``True`` if you want it to be automatically assigned
  1058. tensor_index_type : ``TensorIndexType`` of the index
  1059. is_up : flag for contravariant index (is_up=True by default)
  1060. Attributes
  1061. ==========
  1062. ``name``
  1063. ``tensor_index_type``
  1064. ``is_up``
  1065. Notes
  1066. =====
  1067. Tensor indices are contracted with the Einstein summation convention.
  1068. An index can be in contravariant or in covariant form; in the latter
  1069. case it is represented prepending a ``-`` to the index name. Adding
  1070. ``-`` to a covariant (is_up=False) index makes it contravariant.
  1071. Dummy indices have a name with head given by
  1072. ``tensor_inde_type.dummy_name`` with underscore and a number.
  1073. Similar to ``symbols`` multiple contravariant indices can be created
  1074. at once using ``tensor_indices(s, typ)``, where ``s`` is a string
  1075. of names.
  1076. Examples
  1077. ========
  1078. >>> from sympy.tensor.tensor import TensorIndexType, TensorIndex, TensorHead, tensor_indices
  1079. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  1080. >>> mu = TensorIndex('mu', Lorentz, is_up=False)
  1081. >>> nu, rho = tensor_indices('nu, rho', Lorentz)
  1082. >>> A = TensorHead('A', [Lorentz, Lorentz])
  1083. >>> A(mu, nu)
  1084. A(-mu, nu)
  1085. >>> A(-mu, -rho)
  1086. A(mu, -rho)
  1087. >>> A(mu, -mu)
  1088. A(-L_0, L_0)
  1089. """
  1090. def __new__(cls, name, tensor_index_type, is_up=True):
  1091. if isinstance(name, str):
  1092. name_symbol = Symbol(name)
  1093. elif isinstance(name, Symbol):
  1094. name_symbol = name
  1095. elif name is True:
  1096. name = "_i{}".format(len(tensor_index_type._autogenerated))
  1097. name_symbol = Symbol(name)
  1098. tensor_index_type._autogenerated.append(name_symbol)
  1099. else:
  1100. raise ValueError("invalid name")
  1101. is_up = sympify(is_up)
  1102. return Basic.__new__(cls, name_symbol, tensor_index_type, is_up)
  1103. @property
  1104. def name(self):
  1105. return self.args[0].name
  1106. @property
  1107. def tensor_index_type(self):
  1108. return self.args[1]
  1109. @property
  1110. def is_up(self):
  1111. return self.args[2]
  1112. def _print(self):
  1113. s = self.name
  1114. if not self.is_up:
  1115. s = '-%s' % s
  1116. return s
  1117. def __lt__(self, other):
  1118. return ((self.tensor_index_type, self.name) <
  1119. (other.tensor_index_type, other.name))
  1120. def __neg__(self):
  1121. t1 = TensorIndex(self.name, self.tensor_index_type,
  1122. (not self.is_up))
  1123. return t1
  1124. def tensor_indices(s, typ):
  1125. """
  1126. Returns list of tensor indices given their names and their types.
  1127. Parameters
  1128. ==========
  1129. s : string of comma separated names of indices
  1130. typ : ``TensorIndexType`` of the indices
  1131. Examples
  1132. ========
  1133. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices
  1134. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  1135. >>> a, b, c, d = tensor_indices('a,b,c,d', Lorentz)
  1136. """
  1137. if isinstance(s, str):
  1138. a = [x.name for x in symbols(s, seq=True)]
  1139. else:
  1140. raise ValueError('expecting a string')
  1141. tilist = [TensorIndex(i, typ) for i in a]
  1142. if len(tilist) == 1:
  1143. return tilist[0]
  1144. return tilist
  1145. class TensorSymmetry(Basic):
  1146. """
  1147. Monoterm symmetry of a tensor (i.e. any symmetric or anti-symmetric
  1148. index permutation). For the relevant terminology see ``tensor_can.py``
  1149. section of the combinatorics module.
  1150. Parameters
  1151. ==========
  1152. bsgs : tuple ``(base, sgs)`` BSGS of the symmetry of the tensor
  1153. Attributes
  1154. ==========
  1155. ``base`` : base of the BSGS
  1156. ``generators`` : generators of the BSGS
  1157. ``rank`` : rank of the tensor
  1158. Notes
  1159. =====
  1160. A tensor can have an arbitrary monoterm symmetry provided by its BSGS.
  1161. Multiterm symmetries, like the cyclic symmetry of the Riemann tensor
  1162. (i.e., Bianchi identity), are not covered. See combinatorics module for
  1163. information on how to generate BSGS for a general index permutation group.
  1164. Simple symmetries can be generated using built-in methods.
  1165. See Also
  1166. ========
  1167. sympy.combinatorics.tensor_can.get_symmetric_group_sgs
  1168. Examples
  1169. ========
  1170. Define a symmetric tensor of rank 2
  1171. >>> from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, TensorHead
  1172. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  1173. >>> sym = TensorSymmetry(get_symmetric_group_sgs(2))
  1174. >>> T = TensorHead('T', [Lorentz]*2, sym)
  1175. Note, that the same can also be done using built-in TensorSymmetry methods
  1176. >>> sym2 = TensorSymmetry.fully_symmetric(2)
  1177. >>> sym == sym2
  1178. True
  1179. """
  1180. def __new__(cls, *args, **kw_args):
  1181. if len(args) == 1:
  1182. base, generators = args[0]
  1183. elif len(args) == 2:
  1184. base, generators = args
  1185. else:
  1186. raise TypeError("bsgs required, either two separate parameters or one tuple")
  1187. if not isinstance(base, Tuple):
  1188. base = Tuple(*base)
  1189. if not isinstance(generators, Tuple):
  1190. generators = Tuple(*generators)
  1191. return Basic.__new__(cls, base, generators, **kw_args)
  1192. @property
  1193. def base(self):
  1194. return self.args[0]
  1195. @property
  1196. def generators(self):
  1197. return self.args[1]
  1198. @property
  1199. def rank(self):
  1200. return self.generators[0].size - 2
  1201. @classmethod
  1202. def fully_symmetric(cls, rank):
  1203. """
  1204. Returns a fully symmetric (antisymmetric if ``rank``<0)
  1205. TensorSymmetry object for ``abs(rank)`` indices.
  1206. """
  1207. if rank > 0:
  1208. bsgs = get_symmetric_group_sgs(rank, False)
  1209. elif rank < 0:
  1210. bsgs = get_symmetric_group_sgs(-rank, True)
  1211. elif rank == 0:
  1212. bsgs = ([], [Permutation(1)])
  1213. return TensorSymmetry(bsgs)
  1214. @classmethod
  1215. def direct_product(cls, *args):
  1216. """
  1217. Returns a TensorSymmetry object that is being a direct product of
  1218. fully (anti-)symmetric index permutation groups.
  1219. Notes
  1220. =====
  1221. Some examples for different values of ``(*args)``:
  1222. ``(1)`` vector, equivalent to ``TensorSymmetry.fully_symmetric(1)``
  1223. ``(2)`` tensor with 2 symmetric indices, equivalent to ``.fully_symmetric(2)``
  1224. ``(-2)`` tensor with 2 antisymmetric indices, equivalent to ``.fully_symmetric(-2)``
  1225. ``(2, -2)`` tensor with the first 2 indices commuting and the last 2 anticommuting
  1226. ``(1, 1, 1)`` tensor with 3 indices without any symmetry
  1227. """
  1228. base, sgs = [], [Permutation(1)]
  1229. for arg in args:
  1230. if arg > 0:
  1231. bsgs2 = get_symmetric_group_sgs(arg, False)
  1232. elif arg < 0:
  1233. bsgs2 = get_symmetric_group_sgs(-arg, True)
  1234. else:
  1235. continue
  1236. base, sgs = bsgs_direct_product(base, sgs, *bsgs2)
  1237. return TensorSymmetry(base, sgs)
  1238. @classmethod
  1239. def riemann(cls):
  1240. """
  1241. Returns a monotorem symmetry of the Riemann tensor
  1242. """
  1243. return TensorSymmetry(riemann_bsgs)
  1244. @classmethod
  1245. def no_symmetry(cls, rank):
  1246. """
  1247. TensorSymmetry object for ``rank`` indices with no symmetry
  1248. """
  1249. return TensorSymmetry([], [Permutation(rank+1)])
  1250. @deprecated(
  1251. """
  1252. The tensorsymmetry() function is deprecated. Use the TensorSymmetry
  1253. constructor instead.
  1254. """,
  1255. deprecated_since_version="1.5",
  1256. active_deprecations_target="deprecated-tensorsymmetry",
  1257. )
  1258. def tensorsymmetry(*args):
  1259. """
  1260. Returns a ``TensorSymmetry`` object. This method is deprecated, use
  1261. ``TensorSymmetry.direct_product()`` or ``.riemann()`` instead.
  1262. Explanation
  1263. ===========
  1264. One can represent a tensor with any monoterm slot symmetry group
  1265. using a BSGS.
  1266. ``args`` can be a BSGS
  1267. ``args[0]`` base
  1268. ``args[1]`` sgs
  1269. Usually tensors are in (direct products of) representations
  1270. of the symmetric group;
  1271. ``args`` can be a list of lists representing the shapes of Young tableaux
  1272. Notes
  1273. =====
  1274. For instance:
  1275. ``[[1]]`` vector
  1276. ``[[1]*n]`` symmetric tensor of rank ``n``
  1277. ``[[n]]`` antisymmetric tensor of rank ``n``
  1278. ``[[2, 2]]`` monoterm slot symmetry of the Riemann tensor
  1279. ``[[1],[1]]`` vector*vector
  1280. ``[[2],[1],[1]`` (antisymmetric tensor)*vector*vector
  1281. Notice that with the shape ``[2, 2]`` we associate only the monoterm
  1282. symmetries of the Riemann tensor; this is an abuse of notation,
  1283. since the shape ``[2, 2]`` corresponds usually to the irreducible
  1284. representation characterized by the monoterm symmetries and by the
  1285. cyclic symmetry.
  1286. """
  1287. from sympy.combinatorics import Permutation
  1288. def tableau2bsgs(a):
  1289. if len(a) == 1:
  1290. # antisymmetric vector
  1291. n = a[0]
  1292. bsgs = get_symmetric_group_sgs(n, 1)
  1293. else:
  1294. if all(x == 1 for x in a):
  1295. # symmetric vector
  1296. n = len(a)
  1297. bsgs = get_symmetric_group_sgs(n)
  1298. elif a == [2, 2]:
  1299. bsgs = riemann_bsgs
  1300. else:
  1301. raise NotImplementedError
  1302. return bsgs
  1303. if not args:
  1304. return TensorSymmetry(Tuple(), Tuple(Permutation(1)))
  1305. if len(args) == 2 and isinstance(args[1][0], Permutation):
  1306. return TensorSymmetry(args)
  1307. base, sgs = tableau2bsgs(args[0])
  1308. for a in args[1:]:
  1309. basex, sgsx = tableau2bsgs(a)
  1310. base, sgs = bsgs_direct_product(base, sgs, basex, sgsx)
  1311. return TensorSymmetry(Tuple(base, sgs))
  1312. @deprecated(
  1313. "TensorType is deprecated. Use tensor_heads() instead.",
  1314. deprecated_since_version="1.5",
  1315. active_deprecations_target="deprecated-tensortype",
  1316. )
  1317. class TensorType(Basic):
  1318. """
  1319. Class of tensor types. Deprecated, use tensor_heads() instead.
  1320. Parameters
  1321. ==========
  1322. index_types : list of ``TensorIndexType`` of the tensor indices
  1323. symmetry : ``TensorSymmetry`` of the tensor
  1324. Attributes
  1325. ==========
  1326. ``index_types``
  1327. ``symmetry``
  1328. ``types`` : list of ``TensorIndexType`` without repetitions
  1329. """
  1330. is_commutative = False
  1331. def __new__(cls, index_types, symmetry, **kw_args):
  1332. assert symmetry.rank == len(index_types)
  1333. obj = Basic.__new__(cls, Tuple(*index_types), symmetry, **kw_args)
  1334. return obj
  1335. @property
  1336. def index_types(self):
  1337. return self.args[0]
  1338. @property
  1339. def symmetry(self):
  1340. return self.args[1]
  1341. @property
  1342. def types(self):
  1343. return sorted(set(self.index_types), key=lambda x: x.name)
  1344. def __str__(self):
  1345. return 'TensorType(%s)' % ([str(x) for x in self.index_types])
  1346. def __call__(self, s, comm=0):
  1347. """
  1348. Return a TensorHead object or a list of TensorHead objects.
  1349. Parameters
  1350. ==========
  1351. s : name or string of names.
  1352. comm : Commutation group.
  1353. see ``_TensorManager.set_comm``
  1354. """
  1355. if isinstance(s, str):
  1356. names = [x.name for x in symbols(s, seq=True)]
  1357. else:
  1358. raise ValueError('expecting a string')
  1359. if len(names) == 1:
  1360. return TensorHead(names[0], self.index_types, self.symmetry, comm)
  1361. else:
  1362. return [TensorHead(name, self.index_types, self.symmetry, comm) for name in names]
  1363. @deprecated(
  1364. """
  1365. The tensorhead() function is deprecated. Use tensor_heads() instead.
  1366. """,
  1367. deprecated_since_version="1.5",
  1368. active_deprecations_target="deprecated-tensorhead",
  1369. )
  1370. def tensorhead(name, typ, sym=None, comm=0):
  1371. """
  1372. Function generating tensorhead(s). This method is deprecated,
  1373. use TensorHead constructor or tensor_heads() instead.
  1374. Parameters
  1375. ==========
  1376. name : name or sequence of names (as in ``symbols``)
  1377. typ : index types
  1378. sym : same as ``*args`` in ``tensorsymmetry``
  1379. comm : commutation group number
  1380. see ``_TensorManager.set_comm``
  1381. """
  1382. if sym is None:
  1383. sym = [[1] for i in range(len(typ))]
  1384. with ignore_warnings(SymPyDeprecationWarning):
  1385. sym = tensorsymmetry(*sym)
  1386. return TensorHead(name, typ, sym, comm)
  1387. class TensorHead(Basic):
  1388. """
  1389. Tensor head of the tensor.
  1390. Parameters
  1391. ==========
  1392. name : name of the tensor
  1393. index_types : list of TensorIndexType
  1394. symmetry : TensorSymmetry of the tensor
  1395. comm : commutation group number
  1396. Attributes
  1397. ==========
  1398. ``name``
  1399. ``index_types``
  1400. ``rank`` : total number of indices
  1401. ``symmetry``
  1402. ``comm`` : commutation group
  1403. Notes
  1404. =====
  1405. Similar to ``symbols`` multiple TensorHeads can be created using
  1406. ``tensorhead(s, typ, sym=None, comm=0)`` function, where ``s``
  1407. is the string of names and ``sym`` is the monoterm tensor symmetry
  1408. (see ``tensorsymmetry``).
  1409. A ``TensorHead`` belongs to a commutation group, defined by a
  1410. symbol on number ``comm`` (see ``_TensorManager.set_comm``);
  1411. tensors in a commutation group have the same commutation properties;
  1412. by default ``comm`` is ``0``, the group of the commuting tensors.
  1413. Examples
  1414. ========
  1415. Define a fully antisymmetric tensor of rank 2:
  1416. >>> from sympy.tensor.tensor import TensorIndexType, TensorHead, TensorSymmetry
  1417. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  1418. >>> asym2 = TensorSymmetry.fully_symmetric(-2)
  1419. >>> A = TensorHead('A', [Lorentz, Lorentz], asym2)
  1420. Examples with ndarray values, the components data assigned to the
  1421. ``TensorHead`` object are assumed to be in a fully-contravariant
  1422. representation. In case it is necessary to assign components data which
  1423. represents the values of a non-fully covariant tensor, see the other
  1424. examples.
  1425. >>> from sympy.tensor.tensor import tensor_indices
  1426. >>> from sympy import diag
  1427. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  1428. >>> i0, i1 = tensor_indices('i0:2', Lorentz)
  1429. Specify a replacement dictionary to keep track of the arrays to use for
  1430. replacements in the tensorial expression. The ``TensorIndexType`` is
  1431. associated to the metric used for contractions (in fully covariant form):
  1432. >>> repl = {Lorentz: diag(1, -1, -1, -1)}
  1433. Let's see some examples of working with components with the electromagnetic
  1434. tensor:
  1435. >>> from sympy import symbols
  1436. >>> Ex, Ey, Ez, Bx, By, Bz = symbols('E_x E_y E_z B_x B_y B_z')
  1437. >>> c = symbols('c', positive=True)
  1438. Let's define `F`, an antisymmetric tensor:
  1439. >>> F = TensorHead('F', [Lorentz, Lorentz], asym2)
  1440. Let's update the dictionary to contain the matrix to use in the
  1441. replacements:
  1442. >>> repl.update({F(-i0, -i1): [
  1443. ... [0, Ex/c, Ey/c, Ez/c],
  1444. ... [-Ex/c, 0, -Bz, By],
  1445. ... [-Ey/c, Bz, 0, -Bx],
  1446. ... [-Ez/c, -By, Bx, 0]]})
  1447. Now it is possible to retrieve the contravariant form of the Electromagnetic
  1448. tensor:
  1449. >>> F(i0, i1).replace_with_arrays(repl, [i0, i1])
  1450. [[0, -E_x/c, -E_y/c, -E_z/c], [E_x/c, 0, -B_z, B_y], [E_y/c, B_z, 0, -B_x], [E_z/c, -B_y, B_x, 0]]
  1451. and the mixed contravariant-covariant form:
  1452. >>> F(i0, -i1).replace_with_arrays(repl, [i0, -i1])
  1453. [[0, E_x/c, E_y/c, E_z/c], [E_x/c, 0, B_z, -B_y], [E_y/c, -B_z, 0, B_x], [E_z/c, B_y, -B_x, 0]]
  1454. Energy-momentum of a particle may be represented as:
  1455. >>> from sympy import symbols
  1456. >>> P = TensorHead('P', [Lorentz], TensorSymmetry.no_symmetry(1))
  1457. >>> E, px, py, pz = symbols('E p_x p_y p_z', positive=True)
  1458. >>> repl.update({P(i0): [E, px, py, pz]})
  1459. The contravariant and covariant components are, respectively:
  1460. >>> P(i0).replace_with_arrays(repl, [i0])
  1461. [E, p_x, p_y, p_z]
  1462. >>> P(-i0).replace_with_arrays(repl, [-i0])
  1463. [E, -p_x, -p_y, -p_z]
  1464. The contraction of a 1-index tensor by itself:
  1465. >>> expr = P(i0)*P(-i0)
  1466. >>> expr.replace_with_arrays(repl, [])
  1467. E**2 - p_x**2 - p_y**2 - p_z**2
  1468. """
  1469. is_commutative = False
  1470. def __new__(cls, name, index_types, symmetry=None, comm=0):
  1471. if isinstance(name, str):
  1472. name_symbol = Symbol(name)
  1473. elif isinstance(name, Symbol):
  1474. name_symbol = name
  1475. else:
  1476. raise ValueError("invalid name")
  1477. if symmetry is None:
  1478. symmetry = TensorSymmetry.no_symmetry(len(index_types))
  1479. else:
  1480. assert symmetry.rank == len(index_types)
  1481. obj = Basic.__new__(cls, name_symbol, Tuple(*index_types), symmetry, sympify(comm))
  1482. return obj
  1483. @property
  1484. def name(self):
  1485. return self.args[0].name
  1486. @property
  1487. def index_types(self):
  1488. return list(self.args[1])
  1489. @property
  1490. def symmetry(self):
  1491. return self.args[2]
  1492. @property
  1493. def comm(self):
  1494. return TensorManager.comm_symbols2i(self.args[3])
  1495. @property
  1496. def rank(self):
  1497. return len(self.index_types)
  1498. def __lt__(self, other):
  1499. return (self.name, self.index_types) < (other.name, other.index_types)
  1500. def commutes_with(self, other):
  1501. """
  1502. Returns ``0`` if ``self`` and ``other`` commute, ``1`` if they anticommute.
  1503. Returns ``None`` if ``self`` and ``other`` neither commute nor anticommute.
  1504. """
  1505. r = TensorManager.get_comm(self.comm, other.comm)
  1506. return r
  1507. def _print(self):
  1508. return '%s(%s)' %(self.name, ','.join([str(x) for x in self.index_types]))
  1509. def __call__(self, *indices, **kw_args):
  1510. """
  1511. Returns a tensor with indices.
  1512. Explanation
  1513. ===========
  1514. There is a special behavior in case of indices denoted by ``True``,
  1515. they are considered auto-matrix indices, their slots are automatically
  1516. filled, and confer to the tensor the behavior of a matrix or vector
  1517. upon multiplication with another tensor containing auto-matrix indices
  1518. of the same ``TensorIndexType``. This means indices get summed over the
  1519. same way as in matrix multiplication. For matrix behavior, define two
  1520. auto-matrix indices, for vector behavior define just one.
  1521. Indices can also be strings, in which case the attribute
  1522. ``index_types`` is used to convert them to proper ``TensorIndex``.
  1523. Examples
  1524. ========
  1525. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorSymmetry, TensorHead
  1526. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  1527. >>> a, b = tensor_indices('a,b', Lorentz)
  1528. >>> A = TensorHead('A', [Lorentz]*2, TensorSymmetry.no_symmetry(2))
  1529. >>> t = A(a, -b)
  1530. >>> t
  1531. A(a, -b)
  1532. """
  1533. updated_indices = []
  1534. for idx, typ in zip(indices, self.index_types):
  1535. if isinstance(idx, str):
  1536. idx = idx.strip().replace(" ", "")
  1537. if idx.startswith('-'):
  1538. updated_indices.append(TensorIndex(idx[1:], typ,
  1539. is_up=False))
  1540. else:
  1541. updated_indices.append(TensorIndex(idx, typ))
  1542. else:
  1543. updated_indices.append(idx)
  1544. updated_indices += indices[len(updated_indices):]
  1545. tensor = Tensor(self, updated_indices, **kw_args)
  1546. return tensor.doit()
  1547. # Everything below this line is deprecated
  1548. def __pow__(self, other):
  1549. deprecate_data()
  1550. with ignore_warnings(SymPyDeprecationWarning):
  1551. if self.data is None:
  1552. raise ValueError("No power on abstract tensors.")
  1553. from .array import tensorproduct, tensorcontraction
  1554. metrics = [_.data for _ in self.index_types]
  1555. marray = self.data
  1556. marraydim = marray.rank()
  1557. for metric in metrics:
  1558. marray = tensorproduct(marray, metric, marray)
  1559. marray = tensorcontraction(marray, (0, marraydim), (marraydim+1, marraydim+2))
  1560. return marray ** (other * S.Half)
  1561. @property
  1562. def data(self):
  1563. deprecate_data()
  1564. with ignore_warnings(SymPyDeprecationWarning):
  1565. return _tensor_data_substitution_dict[self]
  1566. @data.setter
  1567. def data(self, data):
  1568. deprecate_data()
  1569. with ignore_warnings(SymPyDeprecationWarning):
  1570. _tensor_data_substitution_dict[self] = data
  1571. @data.deleter
  1572. def data(self):
  1573. deprecate_data()
  1574. if self in _tensor_data_substitution_dict:
  1575. del _tensor_data_substitution_dict[self]
  1576. def __iter__(self):
  1577. deprecate_data()
  1578. with ignore_warnings(SymPyDeprecationWarning):
  1579. return self.data.__iter__()
  1580. def _components_data_full_destroy(self):
  1581. """
  1582. EXPERIMENTAL: do not rely on this API method.
  1583. Destroy components data associated to the ``TensorHead`` object, this
  1584. checks for attached components data, and destroys components data too.
  1585. """
  1586. # do not garbage collect Kronecker tensor (it should be done by
  1587. # ``TensorIndexType`` garbage collection)
  1588. deprecate_data()
  1589. if self.name == "KD":
  1590. return
  1591. # the data attached to a tensor must be deleted only by the TensorHead
  1592. # destructor. If the TensorHead is deleted, it means that there are no
  1593. # more instances of that tensor anywhere.
  1594. if self in _tensor_data_substitution_dict:
  1595. del _tensor_data_substitution_dict[self]
  1596. def tensor_heads(s, index_types, symmetry=None, comm=0):
  1597. """
  1598. Returns a sequence of TensorHeads from a string `s`
  1599. """
  1600. if isinstance(s, str):
  1601. names = [x.name for x in symbols(s, seq=True)]
  1602. else:
  1603. raise ValueError('expecting a string')
  1604. thlist = [TensorHead(name, index_types, symmetry, comm) for name in names]
  1605. if len(thlist) == 1:
  1606. return thlist[0]
  1607. return thlist
  1608. class TensExpr(Expr, ABC):
  1609. """
  1610. Abstract base class for tensor expressions
  1611. Notes
  1612. =====
  1613. A tensor expression is an expression formed by tensors;
  1614. currently the sums of tensors are distributed.
  1615. A ``TensExpr`` can be a ``TensAdd`` or a ``TensMul``.
  1616. ``TensMul`` objects are formed by products of component tensors,
  1617. and include a coefficient, which is a SymPy expression.
  1618. In the internal representation contracted indices are represented
  1619. by ``(ipos1, ipos2, icomp1, icomp2)``, where ``icomp1`` is the position
  1620. of the component tensor with contravariant index, ``ipos1`` is the
  1621. slot which the index occupies in that component tensor.
  1622. Contracted indices are therefore nameless in the internal representation.
  1623. """
  1624. _op_priority = 12.0
  1625. is_commutative = False
  1626. def __neg__(self):
  1627. return self*S.NegativeOne
  1628. def __abs__(self):
  1629. raise NotImplementedError
  1630. def __add__(self, other):
  1631. return TensAdd(self, other).doit(deep=False)
  1632. def __radd__(self, other):
  1633. return TensAdd(other, self).doit(deep=False)
  1634. def __sub__(self, other):
  1635. return TensAdd(self, -other).doit(deep=False)
  1636. def __rsub__(self, other):
  1637. return TensAdd(other, -self).doit(deep=False)
  1638. def __mul__(self, other):
  1639. """
  1640. Multiply two tensors using Einstein summation convention.
  1641. Explanation
  1642. ===========
  1643. If the two tensors have an index in common, one contravariant
  1644. and the other covariant, in their product the indices are summed
  1645. Examples
  1646. ========
  1647. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads
  1648. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  1649. >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz)
  1650. >>> g = Lorentz.metric
  1651. >>> p, q = tensor_heads('p,q', [Lorentz])
  1652. >>> t1 = p(m0)
  1653. >>> t2 = q(-m0)
  1654. >>> t1*t2
  1655. p(L_0)*q(-L_0)
  1656. """
  1657. return TensMul(self, other).doit(deep=False)
  1658. def __rmul__(self, other):
  1659. return TensMul(other, self).doit(deep=False)
  1660. def __truediv__(self, other):
  1661. other = _sympify(other)
  1662. if isinstance(other, TensExpr):
  1663. raise ValueError('cannot divide by a tensor')
  1664. return TensMul(self, S.One/other).doit(deep=False)
  1665. def __rtruediv__(self, other):
  1666. raise ValueError('cannot divide by a tensor')
  1667. def __pow__(self, other):
  1668. deprecate_data()
  1669. with ignore_warnings(SymPyDeprecationWarning):
  1670. if self.data is None:
  1671. raise ValueError("No power without ndarray data.")
  1672. from .array import tensorproduct, tensorcontraction
  1673. free = self.free
  1674. marray = self.data
  1675. mdim = marray.rank()
  1676. for metric in free:
  1677. marray = tensorcontraction(
  1678. tensorproduct(
  1679. marray,
  1680. metric[0].tensor_index_type.data,
  1681. marray),
  1682. (0, mdim), (mdim+1, mdim+2)
  1683. )
  1684. return marray ** (other * S.Half)
  1685. def __rpow__(self, other):
  1686. raise NotImplementedError
  1687. @property
  1688. @abstractmethod
  1689. def nocoeff(self):
  1690. raise NotImplementedError("abstract method")
  1691. @property
  1692. @abstractmethod
  1693. def coeff(self):
  1694. raise NotImplementedError("abstract method")
  1695. @abstractmethod
  1696. def get_indices(self):
  1697. raise NotImplementedError("abstract method")
  1698. @abstractmethod
  1699. def get_free_indices(self) -> list[TensorIndex]:
  1700. raise NotImplementedError("abstract method")
  1701. @abstractmethod
  1702. def _replace_indices(self, repl: dict[TensorIndex, TensorIndex]) -> TensExpr:
  1703. raise NotImplementedError("abstract method")
  1704. def fun_eval(self, *index_tuples):
  1705. deprecate_fun_eval()
  1706. return self.substitute_indices(*index_tuples)
  1707. def get_matrix(self):
  1708. """
  1709. DEPRECATED: do not use.
  1710. Returns ndarray components data as a matrix, if components data are
  1711. available and ndarray dimension does not exceed 2.
  1712. """
  1713. from sympy.matrices.dense import Matrix
  1714. deprecate_data()
  1715. with ignore_warnings(SymPyDeprecationWarning):
  1716. if 0 < self.rank <= 2:
  1717. rows = self.data.shape[0]
  1718. columns = self.data.shape[1] if self.rank == 2 else 1
  1719. if self.rank == 2:
  1720. mat_list = [] * rows
  1721. for i in range(rows):
  1722. mat_list.append([])
  1723. for j in range(columns):
  1724. mat_list[i].append(self[i, j])
  1725. else:
  1726. mat_list = [None] * rows
  1727. for i in range(rows):
  1728. mat_list[i] = self[i]
  1729. return Matrix(mat_list)
  1730. else:
  1731. raise NotImplementedError(
  1732. "missing multidimensional reduction to matrix.")
  1733. @staticmethod
  1734. def _get_indices_permutation(indices1, indices2):
  1735. return [indices1.index(i) for i in indices2]
  1736. def _get_free_indices_set(self):
  1737. indset = set()
  1738. for arg in self.args:
  1739. if isinstance(arg, TensExpr):
  1740. indset.update(arg._get_free_indices_set())
  1741. return indset
  1742. def _get_dummy_indices_set(self):
  1743. indset = set()
  1744. for arg in self.args:
  1745. if isinstance(arg, TensExpr):
  1746. indset.update(arg._get_dummy_indices_set())
  1747. return indset
  1748. def _get_indices_set(self):
  1749. indset = set()
  1750. for arg in self.args:
  1751. if isinstance(arg, TensExpr):
  1752. indset.update(arg._get_indices_set())
  1753. return indset
  1754. @property
  1755. def _iterate_dummy_indices(self):
  1756. dummy_set = self._get_dummy_indices_set()
  1757. def recursor(expr, pos):
  1758. if isinstance(expr, TensorIndex):
  1759. if expr in dummy_set:
  1760. yield (expr, pos)
  1761. elif isinstance(expr, (Tuple, TensExpr)):
  1762. for p, arg in enumerate(expr.args):
  1763. yield from recursor(arg, pos+(p,))
  1764. return recursor(self, ())
  1765. @property
  1766. def _iterate_free_indices(self):
  1767. free_set = self._get_free_indices_set()
  1768. def recursor(expr, pos):
  1769. if isinstance(expr, TensorIndex):
  1770. if expr in free_set:
  1771. yield (expr, pos)
  1772. elif isinstance(expr, (Tuple, TensExpr)):
  1773. for p, arg in enumerate(expr.args):
  1774. yield from recursor(arg, pos+(p,))
  1775. return recursor(self, ())
  1776. @property
  1777. def _iterate_indices(self):
  1778. def recursor(expr, pos):
  1779. if isinstance(expr, TensorIndex):
  1780. yield (expr, pos)
  1781. elif isinstance(expr, (Tuple, TensExpr)):
  1782. for p, arg in enumerate(expr.args):
  1783. yield from recursor(arg, pos+(p,))
  1784. return recursor(self, ())
  1785. @staticmethod
  1786. def _contract_and_permute_with_metric(metric, array, pos, dim):
  1787. # TODO: add possibility of metric after (spinors)
  1788. from .array import tensorcontraction, tensorproduct, permutedims
  1789. array = tensorcontraction(tensorproduct(metric, array), (1, 2+pos))
  1790. permu = list(range(dim))
  1791. permu[0], permu[pos] = permu[pos], permu[0]
  1792. return permutedims(array, permu)
  1793. @staticmethod
  1794. def _match_indices_with_other_tensor(array, free_ind1, free_ind2, replacement_dict):
  1795. from .array import permutedims
  1796. index_types1 = [i.tensor_index_type for i in free_ind1]
  1797. # Check if variance of indices needs to be fixed:
  1798. pos2up = []
  1799. pos2down = []
  1800. free2remaining = free_ind2[:]
  1801. for pos1, index1 in enumerate(free_ind1):
  1802. if index1 in free2remaining:
  1803. pos2 = free2remaining.index(index1)
  1804. free2remaining[pos2] = None
  1805. continue
  1806. if -index1 in free2remaining:
  1807. pos2 = free2remaining.index(-index1)
  1808. free2remaining[pos2] = None
  1809. free_ind2[pos2] = index1
  1810. if index1.is_up:
  1811. pos2up.append(pos2)
  1812. else:
  1813. pos2down.append(pos2)
  1814. else:
  1815. index2 = free2remaining[pos1]
  1816. if index2 is None:
  1817. raise ValueError("incompatible indices: %s and %s" % (free_ind1, free_ind2))
  1818. free2remaining[pos1] = None
  1819. free_ind2[pos1] = index1
  1820. if index1.is_up ^ index2.is_up:
  1821. if index1.is_up:
  1822. pos2up.append(pos1)
  1823. else:
  1824. pos2down.append(pos1)
  1825. if len(set(free_ind1) & set(free_ind2)) < len(free_ind1):
  1826. raise ValueError("incompatible indices: %s and %s" % (free_ind1, free_ind2))
  1827. # Raise indices:
  1828. for pos in pos2up:
  1829. index_type_pos = index_types1[pos]
  1830. if index_type_pos not in replacement_dict:
  1831. raise ValueError("No metric provided to lower index")
  1832. metric = replacement_dict[index_type_pos]
  1833. metric_inverse = _TensorDataLazyEvaluator.inverse_matrix(metric)
  1834. array = TensExpr._contract_and_permute_with_metric(metric_inverse, array, pos, len(free_ind1))
  1835. # Lower indices:
  1836. for pos in pos2down:
  1837. index_type_pos = index_types1[pos]
  1838. if index_type_pos not in replacement_dict:
  1839. raise ValueError("No metric provided to lower index")
  1840. metric = replacement_dict[index_type_pos]
  1841. array = TensExpr._contract_and_permute_with_metric(metric, array, pos, len(free_ind1))
  1842. if free_ind1:
  1843. permutation = TensExpr._get_indices_permutation(free_ind2, free_ind1)
  1844. array = permutedims(array, permutation)
  1845. if hasattr(array, "rank") and array.rank() == 0:
  1846. array = array[()]
  1847. return free_ind2, array
  1848. def replace_with_arrays(self, replacement_dict, indices=None):
  1849. """
  1850. Replace the tensorial expressions with arrays. The final array will
  1851. correspond to the N-dimensional array with indices arranged according
  1852. to ``indices``.
  1853. Parameters
  1854. ==========
  1855. replacement_dict
  1856. dictionary containing the replacement rules for tensors.
  1857. indices
  1858. the index order with respect to which the array is read. The
  1859. original index order will be used if no value is passed.
  1860. Examples
  1861. ========
  1862. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices
  1863. >>> from sympy.tensor.tensor import TensorHead
  1864. >>> from sympy import symbols, diag
  1865. >>> L = TensorIndexType("L")
  1866. >>> i, j = tensor_indices("i j", L)
  1867. >>> A = TensorHead("A", [L])
  1868. >>> A(i).replace_with_arrays({A(i): [1, 2]}, [i])
  1869. [1, 2]
  1870. Since 'indices' is optional, we can also call replace_with_arrays by
  1871. this way if no specific index order is needed:
  1872. >>> A(i).replace_with_arrays({A(i): [1, 2]})
  1873. [1, 2]
  1874. >>> expr = A(i)*A(j)
  1875. >>> expr.replace_with_arrays({A(i): [1, 2]})
  1876. [[1, 2], [2, 4]]
  1877. For contractions, specify the metric of the ``TensorIndexType``, which
  1878. in this case is ``L``, in its covariant form:
  1879. >>> expr = A(i)*A(-i)
  1880. >>> expr.replace_with_arrays({A(i): [1, 2], L: diag(1, -1)})
  1881. -3
  1882. Symmetrization of an array:
  1883. >>> H = TensorHead("H", [L, L])
  1884. >>> a, b, c, d = symbols("a b c d")
  1885. >>> expr = H(i, j)/2 + H(j, i)/2
  1886. >>> expr.replace_with_arrays({H(i, j): [[a, b], [c, d]]})
  1887. [[a, b/2 + c/2], [b/2 + c/2, d]]
  1888. Anti-symmetrization of an array:
  1889. >>> expr = H(i, j)/2 - H(j, i)/2
  1890. >>> repl = {H(i, j): [[a, b], [c, d]]}
  1891. >>> expr.replace_with_arrays(repl)
  1892. [[0, b/2 - c/2], [-b/2 + c/2, 0]]
  1893. The same expression can be read as the transpose by inverting ``i`` and
  1894. ``j``:
  1895. >>> expr.replace_with_arrays(repl, [j, i])
  1896. [[0, -b/2 + c/2], [b/2 - c/2, 0]]
  1897. """
  1898. from .array import Array
  1899. indices = indices or []
  1900. remap = {k.args[0] if k.is_up else -k.args[0]: k for k in self.get_free_indices()}
  1901. for i, index in enumerate(indices):
  1902. if isinstance(index, (Symbol, Mul)):
  1903. if index in remap:
  1904. indices[i] = remap[index]
  1905. else:
  1906. indices[i] = -remap[-index]
  1907. replacement_dict = {tensor: Array(array) for tensor, array in replacement_dict.items()}
  1908. # Check dimensions of replaced arrays:
  1909. for tensor, array in replacement_dict.items():
  1910. if isinstance(tensor, TensorIndexType):
  1911. expected_shape = [tensor.dim for i in range(2)]
  1912. else:
  1913. expected_shape = [index_type.dim for index_type in tensor.index_types]
  1914. if len(expected_shape) != array.rank() or (not all(dim1 == dim2 if
  1915. dim1.is_number else True for dim1, dim2 in zip(expected_shape,
  1916. array.shape))):
  1917. raise ValueError("shapes for tensor %s expected to be %s, "\
  1918. "replacement array shape is %s" % (tensor, expected_shape,
  1919. array.shape))
  1920. ret_indices, array = self._extract_data(replacement_dict)
  1921. last_indices, array = self._match_indices_with_other_tensor(array, indices, ret_indices, replacement_dict)
  1922. return array
  1923. def _check_add_Sum(self, expr, index_symbols):
  1924. from sympy.concrete.summations import Sum
  1925. indices = self.get_indices()
  1926. dum = self.dum
  1927. sum_indices = [ (index_symbols[i], 0,
  1928. indices[i].tensor_index_type.dim-1) for i, j in dum]
  1929. if sum_indices:
  1930. expr = Sum(expr, *sum_indices)
  1931. return expr
  1932. def _expand_partial_derivative(self):
  1933. # simply delegate the _expand_partial_derivative() to
  1934. # its arguments to expand a possibly found PartialDerivative
  1935. return self.func(*[
  1936. a._expand_partial_derivative()
  1937. if isinstance(a, TensExpr) else a
  1938. for a in self.args])
  1939. def _matches_simple(self, expr, repl_dict=None, old=False):
  1940. """
  1941. Matches assuming there are no wild objects in self.
  1942. """
  1943. if repl_dict is None:
  1944. repl_dict = {}
  1945. else:
  1946. repl_dict = repl_dict.copy()
  1947. if not isinstance(expr, TensExpr):
  1948. if len(self.get_free_indices()) > 0:
  1949. #self has indices, but expr does not.
  1950. return None
  1951. elif set(self.get_free_indices()) != set(expr.get_free_indices()):
  1952. #If there are no wilds and the free indices are not the same, they cannot match.
  1953. return None
  1954. if canon_bp(self - expr) == S.Zero:
  1955. return repl_dict
  1956. else:
  1957. return None
  1958. class TensAdd(TensExpr, AssocOp):
  1959. """
  1960. Sum of tensors.
  1961. Parameters
  1962. ==========
  1963. free_args : list of the free indices
  1964. Attributes
  1965. ==========
  1966. ``args`` : tuple of addends
  1967. ``rank`` : rank of the tensor
  1968. ``free_args`` : list of the free indices in sorted order
  1969. Examples
  1970. ========
  1971. >>> from sympy.tensor.tensor import TensorIndexType, tensor_heads, tensor_indices
  1972. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  1973. >>> a, b = tensor_indices('a,b', Lorentz)
  1974. >>> p, q = tensor_heads('p,q', [Lorentz])
  1975. >>> t = p(a) + q(a); t
  1976. p(a) + q(a)
  1977. Examples with components data added to the tensor expression:
  1978. >>> from sympy import symbols, diag
  1979. >>> x, y, z, t = symbols("x y z t")
  1980. >>> repl = {}
  1981. >>> repl[Lorentz] = diag(1, -1, -1, -1)
  1982. >>> repl[p(a)] = [1, 2, 3, 4]
  1983. >>> repl[q(a)] = [x, y, z, t]
  1984. The following are: 2**2 - 3**2 - 2**2 - 7**2 ==> -58
  1985. >>> expr = p(a) + q(a)
  1986. >>> expr.replace_with_arrays(repl, [a])
  1987. [x + 1, y + 2, z + 3, t + 4]
  1988. """
  1989. def __new__(cls, *args, **kw_args):
  1990. args = [_sympify(x) for x in args if x]
  1991. args = TensAdd._tensAdd_flatten(args)
  1992. args.sort(key=default_sort_key)
  1993. if not args:
  1994. return S.Zero
  1995. if len(args) == 1:
  1996. return args[0]
  1997. return Basic.__new__(cls, *args, **kw_args)
  1998. @property
  1999. def coeff(self):
  2000. return S.One
  2001. @property
  2002. def nocoeff(self):
  2003. return self
  2004. def get_free_indices(self) -> list[TensorIndex]:
  2005. return self.free_indices
  2006. def _replace_indices(self, repl: dict[TensorIndex, TensorIndex]) -> TensExpr:
  2007. newargs = [arg._replace_indices(repl) if isinstance(arg, TensExpr) else arg for arg in self.args]
  2008. return self.func(*newargs)
  2009. @memoize_property
  2010. def rank(self):
  2011. if isinstance(self.args[0], TensExpr):
  2012. return self.args[0].rank
  2013. else:
  2014. return 0
  2015. @memoize_property
  2016. def free_args(self):
  2017. if isinstance(self.args[0], TensExpr):
  2018. return self.args[0].free_args
  2019. else:
  2020. return []
  2021. @memoize_property
  2022. def free_indices(self):
  2023. if isinstance(self.args[0], TensExpr):
  2024. return self.args[0].get_free_indices()
  2025. else:
  2026. return set()
  2027. def doit(self, **hints) -> Expr:
  2028. deep = hints.get('deep', True)
  2029. if deep:
  2030. args = [arg.doit(**hints) for arg in self.args]
  2031. else:
  2032. args = self.args # type: ignore
  2033. # if any of the args are zero (after doit), drop them. Otherwise, _tensAdd_check will complain about non-matching indices, even though the TensAdd is correctly formed.
  2034. args = [arg for arg in args if arg != S.Zero]
  2035. if len(args) == 0:
  2036. return S.Zero
  2037. elif len(args) == 1:
  2038. return args[0]
  2039. # now check that all addends have the same indices:
  2040. TensAdd._tensAdd_check(args)
  2041. # Collect terms appearing more than once, differing by their coefficients:
  2042. args = TensAdd._tensAdd_collect_terms(args)
  2043. # collect canonicalized terms
  2044. def sort_key(t):
  2045. if not isinstance(t, TensExpr):
  2046. return [], [], []
  2047. if hasattr(t, "_index_structure") and hasattr(t, "components"):
  2048. x = get_index_structure(t)
  2049. return t.components, x.free, x.dum
  2050. return [], [], []
  2051. args.sort(key=sort_key)
  2052. if not args:
  2053. return S.Zero
  2054. # it there is only a component tensor return it
  2055. if len(args) == 1:
  2056. return args[0]
  2057. obj = self.func(*args)
  2058. return obj
  2059. @staticmethod
  2060. def _tensAdd_flatten(args):
  2061. # flatten TensAdd, coerce terms which are not tensors to tensors
  2062. a = []
  2063. for x in args:
  2064. if isinstance(x, (Add, TensAdd)):
  2065. a.extend(list(x.args))
  2066. else:
  2067. a.append(x)
  2068. args = [x for x in a if x.coeff]
  2069. return args
  2070. @staticmethod
  2071. def _tensAdd_check(args):
  2072. # check that all addends have the same free indices
  2073. def get_indices_set(x: Expr) -> set[TensorIndex]:
  2074. if isinstance(x, TensExpr):
  2075. return set(x.get_free_indices())
  2076. return set()
  2077. indices0 = get_indices_set(args[0])
  2078. list_indices = [get_indices_set(arg) for arg in args[1:]]
  2079. if not all(x == indices0 for x in list_indices):
  2080. raise ValueError('all tensors must have the same indices')
  2081. @staticmethod
  2082. def _tensAdd_collect_terms(args):
  2083. # collect TensMul terms differing at most by their coefficient
  2084. terms_dict = defaultdict(list)
  2085. scalars = S.Zero
  2086. if isinstance(args[0], TensExpr):
  2087. free_indices = set(args[0].get_free_indices())
  2088. else:
  2089. free_indices = set()
  2090. for arg in args:
  2091. if not isinstance(arg, TensExpr):
  2092. if free_indices != set():
  2093. raise ValueError("wrong valence")
  2094. scalars += arg
  2095. continue
  2096. if free_indices != set(arg.get_free_indices()):
  2097. raise ValueError("wrong valence")
  2098. # TODO: what is the part which is not a coeff?
  2099. # needs an implementation similar to .as_coeff_Mul()
  2100. terms_dict[arg.nocoeff].append(arg.coeff)
  2101. new_args = [TensMul(Add(*coeff), t).doit(deep=False) for t, coeff in terms_dict.items() if Add(*coeff) != 0]
  2102. if isinstance(scalars, Add):
  2103. new_args = list(scalars.args) + new_args
  2104. elif scalars != 0:
  2105. new_args = [scalars] + new_args
  2106. return new_args
  2107. def get_indices(self):
  2108. indices = []
  2109. for arg in self.args:
  2110. indices.extend([i for i in get_indices(arg) if i not in indices])
  2111. return indices
  2112. def __call__(self, *indices):
  2113. deprecate_call()
  2114. free_args = self.free_args
  2115. indices = list(indices)
  2116. if [x.tensor_index_type for x in indices] != [x.tensor_index_type for x in free_args]:
  2117. raise ValueError('incompatible types')
  2118. if indices == free_args:
  2119. return self
  2120. index_tuples = list(zip(free_args, indices))
  2121. a = [x.func(*x.substitute_indices(*index_tuples).args) for x in self.args]
  2122. res = TensAdd(*a).doit(deep=False)
  2123. return res
  2124. def canon_bp(self):
  2125. """
  2126. Canonicalize using the Butler-Portugal algorithm for canonicalization
  2127. under monoterm symmetries.
  2128. """
  2129. expr = self.expand()
  2130. if isinstance(expr, self.func):
  2131. args = [canon_bp(x) for x in expr.args]
  2132. res = TensAdd(*args).doit(deep=False)
  2133. return res
  2134. else:
  2135. return canon_bp(expr)
  2136. def equals(self, other):
  2137. other = _sympify(other)
  2138. if isinstance(other, TensMul) and other.coeff == 0:
  2139. return all(x.coeff == 0 for x in self.args)
  2140. if isinstance(other, TensExpr):
  2141. if self.rank != other.rank:
  2142. return False
  2143. if isinstance(other, TensAdd):
  2144. if set(self.args) != set(other.args):
  2145. return False
  2146. else:
  2147. return True
  2148. t = self - other
  2149. if not isinstance(t, TensExpr):
  2150. return t == 0
  2151. else:
  2152. if isinstance(t, TensMul):
  2153. return t.coeff == 0
  2154. else:
  2155. return all(x.coeff == 0 for x in t.args)
  2156. def __getitem__(self, item):
  2157. deprecate_data()
  2158. with ignore_warnings(SymPyDeprecationWarning):
  2159. return self.data[item]
  2160. def contract_delta(self, delta):
  2161. args = [x.contract_delta(delta) if isinstance(x, TensExpr) else x for x in self.args]
  2162. t = TensAdd(*args).doit(deep=False)
  2163. return canon_bp(t)
  2164. def contract_metric(self, g):
  2165. """
  2166. Raise or lower indices with the metric ``g``.
  2167. Parameters
  2168. ==========
  2169. g : metric
  2170. contract_all : if True, eliminate all ``g`` which are contracted
  2171. Notes
  2172. =====
  2173. see the ``TensorIndexType`` docstring for the contraction conventions
  2174. """
  2175. args = [contract_metric(x, g) for x in self.args]
  2176. t = TensAdd(*args).doit(deep=False)
  2177. return canon_bp(t)
  2178. def substitute_indices(self, *index_tuples):
  2179. new_args = []
  2180. for arg in self.args:
  2181. if isinstance(arg, TensExpr):
  2182. arg = arg.substitute_indices(*index_tuples)
  2183. new_args.append(arg)
  2184. return TensAdd(*new_args).doit(deep=False)
  2185. def _print(self):
  2186. a = []
  2187. args = self.args
  2188. for x in args:
  2189. a.append(str(x))
  2190. s = ' + '.join(a)
  2191. s = s.replace('+ -', '- ')
  2192. return s
  2193. def _extract_data(self, replacement_dict):
  2194. from sympy.tensor.array import Array, permutedims
  2195. args_indices, arrays = zip(*[
  2196. arg._extract_data(replacement_dict) if
  2197. isinstance(arg, TensExpr) else ([], arg) for arg in self.args
  2198. ])
  2199. arrays = [Array(i) for i in arrays]
  2200. ref_indices = args_indices[0]
  2201. for i in range(1, len(args_indices)):
  2202. indices = args_indices[i]
  2203. array = arrays[i]
  2204. permutation = TensMul._get_indices_permutation(indices, ref_indices)
  2205. arrays[i] = permutedims(array, permutation)
  2206. return ref_indices, sum(arrays, Array.zeros(*array.shape))
  2207. @property
  2208. def data(self):
  2209. deprecate_data()
  2210. with ignore_warnings(SymPyDeprecationWarning):
  2211. return _tensor_data_substitution_dict[self.expand()]
  2212. @data.setter
  2213. def data(self, data):
  2214. deprecate_data()
  2215. with ignore_warnings(SymPyDeprecationWarning):
  2216. _tensor_data_substitution_dict[self] = data
  2217. @data.deleter
  2218. def data(self):
  2219. deprecate_data()
  2220. with ignore_warnings(SymPyDeprecationWarning):
  2221. if self in _tensor_data_substitution_dict:
  2222. del _tensor_data_substitution_dict[self]
  2223. def __iter__(self):
  2224. deprecate_data()
  2225. if not self.data:
  2226. raise ValueError("No iteration on abstract tensors")
  2227. return self.data.flatten().__iter__()
  2228. def _eval_rewrite_as_Indexed(self, *args, **kwargs):
  2229. return Add.fromiter(args)
  2230. def _eval_partial_derivative(self, s):
  2231. # Evaluation like Add
  2232. list_addends = []
  2233. for a in self.args:
  2234. if isinstance(a, TensExpr):
  2235. list_addends.append(a._eval_partial_derivative(s))
  2236. # do not call diff if s is no symbol
  2237. elif s._diff_wrt:
  2238. list_addends.append(a._eval_derivative(s))
  2239. return self.func(*list_addends).doit(deep=False)
  2240. def matches(self, expr, repl_dict=None, old=False):
  2241. expr = sympify(expr)
  2242. if repl_dict is None:
  2243. repl_dict = {}
  2244. else:
  2245. repl_dict = repl_dict.copy()
  2246. if not isinstance(expr, TensAdd):
  2247. return None
  2248. if len(_get_wilds(self)) == 0:
  2249. return self._matches_simple(expr, repl_dict, old)
  2250. def siftkey(arg):
  2251. wildatoms = _get_wilds(arg)
  2252. wildatom_types = sift(wildatoms, type)
  2253. if len(wildatoms) == 0:
  2254. return "nonwild"
  2255. elif WildTensor in wildatom_types.keys():
  2256. for w in wildatom_types["WildTensor"]:
  2257. if len(w.get_indices()) == 0:
  2258. return "indexless_wildtensor"
  2259. return "wildtensor"
  2260. else:
  2261. return "otherwild"
  2262. query_sifted = sift(self.args, siftkey)
  2263. expr_sifted = sift(expr.args, siftkey)
  2264. #First try to match the terms without WildTensors
  2265. matched_e_tensors = [] #Used to make sure that the same tensor in expr is not matched with more than one tensor in self.
  2266. for q_tensor in query_sifted["nonwild"]:
  2267. matched_this_q = False
  2268. for e_tensor in expr_sifted["nonwild"]:
  2269. if e_tensor in matched_e_tensors:
  2270. continue
  2271. m = q_tensor.matches(e_tensor, repl_dict=repl_dict, old=old)
  2272. if m is None:
  2273. continue
  2274. else:
  2275. matched_this_q = True
  2276. repl_dict.update(m)
  2277. matched_e_tensors.append(e_tensor)
  2278. break
  2279. if not matched_this_q:
  2280. return None
  2281. remaining_e_tensors = [t for t in expr_sifted["nonwild"] if t not in matched_e_tensors]
  2282. for w in query_sifted["otherwild"]:
  2283. for e in remaining_e_tensors:
  2284. m = w.matches(e)
  2285. if m is not None:
  2286. matched_e_tensors.append(e)
  2287. if w in repl_dict.keys():
  2288. repl_dict[w] += m.pop(w)
  2289. repl_dict.update(m)
  2290. remaining_e_tensors = [t for t in expr_sifted["nonwild"] if t not in matched_e_tensors]
  2291. for w in query_sifted["wildtensor"]:
  2292. for e in remaining_e_tensors:
  2293. m = w.matches(e)
  2294. if m is not None:
  2295. matched_e_tensors.append(e)
  2296. if w.component in repl_dict.keys():
  2297. repl_dict[w.component] += m.pop(w.component)
  2298. repl_dict.update(m)
  2299. remaining_e_tensors = [t for t in expr_sifted["nonwild"] if t not in matched_e_tensors]
  2300. for w in query_sifted["indexless_wildtensor"]:
  2301. for e in remaining_e_tensors:
  2302. m = w.matches(e)
  2303. if m is not None:
  2304. matched_e_tensors.append(e)
  2305. if w.component in repl_dict.keys():
  2306. repl_dict[w.component] += m.pop(w.component)
  2307. repl_dict.update(m)
  2308. remaining_e_tensors = [t for t in expr_sifted["nonwild"] if t not in matched_e_tensors]
  2309. if len(remaining_e_tensors) > 0:
  2310. return None
  2311. else:
  2312. return repl_dict
  2313. class Tensor(TensExpr):
  2314. """
  2315. Base tensor class, i.e. this represents a tensor, the single unit to be
  2316. put into an expression.
  2317. Explanation
  2318. ===========
  2319. This object is usually created from a ``TensorHead``, by attaching indices
  2320. to it. Indices preceded by a minus sign are considered contravariant,
  2321. otherwise covariant.
  2322. Examples
  2323. ========
  2324. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead
  2325. >>> Lorentz = TensorIndexType("Lorentz", dummy_name="L")
  2326. >>> mu, nu = tensor_indices('mu nu', Lorentz)
  2327. >>> A = TensorHead("A", [Lorentz, Lorentz])
  2328. >>> A(mu, -nu)
  2329. A(mu, -nu)
  2330. >>> A(mu, -mu)
  2331. A(L_0, -L_0)
  2332. It is also possible to use symbols instead of inidices (appropriate indices
  2333. are then generated automatically).
  2334. >>> from sympy import Symbol
  2335. >>> x = Symbol('x')
  2336. >>> A(x, mu)
  2337. A(x, mu)
  2338. >>> A(x, -x)
  2339. A(L_0, -L_0)
  2340. """
  2341. is_commutative = False
  2342. _index_structure: _IndexStructure
  2343. args: tuple[TensorHead, Tuple]
  2344. def __new__(cls, tensor_head, indices, *, is_canon_bp=False, **kw_args):
  2345. indices = cls._parse_indices(tensor_head, indices)
  2346. obj = Basic.__new__(cls, tensor_head, Tuple(*indices), **kw_args)
  2347. obj._index_structure = _IndexStructure.from_indices(*indices)
  2348. obj._free = obj._index_structure.free[:]
  2349. obj._dum = obj._index_structure.dum[:]
  2350. obj._ext_rank = obj._index_structure._ext_rank
  2351. obj._coeff = S.One
  2352. obj._nocoeff = obj
  2353. obj._component = tensor_head
  2354. obj._components = [tensor_head]
  2355. if tensor_head.rank != len(indices):
  2356. raise ValueError("wrong number of indices")
  2357. obj.is_canon_bp = is_canon_bp
  2358. obj._index_map = Tensor._build_index_map(indices, obj._index_structure)
  2359. return obj
  2360. @property
  2361. def free(self):
  2362. return self._free
  2363. @property
  2364. def dum(self):
  2365. return self._dum
  2366. @property
  2367. def ext_rank(self):
  2368. return self._ext_rank
  2369. @property
  2370. def coeff(self):
  2371. return self._coeff
  2372. @property
  2373. def nocoeff(self):
  2374. return self._nocoeff
  2375. @property
  2376. def component(self):
  2377. return self._component
  2378. @property
  2379. def components(self):
  2380. return self._components
  2381. @property
  2382. def head(self):
  2383. return self.args[0]
  2384. @property
  2385. def indices(self):
  2386. return self.args[1]
  2387. @property
  2388. def free_indices(self):
  2389. return set(self._index_structure.get_free_indices())
  2390. @property
  2391. def index_types(self):
  2392. return self.head.index_types
  2393. @property
  2394. def rank(self):
  2395. return len(self.free_indices)
  2396. @staticmethod
  2397. def _build_index_map(indices, index_structure):
  2398. index_map = {}
  2399. for idx in indices:
  2400. index_map[idx] = (indices.index(idx),)
  2401. return index_map
  2402. def doit(self, **hints):
  2403. args, indices, free, dum = TensMul._tensMul_contract_indices([self])
  2404. return args[0]
  2405. @staticmethod
  2406. def _parse_indices(tensor_head, indices):
  2407. if not isinstance(indices, (tuple, list, Tuple)):
  2408. raise TypeError("indices should be an array, got %s" % type(indices))
  2409. indices = list(indices)
  2410. for i, index in enumerate(indices):
  2411. if isinstance(index, Symbol):
  2412. indices[i] = TensorIndex(index, tensor_head.index_types[i], True)
  2413. elif isinstance(index, Mul):
  2414. c, e = index.as_coeff_Mul()
  2415. if c == -1 and isinstance(e, Symbol):
  2416. indices[i] = TensorIndex(e, tensor_head.index_types[i], False)
  2417. else:
  2418. raise ValueError("index not understood: %s" % index)
  2419. elif not isinstance(index, TensorIndex):
  2420. raise TypeError("wrong type for index: %s is %s" % (index, type(index)))
  2421. return indices
  2422. def _set_new_index_structure(self, im, is_canon_bp=False):
  2423. indices = im.get_indices()
  2424. return self._set_indices(*indices, is_canon_bp=is_canon_bp)
  2425. def _set_indices(self, *indices, is_canon_bp=False, **kw_args):
  2426. if len(indices) != self.ext_rank:
  2427. raise ValueError("indices length mismatch")
  2428. return self.func(self.args[0], indices, is_canon_bp=is_canon_bp).doit()
  2429. def _get_free_indices_set(self):
  2430. return {i[0] for i in self._index_structure.free}
  2431. def _get_dummy_indices_set(self):
  2432. dummy_pos = set(itertools.chain(*self._index_structure.dum))
  2433. return {idx for i, idx in enumerate(self.args[1]) if i in dummy_pos}
  2434. def _get_indices_set(self):
  2435. return set(self.args[1].args)
  2436. @property
  2437. def free_in_args(self):
  2438. return [(ind, pos, 0) for ind, pos in self.free]
  2439. @property
  2440. def dum_in_args(self):
  2441. return [(p1, p2, 0, 0) for p1, p2 in self.dum]
  2442. @property
  2443. def free_args(self):
  2444. return sorted([x[0] for x in self.free])
  2445. def commutes_with(self, other):
  2446. """
  2447. :param other:
  2448. :return:
  2449. 0 commute
  2450. 1 anticommute
  2451. None neither commute nor anticommute
  2452. """
  2453. if not isinstance(other, TensExpr):
  2454. return 0
  2455. elif isinstance(other, Tensor):
  2456. return self.component.commutes_with(other.component)
  2457. return NotImplementedError
  2458. def perm2tensor(self, g, is_canon_bp=False):
  2459. """
  2460. Returns the tensor corresponding to the permutation ``g``.
  2461. For further details, see the method in ``TIDS`` with the same name.
  2462. """
  2463. return perm2tensor(self, g, is_canon_bp)
  2464. def canon_bp(self):
  2465. if self.is_canon_bp:
  2466. return self
  2467. expr = self.expand()
  2468. g, dummies, msym = expr._index_structure.indices_canon_args()
  2469. v = components_canon_args([expr.component])
  2470. can = canonicalize(g, dummies, msym, *v)
  2471. if can == 0:
  2472. return S.Zero
  2473. tensor = self.perm2tensor(can, True)
  2474. return tensor
  2475. def split(self):
  2476. return [self]
  2477. def sorted_components(self):
  2478. return self
  2479. def get_indices(self) -> list[TensorIndex]:
  2480. """
  2481. Get a list of indices, corresponding to those of the tensor.
  2482. """
  2483. return list(self.args[1])
  2484. def get_free_indices(self) -> list[TensorIndex]:
  2485. """
  2486. Get a list of free indices, corresponding to those of the tensor.
  2487. """
  2488. return self._index_structure.get_free_indices()
  2489. def _replace_indices(self, repl: dict[TensorIndex, TensorIndex]) -> TensExpr:
  2490. # TODO: this could be optimized by only swapping the indices
  2491. # instead of visiting the whole expression tree:
  2492. return self.xreplace(repl)
  2493. def as_base_exp(self):
  2494. return self, S.One
  2495. def substitute_indices(self, *index_tuples):
  2496. """
  2497. Return a tensor with free indices substituted according to ``index_tuples``.
  2498. ``index_types`` list of tuples ``(old_index, new_index)``.
  2499. Examples
  2500. ========
  2501. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads, TensorSymmetry
  2502. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  2503. >>> i, j, k, l = tensor_indices('i,j,k,l', Lorentz)
  2504. >>> A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
  2505. >>> t = A(i, k)*B(-k, -j); t
  2506. A(i, L_0)*B(-L_0, -j)
  2507. >>> t.substitute_indices((i, k),(-j, l))
  2508. A(k, L_0)*B(-L_0, l)
  2509. """
  2510. indices = []
  2511. for index in self.indices:
  2512. for ind_old, ind_new in index_tuples:
  2513. if (index.name == ind_old.name and index.tensor_index_type ==
  2514. ind_old.tensor_index_type):
  2515. if index.is_up == ind_old.is_up:
  2516. indices.append(ind_new)
  2517. else:
  2518. indices.append(-ind_new)
  2519. break
  2520. else:
  2521. indices.append(index)
  2522. return self.head(*indices)
  2523. def _get_symmetrized_forms(self):
  2524. """
  2525. Return a list giving all possible permutations of self that are allowed by its symmetries.
  2526. """
  2527. comp = self.component
  2528. gens = comp.symmetry.generators
  2529. rank = comp.rank
  2530. old_perms = None
  2531. new_perms = {self}
  2532. while new_perms != old_perms:
  2533. old_perms = new_perms.copy()
  2534. for tens in old_perms:
  2535. for gen in gens:
  2536. inds = tens.get_indices()
  2537. per = [gen.apply(i) for i in range(0,rank)]
  2538. sign = (-1)**(gen.apply(rank) - rank)
  2539. ind_map = dict(zip(inds, [inds[i] for i in per]))
  2540. new_perms.add( sign * tens._replace_indices(ind_map) )
  2541. return new_perms
  2542. def matches(self, expr, repl_dict=None, old=False):
  2543. expr = sympify(expr)
  2544. if repl_dict is None:
  2545. repl_dict = {}
  2546. else:
  2547. repl_dict = repl_dict.copy()
  2548. #simple checks
  2549. if self == expr:
  2550. return repl_dict
  2551. if not isinstance(expr, Tensor):
  2552. return None
  2553. if self.head != expr.head:
  2554. return None
  2555. #Now consider all index symmetries of expr, and see if any of them allow a match.
  2556. for new_expr in expr._get_symmetrized_forms():
  2557. m = self._matches(new_expr, repl_dict, old=old)
  2558. if m is not None:
  2559. repl_dict.update(m)
  2560. return repl_dict
  2561. return None
  2562. def _matches(self, expr, repl_dict=None, old=False):
  2563. """
  2564. This does not account for index symmetries of expr
  2565. """
  2566. expr = sympify(expr)
  2567. if repl_dict is None:
  2568. repl_dict = {}
  2569. else:
  2570. repl_dict = repl_dict.copy()
  2571. #simple checks
  2572. if self == expr:
  2573. return repl_dict
  2574. if not isinstance(expr, Tensor):
  2575. return None
  2576. if self.head != expr.head:
  2577. return None
  2578. s_indices = self.get_indices()
  2579. e_indices = expr.get_indices()
  2580. if len(s_indices) != len(e_indices):
  2581. return None
  2582. for i in range(len(s_indices)):
  2583. s_ind = s_indices[i]
  2584. m = s_ind.matches(e_indices[i])
  2585. if m is None:
  2586. return None
  2587. elif -s_ind in repl_dict.keys() and -repl_dict[-s_ind] != m[s_ind]:
  2588. return None
  2589. else:
  2590. repl_dict.update(m)
  2591. return repl_dict
  2592. def __call__(self, *indices):
  2593. deprecate_call()
  2594. free_args = self.free_args
  2595. indices = list(indices)
  2596. if [x.tensor_index_type for x in indices] != [x.tensor_index_type for x in free_args]:
  2597. raise ValueError('incompatible types')
  2598. if indices == free_args:
  2599. return self
  2600. t = self.substitute_indices(*list(zip(free_args, indices)))
  2601. # object is rebuilt in order to make sure that all contracted indices
  2602. # get recognized as dummies, but only if there are contracted indices.
  2603. if len({i if i.is_up else -i for i in indices}) != len(indices):
  2604. return t.func(*t.args)
  2605. return t
  2606. # TODO: put this into TensExpr?
  2607. def __iter__(self):
  2608. deprecate_data()
  2609. with ignore_warnings(SymPyDeprecationWarning):
  2610. return self.data.__iter__()
  2611. # TODO: put this into TensExpr?
  2612. def __getitem__(self, item):
  2613. deprecate_data()
  2614. with ignore_warnings(SymPyDeprecationWarning):
  2615. return self.data[item]
  2616. def _extract_data(self, replacement_dict):
  2617. from .array import Array
  2618. for k, v in replacement_dict.items():
  2619. if isinstance(k, Tensor) and k.args[0] == self.args[0]:
  2620. other = k
  2621. array = v
  2622. break
  2623. else:
  2624. raise ValueError("%s not found in %s" % (self, replacement_dict))
  2625. # TODO: inefficient, this should be done at root level only:
  2626. replacement_dict = {k: Array(v) for k, v in replacement_dict.items()}
  2627. array = Array(array)
  2628. dum1 = self.dum
  2629. dum2 = other.dum
  2630. if len(dum2) > 0:
  2631. for pair in dum2:
  2632. # allow `dum2` if the contained values are also in `dum1`.
  2633. if pair not in dum1:
  2634. raise NotImplementedError("%s with contractions is not implemented" % other)
  2635. # Remove elements in `dum2` from `dum1`:
  2636. dum1 = [pair for pair in dum1 if pair not in dum2]
  2637. if len(dum1) > 0:
  2638. indices1 = self.get_indices()
  2639. indices2 = other.get_indices()
  2640. repl = {}
  2641. for p1, p2 in dum1:
  2642. repl[indices2[p2]] = -indices2[p1]
  2643. for pos in (p1, p2):
  2644. if indices1[pos].is_up ^ indices2[pos].is_up:
  2645. metric = replacement_dict[indices1[pos].tensor_index_type]
  2646. if indices1[pos].is_up:
  2647. metric = _TensorDataLazyEvaluator.inverse_matrix(metric)
  2648. array = self._contract_and_permute_with_metric(metric, array, pos, len(indices2))
  2649. other = other.xreplace(repl).doit()
  2650. array = _TensorDataLazyEvaluator.data_contract_dum([array], dum1, len(indices2))
  2651. free_ind1 = self.get_free_indices()
  2652. free_ind2 = other.get_free_indices()
  2653. return self._match_indices_with_other_tensor(array, free_ind1, free_ind2, replacement_dict)
  2654. @property
  2655. def data(self):
  2656. deprecate_data()
  2657. with ignore_warnings(SymPyDeprecationWarning):
  2658. return _tensor_data_substitution_dict[self]
  2659. @data.setter
  2660. def data(self, data):
  2661. deprecate_data()
  2662. # TODO: check data compatibility with properties of tensor.
  2663. with ignore_warnings(SymPyDeprecationWarning):
  2664. _tensor_data_substitution_dict[self] = data
  2665. @data.deleter
  2666. def data(self):
  2667. deprecate_data()
  2668. with ignore_warnings(SymPyDeprecationWarning):
  2669. if self in _tensor_data_substitution_dict:
  2670. del _tensor_data_substitution_dict[self]
  2671. if self.metric in _tensor_data_substitution_dict:
  2672. del _tensor_data_substitution_dict[self.metric]
  2673. def _print(self):
  2674. indices = [str(ind) for ind in self.indices]
  2675. component = self.component
  2676. if component.rank > 0:
  2677. return ('%s(%s)' % (component.name, ', '.join(indices)))
  2678. else:
  2679. return ('%s' % component.name)
  2680. def equals(self, other):
  2681. if other == 0:
  2682. return self.coeff == 0
  2683. other = _sympify(other)
  2684. if not isinstance(other, TensExpr):
  2685. assert not self.components
  2686. return S.One == other
  2687. def _get_compar_comp(self):
  2688. t = self.canon_bp()
  2689. r = (t.coeff, tuple(t.components), \
  2690. tuple(sorted(t.free)), tuple(sorted(t.dum)))
  2691. return r
  2692. return _get_compar_comp(self) == _get_compar_comp(other)
  2693. def contract_metric(self, g):
  2694. # if metric is not the same, ignore this step:
  2695. if self.component != g:
  2696. return self
  2697. # in case there are free components, do not perform anything:
  2698. if len(self.free) != 0:
  2699. return self
  2700. #antisym = g.index_types[0].metric_antisym
  2701. if g.symmetry == TensorSymmetry.fully_symmetric(-2):
  2702. antisym = 1
  2703. elif g.symmetry == TensorSymmetry.fully_symmetric(2):
  2704. antisym = 0
  2705. elif g.symmetry == TensorSymmetry.no_symmetry(2):
  2706. antisym = None
  2707. else:
  2708. raise NotImplementedError
  2709. sign = S.One
  2710. typ = g.index_types[0]
  2711. if not antisym:
  2712. # g(i, -i)
  2713. sign = sign*typ.dim
  2714. else:
  2715. # g(i, -i)
  2716. sign = sign*typ.dim
  2717. dp0, dp1 = self.dum[0]
  2718. if dp0 < dp1:
  2719. # g(i, -i) = -D with antisymmetric metric
  2720. sign = -sign
  2721. return sign
  2722. def contract_delta(self, metric):
  2723. return self.contract_metric(metric)
  2724. def _eval_rewrite_as_Indexed(self, tens, indices, **kwargs):
  2725. from sympy.tensor.indexed import Indexed
  2726. # TODO: replace .args[0] with .name:
  2727. index_symbols = [i.args[0] for i in self.get_indices()]
  2728. expr = Indexed(tens.args[0], *index_symbols)
  2729. return self._check_add_Sum(expr, index_symbols)
  2730. def _eval_partial_derivative(self, s: Tensor) -> Expr:
  2731. if not isinstance(s, Tensor):
  2732. return S.Zero
  2733. else:
  2734. # @a_i/@a_k = delta_i^k
  2735. # @a_i/@a^k = g_ij delta^j_k
  2736. # @a^i/@a^k = delta^i_k
  2737. # @a^i/@a_k = g^ij delta_j^k
  2738. # TODO: if there is no metric present, the derivative should be zero?
  2739. if self.head != s.head:
  2740. return S.Zero
  2741. # if heads are the same, provide delta and/or metric products
  2742. # for every free index pair in the appropriate tensor
  2743. # assumed that the free indices are in proper order
  2744. # A contravariante index in the derivative becomes covariant
  2745. # after performing the derivative and vice versa
  2746. kronecker_delta_list = [1]
  2747. # not guarantee a correct index order
  2748. for (count, (iself, iother)) in enumerate(zip(self.get_free_indices(), s.get_free_indices())):
  2749. if iself.tensor_index_type != iother.tensor_index_type:
  2750. raise ValueError("index types not compatible")
  2751. else:
  2752. tensor_index_type = iself.tensor_index_type
  2753. tensor_metric = tensor_index_type.metric
  2754. dummy = TensorIndex("d_" + str(count), tensor_index_type,
  2755. is_up=iself.is_up)
  2756. if iself.is_up == iother.is_up:
  2757. kroneckerdelta = tensor_index_type.delta(iself, -iother)
  2758. else:
  2759. kroneckerdelta = (
  2760. TensMul(tensor_metric(iself, dummy),
  2761. tensor_index_type.delta(-dummy, -iother))
  2762. )
  2763. kronecker_delta_list.append(kroneckerdelta)
  2764. return TensMul.fromiter(kronecker_delta_list).doit(deep=False)
  2765. # doit necessary to rename dummy indices accordingly
  2766. class TensMul(TensExpr, AssocOp):
  2767. """
  2768. Product of tensors.
  2769. Parameters
  2770. ==========
  2771. coeff : SymPy coefficient of the tensor
  2772. args
  2773. Attributes
  2774. ==========
  2775. ``components`` : list of ``TensorHead`` of the component tensors
  2776. ``types`` : list of nonrepeated ``TensorIndexType``
  2777. ``free`` : list of ``(ind, ipos, icomp)``, see Notes
  2778. ``dum`` : list of ``(ipos1, ipos2, icomp1, icomp2)``, see Notes
  2779. ``ext_rank`` : rank of the tensor counting the dummy indices
  2780. ``rank`` : rank of the tensor
  2781. ``coeff`` : SymPy coefficient of the tensor
  2782. ``free_args`` : list of the free indices in sorted order
  2783. ``is_canon_bp`` : ``True`` if the tensor in in canonical form
  2784. Notes
  2785. =====
  2786. ``args[0]`` list of ``TensorHead`` of the component tensors.
  2787. ``args[1]`` list of ``(ind, ipos, icomp)``
  2788. where ``ind`` is a free index, ``ipos`` is the slot position
  2789. of ``ind`` in the ``icomp``-th component tensor.
  2790. ``args[2]`` list of tuples representing dummy indices.
  2791. ``(ipos1, ipos2, icomp1, icomp2)`` indicates that the contravariant
  2792. dummy index is the ``ipos1``-th slot position in the ``icomp1``-th
  2793. component tensor; the corresponding covariant index is
  2794. in the ``ipos2`` slot position in the ``icomp2``-th component tensor.
  2795. """
  2796. identity = S.One
  2797. _index_structure: _IndexStructure
  2798. def __new__(cls, *args, **kw_args):
  2799. is_canon_bp = kw_args.get('is_canon_bp', False)
  2800. args = list(map(_sympify, args))
  2801. """
  2802. If the internal dummy indices in one arg conflict with the free indices
  2803. of the remaining args, we need to rename those internal dummy indices.
  2804. """
  2805. free = [get_free_indices(arg) for arg in args]
  2806. free = set(itertools.chain(*free)) #flatten free
  2807. newargs = []
  2808. for arg in args:
  2809. dum_this = set(get_dummy_indices(arg))
  2810. dum_other = [get_dummy_indices(a) for a in newargs]
  2811. dum_other = set(itertools.chain(*dum_other)) #flatten dum_other
  2812. free_this = set(get_free_indices(arg))
  2813. if len(dum_this.intersection(free)) > 0:
  2814. exclude = free_this.union(free, dum_other)
  2815. newarg = TensMul._dedupe_indices(arg, exclude)
  2816. else:
  2817. newarg = arg
  2818. newargs.append(newarg)
  2819. args = newargs
  2820. # Flatten:
  2821. args = [i for arg in args for i in (arg.args if isinstance(arg, (TensMul, Mul)) else [arg])]
  2822. args, indices, free, dum = TensMul._tensMul_contract_indices(args, replace_indices=False)
  2823. # Data for indices:
  2824. index_types = [i.tensor_index_type for i in indices]
  2825. index_structure = _IndexStructure(free, dum, index_types, indices, canon_bp=is_canon_bp)
  2826. obj = TensExpr.__new__(cls, *args)
  2827. obj._indices = indices
  2828. obj._index_types = index_types.copy()
  2829. obj._index_structure = index_structure
  2830. obj._free = index_structure.free[:]
  2831. obj._dum = index_structure.dum[:]
  2832. obj._free_indices = {x[0] for x in obj.free}
  2833. obj._rank = len(obj.free)
  2834. obj._ext_rank = len(obj._index_structure.free) + 2*len(obj._index_structure.dum)
  2835. obj._coeff = S.One
  2836. obj._is_canon_bp = is_canon_bp
  2837. return obj
  2838. index_types = property(lambda self: self._index_types)
  2839. free = property(lambda self: self._free)
  2840. dum = property(lambda self: self._dum)
  2841. free_indices = property(lambda self: self._free_indices)
  2842. rank = property(lambda self: self._rank)
  2843. ext_rank = property(lambda self: self._ext_rank)
  2844. @staticmethod
  2845. def _indices_to_free_dum(args_indices):
  2846. free2pos1 = {}
  2847. free2pos2 = {}
  2848. dummy_data = []
  2849. indices = []
  2850. # Notation for positions (to better understand the code):
  2851. # `pos1`: position in the `args`.
  2852. # `pos2`: position in the indices.
  2853. # Example:
  2854. # A(i, j)*B(k, m, n)*C(p)
  2855. # `pos1` of `n` is 1 because it's in `B` (second `args` of TensMul).
  2856. # `pos2` of `n` is 4 because it's the fifth overall index.
  2857. # Counter for the index position wrt the whole expression:
  2858. pos2 = 0
  2859. for pos1, arg_indices in enumerate(args_indices):
  2860. for index in arg_indices:
  2861. if not isinstance(index, TensorIndex):
  2862. raise TypeError("expected TensorIndex")
  2863. if -index in free2pos1:
  2864. # Dummy index detected:
  2865. other_pos1 = free2pos1.pop(-index)
  2866. other_pos2 = free2pos2.pop(-index)
  2867. if index.is_up:
  2868. dummy_data.append((index, pos1, other_pos1, pos2, other_pos2))
  2869. else:
  2870. dummy_data.append((-index, other_pos1, pos1, other_pos2, pos2))
  2871. indices.append(index)
  2872. elif index in free2pos1:
  2873. raise ValueError("Repeated index: %s" % index)
  2874. else:
  2875. free2pos1[index] = pos1
  2876. free2pos2[index] = pos2
  2877. indices.append(index)
  2878. pos2 += 1
  2879. free = list(free2pos2.items())
  2880. free_names = [i.name for i in free2pos2.keys()]
  2881. dummy_data.sort(key=lambda x: x[3])
  2882. return indices, free, free_names, dummy_data
  2883. @staticmethod
  2884. def _dummy_data_to_dum(dummy_data):
  2885. return [(p2a, p2b) for (i, p1a, p1b, p2a, p2b) in dummy_data]
  2886. @staticmethod
  2887. def _tensMul_contract_indices(args, replace_indices=True):
  2888. replacements = [{} for _ in args]
  2889. #_index_order = all(_has_index_order(arg) for arg in args)
  2890. args_indices = [get_indices(arg) for arg in args]
  2891. indices, free, free_names, dummy_data = TensMul._indices_to_free_dum(args_indices)
  2892. cdt = defaultdict(int)
  2893. def dummy_name_gen(tensor_index_type):
  2894. nd = str(cdt[tensor_index_type])
  2895. cdt[tensor_index_type] += 1
  2896. return tensor_index_type.dummy_name + '_' + nd
  2897. if replace_indices:
  2898. for old_index, pos1cov, pos1contra, pos2cov, pos2contra in dummy_data:
  2899. index_type = old_index.tensor_index_type
  2900. while True:
  2901. dummy_name = dummy_name_gen(index_type)
  2902. if dummy_name not in free_names:
  2903. break
  2904. dummy = old_index.func(dummy_name, index_type, *old_index.args[2:])
  2905. replacements[pos1cov][old_index] = dummy
  2906. replacements[pos1contra][-old_index] = -dummy
  2907. indices[pos2cov] = dummy
  2908. indices[pos2contra] = -dummy
  2909. args = [
  2910. arg._replace_indices(repl) if isinstance(arg, TensExpr) else arg
  2911. for arg, repl in zip(args, replacements)]
  2912. """
  2913. The order of indices might've changed due to the replacements (e.g. if one of the args is a TensAdd, replacing an index can change the sort order of the terms, thus changing the order of indices returned by its get_indices() method).
  2914. To stay on the safe side, we calculate these quantities again.
  2915. """
  2916. args_indices = [get_indices(arg) for arg in args]
  2917. indices, free, free_names, dummy_data = TensMul._indices_to_free_dum(args_indices)
  2918. dum = TensMul._dummy_data_to_dum(dummy_data)
  2919. return args, indices, free, dum
  2920. @staticmethod
  2921. def _get_components_from_args(args):
  2922. """
  2923. Get a list of ``Tensor`` objects having the same ``TIDS`` if multiplied
  2924. by one another.
  2925. """
  2926. components = []
  2927. for arg in args:
  2928. if not isinstance(arg, TensExpr):
  2929. continue
  2930. if isinstance(arg, TensAdd):
  2931. continue
  2932. components.extend(arg.components)
  2933. return components
  2934. @staticmethod
  2935. def _rebuild_tensors_list(args, index_structure):
  2936. indices = index_structure.get_indices()
  2937. #tensors = [None for i in components] # pre-allocate list
  2938. ind_pos = 0
  2939. for i, arg in enumerate(args):
  2940. if not isinstance(arg, TensExpr):
  2941. continue
  2942. prev_pos = ind_pos
  2943. ind_pos += arg.ext_rank
  2944. args[i] = Tensor(arg.component, indices[prev_pos:ind_pos])
  2945. def doit(self, **hints):
  2946. is_canon_bp = self._is_canon_bp
  2947. deep = hints.get('deep', True)
  2948. if deep:
  2949. args = [arg.doit(**hints) for arg in self.args]
  2950. """
  2951. There may now be conflicts between dummy indices of different args
  2952. (each arg's doit method does not have any information about which
  2953. dummy indices are already used in the other args), so we
  2954. deduplicate them.
  2955. """
  2956. rule = dict(zip(self.args, args))
  2957. rule = self._dedupe_indices_in_rule(rule)
  2958. args = [rule[a] for a in self.args]
  2959. else:
  2960. args = self.args
  2961. args = [arg for arg in args if arg != self.identity]
  2962. # Extract non-tensor coefficients:
  2963. coeff = reduce(lambda a, b: a*b, [arg for arg in args if not isinstance(arg, TensExpr)], S.One)
  2964. args = [arg for arg in args if isinstance(arg, TensExpr)]
  2965. if len(args) == 0:
  2966. return coeff
  2967. if coeff != self.identity:
  2968. args = [coeff] + args
  2969. if coeff == 0:
  2970. return S.Zero
  2971. if len(args) == 1:
  2972. return args[0]
  2973. args, indices, free, dum = TensMul._tensMul_contract_indices(args)
  2974. # Data for indices:
  2975. index_types = [i.tensor_index_type for i in indices]
  2976. index_structure = _IndexStructure(free, dum, index_types, indices, canon_bp=is_canon_bp)
  2977. obj = self.func(*args)
  2978. obj._index_types = index_types
  2979. obj._index_structure = index_structure
  2980. obj._ext_rank = len(obj._index_structure.free) + 2*len(obj._index_structure.dum)
  2981. obj._coeff = coeff
  2982. obj._is_canon_bp = is_canon_bp
  2983. return obj
  2984. # TODO: this method should be private
  2985. # TODO: should this method be renamed _from_components_free_dum ?
  2986. @staticmethod
  2987. def from_data(coeff, components, free, dum, **kw_args):
  2988. return TensMul(coeff, *TensMul._get_tensors_from_components_free_dum(components, free, dum), **kw_args).doit(deep=False)
  2989. @staticmethod
  2990. def _get_tensors_from_components_free_dum(components, free, dum):
  2991. """
  2992. Get a list of ``Tensor`` objects by distributing ``free`` and ``dum`` indices on the ``components``.
  2993. """
  2994. index_structure = _IndexStructure.from_components_free_dum(components, free, dum)
  2995. indices = index_structure.get_indices()
  2996. tensors = [None for i in components] # pre-allocate list
  2997. # distribute indices on components to build a list of tensors:
  2998. ind_pos = 0
  2999. for i, component in enumerate(components):
  3000. prev_pos = ind_pos
  3001. ind_pos += component.rank
  3002. tensors[i] = Tensor(component, indices[prev_pos:ind_pos])
  3003. return tensors
  3004. def _get_free_indices_set(self):
  3005. return {i[0] for i in self.free}
  3006. def _get_dummy_indices_set(self):
  3007. dummy_pos = set(itertools.chain(*self.dum))
  3008. return {idx for i, idx in enumerate(self._index_structure.get_indices()) if i in dummy_pos}
  3009. def _get_position_offset_for_indices(self):
  3010. arg_offset = [None for i in range(self.ext_rank)]
  3011. counter = 0
  3012. for arg in self.args:
  3013. if not isinstance(arg, TensExpr):
  3014. continue
  3015. for j in range(arg.ext_rank):
  3016. arg_offset[j + counter] = counter
  3017. counter += arg.ext_rank
  3018. return arg_offset
  3019. @property
  3020. def free_args(self):
  3021. return sorted([x[0] for x in self.free])
  3022. @property
  3023. def components(self):
  3024. return self._get_components_from_args(self.args)
  3025. @property
  3026. def free_in_args(self):
  3027. arg_offset = self._get_position_offset_for_indices()
  3028. argpos = self._get_indices_to_args_pos()
  3029. return [(ind, pos-arg_offset[pos], argpos[pos]) for (ind, pos) in self.free]
  3030. @property
  3031. def coeff(self):
  3032. # return Mul.fromiter([c for c in self.args if not isinstance(c, TensExpr)])
  3033. return self._coeff
  3034. @property
  3035. def nocoeff(self):
  3036. return self.func(*self.args, 1/self.coeff).doit(deep=False)
  3037. @property
  3038. def dum_in_args(self):
  3039. arg_offset = self._get_position_offset_for_indices()
  3040. argpos = self._get_indices_to_args_pos()
  3041. return [(p1-arg_offset[p1], p2-arg_offset[p2], argpos[p1], argpos[p2]) for p1, p2 in self.dum]
  3042. def equals(self, other):
  3043. if other == 0:
  3044. return self.coeff == 0
  3045. other = _sympify(other)
  3046. if not isinstance(other, TensExpr):
  3047. assert not self.components
  3048. return self.coeff == other
  3049. return self.canon_bp() == other.canon_bp()
  3050. def get_indices(self):
  3051. """
  3052. Returns the list of indices of the tensor.
  3053. Explanation
  3054. ===========
  3055. The indices are listed in the order in which they appear in the
  3056. component tensors.
  3057. The dummy indices are given a name which does not collide with
  3058. the names of the free indices.
  3059. Examples
  3060. ========
  3061. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads
  3062. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  3063. >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz)
  3064. >>> g = Lorentz.metric
  3065. >>> p, q = tensor_heads('p,q', [Lorentz])
  3066. >>> t = p(m1)*g(m0,m2)
  3067. >>> t.get_indices()
  3068. [m1, m0, m2]
  3069. >>> t2 = p(m1)*g(-m1, m2)
  3070. >>> t2.get_indices()
  3071. [L_0, -L_0, m2]
  3072. """
  3073. return self._indices
  3074. def get_free_indices(self) -> list[TensorIndex]:
  3075. """
  3076. Returns the list of free indices of the tensor.
  3077. Explanation
  3078. ===========
  3079. The indices are listed in the order in which they appear in the
  3080. component tensors.
  3081. Examples
  3082. ========
  3083. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads
  3084. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  3085. >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz)
  3086. >>> g = Lorentz.metric
  3087. >>> p, q = tensor_heads('p,q', [Lorentz])
  3088. >>> t = p(m1)*g(m0,m2)
  3089. >>> t.get_free_indices()
  3090. [m1, m0, m2]
  3091. >>> t2 = p(m1)*g(-m1, m2)
  3092. >>> t2.get_free_indices()
  3093. [m2]
  3094. """
  3095. return self._index_structure.get_free_indices()
  3096. def _replace_indices(self, repl: dict[TensorIndex, TensorIndex]) -> TensExpr:
  3097. return self.func(*[arg._replace_indices(repl) if isinstance(arg, TensExpr) else arg for arg in self.args])
  3098. def split(self):
  3099. """
  3100. Returns a list of tensors, whose product is ``self``.
  3101. Explanation
  3102. ===========
  3103. Dummy indices contracted among different tensor components
  3104. become free indices with the same name as the one used to
  3105. represent the dummy indices.
  3106. Examples
  3107. ========
  3108. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads, TensorSymmetry
  3109. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  3110. >>> a, b, c, d = tensor_indices('a,b,c,d', Lorentz)
  3111. >>> A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
  3112. >>> t = A(a,b)*B(-b,c)
  3113. >>> t
  3114. A(a, L_0)*B(-L_0, c)
  3115. >>> t.split()
  3116. [A(a, L_0), B(-L_0, c)]
  3117. """
  3118. if self.args == ():
  3119. return [self]
  3120. splitp = []
  3121. res = 1
  3122. for arg in self.args:
  3123. if isinstance(arg, Tensor):
  3124. splitp.append(res*arg)
  3125. res = 1
  3126. else:
  3127. res *= arg
  3128. return splitp
  3129. def _eval_expand_mul(self, **hints):
  3130. args1 = [arg.args if isinstance(arg, (Add, TensAdd)) else (arg,) for arg in self.args]
  3131. return TensAdd(*[
  3132. TensMul(*i).doit(deep=False) for i in itertools.product(*args1)]
  3133. )
  3134. def __neg__(self):
  3135. return TensMul(S.NegativeOne, self, is_canon_bp=self._is_canon_bp).doit(deep=False)
  3136. def __getitem__(self, item):
  3137. deprecate_data()
  3138. with ignore_warnings(SymPyDeprecationWarning):
  3139. return self.data[item]
  3140. def _get_args_for_traditional_printer(self):
  3141. args = list(self.args)
  3142. if self.coeff.could_extract_minus_sign():
  3143. # expressions like "-A(a)"
  3144. sign = "-"
  3145. if args[0] == S.NegativeOne:
  3146. args = args[1:]
  3147. else:
  3148. args[0] = -args[0]
  3149. else:
  3150. sign = ""
  3151. return sign, args
  3152. def _sort_args_for_sorted_components(self):
  3153. """
  3154. Returns the ``args`` sorted according to the components commutation
  3155. properties.
  3156. Explanation
  3157. ===========
  3158. The sorting is done taking into account the commutation group
  3159. of the component tensors.
  3160. """
  3161. cv = [arg for arg in self.args if isinstance(arg, TensExpr)]
  3162. sign = 1
  3163. n = len(cv) - 1
  3164. for i in range(n):
  3165. for j in range(n, i, -1):
  3166. c = cv[j-1].commutes_with(cv[j])
  3167. # if `c` is `None`, it does neither commute nor anticommute, skip:
  3168. if c not in (0, 1):
  3169. continue
  3170. typ1 = sorted(set(cv[j-1].component.index_types), key=lambda x: x.name)
  3171. typ2 = sorted(set(cv[j].component.index_types), key=lambda x: x.name)
  3172. if (typ1, cv[j-1].component.name) > (typ2, cv[j].component.name):
  3173. cv[j-1], cv[j] = cv[j], cv[j-1]
  3174. # if `c` is 1, the anticommute, so change sign:
  3175. if c:
  3176. sign = -sign
  3177. coeff = sign * self.coeff
  3178. if coeff != 1:
  3179. return [coeff] + cv
  3180. return cv
  3181. def sorted_components(self):
  3182. """
  3183. Returns a tensor product with sorted components.
  3184. """
  3185. return TensMul(*self._sort_args_for_sorted_components()).doit(deep=False)
  3186. def perm2tensor(self, g, is_canon_bp=False):
  3187. """
  3188. Returns the tensor corresponding to the permutation ``g``
  3189. For further details, see the method in ``TIDS`` with the same name.
  3190. """
  3191. return perm2tensor(self, g, is_canon_bp=is_canon_bp)
  3192. def canon_bp(self):
  3193. """
  3194. Canonicalize using the Butler-Portugal algorithm for canonicalization
  3195. under monoterm symmetries.
  3196. Examples
  3197. ========
  3198. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, TensorSymmetry
  3199. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  3200. >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz)
  3201. >>> A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2))
  3202. >>> t = A(m0,-m1)*A(m1,-m0)
  3203. >>> t.canon_bp()
  3204. -A(L_0, L_1)*A(-L_0, -L_1)
  3205. >>> t = A(m0,-m1)*A(m1,-m2)*A(m2,-m0)
  3206. >>> t.canon_bp()
  3207. 0
  3208. """
  3209. if self._is_canon_bp:
  3210. return self
  3211. expr = self.expand()
  3212. if isinstance(expr, TensAdd):
  3213. return expr.canon_bp()
  3214. if not expr.components:
  3215. return expr
  3216. expr = expr.doit(deep=False) #make sure self.coeff is populated correctly
  3217. t = expr.sorted_components()
  3218. g, dummies, msym = t._index_structure.indices_canon_args()
  3219. v = components_canon_args(t.components)
  3220. can = canonicalize(g, dummies, msym, *v)
  3221. if can == 0:
  3222. return S.Zero
  3223. tmul = t.perm2tensor(can, True)
  3224. return tmul
  3225. def contract_delta(self, delta):
  3226. t = self.contract_metric(delta)
  3227. return t
  3228. def _get_indices_to_args_pos(self):
  3229. """
  3230. Get a dict mapping the index position to TensMul's argument number.
  3231. """
  3232. pos_map = {}
  3233. pos_counter = 0
  3234. for arg_i, arg in enumerate(self.args):
  3235. if not isinstance(arg, TensExpr):
  3236. continue
  3237. assert isinstance(arg, Tensor)
  3238. for i in range(arg.ext_rank):
  3239. pos_map[pos_counter] = arg_i
  3240. pos_counter += 1
  3241. return pos_map
  3242. def contract_metric(self, g):
  3243. """
  3244. Raise or lower indices with the metric ``g``.
  3245. Parameters
  3246. ==========
  3247. g : metric
  3248. Notes
  3249. =====
  3250. See the ``TensorIndexType`` docstring for the contraction conventions.
  3251. Examples
  3252. ========
  3253. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads
  3254. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  3255. >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz)
  3256. >>> g = Lorentz.metric
  3257. >>> p, q = tensor_heads('p,q', [Lorentz])
  3258. >>> t = p(m0)*q(m1)*g(-m0, -m1)
  3259. >>> t.canon_bp()
  3260. metric(L_0, L_1)*p(-L_0)*q(-L_1)
  3261. >>> t.contract_metric(g).canon_bp()
  3262. p(L_0)*q(-L_0)
  3263. """
  3264. expr = self.expand().doit(deep=False)
  3265. if self != expr:
  3266. expr = canon_bp(expr)
  3267. return contract_metric(expr, g)
  3268. pos_map = self._get_indices_to_args_pos()
  3269. args = list(self.args)
  3270. #antisym = g.index_types[0].metric_antisym
  3271. if g.symmetry == TensorSymmetry.fully_symmetric(-2):
  3272. antisym = 1
  3273. elif g.symmetry == TensorSymmetry.fully_symmetric(2):
  3274. antisym = 0
  3275. elif g.symmetry == TensorSymmetry.no_symmetry(2):
  3276. antisym = None
  3277. else:
  3278. raise NotImplementedError
  3279. # list of positions of the metric ``g`` inside ``args``
  3280. gpos = [i for i, x in enumerate(self.args) if isinstance(x, Tensor) and x.component == g]
  3281. if not gpos:
  3282. return self
  3283. # Sign is either 1 or -1, to correct the sign after metric contraction
  3284. # (for spinor indices).
  3285. sign = 1
  3286. dum = self.dum[:]
  3287. free = self.free[:]
  3288. elim = set()
  3289. for gposx in gpos:
  3290. if gposx in elim:
  3291. continue
  3292. free1 = [x for x in free if pos_map[x[1]] == gposx]
  3293. dum1 = [x for x in dum if pos_map[x[0]] == gposx or pos_map[x[1]] == gposx]
  3294. if not dum1:
  3295. continue
  3296. elim.add(gposx)
  3297. # subs with the multiplication neutral element, that is, remove it:
  3298. args[gposx] = 1
  3299. if len(dum1) == 2:
  3300. if not antisym:
  3301. dum10, dum11 = dum1
  3302. if pos_map[dum10[1]] == gposx:
  3303. # the index with pos p0 contravariant
  3304. p0 = dum10[0]
  3305. else:
  3306. # the index with pos p0 is covariant
  3307. p0 = dum10[1]
  3308. if pos_map[dum11[1]] == gposx:
  3309. # the index with pos p1 is contravariant
  3310. p1 = dum11[0]
  3311. else:
  3312. # the index with pos p1 is covariant
  3313. p1 = dum11[1]
  3314. dum.append((p0, p1))
  3315. else:
  3316. dum10, dum11 = dum1
  3317. # change the sign to bring the indices of the metric to contravariant
  3318. # form; change the sign if dum10 has the metric index in position 0
  3319. if pos_map[dum10[1]] == gposx:
  3320. # the index with pos p0 is contravariant
  3321. p0 = dum10[0]
  3322. if dum10[1] == 1:
  3323. sign = -sign
  3324. else:
  3325. # the index with pos p0 is covariant
  3326. p0 = dum10[1]
  3327. if dum10[0] == 0:
  3328. sign = -sign
  3329. if pos_map[dum11[1]] == gposx:
  3330. # the index with pos p1 is contravariant
  3331. p1 = dum11[0]
  3332. sign = -sign
  3333. else:
  3334. # the index with pos p1 is covariant
  3335. p1 = dum11[1]
  3336. dum.append((p0, p1))
  3337. elif len(dum1) == 1:
  3338. if not antisym:
  3339. dp0, dp1 = dum1[0]
  3340. if pos_map[dp0] == pos_map[dp1]:
  3341. # g(i, -i)
  3342. typ = g.index_types[0]
  3343. sign = sign*typ.dim
  3344. else:
  3345. # g(i0, i1)*p(-i1)
  3346. if pos_map[dp0] == gposx:
  3347. p1 = dp1
  3348. else:
  3349. p1 = dp0
  3350. ind, p = free1[0]
  3351. free.append((ind, p1))
  3352. else:
  3353. dp0, dp1 = dum1[0]
  3354. if pos_map[dp0] == pos_map[dp1]:
  3355. # g(i, -i)
  3356. typ = g.index_types[0]
  3357. sign = sign*typ.dim
  3358. if dp0 < dp1:
  3359. # g(i, -i) = -D with antisymmetric metric
  3360. sign = -sign
  3361. else:
  3362. # g(i0, i1)*p(-i1)
  3363. if pos_map[dp0] == gposx:
  3364. p1 = dp1
  3365. if dp0 == 0:
  3366. sign = -sign
  3367. else:
  3368. p1 = dp0
  3369. ind, p = free1[0]
  3370. free.append((ind, p1))
  3371. dum = [x for x in dum if x not in dum1]
  3372. free = [x for x in free if x not in free1]
  3373. # shift positions:
  3374. shift = 0
  3375. shifts = [0]*len(args)
  3376. for i in range(len(args)):
  3377. if i in elim:
  3378. shift += 2
  3379. continue
  3380. shifts[i] = shift
  3381. free = [(ind, p - shifts[pos_map[p]]) for (ind, p) in free if pos_map[p] not in elim]
  3382. dum = [(p0 - shifts[pos_map[p0]], p1 - shifts[pos_map[p1]]) for p0, p1 in dum if pos_map[p0] not in elim and pos_map[p1] not in elim]
  3383. res = ( sign*TensMul(*args) ).doit(deep=False)
  3384. if not isinstance(res, TensExpr):
  3385. return res
  3386. im = _IndexStructure.from_components_free_dum(res.components, free, dum)
  3387. return res._set_new_index_structure(im)
  3388. def _set_new_index_structure(self, im, is_canon_bp=False):
  3389. indices = im.get_indices()
  3390. return self._set_indices(*indices, is_canon_bp=is_canon_bp)
  3391. def _set_indices(self, *indices, is_canon_bp=False, **kw_args):
  3392. if len(indices) != self.ext_rank:
  3393. raise ValueError("indices length mismatch")
  3394. args = list(self.args)
  3395. pos = 0
  3396. for i, arg in enumerate(args):
  3397. if not isinstance(arg, TensExpr):
  3398. continue
  3399. assert isinstance(arg, Tensor)
  3400. ext_rank = arg.ext_rank
  3401. args[i] = arg._set_indices(*indices[pos:pos+ext_rank])
  3402. pos += ext_rank
  3403. return TensMul(*args, is_canon_bp=is_canon_bp).doit(deep=False)
  3404. @staticmethod
  3405. def _index_replacement_for_contract_metric(args, free, dum):
  3406. for arg in args:
  3407. if not isinstance(arg, TensExpr):
  3408. continue
  3409. assert isinstance(arg, Tensor)
  3410. def substitute_indices(self, *index_tuples):
  3411. new_args = []
  3412. for arg in self.args:
  3413. if isinstance(arg, TensExpr):
  3414. arg = arg.substitute_indices(*index_tuples)
  3415. new_args.append(arg)
  3416. return TensMul(*new_args).doit(deep=False)
  3417. def __call__(self, *indices):
  3418. deprecate_call()
  3419. free_args = self.free_args
  3420. indices = list(indices)
  3421. if [x.tensor_index_type for x in indices] != [x.tensor_index_type for x in free_args]:
  3422. raise ValueError('incompatible types')
  3423. if indices == free_args:
  3424. return self
  3425. t = self.substitute_indices(*list(zip(free_args, indices)))
  3426. # object is rebuilt in order to make sure that all contracted indices
  3427. # get recognized as dummies, but only if there are contracted indices.
  3428. if len({i if i.is_up else -i for i in indices}) != len(indices):
  3429. return t.func(*t.args)
  3430. return t
  3431. def _extract_data(self, replacement_dict):
  3432. args_indices, arrays = zip(*[arg._extract_data(replacement_dict) for arg in self.args if isinstance(arg, TensExpr)])
  3433. coeff = reduce(operator.mul, [a for a in self.args if not isinstance(a, TensExpr)], S.One)
  3434. indices, free, free_names, dummy_data = TensMul._indices_to_free_dum(args_indices)
  3435. dum = TensMul._dummy_data_to_dum(dummy_data)
  3436. ext_rank = self.ext_rank
  3437. free.sort(key=lambda x: x[1])
  3438. free_indices = [i[0] for i in free]
  3439. return free_indices, coeff*_TensorDataLazyEvaluator.data_contract_dum(arrays, dum, ext_rank)
  3440. @property
  3441. def data(self):
  3442. deprecate_data()
  3443. with ignore_warnings(SymPyDeprecationWarning):
  3444. dat = _tensor_data_substitution_dict[self.expand()]
  3445. return dat
  3446. @data.setter
  3447. def data(self, data):
  3448. deprecate_data()
  3449. raise ValueError("Not possible to set component data to a tensor expression")
  3450. @data.deleter
  3451. def data(self):
  3452. deprecate_data()
  3453. raise ValueError("Not possible to delete component data to a tensor expression")
  3454. def __iter__(self):
  3455. deprecate_data()
  3456. with ignore_warnings(SymPyDeprecationWarning):
  3457. if self.data is None:
  3458. raise ValueError("No iteration on abstract tensors")
  3459. return self.data.__iter__()
  3460. @staticmethod
  3461. def _dedupe_indices(new, exclude):
  3462. """
  3463. exclude: set
  3464. new: TensExpr
  3465. If ``new`` has any dummy indices that are in ``exclude``, return a version
  3466. of new with those indices replaced. If no replacements are needed,
  3467. return None
  3468. """
  3469. exclude = set(exclude)
  3470. dums_new = set(get_dummy_indices(new))
  3471. free_new = set(get_free_indices(new))
  3472. conflicts = dums_new.intersection(exclude)
  3473. if len(conflicts) == 0:
  3474. return None
  3475. """
  3476. ``exclude_for_gen`` is to be passed to ``_IndexStructure._get_generator_for_dummy_indices()``.
  3477. Since the latter does not use the index position for anything, we just
  3478. set it as ``None`` here.
  3479. """
  3480. exclude.update(dums_new)
  3481. exclude.update(free_new)
  3482. exclude_for_gen = [(i, None) for i in exclude]
  3483. gen = _IndexStructure._get_generator_for_dummy_indices(exclude_for_gen)
  3484. repl = {}
  3485. for d in conflicts:
  3486. if -d in repl.keys():
  3487. continue
  3488. newname = gen(d.tensor_index_type)
  3489. new_d = d.func(newname, *d.args[1:])
  3490. repl[d] = new_d
  3491. repl[-d] = -new_d
  3492. if len(repl) == 0:
  3493. return None
  3494. new_renamed = new._replace_indices(repl)
  3495. return new_renamed
  3496. def _dedupe_indices_in_rule(self, rule):
  3497. """
  3498. rule: dict
  3499. This applies TensMul._dedupe_indices on all values of rule.
  3500. """
  3501. index_rules = {k:v for k,v in rule.items() if isinstance(k, TensorIndex)}
  3502. other_rules = {k:v for k,v in rule.items() if k not in index_rules.keys()}
  3503. exclude = set(self.get_indices())
  3504. newrule = {}
  3505. newrule.update(index_rules)
  3506. exclude.update(index_rules.keys())
  3507. exclude.update(index_rules.values())
  3508. for old, new in other_rules.items():
  3509. new_renamed = TensMul._dedupe_indices(new, exclude)
  3510. if old == new or new_renamed is None:
  3511. newrule[old] = new
  3512. else:
  3513. newrule[old] = new_renamed
  3514. exclude.update(get_indices(new_renamed))
  3515. return newrule
  3516. def _eval_subs(self, old, new):
  3517. """
  3518. If new is an index which is already present in self as a dummy, the dummies in self should be renamed.
  3519. """
  3520. if not isinstance(new, TensorIndex):
  3521. return None
  3522. exclude = {new}
  3523. self_renamed = self._dedupe_indices(self, exclude)
  3524. if self_renamed is None:
  3525. return None
  3526. else:
  3527. return self_renamed._subs(old, new).doit(deep=False)
  3528. def _eval_rewrite_as_Indexed(self, *args, **kwargs):
  3529. from sympy.concrete.summations import Sum
  3530. index_symbols = [i.args[0] for i in self.get_indices()]
  3531. args = [arg.args[0] if isinstance(arg, Sum) else arg for arg in args]
  3532. expr = Mul.fromiter(args)
  3533. return self._check_add_Sum(expr, index_symbols)
  3534. def _eval_partial_derivative(self, s):
  3535. # Evaluation like Mul
  3536. terms = []
  3537. for i, arg in enumerate(self.args):
  3538. # checking whether some tensor instance is differentiated
  3539. # or some other thing is necessary, but ugly
  3540. if isinstance(arg, TensExpr):
  3541. d = arg._eval_partial_derivative(s)
  3542. else:
  3543. # do not call diff is s is no symbol
  3544. if s._diff_wrt:
  3545. d = arg._eval_derivative(s)
  3546. else:
  3547. d = S.Zero
  3548. if d:
  3549. terms.append(TensMul.fromiter(self.args[:i] + (d,) + self.args[i + 1:]).doit(deep=False))
  3550. return TensAdd.fromiter(terms).doit(deep=False)
  3551. def _matches_commutative(self, expr, repl_dict=None, old=False):
  3552. """
  3553. Match assuming all tensors commute. But note that we are not assuming anything about their symmetry under index permutations.
  3554. """
  3555. #Take care of the various possible types for expr.
  3556. if not isinstance(expr, TensMul):
  3557. if isinstance(expr, (TensExpr, Expr)):
  3558. expr = TensMul(expr)
  3559. else:
  3560. return None
  3561. #The code that follows assumes expr is a TensMul
  3562. if repl_dict is None:
  3563. repl_dict = {}
  3564. else:
  3565. repl_dict = repl_dict.copy()
  3566. #Make sure that none of the dummy indices in self, expr conflict with the values already present in repl_dict. This may happen due to automatic index relabelling when rem_query and rem_expr are formed later on in this function (it calls itself recursively).
  3567. indices = [k for k in repl_dict.values() if isinstance(k ,TensorIndex)]
  3568. def dedupe(expr):
  3569. renamed = TensMul._dedupe_indices(expr, indices)
  3570. if renamed is not None:
  3571. return renamed
  3572. else:
  3573. return expr
  3574. self = dedupe(self)
  3575. expr = dedupe(expr)
  3576. #Find the non-tensor part of expr. This need not be the same as expr.coeff when expr.doit() has not been called.
  3577. expr_coeff = reduce(lambda a, b: a*b, [arg for arg in expr.args if not isinstance(arg, TensExpr)], S.One)
  3578. # handle simple patterns
  3579. if self == expr:
  3580. return repl_dict
  3581. if len(_get_wilds(self)) == 0:
  3582. return self._matches_simple(expr, repl_dict, old)
  3583. def siftkey(arg):
  3584. if isinstance(arg, WildTensor):
  3585. return "WildTensor"
  3586. elif isinstance(arg, (Tensor, TensExpr)):
  3587. return "Tensor"
  3588. else:
  3589. return "coeff"
  3590. query_sifted = sift(self.args, siftkey)
  3591. expr_sifted = sift(expr.args, siftkey)
  3592. #Sanity checks
  3593. if "coeff" in query_sifted.keys():
  3594. if TensMul(*query_sifted["coeff"]).doit(deep=False) != self.coeff:
  3595. raise NotImplementedError(f"Found something that we do not know to handle: {query_sifted['coeff']}")
  3596. if "coeff" in expr_sifted.keys():
  3597. if TensMul(*expr_sifted["coeff"]).doit(deep=False) != expr_coeff:
  3598. raise NotImplementedError(f"Found something that we do not know to handle: {expr_sifted['coeff']}")
  3599. query_tens_heads = {tuple(getattr(x, "components", [])) for x in query_sifted["Tensor"]} #We use getattr because, e.g. TensAdd does not have the 'components' attribute.
  3600. expr_tens_heads = {tuple(getattr(x, "components", [])) for x in expr_sifted["Tensor"]}
  3601. if not query_tens_heads.issubset(expr_tens_heads):
  3602. #Some tensorheads in self are not present in the expr
  3603. return None
  3604. #Try to match all non-wild tensors of self with tensors that compose expr
  3605. if len(query_sifted["Tensor"]) > 0:
  3606. q_tensor = query_sifted["Tensor"][0]
  3607. """
  3608. We need to iterate over all possible symmetrized forms of q_tensor since the matches given by some of them may map dummy indices to free indices; the information about which indices are dummy/free will only be available later, when we are doing rem_q.matches(rem_e)
  3609. """
  3610. for q_tens in q_tensor._get_symmetrized_forms():
  3611. for e in expr_sifted["Tensor"]:
  3612. if isinstance(q_tens, TensMul):
  3613. #q_tensor got a minus sign due to this permutation.
  3614. sign = -1
  3615. else:
  3616. sign = 1
  3617. """
  3618. _matches is used here since we are already iterating over index permutations of q_tensor. Also note that the sign is removed from q_tensor, and will later be put into rem_q.
  3619. """
  3620. m = (sign*q_tens)._matches(e)
  3621. if m is None:
  3622. continue
  3623. rem_query = self.func(sign, *[a for a in self.args if a != q_tensor]).doit(deep=False)
  3624. rem_expr = expr.func(*[a for a in expr.args if a != e]).doit(deep=False)
  3625. tmp_repl = {}
  3626. tmp_repl.update(repl_dict)
  3627. tmp_repl.update(m)
  3628. rem_m = rem_query.matches(rem_expr, repl_dict=tmp_repl)
  3629. if rem_m is not None:
  3630. #Check that contracted indices are not mapped to different indices.
  3631. internally_consistent = True
  3632. for k in rem_m.keys():
  3633. if isinstance(k,TensorIndex):
  3634. if -k in rem_m.keys() and rem_m[-k] != -rem_m[k]:
  3635. internally_consistent = False
  3636. break
  3637. if internally_consistent:
  3638. repl_dict.update(rem_m)
  3639. return repl_dict
  3640. return None
  3641. #Try to match WildTensor instances which have indices
  3642. matched_e_tensors = []
  3643. remaining_e_tensors = expr_sifted["Tensor"]
  3644. indexless_wilds, wilds = sift(query_sifted["WildTensor"], lambda x: len(x.get_free_indices()) == 0, binary=True)
  3645. for w in wilds:
  3646. free_this_wild = set(w.get_free_indices())
  3647. tensors_to_try = []
  3648. for t in remaining_e_tensors:
  3649. free = t.get_free_indices()
  3650. shares_indices_with_wild = True
  3651. for i in free:
  3652. if all(j.matches(i) is None for j in free_this_wild):
  3653. #The index i matches none of the indices in free_this_wild
  3654. shares_indices_with_wild = False
  3655. if shares_indices_with_wild:
  3656. tensors_to_try.append(t)
  3657. m = w.matches(TensMul(*tensors_to_try).doit(deep=False) )
  3658. if m is None:
  3659. return None
  3660. else:
  3661. for tens in tensors_to_try:
  3662. matched_e_tensors.append(tens)
  3663. repl_dict.update(m)
  3664. #Try to match indexless WildTensor instances
  3665. remaining_e_tensors = [t for t in expr_sifted["Tensor"] if t not in matched_e_tensors]
  3666. if len(indexless_wilds) > 0:
  3667. #If there are any remaining tensors, match them with the indexless WildTensor
  3668. m = indexless_wilds[0].matches( TensMul(1,*remaining_e_tensors).doit(deep=False) )
  3669. if m is None:
  3670. return None
  3671. else:
  3672. repl_dict.update(m)
  3673. elif len(remaining_e_tensors) > 0:
  3674. return None
  3675. #Try to match the non-tensorial coefficient
  3676. m = self.coeff.matches(expr_coeff, old=old)
  3677. if m is None:
  3678. return None
  3679. else:
  3680. repl_dict.update(m)
  3681. return repl_dict
  3682. def matches(self, expr, repl_dict=None, old=False):
  3683. expr = sympify(expr)
  3684. if repl_dict is None:
  3685. repl_dict = {}
  3686. else:
  3687. repl_dict = repl_dict.copy()
  3688. commute = all(arg.component.comm == 0 for arg in expr.args if isinstance(arg, Tensor))
  3689. if commute:
  3690. return self._matches_commutative(expr, repl_dict, old)
  3691. else:
  3692. raise NotImplementedError("Tensor matching not implemented for non-commuting tensors")
  3693. class TensorElement(TensExpr):
  3694. """
  3695. Tensor with evaluated components.
  3696. Examples
  3697. ========
  3698. >>> from sympy.tensor.tensor import TensorIndexType, TensorHead, TensorSymmetry
  3699. >>> from sympy import symbols
  3700. >>> L = TensorIndexType("L")
  3701. >>> i, j, k = symbols("i j k")
  3702. >>> A = TensorHead("A", [L, L], TensorSymmetry.fully_symmetric(2))
  3703. >>> A(i, j).get_free_indices()
  3704. [i, j]
  3705. If we want to set component ``i`` to a specific value, use the
  3706. ``TensorElement`` class:
  3707. >>> from sympy.tensor.tensor import TensorElement
  3708. >>> te = TensorElement(A(i, j), {i: 2})
  3709. As index ``i`` has been accessed (``{i: 2}`` is the evaluation of its 3rd
  3710. element), the free indices will only contain ``j``:
  3711. >>> te.get_free_indices()
  3712. [j]
  3713. """
  3714. def __new__(cls, expr, index_map):
  3715. if not isinstance(expr, Tensor):
  3716. # remap
  3717. if not isinstance(expr, TensExpr):
  3718. raise TypeError("%s is not a tensor expression" % expr)
  3719. return expr.func(*[TensorElement(arg, index_map) for arg in expr.args])
  3720. expr_free_indices = expr.get_free_indices()
  3721. name_translation = {i.args[0]: i for i in expr_free_indices}
  3722. index_map = {name_translation.get(index, index): value for index, value in index_map.items()}
  3723. index_map = {index: value for index, value in index_map.items() if index in expr_free_indices}
  3724. if len(index_map) == 0:
  3725. return expr
  3726. free_indices = [i for i in expr_free_indices if i not in index_map.keys()]
  3727. index_map = Dict(index_map)
  3728. obj = TensExpr.__new__(cls, expr, index_map)
  3729. obj._free_indices = free_indices
  3730. return obj
  3731. @property
  3732. def free(self):
  3733. return [(index, i) for i, index in enumerate(self.get_free_indices())]
  3734. @property
  3735. def dum(self):
  3736. # TODO: inherit dummies from expr
  3737. return []
  3738. @property
  3739. def expr(self):
  3740. return self._args[0]
  3741. @property
  3742. def index_map(self):
  3743. return self._args[1]
  3744. @property
  3745. def coeff(self):
  3746. return S.One
  3747. @property
  3748. def nocoeff(self):
  3749. return self
  3750. def get_free_indices(self):
  3751. return self._free_indices
  3752. def _replace_indices(self, repl: dict[TensorIndex, TensorIndex]) -> TensExpr:
  3753. # TODO: can be improved:
  3754. return self.xreplace(repl)
  3755. def get_indices(self):
  3756. return self.get_free_indices()
  3757. def _extract_data(self, replacement_dict):
  3758. ret_indices, array = self.expr._extract_data(replacement_dict)
  3759. index_map = self.index_map
  3760. slice_tuple = tuple(index_map.get(i, slice(None)) for i in ret_indices)
  3761. ret_indices = [i for i in ret_indices if i not in index_map]
  3762. array = array.__getitem__(slice_tuple)
  3763. return ret_indices, array
  3764. class WildTensorHead(TensorHead):
  3765. """
  3766. A wild object that is used to create ``WildTensor`` instances
  3767. Explanation
  3768. ===========
  3769. Examples
  3770. ========
  3771. >>> from sympy.tensor.tensor import TensorHead, TensorIndex, WildTensorHead, TensorIndexType
  3772. >>> R3 = TensorIndexType('R3', dim=3)
  3773. >>> p = TensorIndex('p', R3)
  3774. >>> q = TensorIndex('q', R3)
  3775. A WildTensorHead can be created without specifying a ``TensorIndexType``
  3776. >>> W = WildTensorHead("W")
  3777. Calling it with a ``TensorIndex`` creates a ``WildTensor`` instance.
  3778. >>> type(W(p))
  3779. <class 'sympy.tensor.tensor.WildTensor'>
  3780. The ``TensorIndexType`` is automatically detected from the index that is passed
  3781. >>> W(p).component
  3782. W(R3)
  3783. Calling it with no indices returns an object that can match tensors with any number of indices.
  3784. >>> K = TensorHead('K', [R3])
  3785. >>> Q = TensorHead('Q', [R3, R3])
  3786. >>> W().matches(K(p))
  3787. {W: K(p)}
  3788. >>> W().matches(Q(p,q))
  3789. {W: Q(p, q)}
  3790. If you want to ignore the order of indices while matching, pass ``unordered_indices=True``.
  3791. >>> U = WildTensorHead("U", unordered_indices=True)
  3792. >>> W(p,q).matches(Q(q,p))
  3793. >>> U(p,q).matches(Q(q,p))
  3794. {U(R3,R3): _WildTensExpr(Q(q, p))}
  3795. Parameters
  3796. ==========
  3797. name : name of the tensor
  3798. unordered_indices : whether the order of the indices matters for matching
  3799. (default: False)
  3800. See also
  3801. ========
  3802. ``WildTensor``
  3803. ``TensorHead``
  3804. """
  3805. def __new__(cls, name, index_types=None, symmetry=None, comm=0, unordered_indices=False):
  3806. if isinstance(name, str):
  3807. name_symbol = Symbol(name)
  3808. elif isinstance(name, Symbol):
  3809. name_symbol = name
  3810. else:
  3811. raise ValueError("invalid name")
  3812. if index_types is None:
  3813. index_types = []
  3814. if symmetry is None:
  3815. symmetry = TensorSymmetry.no_symmetry(len(index_types))
  3816. else:
  3817. assert symmetry.rank == len(index_types)
  3818. if symmetry != TensorSymmetry.no_symmetry(len(index_types)):
  3819. raise NotImplementedError("Wild matching based on symmetry is not implemented.")
  3820. obj = Basic.__new__(cls, name_symbol, Tuple(*index_types), sympify(symmetry), sympify(comm), sympify(unordered_indices))
  3821. return obj
  3822. @property
  3823. def unordered_indices(self):
  3824. return self.args[4]
  3825. def __call__(self, *indices, **kwargs):
  3826. tensor = WildTensor(self, indices, **kwargs)
  3827. return tensor.doit()
  3828. class WildTensor(Tensor):
  3829. """
  3830. A wild object which matches ``Tensor`` instances
  3831. Explanation
  3832. ===========
  3833. This is instantiated by attaching indices to a ``WildTensorHead`` instance.
  3834. Examples
  3835. ========
  3836. >>> from sympy.tensor.tensor import TensorHead, TensorIndex, WildTensorHead, TensorIndexType
  3837. >>> W = WildTensorHead("W")
  3838. >>> R3 = TensorIndexType('R3', dim=3)
  3839. >>> p = TensorIndex('p', R3)
  3840. >>> q = TensorIndex('q', R3)
  3841. >>> K = TensorHead('K', [R3])
  3842. >>> Q = TensorHead('Q', [R3, R3])
  3843. Matching also takes the indices into account
  3844. >>> W(p).matches(K(p))
  3845. {W(R3): _WildTensExpr(K(p))}
  3846. >>> W(p).matches(K(q))
  3847. >>> W(p).matches(K(-p))
  3848. If you want to match objects with any number of indices, just use a ``WildTensor`` with no indices.
  3849. >>> W().matches(K(p))
  3850. {W: K(p)}
  3851. >>> W().matches(Q(p,q))
  3852. {W: Q(p, q)}
  3853. See Also
  3854. ========
  3855. ``WildTensorHead``
  3856. ``Tensor``
  3857. """
  3858. def __new__(cls, tensor_head, indices, **kw_args):
  3859. is_canon_bp = kw_args.pop("is_canon_bp", False)
  3860. if tensor_head.func == TensorHead:
  3861. """
  3862. If someone tried to call WildTensor by supplying a TensorHead (not a WildTensorHead), return a normal tensor instead. This is helpful when using subs on an expression to replace occurrences of a WildTensorHead with a TensorHead.
  3863. """
  3864. return Tensor(tensor_head, indices, is_canon_bp=is_canon_bp, **kw_args)
  3865. elif tensor_head.func == _WildTensExpr:
  3866. return tensor_head(*indices)
  3867. indices = cls._parse_indices(tensor_head, indices)
  3868. index_types = [ind.tensor_index_type for ind in indices]
  3869. tensor_head = tensor_head.func(
  3870. tensor_head.name,
  3871. index_types,
  3872. symmetry=None,
  3873. comm=tensor_head.comm,
  3874. unordered_indices=tensor_head.unordered_indices,
  3875. )
  3876. obj = Basic.__new__(cls, tensor_head, Tuple(*indices))
  3877. obj.name = tensor_head.name
  3878. obj._index_structure = _IndexStructure.from_indices(*indices)
  3879. obj._free = obj._index_structure.free[:]
  3880. obj._dum = obj._index_structure.dum[:]
  3881. obj._ext_rank = obj._index_structure._ext_rank
  3882. obj._coeff = S.One
  3883. obj._nocoeff = obj
  3884. obj._component = tensor_head
  3885. obj._components = [tensor_head]
  3886. if tensor_head.rank != len(indices):
  3887. raise ValueError("wrong number of indices")
  3888. obj.is_canon_bp = is_canon_bp
  3889. obj._index_map = obj._build_index_map(indices, obj._index_structure)
  3890. return obj
  3891. def matches(self, expr, repl_dict=None, old=False):
  3892. if not isinstance(expr, TensExpr) and expr != S(1):
  3893. return None
  3894. if repl_dict is None:
  3895. repl_dict = {}
  3896. else:
  3897. repl_dict = repl_dict.copy()
  3898. if len(self.indices) > 0:
  3899. if not hasattr(expr, "get_free_indices"):
  3900. return None
  3901. expr_indices = expr.get_free_indices()
  3902. if len(expr_indices) != len(self.indices):
  3903. return None
  3904. if self._component.unordered_indices:
  3905. m = self._match_indices_ignoring_order(expr)
  3906. if m is None:
  3907. return None
  3908. else:
  3909. repl_dict.update(m)
  3910. else:
  3911. for i in range(len(expr_indices)):
  3912. m = self.indices[i].matches(expr_indices[i])
  3913. if m is None:
  3914. return None
  3915. else:
  3916. repl_dict.update(m)
  3917. repl_dict[self.component] = _WildTensExpr(expr)
  3918. else:
  3919. #If no indices were passed to the WildTensor, it may match tensors with any number of indices.
  3920. repl_dict[self] = expr
  3921. return repl_dict
  3922. def _match_indices_ignoring_order(self, expr, repl_dict=None, old=False):
  3923. """
  3924. Helper method for matches. Checks if the indices of self and expr
  3925. match disregarding index ordering.
  3926. """
  3927. if repl_dict is None:
  3928. repl_dict = {}
  3929. else:
  3930. repl_dict = repl_dict.copy()
  3931. def siftkey(ind):
  3932. if isinstance(ind, WildTensorIndex):
  3933. if ind.ignore_updown:
  3934. return "wild, updown"
  3935. else:
  3936. return "wild"
  3937. else:
  3938. return "nonwild"
  3939. indices_sifted = sift(self.indices, siftkey)
  3940. matched_indices = []
  3941. expr_indices_remaining = expr.get_indices()
  3942. for ind in indices_sifted["nonwild"]:
  3943. matched_this_ind = False
  3944. for e_ind in expr_indices_remaining:
  3945. if e_ind in matched_indices:
  3946. continue
  3947. m = ind.matches(e_ind)
  3948. if m is not None:
  3949. matched_this_ind = True
  3950. repl_dict.update(m)
  3951. matched_indices.append(e_ind)
  3952. break
  3953. if not matched_this_ind:
  3954. return None
  3955. expr_indices_remaining = [i for i in expr_indices_remaining if i not in matched_indices]
  3956. for ind in indices_sifted["wild"]:
  3957. matched_this_ind = False
  3958. for e_ind in expr_indices_remaining:
  3959. m = ind.matches(e_ind)
  3960. if m is not None:
  3961. if -ind in repl_dict.keys() and -repl_dict[-ind] != m[ind]:
  3962. return None
  3963. matched_this_ind = True
  3964. repl_dict.update(m)
  3965. matched_indices.append(e_ind)
  3966. break
  3967. if not matched_this_ind:
  3968. return None
  3969. expr_indices_remaining = [i for i in expr_indices_remaining if i not in matched_indices]
  3970. for ind in indices_sifted["wild, updown"]:
  3971. matched_this_ind = False
  3972. for e_ind in expr_indices_remaining:
  3973. m = ind.matches(e_ind)
  3974. if m is not None:
  3975. if -ind in repl_dict.keys() and -repl_dict[-ind] != m[ind]:
  3976. return None
  3977. matched_this_ind = True
  3978. repl_dict.update(m)
  3979. matched_indices.append(e_ind)
  3980. break
  3981. if not matched_this_ind:
  3982. return None
  3983. if len(matched_indices) < len(self.indices):
  3984. return None
  3985. else:
  3986. return repl_dict
  3987. class WildTensorIndex(TensorIndex):
  3988. """
  3989. A wild object that matches TensorIndex instances.
  3990. Examples
  3991. ========
  3992. >>> from sympy.tensor.tensor import TensorIndex, TensorIndexType, WildTensorIndex
  3993. >>> R3 = TensorIndexType('R3', dim=3)
  3994. >>> p = TensorIndex("p", R3)
  3995. By default, covariant indices only match with covariant indices (and
  3996. similarly for contravariant)
  3997. >>> q = WildTensorIndex("q", R3)
  3998. >>> (q).matches(p)
  3999. {q: p}
  4000. >>> (q).matches(-p)
  4001. If you want matching to ignore whether the index is co/contra-variant, set
  4002. ignore_updown=True
  4003. >>> r = WildTensorIndex("r", R3, ignore_updown=True)
  4004. >>> (r).matches(-p)
  4005. {r: -p}
  4006. >>> (r).matches(p)
  4007. {r: p}
  4008. Parameters
  4009. ==========
  4010. name : name of the index (string), or ``True`` if you want it to be
  4011. automatically assigned
  4012. tensor_index_type : ``TensorIndexType`` of the index
  4013. is_up : flag for contravariant index (is_up=True by default)
  4014. ignore_updown : bool, Whether this should match both co- and contra-variant
  4015. indices (default:False)
  4016. """
  4017. def __new__(cls, name, tensor_index_type, is_up=True, ignore_updown=False):
  4018. if isinstance(name, str):
  4019. name_symbol = Symbol(name)
  4020. elif isinstance(name, Symbol):
  4021. name_symbol = name
  4022. elif name is True:
  4023. name = "_i{}".format(len(tensor_index_type._autogenerated))
  4024. name_symbol = Symbol(name)
  4025. tensor_index_type._autogenerated.append(name_symbol)
  4026. else:
  4027. raise ValueError("invalid name")
  4028. is_up = sympify(is_up)
  4029. ignore_updown = sympify(ignore_updown)
  4030. return Basic.__new__(cls, name_symbol, tensor_index_type, is_up, ignore_updown)
  4031. @property
  4032. def ignore_updown(self):
  4033. return self.args[3]
  4034. def __neg__(self):
  4035. t1 = WildTensorIndex(self.name, self.tensor_index_type,
  4036. (not self.is_up), self.ignore_updown)
  4037. return t1
  4038. def matches(self, expr, repl_dict=None, old=False):
  4039. if not isinstance(expr, TensorIndex):
  4040. return None
  4041. if self.tensor_index_type != expr.tensor_index_type:
  4042. return None
  4043. if not self.ignore_updown:
  4044. if self.is_up != expr.is_up:
  4045. return None
  4046. if repl_dict is None:
  4047. repl_dict = {}
  4048. else:
  4049. repl_dict = repl_dict.copy()
  4050. repl_dict[self] = expr
  4051. return repl_dict
  4052. class _WildTensExpr(Basic):
  4053. """
  4054. INTERNAL USE ONLY
  4055. This is an object that helps with replacement of WildTensors in expressions.
  4056. When this object is set as the tensor_head of a WildTensor, it replaces the
  4057. WildTensor by a TensExpr (passed when initializing this object).
  4058. Examples
  4059. ========
  4060. >>> from sympy.tensor.tensor import WildTensorHead, TensorIndex, TensorHead, TensorIndexType
  4061. >>> W = WildTensorHead("W")
  4062. >>> R3 = TensorIndexType('R3', dim=3)
  4063. >>> p = TensorIndex('p', R3)
  4064. >>> q = TensorIndex('q', R3)
  4065. >>> K = TensorHead('K', [R3])
  4066. >>> print( ( K(p) ).replace( W(p), W(q)*W(-q)*W(p) ) )
  4067. K(R_0)*K(-R_0)*K(p)
  4068. """
  4069. def __init__(self, expr):
  4070. if not isinstance(expr, TensExpr):
  4071. raise TypeError("_WildTensExpr expects a TensExpr as argument")
  4072. self.expr = expr
  4073. def __call__(self, *indices):
  4074. return self.expr._replace_indices(dict(zip(self.expr.get_free_indices(), indices)))
  4075. def __neg__(self):
  4076. return self.func(self.expr*S.NegativeOne)
  4077. def __abs__(self):
  4078. raise NotImplementedError
  4079. def __add__(self, other):
  4080. if other.func != self.func:
  4081. raise TypeError(f"Cannot add {self.func} to {other.func}")
  4082. return self.func(self.expr+other.expr)
  4083. def __radd__(self, other):
  4084. if other.func != self.func:
  4085. raise TypeError(f"Cannot add {self.func} to {other.func}")
  4086. return self.func(other.expr+self.expr)
  4087. def __sub__(self, other):
  4088. return self + (-other)
  4089. def __rsub__(self, other):
  4090. return other + (-self)
  4091. def __mul__(self, other):
  4092. raise NotImplementedError
  4093. def __rmul__(self, other):
  4094. raise NotImplementedError
  4095. def __truediv__(self, other):
  4096. raise NotImplementedError
  4097. def __rtruediv__(self, other):
  4098. raise NotImplementedError
  4099. def __pow__(self, other):
  4100. raise NotImplementedError
  4101. def __rpow__(self, other):
  4102. raise NotImplementedError
  4103. def canon_bp(p):
  4104. """
  4105. Butler-Portugal canonicalization. See ``tensor_can.py`` from the
  4106. combinatorics module for the details.
  4107. """
  4108. if isinstance(p, TensExpr):
  4109. return p.canon_bp()
  4110. return p
  4111. def tensor_mul(*a):
  4112. """
  4113. product of tensors
  4114. """
  4115. if not a:
  4116. return TensMul.from_data(S.One, [], [], [])
  4117. t = a[0]
  4118. for tx in a[1:]:
  4119. t = t*tx
  4120. return t
  4121. def riemann_cyclic_replace(t_r):
  4122. """
  4123. replace Riemann tensor with an equivalent expression
  4124. ``R(m,n,p,q) -> 2/3*R(m,n,p,q) - 1/3*R(m,q,n,p) + 1/3*R(m,p,n,q)``
  4125. """
  4126. free = sorted(t_r.free, key=lambda x: x[1])
  4127. m, n, p, q = [x[0] for x in free]
  4128. t0 = t_r*Rational(2, 3)
  4129. t1 = -t_r.substitute_indices((m,m),(n,q),(p,n),(q,p))*Rational(1, 3)
  4130. t2 = t_r.substitute_indices((m,m),(n,p),(p,n),(q,q))*Rational(1, 3)
  4131. t3 = t0 + t1 + t2
  4132. return t3
  4133. def riemann_cyclic(t2):
  4134. """
  4135. Replace each Riemann tensor with an equivalent expression
  4136. satisfying the cyclic identity.
  4137. This trick is discussed in the reference guide to Cadabra.
  4138. Examples
  4139. ========
  4140. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, riemann_cyclic, TensorSymmetry
  4141. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  4142. >>> i, j, k, l = tensor_indices('i,j,k,l', Lorentz)
  4143. >>> R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
  4144. >>> t = R(i,j,k,l)*(R(-i,-j,-k,-l) - 2*R(-i,-k,-j,-l))
  4145. >>> riemann_cyclic(t)
  4146. 0
  4147. """
  4148. t2 = t2.expand()
  4149. if isinstance(t2, (TensMul, Tensor)):
  4150. args = [t2]
  4151. else:
  4152. args = t2.args
  4153. a1 = [x.split() for x in args]
  4154. a2 = [[riemann_cyclic_replace(tx) for tx in y] for y in a1]
  4155. a3 = [tensor_mul(*v) for v in a2]
  4156. t3 = TensAdd(*a3).doit(deep=False)
  4157. if not t3:
  4158. return t3
  4159. else:
  4160. return canon_bp(t3)
  4161. def get_lines(ex, index_type):
  4162. """
  4163. Returns ``(lines, traces, rest)`` for an index type,
  4164. where ``lines`` is the list of list of positions of a matrix line,
  4165. ``traces`` is the list of list of traced matrix lines,
  4166. ``rest`` is the rest of the elements of the tensor.
  4167. """
  4168. def _join_lines(a):
  4169. i = 0
  4170. while i < len(a):
  4171. x = a[i]
  4172. xend = x[-1]
  4173. xstart = x[0]
  4174. hit = True
  4175. while hit:
  4176. hit = False
  4177. for j in range(i + 1, len(a)):
  4178. if j >= len(a):
  4179. break
  4180. if a[j][0] == xend:
  4181. hit = True
  4182. x.extend(a[j][1:])
  4183. xend = x[-1]
  4184. a.pop(j)
  4185. continue
  4186. if a[j][0] == xstart:
  4187. hit = True
  4188. a[i] = reversed(a[j][1:]) + x
  4189. x = a[i]
  4190. xstart = a[i][0]
  4191. a.pop(j)
  4192. continue
  4193. if a[j][-1] == xend:
  4194. hit = True
  4195. x.extend(reversed(a[j][:-1]))
  4196. xend = x[-1]
  4197. a.pop(j)
  4198. continue
  4199. if a[j][-1] == xstart:
  4200. hit = True
  4201. a[i] = a[j][:-1] + x
  4202. x = a[i]
  4203. xstart = x[0]
  4204. a.pop(j)
  4205. continue
  4206. i += 1
  4207. return a
  4208. arguments = ex.args
  4209. dt = {}
  4210. for c in ex.args:
  4211. if not isinstance(c, TensExpr):
  4212. continue
  4213. if c in dt:
  4214. continue
  4215. index_types = c.index_types
  4216. a = []
  4217. for i in range(len(index_types)):
  4218. if index_types[i] is index_type:
  4219. a.append(i)
  4220. if len(a) > 2:
  4221. raise ValueError('at most two indices of type %s allowed' % index_type)
  4222. if len(a) == 2:
  4223. dt[c] = a
  4224. #dum = ex.dum
  4225. lines = []
  4226. traces = []
  4227. traces1 = []
  4228. #indices_to_args_pos = ex._get_indices_to_args_pos()
  4229. # TODO: add a dum_to_components_map ?
  4230. for p0, p1, c0, c1 in ex.dum_in_args:
  4231. if arguments[c0] not in dt:
  4232. continue
  4233. if c0 == c1:
  4234. traces.append([c0])
  4235. continue
  4236. ta0 = dt[arguments[c0]]
  4237. ta1 = dt[arguments[c1]]
  4238. if p0 not in ta0:
  4239. continue
  4240. if ta0.index(p0) == ta1.index(p1):
  4241. # case gamma(i,s0,-s1) in c0, gamma(j,-s0,s2) in c1;
  4242. # to deal with this case one could add to the position
  4243. # a flag for transposition;
  4244. # one could write [(c0, False), (c1, True)]
  4245. raise NotImplementedError
  4246. # if p0 == ta0[1] then G in pos c0 is mult on the right by G in c1
  4247. # if p0 == ta0[0] then G in pos c1 is mult on the right by G in c0
  4248. ta0 = dt[arguments[c0]]
  4249. b0, b1 = (c0, c1) if p0 == ta0[1] else (c1, c0)
  4250. lines1 = lines.copy()
  4251. for line in lines:
  4252. if line[-1] == b0:
  4253. if line[0] == b1:
  4254. n = line.index(min(line))
  4255. traces1.append(line)
  4256. traces.append(line[n:] + line[:n])
  4257. else:
  4258. line.append(b1)
  4259. break
  4260. elif line[0] == b1:
  4261. line.insert(0, b0)
  4262. break
  4263. else:
  4264. lines1.append([b0, b1])
  4265. lines = [x for x in lines1 if x not in traces1]
  4266. lines = _join_lines(lines)
  4267. rest = []
  4268. for line in lines:
  4269. for y in line:
  4270. rest.append(y)
  4271. for line in traces:
  4272. for y in line:
  4273. rest.append(y)
  4274. rest = [x for x in range(len(arguments)) if x not in rest]
  4275. return lines, traces, rest
  4276. def get_free_indices(t):
  4277. if not isinstance(t, TensExpr):
  4278. return ()
  4279. return t.get_free_indices()
  4280. def get_indices(t):
  4281. if not isinstance(t, TensExpr):
  4282. return ()
  4283. return t.get_indices()
  4284. def get_dummy_indices(t):
  4285. if not isinstance(t, TensExpr):
  4286. return ()
  4287. inds = t.get_indices()
  4288. free = t.get_free_indices()
  4289. return [i for i in inds if i not in free]
  4290. def get_index_structure(t):
  4291. if isinstance(t, TensExpr):
  4292. return t._index_structure
  4293. return _IndexStructure([], [], [], [])
  4294. def get_coeff(t):
  4295. if isinstance(t, Tensor):
  4296. return S.One
  4297. if isinstance(t, TensMul):
  4298. return t.coeff
  4299. if isinstance(t, TensExpr):
  4300. raise ValueError("no coefficient associated to this tensor expression")
  4301. return t
  4302. def contract_metric(t, g):
  4303. if isinstance(t, TensExpr):
  4304. return t.contract_metric(g)
  4305. return t
  4306. def perm2tensor(t, g, is_canon_bp=False):
  4307. """
  4308. Returns the tensor corresponding to the permutation ``g``
  4309. For further details, see the method in ``TIDS`` with the same name.
  4310. """
  4311. if not isinstance(t, TensExpr):
  4312. return t
  4313. elif isinstance(t, (Tensor, TensMul)):
  4314. nim = get_index_structure(t).perm2tensor(g, is_canon_bp=is_canon_bp)
  4315. res = t._set_new_index_structure(nim, is_canon_bp=is_canon_bp)
  4316. if g[-1] != len(g) - 1:
  4317. return -res
  4318. return res
  4319. raise NotImplementedError()
  4320. def substitute_indices(t, *index_tuples):
  4321. if not isinstance(t, TensExpr):
  4322. return t
  4323. return t.substitute_indices(*index_tuples)
  4324. def _get_wilds(expr):
  4325. return list(expr.atoms(Wild, WildFunction, WildTensor, WildTensorIndex, WildTensorHead))
  4326. def get_postprocessor(cls):
  4327. def _postprocessor(expr):
  4328. tens_class = {Mul: TensMul, Add: TensAdd}[cls]
  4329. if any(isinstance(a, TensExpr) for a in expr.args):
  4330. return tens_class(*expr.args)
  4331. else:
  4332. return expr
  4333. return _postprocessor
  4334. Basic._constructor_postprocessor_mapping[TensExpr] = {
  4335. "Mul": [get_postprocessor(Mul)],
  4336. }