cvode.c 118 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335
  1. /*
  2. * -----------------------------------------------------------------
  3. * $Revision: 4285 $
  4. * $Date: 2014-12-12 13:39:23 -0800 (Fri, 12 Dec 2014) $
  5. * -----------------------------------------------------------------
  6. * Programmer(s): Scott D. Cohen, Alan C. Hindmarsh, Radu Serban,
  7. * and Dan Shumaker @ LLNL
  8. * -----------------------------------------------------------------
  9. * LLNS Copyright Start
  10. * Copyright (c) 2014, Lawrence Livermore National Security
  11. * This work was performed under the auspices of the U.S. Department
  12. * of Energy by Lawrence Livermore National Laboratory in part under
  13. * Contract W-7405-Eng-48 and in part under Contract DE-AC52-07NA27344.
  14. * Produced at the Lawrence Livermore National Laboratory.
  15. * All rights reserved.
  16. * For details, see the LICENSE file.
  17. * LLNS Copyright End
  18. * -----------------------------------------------------------------
  19. * This is the implementation file for the main CVODE integrator.
  20. * It is independent of the CVODE linear solver in use.
  21. * -----------------------------------------------------------------
  22. */
  23. /*=================================================================*/
  24. /* Import Header Files */
  25. /*=================================================================*/
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <stdarg.h>
  29. #include <string.h>
  30. #include "cvode_impl.h"
  31. #include <sundials/sundials_math.h>
  32. #include <sundials/sundials_types.h>
  33. /*=================================================================*/
  34. /* Macros */
  35. /*=================================================================*/
  36. /* Macro: loop */
  37. #define loop for(;;)
  38. /*=================================================================*/
  39. /* CVODE Private Constants */
  40. /*=================================================================*/
  41. #define ZERO RCONST(0.0) /* real 0.0 */
  42. #define TINY RCONST(1.0e-10) /* small number */
  43. #define PT1 RCONST(0.1) /* real 0.1 */
  44. #define POINT2 RCONST(0.2) /* real 0.2 */
  45. #define FOURTH RCONST(0.25) /* real 0.25 */
  46. #define HALF RCONST(0.5) /* real 0.5 */
  47. #define ONE RCONST(1.0) /* real 1.0 */
  48. #define TWO RCONST(2.0) /* real 2.0 */
  49. #define THREE RCONST(3.0) /* real 3.0 */
  50. #define FOUR RCONST(4.0) /* real 4.0 */
  51. #define FIVE RCONST(5.0) /* real 5.0 */
  52. #define TWELVE RCONST(12.0) /* real 12.0 */
  53. #define HUNDRED RCONST(100.0) /* real 100.0 */
  54. /*=================================================================*/
  55. /* CVODE Routine-Specific Constants */
  56. /*=================================================================*/
  57. /*
  58. * Control constants for lower-level functions used by cvStep
  59. * ----------------------------------------------------------
  60. *
  61. * cvHin return values:
  62. * CV_SUCCESS
  63. * CV_RHSFUNC_FAIL
  64. * CV_TOO_CLOSE
  65. *
  66. * cvStep control constants:
  67. * DO_ERROR_TEST
  68. * PREDICT_AGAIN
  69. *
  70. * cvStep return values:
  71. * CV_SUCCESS,
  72. * CV_LSETUP_FAIL, CV_LSOLVE_FAIL,
  73. * CV_RHSFUNC_FAIL, CV_RTFUNC_FAIL
  74. * CV_CONV_FAILURE, CV_ERR_FAILURE,
  75. * CV_FIRST_RHSFUNC_ERR
  76. *
  77. * cvNls input nflag values:
  78. * FIRST_CALL
  79. * PREV_CONV_FAIL
  80. * PREV_ERR_FAIL
  81. *
  82. * cvNls return values:
  83. * CV_SUCCESS,
  84. * CV_LSETUP_FAIL, CV_LSOLVE_FAIL, CV_RHSFUNC_FAIL,
  85. * CONV_FAIL, RHSFUNC_RECVR
  86. *
  87. * cvNewtonIteration return values:
  88. * CV_SUCCESS,
  89. * CV_LSOLVE_FAIL, CV_RHSFUNC_FAIL
  90. * CONV_FAIL, RHSFUNC_RECVR,
  91. * CV_TRY_AGAIN (Renamed from TRY_AGAIN by 3ds.com due to name-collision)
  92. *
  93. */
  94. #define DO_ERROR_TEST +2
  95. #define PREDICT_AGAIN +3
  96. #define CONV_FAIL +4
  97. #define CV_TRY_AGAIN +5
  98. #define FIRST_CALL +6
  99. #define PREV_CONV_FAIL +7
  100. #define PREV_ERR_FAIL +8
  101. #define RHSFUNC_RECVR +9
  102. /*
  103. * Control constants for lower-level rootfinding functions
  104. * -------------------------------------------------------
  105. *
  106. * cvRcheck1 return values:
  107. * CV_SUCCESS,
  108. * CV_RTFUNC_FAIL,
  109. * cvRcheck2 return values:
  110. * CV_SUCCESS
  111. * CV_RTFUNC_FAIL,
  112. * CLOSERT
  113. * RTFOUND
  114. * cvRcheck3 return values:
  115. * CV_SUCCESS
  116. * CV_RTFUNC_FAIL,
  117. * RTFOUND
  118. * cvRootfind return values:
  119. * CV_SUCCESS
  120. * CV_RTFUNC_FAIL,
  121. * RTFOUND
  122. */
  123. #define RTFOUND +1
  124. #define CLOSERT +3
  125. /*
  126. * Control constants for tolerances
  127. * --------------------------------
  128. */
  129. #define CV_NN 0
  130. #define CV_SS 1
  131. #define CV_SV 2
  132. #define CV_WF 3
  133. /*
  134. * Algorithmic constants
  135. * ---------------------
  136. *
  137. * CVodeGetDky and cvStep
  138. *
  139. * FUZZ_FACTOR
  140. *
  141. * cvHin
  142. *
  143. * HLB_FACTOR
  144. * HUB_FACTOR
  145. * H_BIAS
  146. * MAX_ITERS
  147. *
  148. * CVodeCreate
  149. *
  150. * CORTES
  151. *
  152. * cvStep
  153. *
  154. * THRESH
  155. * ETAMX1
  156. * ETAMX2
  157. * ETAMX3
  158. * ETAMXF
  159. * ETAMIN
  160. * ETACF
  161. * ADDON
  162. * BIAS1
  163. * BIAS2
  164. * BIAS3
  165. * ONEPSM
  166. *
  167. * SMALL_NST nst > SMALL_NST => use ETAMX3
  168. * MXNCF max no. of convergence failures during one step try
  169. * MXNEF max no. of error test failures during one step try
  170. * MXNEF1 max no. of error test failures before forcing a reduction of order
  171. * SMALL_NEF if an error failure occurs and SMALL_NEF <= nef <= MXNEF1, then
  172. * reset eta = SUNMIN(eta, ETAMXF)
  173. * LONG_WAIT number of steps to wait before considering an order change when
  174. * q==1 and MXNEF1 error test failures have occurred
  175. *
  176. * cvNls
  177. *
  178. * NLS_MAXCOR maximum no. of corrector iterations for the nonlinear solver
  179. * CRDOWN constant used in the estimation of the convergence rate (crate)
  180. * of the iterates for the nonlinear equation
  181. * DGMAX iter == CV_NEWTON, |gamma/gammap-1| > DGMAX => call lsetup
  182. * RDIV declare divergence if ratio del/delp > RDIV
  183. * MSBP max no. of steps between lsetup calls
  184. *
  185. */
  186. #define FUZZ_FACTOR RCONST(100.0)
  187. #define HLB_FACTOR RCONST(100.0)
  188. #define HUB_FACTOR RCONST(0.1)
  189. #define H_BIAS HALF
  190. #define MAX_ITERS 4
  191. #define CORTES RCONST(0.1)
  192. #define THRESH RCONST(1.5)
  193. #define ETAMX1 RCONST(10000.0)
  194. #define ETAMX2 RCONST(10.0)
  195. #define ETAMX3 RCONST(10.0)
  196. #define ETAMXF RCONST(0.2)
  197. #define ETAMIN RCONST(0.1)
  198. #define ETACF RCONST(0.25)
  199. #define ADDON RCONST(0.000001)
  200. #define BIAS1 RCONST(6.0)
  201. #define BIAS2 RCONST(6.0)
  202. #define BIAS3 RCONST(10.0)
  203. #define ONEPSM RCONST(1.000001)
  204. #define SMALL_NST 10
  205. #define MXNCF 10
  206. #define MXNEF 7
  207. #define MXNEF1 3
  208. #define SMALL_NEF 2
  209. #define LONG_WAIT 10
  210. #define NLS_MAXCOR 3
  211. #define CRDOWN RCONST(0.3)
  212. #define DGMAX RCONST(0.3)
  213. #define RDIV TWO
  214. #define MSBP 20
  215. /*=================================================================*/
  216. /* Private Helper Functions Prototypes */
  217. /*=================================================================*/
  218. static booleantype cvCheckNvector(N_Vector tmpl);
  219. static int cvInitialSetup(CVodeMem cv_mem);
  220. static booleantype cvAllocVectors(CVodeMem cv_mem, N_Vector tmpl);
  221. static void cvFreeVectors(CVodeMem cv_mem);
  222. static int cvEwtSetSS(CVodeMem cv_mem, N_Vector ycur, N_Vector weight);
  223. static int cvEwtSetSV(CVodeMem cv_mem, N_Vector ycur, N_Vector weight);
  224. static int cvHin(CVodeMem cv_mem, realtype tout);
  225. static realtype cvUpperBoundH0(CVodeMem cv_mem, realtype tdist);
  226. static int cvYddNorm(CVodeMem cv_mem, realtype hg, realtype *yddnrm);
  227. static int cvStep(CVodeMem cv_mem);
  228. static int cvSLdet(CVodeMem cv_mem);
  229. static void cvAdjustParams(CVodeMem cv_mem);
  230. static void cvAdjustOrder(CVodeMem cv_mem, int deltaq);
  231. static void cvAdjustAdams(CVodeMem cv_mem, int deltaq);
  232. static void cvAdjustBDF(CVodeMem cv_mem, int deltaq);
  233. static void cvIncreaseBDF(CVodeMem cv_mem);
  234. static void cvDecreaseBDF(CVodeMem cv_mem);
  235. static void cvRescale(CVodeMem cv_mem);
  236. static void cvPredict(CVodeMem cv_mem);
  237. static void cvSet(CVodeMem cv_mem);
  238. static void cvSetAdams(CVodeMem cv_mem);
  239. static realtype cvAdamsStart(CVodeMem cv_mem, realtype m[]);
  240. static void cvAdamsFinish(CVodeMem cv_mem, realtype m[], realtype M[], realtype hsum);
  241. static realtype cvAltSum(int iend, realtype a[], int k);
  242. static void cvSetBDF(CVodeMem cv_mem);
  243. static void cvSetTqBDF(CVodeMem cv_mem, realtype hsum, realtype alpha0,
  244. realtype alpha0_hat, realtype xi_inv, realtype xistar_inv);
  245. static int cvNls(CVodeMem cv_mem, int nflag);
  246. static int cvNlsFunctional(CVodeMem cv_mem);
  247. static int cvNlsNewton(CVodeMem cv_mem, int nflag);
  248. static int cvNewtonIteration(CVodeMem cv_mem);
  249. static int cvHandleNFlag(CVodeMem cv_mem, int *nflagPtr, realtype saved_t,
  250. int *ncfPtr);
  251. static void cvRestore(CVodeMem cv_mem, realtype saved_t);
  252. static int cvDoErrorTest(CVodeMem cv_mem, int *nflagPtr,
  253. realtype saved_t, int *nefPtr, realtype *dsmPtr);
  254. static void cvCompleteStep(CVodeMem cv_mem);
  255. static void cvPrepareNextStep(CVodeMem cv_mem, realtype dsm);
  256. static void cvSetEta(CVodeMem cv_mem);
  257. static realtype cvComputeEtaqm1(CVodeMem cv_mem);
  258. static realtype cvComputeEtaqp1(CVodeMem cv_mem);
  259. static void cvChooseEta(CVodeMem cv_mem);
  260. static void cvBDFStab(CVodeMem cv_mem);
  261. static int cvHandleFailure(CVodeMem cv_mem,int flag);
  262. static int cvRcheck1(CVodeMem cv_mem);
  263. static int cvRcheck2(CVodeMem cv_mem);
  264. static int cvRcheck3(CVodeMem cv_mem);
  265. static int cvRootfind(CVodeMem cv_mem);
  266. /*
  267. * =================================================================
  268. * EXPORTED FUNCTIONS IMPLEMENTATION
  269. * =================================================================
  270. */
  271. /*
  272. * CVodeCreate
  273. *
  274. * CVodeCreate creates an internal memory block for a problem to
  275. * be solved by CVODE.
  276. * If successful, CVodeCreate returns a pointer to the problem memory.
  277. * This pointer should be passed to CVodeInit.
  278. * If an initialization error occurs, CVodeCreate prints an error
  279. * message to standard err and returns NULL.
  280. */
  281. SUNDIALS_EXPORT void *CVodeCreate(int lmm, int iter)
  282. {
  283. int maxord;
  284. CVodeMem cv_mem;
  285. /* Test inputs */
  286. if ((lmm != CV_ADAMS) && (lmm != CV_BDF)) {
  287. cvProcessError(NULL, 0, "CVODE", "CVodeCreate", MSGCV_BAD_LMM);
  288. return(NULL);
  289. }
  290. if ((iter != CV_FUNCTIONAL) && (iter != CV_NEWTON)) {
  291. cvProcessError(NULL, 0, "CVODE", "CVodeCreate", MSGCV_BAD_ITER);
  292. return(NULL);
  293. }
  294. cv_mem = NULL;
  295. cv_mem = (CVodeMem) malloc(sizeof(struct CVodeMemRec));
  296. if (cv_mem == NULL) {
  297. cvProcessError(NULL, 0, "CVODE", "CVodeCreate", MSGCV_CVMEM_FAIL);
  298. return(NULL);
  299. }
  300. /* Zero out cv_mem */
  301. memset(cv_mem, 0, sizeof(struct CVodeMemRec));
  302. maxord = (lmm == CV_ADAMS) ? ADAMS_Q_MAX : BDF_Q_MAX;
  303. /* copy input parameters into cv_mem */
  304. cv_mem->cv_lmm = lmm;
  305. cv_mem->cv_iter = iter;
  306. /* Set uround */
  307. cv_mem->cv_uround = UNIT_ROUNDOFF;
  308. /* Set default values for integrator optional inputs */
  309. cv_mem->cv_f = NULL;
  310. cv_mem->cv_user_data = NULL;
  311. cv_mem->cv_itol = CV_NN;
  312. cv_mem->cv_user_efun = FALSE;
  313. cv_mem->cv_efun = NULL;
  314. cv_mem->cv_e_data = NULL;
  315. cv_mem->cv_ehfun = cvErrHandler;
  316. cv_mem->cv_eh_data = cv_mem;
  317. cv_mem->cv_errfp = stderr;
  318. cv_mem->cv_qmax = maxord;
  319. cv_mem->cv_mxstep = MXSTEP_DEFAULT;
  320. cv_mem->cv_mxhnil = MXHNIL_DEFAULT;
  321. cv_mem->cv_sldeton = FALSE;
  322. cv_mem->cv_hin = ZERO;
  323. cv_mem->cv_hmin = HMIN_DEFAULT;
  324. cv_mem->cv_hmax_inv = HMAX_INV_DEFAULT;
  325. cv_mem->cv_tstopset = FALSE;
  326. cv_mem->cv_maxcor = NLS_MAXCOR;
  327. cv_mem->cv_maxnef = MXNEF;
  328. cv_mem->cv_maxncf = MXNCF;
  329. cv_mem->cv_nlscoef = CORTES;
  330. /* Initialize root finding variables */
  331. cv_mem->cv_glo = NULL;
  332. cv_mem->cv_ghi = NULL;
  333. cv_mem->cv_grout = NULL;
  334. cv_mem->cv_iroots = NULL;
  335. cv_mem->cv_rootdir = NULL;
  336. cv_mem->cv_gfun = NULL;
  337. cv_mem->cv_nrtfn = 0;
  338. cv_mem->cv_gactive = NULL;
  339. cv_mem->cv_mxgnull = 1;
  340. /* Set the saved value qmax_alloc */
  341. cv_mem->cv_qmax_alloc = maxord;
  342. /* Initialize lrw and liw */
  343. cv_mem->cv_lrw = 58 + 2*L_MAX + NUM_TESTS;
  344. cv_mem->cv_liw = 40;
  345. /* No mallocs have been done yet */
  346. cv_mem->cv_VabstolMallocDone = FALSE;
  347. cv_mem->cv_MallocDone = FALSE;
  348. cv_mem->cv_stepgfun = NULL;
  349. /* Return pointer to CVODE memory block */
  350. return((void *)cv_mem);
  351. }
  352. /*-----------------------------------------------------------------*/
  353. #define iter (cv_mem->cv_iter)
  354. #define lmm (cv_mem->cv_lmm)
  355. #define lrw (cv_mem->cv_lrw)
  356. #define liw (cv_mem->cv_liw)
  357. /*-----------------------------------------------------------------*/
  358. /*
  359. * CVodeInit
  360. *
  361. * CVodeInit allocates and initializes memory for a problem. All
  362. * problem inputs are checked for errors. If any error occurs during
  363. * initialization, it is reported to the file whose file pointer is
  364. * errfp and an error flag is returned. Otherwise, it returns CV_SUCCESS
  365. */
  366. SUNDIALS_EXPORT int CVodeInit(void *cvode_mem, CVRhsFn f, realtype t0, N_Vector y0)
  367. {
  368. CVodeMem cv_mem;
  369. booleantype nvectorOK, allocOK;
  370. long int lrw1, liw1;
  371. int i,k;
  372. /* Check cvode_mem */
  373. if (cvode_mem==NULL) {
  374. cvProcessError(NULL, CV_MEM_NULL, "CVODE", "CVodeInit", MSGCV_NO_MEM);
  375. return(CV_MEM_NULL);
  376. }
  377. cv_mem = (CVodeMem) cvode_mem;
  378. /* Check for legal input parameters */
  379. if (y0==NULL) {
  380. cvProcessError(cv_mem, CV_ILL_INPUT, "CVODE", "CVodeInit", MSGCV_NULL_Y0);
  381. return(CV_ILL_INPUT);
  382. }
  383. if (f == NULL) {
  384. cvProcessError(cv_mem, CV_ILL_INPUT, "CVODE", "CVodeInit", MSGCV_NULL_F);
  385. return(CV_ILL_INPUT);
  386. }
  387. /* Test if all required vector operations are implemented */
  388. nvectorOK = cvCheckNvector(y0);
  389. if(!nvectorOK) {
  390. cvProcessError(cv_mem, CV_ILL_INPUT, "CVODE", "CVodeInit", MSGCV_BAD_NVECTOR);
  391. return(CV_ILL_INPUT);
  392. }
  393. /* Set space requirements for one N_Vector */
  394. if (y0->ops->nvspace != NULL) {
  395. N_VSpace(y0, &lrw1, &liw1);
  396. } else {
  397. lrw1 = 0;
  398. liw1 = 0;
  399. }
  400. cv_mem->cv_lrw1 = lrw1;
  401. cv_mem->cv_liw1 = liw1;
  402. /* Allocate the vectors (using y0 as a template) */
  403. allocOK = cvAllocVectors(cv_mem, y0);
  404. if (!allocOK) {
  405. cvProcessError(cv_mem, CV_MEM_FAIL, "CVODE", "CVodeInit", MSGCV_MEM_FAIL);
  406. return(CV_MEM_FAIL);
  407. }
  408. /* All error checking is complete at this point */
  409. /* Copy the input parameters into CVODE state */
  410. cv_mem->cv_f = f;
  411. cv_mem->cv_tn = t0;
  412. /* Set step parameters */
  413. cv_mem->cv_q = 1;
  414. cv_mem->cv_L = 2;
  415. cv_mem->cv_qwait = cv_mem->cv_L;
  416. cv_mem->cv_etamax = ETAMX1;
  417. cv_mem->cv_qu = 0;
  418. cv_mem->cv_hu = ZERO;
  419. cv_mem->cv_tolsf = ONE;
  420. /* Set the linear solver addresses to NULL.
  421. (We check != NULL later, in CVode, if using CV_NEWTON.) */
  422. cv_mem->cv_linit = NULL;
  423. cv_mem->cv_lsetup = NULL;
  424. cv_mem->cv_lsolve = NULL;
  425. cv_mem->cv_lfree = NULL;
  426. cv_mem->cv_lmem = NULL;
  427. /* Initialize zn[0] in the history array */
  428. N_VScale(ONE, y0, cv_mem->cv_zn[0]);
  429. /* Initialize all the counters */
  430. cv_mem->cv_nst = 0;
  431. cv_mem->cv_nfe = 0;
  432. cv_mem->cv_ncfn = 0;
  433. cv_mem->cv_netf = 0;
  434. cv_mem->cv_nni = 0;
  435. cv_mem->cv_nsetups = 0;
  436. cv_mem->cv_nhnil = 0;
  437. cv_mem->cv_nstlp = 0;
  438. cv_mem->cv_nscon = 0;
  439. cv_mem->cv_nge = 0;
  440. cv_mem->cv_irfnd = 0;
  441. /* Initialize other integrator optional outputs */
  442. cv_mem->cv_h0u = ZERO;
  443. cv_mem->cv_next_h = ZERO;
  444. cv_mem->cv_next_q = 0;
  445. /* Initialize Stablilty Limit Detection data */
  446. /* NOTE: We do this even if stab lim det was not
  447. turned on yet. This way, the user can turn it
  448. on at any time */
  449. cv_mem->cv_nor = 0;
  450. for (i = 1; i <= 5; i++)
  451. for (k = 1; k <= 3; k++)
  452. cv_mem->cv_ssdat[i-1][k-1] = ZERO;
  453. /* Problem has been successfully initialized */
  454. cv_mem->cv_MallocDone = TRUE;
  455. return(CV_SUCCESS);
  456. }
  457. /*-----------------------------------------------------------------*/
  458. #define lrw1 (cv_mem->cv_lrw1)
  459. #define liw1 (cv_mem->cv_liw1)
  460. /*-----------------------------------------------------------------*/
  461. /*
  462. * CVodeReInit
  463. *
  464. * CVodeReInit re-initializes CVODE's memory for a problem, assuming
  465. * it has already been allocated in a prior CVodeInit call.
  466. * All problem specification inputs are checked for errors.
  467. * If any error occurs during initialization, it is reported to the
  468. * file whose file pointer is errfp.
  469. * The return value is CV_SUCCESS = 0 if no errors occurred, or
  470. * a negative value otherwise.
  471. */
  472. SUNDIALS_EXPORT int CVodeReInit(void *cvode_mem, realtype t0, N_Vector y0)
  473. {
  474. CVodeMem cv_mem;
  475. int i,k;
  476. /* Check cvode_mem */
  477. if (cvode_mem==NULL) {
  478. cvProcessError(NULL, CV_MEM_NULL, "CVODE", "CVodeReInit", MSGCV_NO_MEM);
  479. return(CV_MEM_NULL);
  480. }
  481. cv_mem = (CVodeMem) cvode_mem;
  482. /* Check if cvode_mem was allocated */
  483. if (cv_mem->cv_MallocDone == FALSE) {
  484. cvProcessError(cv_mem, CV_NO_MALLOC, "CVODE", "CVodeReInit", MSGCV_NO_MALLOC);
  485. return(CV_NO_MALLOC);
  486. }
  487. /* Check for legal input parameters */
  488. if (y0 == NULL) {
  489. cvProcessError(cv_mem, CV_ILL_INPUT, "CVODE", "CVodeReInit", MSGCV_NULL_Y0);
  490. return(CV_ILL_INPUT);
  491. }
  492. /* Copy the input parameters into CVODE state */
  493. cv_mem->cv_tn = t0;
  494. /* Set step parameters */
  495. cv_mem->cv_q = 1;
  496. cv_mem->cv_L = 2;
  497. cv_mem->cv_qwait = cv_mem->cv_L;
  498. cv_mem->cv_etamax = ETAMX1;
  499. cv_mem->cv_qu = 0;
  500. cv_mem->cv_hu = ZERO;
  501. cv_mem->cv_tolsf = ONE;
  502. /* Initialize zn[0] in the history array */
  503. N_VScale(ONE, y0, cv_mem->cv_zn[0]);
  504. /* Initialize all the counters */
  505. cv_mem->cv_nst = 0;
  506. cv_mem->cv_nfe = 0;
  507. cv_mem->cv_ncfn = 0;
  508. cv_mem->cv_netf = 0;
  509. cv_mem->cv_nni = 0;
  510. cv_mem->cv_nsetups = 0;
  511. cv_mem->cv_nhnil = 0;
  512. cv_mem->cv_nstlp = 0;
  513. cv_mem->cv_nscon = 0;
  514. cv_mem->cv_nge = 0;
  515. cv_mem->cv_irfnd = 0;
  516. /* Initialize other integrator optional outputs */
  517. cv_mem->cv_h0u = ZERO;
  518. cv_mem->cv_next_h = ZERO;
  519. cv_mem->cv_next_q = 0;
  520. /* Initialize Stablilty Limit Detection data */
  521. cv_mem->cv_nor = 0;
  522. for (i = 1; i <= 5; i++)
  523. for (k = 1; k <= 3; k++)
  524. cv_mem->cv_ssdat[i-1][k-1] = ZERO;
  525. /* Problem has been successfully re-initialized */
  526. return(CV_SUCCESS);
  527. }
  528. /*-----------------------------------------------------------------*/
  529. /*
  530. * CVodeSStolerances
  531. * CVodeSVtolerances
  532. * CVodeWFtolerances
  533. *
  534. * These functions specify the integration tolerances. One of them
  535. * MUST be called before the first call to CVode.
  536. *
  537. * CVodeSStolerances specifies scalar relative and absolute tolerances.
  538. * CVodeSVtolerances specifies scalar relative tolerance and a vector
  539. * absolute tolerance (a potentially different absolute tolerance
  540. * for each vector component).
  541. * CVodeWFtolerances specifies a user-provides function (of type CVEwtFn)
  542. * which will be called to set the error weight vector.
  543. */
  544. SUNDIALS_EXPORT int CVodeSStolerances(void *cvode_mem, realtype reltol, realtype abstol)
  545. {
  546. CVodeMem cv_mem;
  547. if (cvode_mem==NULL) {
  548. cvProcessError(NULL, CV_MEM_NULL, "CVODE", "CVodeSStolerances", MSGCV_NO_MEM);
  549. return(CV_MEM_NULL);
  550. }
  551. cv_mem = (CVodeMem) cvode_mem;
  552. if (cv_mem->cv_MallocDone == FALSE) {
  553. cvProcessError(cv_mem, CV_NO_MALLOC, "CVODE", "CVodeSStolerances", MSGCV_NO_MALLOC);
  554. return(CV_NO_MALLOC);
  555. }
  556. /* Check inputs */
  557. if (reltol < ZERO) {
  558. cvProcessError(cv_mem, CV_ILL_INPUT, "CVODE", "CVodeSStolerances", MSGCV_BAD_RELTOL);
  559. return(CV_ILL_INPUT);
  560. }
  561. if (abstol < ZERO) {
  562. cvProcessError(cv_mem, CV_ILL_INPUT, "CVODE", "CVodeSStolerances", MSGCV_BAD_ABSTOL);
  563. return(CV_ILL_INPUT);
  564. }
  565. /* Copy tolerances into memory */
  566. cv_mem->cv_reltol = reltol;
  567. cv_mem->cv_Sabstol = abstol;
  568. cv_mem->cv_itol = CV_SS;
  569. cv_mem->cv_user_efun = FALSE;
  570. cv_mem->cv_efun = cvEwtSet;
  571. cv_mem->cv_e_data = NULL; /* will be set to cvode_mem in InitialSetup */
  572. return(CV_SUCCESS);
  573. }
  574. SUNDIALS_EXPORT int CVodeSVtolerances(void *cvode_mem, realtype reltol, N_Vector abstol)
  575. {
  576. CVodeMem cv_mem;
  577. if (cvode_mem==NULL) {
  578. cvProcessError(NULL, CV_MEM_NULL, "CVODE", "CVodeSVtolerances", MSGCV_NO_MEM);
  579. return(CV_MEM_NULL);
  580. }
  581. cv_mem = (CVodeMem) cvode_mem;
  582. if (cv_mem->cv_MallocDone == FALSE) {
  583. cvProcessError(cv_mem, CV_NO_MALLOC, "CVODE", "CVodeSVtolerances", MSGCV_NO_MALLOC);
  584. return(CV_NO_MALLOC);
  585. }
  586. /* Check inputs */
  587. if (reltol < ZERO) {
  588. cvProcessError(cv_mem, CV_ILL_INPUT, "CVODE", "CVodeSVtolerances", MSGCV_BAD_RELTOL);
  589. return(CV_ILL_INPUT);
  590. }
  591. if (N_VMin(abstol) < ZERO) {
  592. cvProcessError(cv_mem, CV_ILL_INPUT, "CVODE", "CVodeSVtolerances", MSGCV_BAD_ABSTOL);
  593. return(CV_ILL_INPUT);
  594. }
  595. /* Copy tolerances into memory */
  596. if ( !(cv_mem->cv_VabstolMallocDone) ) {
  597. cv_mem->cv_Vabstol = N_VClone(cv_mem->cv_ewt);
  598. lrw += lrw1;
  599. liw += liw1;
  600. cv_mem->cv_VabstolMallocDone = TRUE;
  601. }
  602. cv_mem->cv_reltol = reltol;
  603. N_VScale(ONE, abstol, cv_mem->cv_Vabstol);
  604. cv_mem->cv_itol = CV_SV;
  605. cv_mem->cv_user_efun = FALSE;
  606. cv_mem->cv_efun = cvEwtSet;
  607. cv_mem->cv_e_data = NULL; /* will be set to cvode_mem in InitialSetup */
  608. return(CV_SUCCESS);
  609. }
  610. SUNDIALS_EXPORT int CVodeWFtolerances(void *cvode_mem, CVEwtFn efun)
  611. {
  612. CVodeMem cv_mem;
  613. if (cvode_mem==NULL) {
  614. cvProcessError(NULL, CV_MEM_NULL, "CVODE", "CVodeWFtolerances", MSGCV_NO_MEM);
  615. return(CV_MEM_NULL);
  616. }
  617. cv_mem = (CVodeMem) cvode_mem;
  618. if (cv_mem->cv_MallocDone == FALSE) {
  619. cvProcessError(cv_mem, CV_NO_MALLOC, "CVODE", "CVodeWFtolerances", MSGCV_NO_MALLOC);
  620. return(CV_NO_MALLOC);
  621. }
  622. cv_mem->cv_itol = CV_WF;
  623. cv_mem->cv_user_efun = TRUE;
  624. cv_mem->cv_efun = efun;
  625. cv_mem->cv_e_data = NULL; /* will be set to user_data in InitialSetup */
  626. return(CV_SUCCESS);
  627. }
  628. /*-----------------------------------------------------------------*/
  629. #define gfun (cv_mem->cv_gfun)
  630. #define glo (cv_mem->cv_glo)
  631. #define ghi (cv_mem->cv_ghi)
  632. #define grout (cv_mem->cv_grout)
  633. #define iroots (cv_mem->cv_iroots)
  634. #define rootdir (cv_mem->cv_rootdir)
  635. #define gactive (cv_mem->cv_gactive)
  636. /*-----------------------------------------------------------------*/
  637. /*
  638. * CVodeRootInit
  639. *
  640. * CVodeRootInit initializes a rootfinding problem to be solved
  641. * during the integration of the ODE system. It loads the root
  642. * function pointer and the number of root functions, and allocates
  643. * workspace memory. The return value is CV_SUCCESS = 0 if no errors
  644. * occurred, or a negative value otherwise.
  645. */
  646. SUNDIALS_EXPORT int CVodeRootInit(void *cvode_mem, int nrtfn, CVRootFn g)
  647. {
  648. CVodeMem cv_mem;
  649. int i, nrt;
  650. /* Check cvode_mem pointer */
  651. if (cvode_mem == NULL) {
  652. cvProcessError(NULL, CV_MEM_NULL, "CVODE", "CVodeRootInit", MSGCV_NO_MEM);
  653. return(CV_MEM_NULL);
  654. }
  655. cv_mem = (CVodeMem) cvode_mem;
  656. nrt = (nrtfn < 0) ? 0 : nrtfn;
  657. /* If rerunning CVodeRootInit() with a different number of root
  658. functions (changing number of gfun components), then free
  659. currently held memory resources */
  660. if ((nrt != cv_mem->cv_nrtfn) && (cv_mem->cv_nrtfn > 0)) {
  661. free(glo); glo = NULL;
  662. free(ghi); ghi = NULL;
  663. free(grout); grout = NULL;
  664. free(iroots); iroots = NULL;
  665. free(rootdir); rootdir = NULL;
  666. free(gactive); gactive = NULL;
  667. lrw -= 3 * (cv_mem->cv_nrtfn);
  668. liw -= 3 * (cv_mem->cv_nrtfn);
  669. }
  670. /* If CVodeRootInit() was called with nrtfn == 0, then set cv_nrtfn to
  671. zero and cv_gfun to NULL before returning */
  672. if (nrt == 0) {
  673. cv_mem->cv_nrtfn = nrt;
  674. gfun = NULL;
  675. return(CV_SUCCESS);
  676. }
  677. /* If rerunning CVodeRootInit() with the same number of root functions
  678. (not changing number of gfun components), then check if the root
  679. function argument has changed */
  680. /* If g != NULL then return as currently reserved memory resources
  681. will suffice */
  682. if (nrt == cv_mem->cv_nrtfn) {
  683. if (g != gfun) {
  684. if (g == NULL) {
  685. free(glo); glo = NULL;
  686. free(ghi); ghi = NULL;
  687. free(grout); grout = NULL;
  688. free(iroots); iroots = NULL;
  689. free(rootdir); rootdir = NULL;
  690. free(gactive); gactive = NULL;
  691. lrw -= 3*nrt;
  692. liw -= 3*nrt;
  693. cvProcessError(cv_mem, CV_ILL_INPUT, "CVODE", "CVodeRootInit", MSGCV_NULL_G);
  694. return(CV_ILL_INPUT);
  695. }
  696. else {
  697. gfun = g;
  698. return(CV_SUCCESS);
  699. }
  700. }
  701. else return(CV_SUCCESS);
  702. }
  703. /* Set variable values in CVode memory block */
  704. cv_mem->cv_nrtfn = nrt;
  705. if (g == NULL) {
  706. cvProcessError(cv_mem, CV_ILL_INPUT, "CVODE", "CVodeRootInit", MSGCV_NULL_G);
  707. return(CV_ILL_INPUT);
  708. }
  709. else gfun = g;
  710. /* Allocate necessary memory and return */
  711. glo = NULL;
  712. glo = (realtype *) malloc(nrt*sizeof(realtype));
  713. if (glo == NULL) {
  714. cvProcessError(cv_mem, CV_MEM_FAIL, "CVODE", "CVodeRootInit", MSGCV_MEM_FAIL);
  715. return(CV_MEM_FAIL);
  716. }
  717. ghi = NULL;
  718. ghi = (realtype *) malloc(nrt*sizeof(realtype));
  719. if (ghi == NULL) {
  720. free(glo); glo = NULL;
  721. cvProcessError(cv_mem, CV_MEM_FAIL, "CVODE", "CVodeRootInit", MSGCV_MEM_FAIL);
  722. return(CV_MEM_FAIL);
  723. }
  724. grout = NULL;
  725. grout = (realtype *) malloc(nrt*sizeof(realtype));
  726. if (grout == NULL) {
  727. free(glo); glo = NULL;
  728. free(ghi); ghi = NULL;
  729. cvProcessError(cv_mem, CV_MEM_FAIL, "CVODE", "CVodeRootInit", MSGCV_MEM_FAIL);
  730. return(CV_MEM_FAIL);
  731. }
  732. iroots = NULL;
  733. iroots = (int *) malloc(nrt*sizeof(int));
  734. if (iroots == NULL) {
  735. free(glo); glo = NULL;
  736. free(ghi); ghi = NULL;
  737. free(grout); grout = NULL;
  738. cvProcessError(cv_mem, CV_MEM_FAIL, "CVODE", "CVodeRootInit", MSGCV_MEM_FAIL);
  739. return(CV_MEM_FAIL);
  740. }
  741. rootdir = NULL;
  742. rootdir = (int *) malloc(nrt*sizeof(int));
  743. if (rootdir == NULL) {
  744. free(glo); glo = NULL;
  745. free(ghi); ghi = NULL;
  746. free(grout); grout = NULL;
  747. free(iroots); iroots = NULL;
  748. cvProcessError(cv_mem, CV_MEM_FAIL, "CVODE", "CVodeRootInit", MSGCV_MEM_FAIL);
  749. return(CV_MEM_FAIL);
  750. }
  751. gactive = NULL;
  752. gactive = (booleantype *) malloc(nrt*sizeof(booleantype));
  753. if (gactive == NULL) {
  754. free(glo); glo = NULL;
  755. free(ghi); ghi = NULL;
  756. free(grout); grout = NULL;
  757. free(iroots); iroots = NULL;
  758. free(rootdir); rootdir = NULL;
  759. cvProcessError(cv_mem, CV_MEM_FAIL, "CVODES", "CVodeRootInit", MSGCV_MEM_FAIL);
  760. return(CV_MEM_FAIL);
  761. }
  762. /* Set default values for rootdir (both directions) */
  763. for(i=0; i<nrt; i++) rootdir[i] = 0;
  764. /* Set default values for gactive (all active) */
  765. for(i=0; i<nrt; i++) gactive[i] = TRUE;
  766. lrw += 3*nrt;
  767. liw += 3*nrt;
  768. return(CV_SUCCESS);
  769. }
  770. /* Step Root functionality Added by 3ds.com */
  771. SUNDIALS_EXPORT int CVodeStepRootInit(void *cvode_mem, CVStepRootFn g) {
  772. CVodeMem cv_mem;
  773. /* Check cvode_mem pointer */
  774. if (cvode_mem == NULL) {
  775. cvProcessError(NULL, CV_MEM_NULL, "CVODE", "CVodeRootInit", MSGCV_NO_MEM);
  776. return(CV_MEM_NULL);
  777. }
  778. cv_mem = (CVodeMem) cvode_mem;
  779. cv_mem->cv_stepgfun = g;
  780. return(CV_SUCCESS);
  781. }
  782. /*
  783. * =================================================================
  784. * Readibility Constants
  785. * =================================================================
  786. */
  787. #define f (cv_mem->cv_f)
  788. #define user_data (cv_mem->cv_user_data)
  789. #define efun (cv_mem->cv_efun)
  790. #define e_data (cv_mem->cv_e_data)
  791. #define qmax (cv_mem->cv_qmax)
  792. #define mxstep (cv_mem->cv_mxstep)
  793. #define mxhnil (cv_mem->cv_mxhnil)
  794. #define sldeton (cv_mem->cv_sldeton)
  795. #define hin (cv_mem->cv_hin)
  796. #define hmin (cv_mem->cv_hmin)
  797. #define hmax_inv (cv_mem->cv_hmax_inv)
  798. #define tstop (cv_mem->cv_tstop)
  799. #define tstopset (cv_mem->cv_tstopset)
  800. #define maxnef (cv_mem->cv_maxnef)
  801. #define maxncf (cv_mem->cv_maxncf)
  802. #define maxcor (cv_mem->cv_maxcor)
  803. #define nlscoef (cv_mem->cv_nlscoef)
  804. #define itol (cv_mem->cv_itol)
  805. #define reltol (cv_mem->cv_reltol)
  806. #define Sabstol (cv_mem->cv_Sabstol)
  807. #define Vabstol (cv_mem->cv_Vabstol)
  808. #define uround (cv_mem->cv_uround)
  809. #define zn (cv_mem->cv_zn)
  810. #define ewt (cv_mem->cv_ewt)
  811. #define y (cv_mem->cv_y)
  812. #define acor (cv_mem->cv_acor)
  813. #define tempv (cv_mem->cv_tempv)
  814. #define ftemp (cv_mem->cv_ftemp)
  815. #define q (cv_mem->cv_q)
  816. #define qprime (cv_mem->cv_qprime)
  817. #define next_q (cv_mem->cv_next_q)
  818. #define qwait (cv_mem->cv_qwait)
  819. #define L (cv_mem->cv_L)
  820. #define h (cv_mem->cv_h)
  821. #define hprime (cv_mem->cv_hprime)
  822. #define next_h (cv_mem->cv_next_h)
  823. #define eta (cv_mem->cv_eta)
  824. #define etaqm1 (cv_mem->cv_etaqm1)
  825. #define etaq (cv_mem->cv_etaq)
  826. #define etaqp1 (cv_mem->cv_etaqp1)
  827. #define nscon (cv_mem->cv_nscon)
  828. #define hscale (cv_mem->cv_hscale)
  829. #define tn (cv_mem->cv_tn)
  830. #define tau (cv_mem->cv_tau)
  831. #define tq (cv_mem->cv_tq)
  832. #define l (cv_mem->cv_l)
  833. #define rl1 (cv_mem->cv_rl1)
  834. #define gamma (cv_mem->cv_gamma)
  835. #define gammap (cv_mem->cv_gammap)
  836. #define gamrat (cv_mem->cv_gamrat)
  837. #define crate (cv_mem->cv_crate)
  838. #define acnrm (cv_mem->cv_acnrm)
  839. #define mnewt (cv_mem->cv_mnewt)
  840. #define etamax (cv_mem->cv_etamax)
  841. #define nst (cv_mem->cv_nst)
  842. #define nfe (cv_mem->cv_nfe)
  843. #define ncfn (cv_mem->cv_ncfn)
  844. #define netf (cv_mem->cv_netf)
  845. #define nni (cv_mem->cv_nni)
  846. #define nsetups (cv_mem->cv_nsetups)
  847. #define nhnil (cv_mem->cv_nhnil)
  848. #define linit (cv_mem->cv_linit)
  849. #define lsetup (cv_mem->cv_lsetup)
  850. #define lsolve (cv_mem->cv_lsolve)
  851. #define lfree (cv_mem->cv_lfree)
  852. #define lmem (cv_mem->cv_lmem)
  853. #define qu (cv_mem->cv_qu)
  854. #define nstlp (cv_mem->cv_nstlp)
  855. #define h0u (cv_mem->cv_h0u)
  856. #define hu (cv_mem->cv_hu)
  857. #define saved_tq5 (cv_mem->cv_saved_tq5)
  858. #define indx_acor (cv_mem->cv_indx_acor)
  859. #define jcur (cv_mem->cv_jcur)
  860. #define tolsf (cv_mem->cv_tolsf)
  861. #define setupNonNull (cv_mem->cv_setupNonNull)
  862. #define nor (cv_mem->cv_nor)
  863. #define ssdat (cv_mem->cv_ssdat)
  864. #define nrtfn (cv_mem->cv_nrtfn)
  865. #define tlo (cv_mem->cv_tlo)
  866. #define thi (cv_mem->cv_thi)
  867. #define tretlast (cv_mem->cv_tretlast)
  868. #define toutc (cv_mem->cv_toutc)
  869. #define trout (cv_mem->cv_trout)
  870. #define ttol (cv_mem->cv_ttol)
  871. #define taskc (cv_mem->cv_taskc)
  872. #define irfnd (cv_mem->cv_irfnd)
  873. #define nge (cv_mem->cv_nge)
  874. /*-----------------------------------------------------------------*/
  875. /*
  876. * CVode
  877. *
  878. * This routine is the main driver of the CVODE package.
  879. *
  880. * It integrates over a time interval defined by the user, by calling
  881. * cvStep to do internal time steps.
  882. *
  883. * The first time that CVode is called for a successfully initialized
  884. * problem, it computes a tentative initial step size h.
  885. *
  886. * CVode supports two modes, specified by itask: CV_NORMAL, CV_ONE_STEP.
  887. * In the CV_NORMAL mode, the solver steps until it reaches or passes tout
  888. * and then interpolates to obtain y(tout).
  889. * In the CV_ONE_STEP mode, it takes one internal step and returns.
  890. */
  891. SUNDIALS_EXPORT int CVode(void *cvode_mem, realtype tout, N_Vector yout,
  892. realtype *tret, int itask)
  893. {
  894. CVodeMem cv_mem;
  895. long int nstloc;
  896. int retval, hflag, kflag, istate, ir, ier, irfndp;
  897. int ewtsetOK;
  898. realtype troundoff, tout_hin, rh, nrm;
  899. booleantype inactive_roots;
  900. /*
  901. * -------------------------------------
  902. * 1. Check and process inputs
  903. * -------------------------------------
  904. */
  905. /* Check if cvode_mem exists */
  906. if (cvode_mem == NULL) {
  907. cvProcessError(NULL, CV_MEM_NULL, "CVODE", "CVode", MSGCV_NO_MEM);
  908. return(CV_MEM_NULL);
  909. }
  910. cv_mem = (CVodeMem) cvode_mem;
  911. /* Check if cvode_mem was allocated */
  912. if (cv_mem->cv_MallocDone == FALSE) {
  913. cvProcessError(cv_mem, CV_NO_MALLOC, "CVODE", "CVode", MSGCV_NO_MALLOC);
  914. return(CV_NO_MALLOC);
  915. }
  916. /* Check for yout != NULL */
  917. if ((y = yout) == NULL) {
  918. cvProcessError(cv_mem, CV_ILL_INPUT, "CVODE", "CVode", MSGCV_YOUT_NULL);
  919. return(CV_ILL_INPUT);
  920. }
  921. /* Check for tret != NULL */
  922. if (tret == NULL) {
  923. cvProcessError(cv_mem, CV_ILL_INPUT, "CVODE", "CVode", MSGCV_TRET_NULL);
  924. return(CV_ILL_INPUT);
  925. }
  926. /* Check for valid itask */
  927. if ( (itask != CV_NORMAL) && (itask != CV_ONE_STEP) ) {
  928. cvProcessError(cv_mem, CV_ILL_INPUT, "CVODE", "CVode", MSGCV_BAD_ITASK);
  929. return(CV_ILL_INPUT);
  930. }
  931. if (itask == CV_NORMAL) toutc = tout;
  932. taskc = itask;
  933. /*
  934. * ----------------------------------------
  935. * 2. Initializations performed only at
  936. * the first step (nst=0):
  937. * - initial setup
  938. * - initialize Nordsieck history array
  939. * - compute initial step size
  940. * - check for approach to tstop
  941. * - check for approach to a root
  942. * ----------------------------------------
  943. */
  944. if (nst == 0) {
  945. tretlast = *tret = tn;
  946. ier = cvInitialSetup(cv_mem);
  947. if (ier!= CV_SUCCESS) return(ier);
  948. /* Call f at (t0,y0), set zn[1] = y'(t0),
  949. set initial h (from H0 or cvHin), and scale zn[1] by h.
  950. Also check for zeros of root function g at and near t0. */
  951. retval = f(tn, zn[0], zn[1], user_data);
  952. nfe++;
  953. if (retval < 0) {
  954. cvProcessError(cv_mem, CV_RHSFUNC_FAIL, "CVODE", "CVode", MSGCV_RHSFUNC_FAILED, tn);
  955. return(CV_RHSFUNC_FAIL);
  956. }
  957. if (retval > 0) {
  958. cvProcessError(cv_mem, CV_FIRST_RHSFUNC_ERR, "CVODE", "CVode", MSGCV_RHSFUNC_FIRST);
  959. return(CV_FIRST_RHSFUNC_ERR);
  960. }
  961. /* Test input tstop for legality. */
  962. if (tstopset) {
  963. if ( (tstop - tn)*(tout - tn) <= ZERO ) {
  964. cvProcessError(cv_mem, CV_ILL_INPUT, "CVODE", "CVode", MSGCV_BAD_TSTOP, tstop, tn);
  965. return(CV_ILL_INPUT);
  966. }
  967. }
  968. /* Set initial h (from H0 or cvHin). */
  969. h = hin;
  970. if ( (h != ZERO) && ((tout-tn)*h < ZERO) ) {
  971. cvProcessError(cv_mem, CV_ILL_INPUT, "CVODE", "CVode", MSGCV_BAD_H0);
  972. return(CV_ILL_INPUT);
  973. }
  974. if (h == ZERO) {
  975. tout_hin = tout;
  976. if ( tstopset && (tout-tn)*(tout-tstop) > ZERO ) tout_hin = tstop;
  977. hflag = cvHin(cv_mem, tout_hin);
  978. if (hflag != CV_SUCCESS) {
  979. istate = cvHandleFailure(cv_mem, hflag);
  980. return(istate);
  981. }
  982. }
  983. rh = SUNRabs(h)*hmax_inv;
  984. if (rh > ONE) h /= rh;
  985. if (SUNRabs(h) < hmin) h *= hmin/SUNRabs(h);
  986. /* Check for approach to tstop */
  987. if (tstopset) {
  988. if ( (tn + h - tstop)*h > ZERO )
  989. h = (tstop - tn)*(ONE-FOUR*uround);
  990. }
  991. /* Scale zn[1] by h.*/
  992. hscale = h;
  993. h0u = h;
  994. hprime = h;
  995. N_VScale(h, zn[1], zn[1]);
  996. /* Check for zeros of root function g at and near t0. */
  997. if (nrtfn > 0) {
  998. retval = cvRcheck1(cv_mem);
  999. if (retval == CV_RTFUNC_FAIL) {
  1000. cvProcessError(cv_mem, CV_RTFUNC_FAIL, "CVODE", "cvRcheck1", MSGCV_RTFUNC_FAILED, tn);
  1001. return(CV_RTFUNC_FAIL);
  1002. }
  1003. }
  1004. } /* end of first call block */
  1005. /*
  1006. * ------------------------------------------------------
  1007. * 3. At following steps, perform stop tests:
  1008. * - check for root in last step
  1009. * - check if we passed tstop
  1010. * - check if we passed tout (NORMAL mode)
  1011. * - check if current tn was returned (ONE_STEP mode)
  1012. * - check if we are close to tstop
  1013. * (adjust step size if needed)
  1014. * -------------------------------------------------------
  1015. */
  1016. if (nst > 0) {
  1017. /* Estimate an infinitesimal time interval to be used as
  1018. a roundoff for time quantities (based on current time
  1019. and step size) */
  1020. troundoff = FUZZ_FACTOR*uround*(SUNRabs(tn) + SUNRabs(h));
  1021. /* First, check for a root in the last step taken, other than the
  1022. last root found, if any. If itask = CV_ONE_STEP and y(tn) was not
  1023. returned because of an intervening root, return y(tn) now. */
  1024. if (nrtfn > 0) {
  1025. irfndp = irfnd;
  1026. retval = cvRcheck2(cv_mem);
  1027. if (retval == CLOSERT) {
  1028. cvProcessError(cv_mem, CV_ILL_INPUT, "CVODE", "cvRcheck2", MSGCV_CLOSE_ROOTS, tlo);
  1029. return(CV_ILL_INPUT);
  1030. } else if (retval == CV_RTFUNC_FAIL) {
  1031. cvProcessError(cv_mem, CV_RTFUNC_FAIL, "CVODE", "cvRcheck2", MSGCV_RTFUNC_FAILED, tlo);
  1032. return(CV_RTFUNC_FAIL);
  1033. } else if (retval == RTFOUND) {
  1034. tretlast = *tret = tlo;
  1035. return(CV_ROOT_RETURN);
  1036. }
  1037. /* If tn is distinct from tretlast (within roundoff),
  1038. check remaining interval for roots */
  1039. if ( SUNRabs(tn - tretlast) > troundoff ) {
  1040. retval = cvRcheck3(cv_mem);
  1041. if (retval == CV_SUCCESS) { /* no root found */
  1042. irfnd = 0;
  1043. if ((irfndp == 1) && (itask == CV_ONE_STEP)) {
  1044. tretlast = *tret = tn;
  1045. N_VScale(ONE, zn[0], yout);
  1046. return(CV_SUCCESS);
  1047. }
  1048. } else if (retval == RTFOUND) { /* a new root was found */
  1049. irfnd = 1;
  1050. tretlast = *tret = tlo;
  1051. return(CV_ROOT_RETURN);
  1052. } else if (retval == CV_RTFUNC_FAIL) { /* g failed */
  1053. cvProcessError(cv_mem, CV_RTFUNC_FAIL, "CVODE", "cvRcheck3", MSGCV_RTFUNC_FAILED, tlo);
  1054. return(CV_RTFUNC_FAIL);
  1055. }
  1056. }
  1057. } /* end of root stop check */
  1058. /* In CV_NORMAL mode, test if tout was reached */
  1059. if ( (itask == CV_NORMAL) && ((tn-tout)*h >= ZERO) ) {
  1060. tretlast = *tret = tout;
  1061. ier = CVodeGetDky(cv_mem, tout, 0, yout);
  1062. if (ier != CV_SUCCESS) {
  1063. cvProcessError(cv_mem, CV_ILL_INPUT, "CVODE", "CVode", MSGCV_BAD_TOUT, tout);
  1064. return(CV_ILL_INPUT);
  1065. }
  1066. return(CV_SUCCESS);
  1067. }
  1068. /* In CV_ONE_STEP mode, test if tn was returned */
  1069. if ( itask == CV_ONE_STEP && SUNRabs(tn - tretlast) > troundoff ) {
  1070. tretlast = *tret = tn;
  1071. N_VScale(ONE, zn[0], yout);
  1072. return(CV_SUCCESS);
  1073. }
  1074. /* Test for tn at tstop or near tstop */
  1075. if ( tstopset ) {
  1076. if ( SUNRabs(tn - tstop) <= troundoff) {
  1077. ier = CVodeGetDky(cv_mem, tstop, 0, yout);
  1078. if (ier != CV_SUCCESS) {
  1079. cvProcessError(cv_mem, CV_ILL_INPUT, "CVODE", "CVode", MSGCV_BAD_TSTOP, tstop, tn);
  1080. return(CV_ILL_INPUT);
  1081. }
  1082. tretlast = *tret = tstop;
  1083. tstopset = FALSE;
  1084. return(CV_TSTOP_RETURN);
  1085. }
  1086. /* If next step would overtake tstop, adjust stepsize */
  1087. if ( (tn + hprime - tstop)*h > ZERO ) {
  1088. hprime = (tstop - tn)*(ONE-FOUR*uround);
  1089. eta = hprime/h;
  1090. }
  1091. }
  1092. } /* end stopping tests block */
  1093. /*
  1094. * --------------------------------------------------
  1095. * 4. Looping point for internal steps
  1096. *
  1097. * 4.1. check for errors (too many steps, too much
  1098. * accuracy requested, step size too small)
  1099. * 4.2. take a new step (call cvStep)
  1100. * 4.3. stop on error
  1101. * 4.4. perform stop tests:
  1102. * - check for root in last step
  1103. * - check if tout was passed
  1104. * - check if close to tstop
  1105. * - check if in ONE_STEP mode (must return)
  1106. * --------------------------------------------------
  1107. */
  1108. nstloc = 0;
  1109. loop {
  1110. next_h = h;
  1111. next_q = q;
  1112. /* Reset and check ewt */
  1113. if (nst > 0) {
  1114. ewtsetOK = efun(zn[0], ewt, e_data);
  1115. if (ewtsetOK != 0) {
  1116. if (itol == CV_WF)
  1117. cvProcessError(cv_mem, CV_ILL_INPUT, "CVODE", "CVode", MSGCV_EWT_NOW_FAIL, tn);
  1118. else
  1119. cvProcessError(cv_mem, CV_ILL_INPUT, "CVODE", "CVode", MSGCV_EWT_NOW_BAD, tn);
  1120. istate = CV_ILL_INPUT;
  1121. tretlast = *tret = tn;
  1122. N_VScale(ONE, zn[0], yout);
  1123. break;
  1124. }
  1125. }
  1126. /* Check for too many steps */
  1127. if ( (mxstep>0) && (nstloc >= mxstep) ) {
  1128. cvProcessError(cv_mem, CV_TOO_MUCH_WORK, "CVODE", "CVode", MSGCV_MAX_STEPS, tn);
  1129. istate = CV_TOO_MUCH_WORK;
  1130. tretlast = *tret = tn;
  1131. N_VScale(ONE, zn[0], yout);
  1132. break;
  1133. }
  1134. /* Check for too much accuracy requested */
  1135. nrm = N_VWrmsNorm(zn[0], ewt);
  1136. tolsf = uround * nrm;
  1137. if (tolsf > ONE) {
  1138. cvProcessError(cv_mem, CV_TOO_MUCH_ACC, "CVODE", "CVode", MSGCV_TOO_MUCH_ACC, tn);
  1139. istate = CV_TOO_MUCH_ACC;
  1140. tretlast = *tret = tn;
  1141. N_VScale(ONE, zn[0], yout);
  1142. tolsf *= TWO;
  1143. break;
  1144. } else {
  1145. tolsf = ONE;
  1146. }
  1147. /* Check for h below roundoff level in tn */
  1148. if (tn + h == tn) {
  1149. nhnil++;
  1150. if (nhnil <= mxhnil)
  1151. cvProcessError(cv_mem, CV_WARNING, "CVODE", "CVode", MSGCV_HNIL, tn, h);
  1152. if (nhnil == mxhnil)
  1153. cvProcessError(cv_mem, CV_WARNING, "CVODE", "CVode", MSGCV_HNIL_DONE);
  1154. }
  1155. /* Call cvStep to take a step */
  1156. kflag = cvStep(cv_mem);
  1157. /* Process failed step cases, and exit loop */
  1158. if (kflag != CV_SUCCESS) {
  1159. istate = cvHandleFailure(cv_mem, kflag);
  1160. tretlast = *tret = tn;
  1161. N_VScale(ONE, zn[0], yout);
  1162. break;
  1163. }
  1164. nstloc++;
  1165. /* Check for root in last step taken. */
  1166. if (nrtfn > 0) {
  1167. retval = cvRcheck3(cv_mem);
  1168. if (retval == RTFOUND) { /* A new root was found */
  1169. irfnd = 1;
  1170. istate = CV_ROOT_RETURN;
  1171. tretlast = *tret = tlo;
  1172. break;
  1173. } else if (retval == CV_RTFUNC_FAIL) { /* g failed */
  1174. cvProcessError(cv_mem, CV_RTFUNC_FAIL, "CVODE", "cvRcheck3", MSGCV_RTFUNC_FAILED, tlo);
  1175. istate = CV_RTFUNC_FAIL;
  1176. break;
  1177. }
  1178. /* If we are at the end of the first step and we still have
  1179. * some event functions that are inactive, issue a warning
  1180. * as this may indicate a user error in the implementation
  1181. * of the root function. */
  1182. if (nst==1) {
  1183. inactive_roots = FALSE;
  1184. for (ir=0; ir<nrtfn; ir++) {
  1185. if (!gactive[ir]) {
  1186. inactive_roots = TRUE;
  1187. break;
  1188. }
  1189. }
  1190. if ((cv_mem->cv_mxgnull > 0) && inactive_roots) {
  1191. cvProcessError(cv_mem, CV_WARNING, "CVODES", "CVode", MSGCV_INACTIVE_ROOTS);
  1192. }
  1193. }
  1194. }
  1195. if (cv_mem->cv_stepgfun && (cv_mem->cv_stepgfun)(user_data)) {
  1196. if (taskc == CV_ONE_STEP) {
  1197. thi = tn;
  1198. N_VScale(ONE, zn[0], y);
  1199. }
  1200. if (taskc == CV_NORMAL) {
  1201. if ( (toutc - tn)*h >= ZERO) {
  1202. thi = tn;
  1203. N_VScale(ONE, zn[0], y);
  1204. } else {
  1205. thi = toutc;
  1206. (void) CVodeGetDky(cv_mem, thi, 0, y);
  1207. }
  1208. }
  1209. irfnd = 1;
  1210. istate = CV_ROOT_RETURN;
  1211. tretlast = *tret = thi;
  1212. break;
  1213. }
  1214. /* In NORMAL mode, check if tout reached */
  1215. if ( (itask == CV_NORMAL) && (tn-tout)*h >= ZERO ) {
  1216. istate = CV_SUCCESS;
  1217. tretlast = *tret = tout;
  1218. (void) CVodeGetDky(cv_mem, tout, 0, yout);
  1219. next_q = qprime;
  1220. next_h = hprime;
  1221. break;
  1222. }
  1223. /* Check if tn is at tstop or near tstop */
  1224. if ( tstopset ) {
  1225. troundoff = FUZZ_FACTOR*uround*(SUNRabs(tn) + SUNRabs(h));
  1226. if ( SUNRabs(tn - tstop) <= troundoff) {
  1227. (void) CVodeGetDky(cv_mem, tstop, 0, yout);
  1228. tretlast = *tret = tstop;
  1229. tstopset = FALSE;
  1230. istate = CV_TSTOP_RETURN;
  1231. break;
  1232. }
  1233. if ( (tn + hprime - tstop)*h > ZERO ) {
  1234. hprime = (tstop - tn)*(ONE-FOUR*uround);
  1235. eta = hprime/h;
  1236. }
  1237. }
  1238. /* In ONE_STEP mode, copy y and exit loop */
  1239. if (itask == CV_ONE_STEP) {
  1240. istate = CV_SUCCESS;
  1241. tretlast = *tret = tn;
  1242. N_VScale(ONE, zn[0], yout);
  1243. next_q = qprime;
  1244. next_h = hprime;
  1245. break;
  1246. }
  1247. } /* end looping for internal steps */
  1248. return(istate);
  1249. }
  1250. /*-----------------------------------------------------------------*/
  1251. /*
  1252. * CVodeGetDky
  1253. *
  1254. * This routine computes the k-th derivative of the interpolating
  1255. * polynomial at the time t and stores the result in the vector dky.
  1256. * The formula is:
  1257. * q
  1258. * dky = SUM c(j,k) * (t - tn)^(j-k) * h^(-j) * zn[j] ,
  1259. * j=k
  1260. * where c(j,k) = j*(j-1)*...*(j-k+1), q is the current order, and
  1261. * zn[j] is the j-th column of the Nordsieck history array.
  1262. *
  1263. * This function is called by CVode with k = 0 and t = tout, but
  1264. * may also be called directly by the user.
  1265. */
  1266. SUNDIALS_EXPORT int CVodeGetDky(void *cvode_mem, realtype t, int k, N_Vector dky)
  1267. {
  1268. realtype s, c, r;
  1269. realtype tfuzz, tp, tn1;
  1270. int i, j;
  1271. CVodeMem cv_mem;
  1272. /* Check all inputs for legality */
  1273. if (cvode_mem == NULL) {
  1274. cvProcessError(NULL, CV_MEM_NULL, "CVODE", "CVodeGetDky", MSGCV_NO_MEM);
  1275. return(CV_MEM_NULL);
  1276. }
  1277. cv_mem = (CVodeMem) cvode_mem;
  1278. if (dky == NULL) {
  1279. cvProcessError(cv_mem, CV_BAD_DKY, "CVODE", "CVodeGetDky", MSGCV_NULL_DKY);
  1280. return(CV_BAD_DKY);
  1281. }
  1282. if ((k < 0) || (k > q)) {
  1283. cvProcessError(cv_mem, CV_BAD_K, "CVODE", "CVodeGetDky", MSGCV_BAD_K);
  1284. return(CV_BAD_K);
  1285. }
  1286. /* Allow for some slack */
  1287. tfuzz = FUZZ_FACTOR * uround * (SUNRabs(tn) + SUNRabs(hu));
  1288. if (hu < ZERO) tfuzz = -tfuzz;
  1289. tp = tn - hu - tfuzz;
  1290. tn1 = tn + tfuzz;
  1291. if ((t-tp)*(t-tn1) > ZERO) {
  1292. cvProcessError(cv_mem, CV_BAD_T, "CVODE", "CVodeGetDky", MSGCV_BAD_T, t, tn-hu, tn);
  1293. return(CV_BAD_T);
  1294. }
  1295. /* Sum the differentiated interpolating polynomial */
  1296. s = (t - tn) / h;
  1297. for (j=q; j >= k; j--) {
  1298. c = ONE;
  1299. for (i=j; i >= j-k+1; i--) c *= i;
  1300. if (j == q) {
  1301. N_VScale(c, zn[q], dky);
  1302. } else {
  1303. N_VLinearSum(c, zn[j], s, dky, dky);
  1304. }
  1305. }
  1306. if (k == 0) return(CV_SUCCESS);
  1307. r = SUNRpowerI(h,-k);
  1308. N_VScale(r, dky, dky);
  1309. return(CV_SUCCESS);
  1310. }
  1311. /*
  1312. * CVodeFree
  1313. *
  1314. * This routine frees the problem memory allocated by CVodeInit.
  1315. * Such memory includes all the vectors allocated by cvAllocVectors,
  1316. * and the memory lmem for the linear solver (deallocated by a call
  1317. * to lfree).
  1318. */
  1319. SUNDIALS_EXPORT void CVodeFree(void **cvode_mem)
  1320. {
  1321. CVodeMem cv_mem;
  1322. if (*cvode_mem == NULL) return;
  1323. cv_mem = (CVodeMem) (*cvode_mem);
  1324. cvFreeVectors(cv_mem);
  1325. if (iter == CV_NEWTON && lfree != NULL) lfree(cv_mem);
  1326. if (nrtfn > 0) {
  1327. free(glo); glo = NULL;
  1328. free(ghi); ghi = NULL;
  1329. free(grout); grout = NULL;
  1330. free(iroots); iroots = NULL;
  1331. free(rootdir); rootdir = NULL;
  1332. free(gactive); gactive = NULL;
  1333. }
  1334. free(*cvode_mem);
  1335. *cvode_mem = NULL;
  1336. }
  1337. /*
  1338. * =================================================================
  1339. * Private Functions Implementation
  1340. * =================================================================
  1341. */
  1342. /*
  1343. * cvCheckNvector
  1344. * This routine checks if all required vector operations are present.
  1345. * If any of them is missing it returns FALSE.
  1346. */
  1347. static booleantype cvCheckNvector(N_Vector tmpl)
  1348. {
  1349. if((tmpl->ops->nvclone == NULL) ||
  1350. (tmpl->ops->nvdestroy == NULL) ||
  1351. (tmpl->ops->nvlinearsum == NULL) ||
  1352. (tmpl->ops->nvconst == NULL) ||
  1353. (tmpl->ops->nvprod == NULL) ||
  1354. (tmpl->ops->nvdiv == NULL) ||
  1355. (tmpl->ops->nvscale == NULL) ||
  1356. (tmpl->ops->nvabs == NULL) ||
  1357. (tmpl->ops->nvinv == NULL) ||
  1358. (tmpl->ops->nvaddconst == NULL) ||
  1359. (tmpl->ops->nvmaxnorm == NULL) ||
  1360. (tmpl->ops->nvwrmsnorm == NULL) ||
  1361. (tmpl->ops->nvmin == NULL))
  1362. return(FALSE);
  1363. else
  1364. return(TRUE);
  1365. }
  1366. /*
  1367. * cvAllocVectors
  1368. *
  1369. * This routine allocates the CVODE vectors ewt, acor, tempv, ftemp, and
  1370. * zn[0], ..., zn[maxord].
  1371. * If all memory allocations are successful, cvAllocVectors returns TRUE.
  1372. * Otherwise all allocated memory is freed and cvAllocVectors returns FALSE.
  1373. * This routine also sets the optional outputs lrw and liw, which are
  1374. * (respectively) the lengths of the real and integer work spaces
  1375. * allocated here.
  1376. */
  1377. static booleantype cvAllocVectors(CVodeMem cv_mem, N_Vector tmpl)
  1378. {
  1379. int i, j;
  1380. /* Allocate ewt, acor, tempv, ftemp */
  1381. ewt = N_VClone(tmpl);
  1382. if (ewt == NULL) return(FALSE);
  1383. acor = N_VClone(tmpl);
  1384. if (acor == NULL) {
  1385. N_VDestroy(ewt);
  1386. return(FALSE);
  1387. }
  1388. tempv = N_VClone(tmpl);
  1389. if (tempv == NULL) {
  1390. N_VDestroy(ewt);
  1391. N_VDestroy(acor);
  1392. return(FALSE);
  1393. }
  1394. ftemp = N_VClone(tmpl);
  1395. if (ftemp == NULL) {
  1396. N_VDestroy(tempv);
  1397. N_VDestroy(ewt);
  1398. N_VDestroy(acor);
  1399. return(FALSE);
  1400. }
  1401. /* Allocate zn[0] ... zn[qmax] */
  1402. for (j=0; j <= qmax; j++) {
  1403. zn[j] = N_VClone(tmpl);
  1404. if (zn[j] == NULL) {
  1405. N_VDestroy(ewt);
  1406. N_VDestroy(acor);
  1407. N_VDestroy(tempv);
  1408. N_VDestroy(ftemp);
  1409. for (i=0; i < j; i++) N_VDestroy(zn[i]);
  1410. return(FALSE);
  1411. }
  1412. }
  1413. /* Update solver workspace lengths */
  1414. lrw += (qmax + 5)*lrw1;
  1415. liw += (qmax + 5)*liw1;
  1416. /* Store the value of qmax used here */
  1417. cv_mem->cv_qmax_alloc = qmax;
  1418. return(TRUE);
  1419. }
  1420. /*
  1421. * cvFreeVectors
  1422. *
  1423. * This routine frees the CVODE vectors allocated in cvAllocVectors.
  1424. */
  1425. static void cvFreeVectors(CVodeMem cv_mem)
  1426. {
  1427. int j, maxord;
  1428. maxord = cv_mem->cv_qmax_alloc;
  1429. N_VDestroy(ewt);
  1430. N_VDestroy(acor);
  1431. N_VDestroy(tempv);
  1432. N_VDestroy(ftemp);
  1433. for (j=0; j <= maxord; j++) N_VDestroy(zn[j]);
  1434. lrw -= (maxord + 5)*lrw1;
  1435. liw -= (maxord + 5)*liw1;
  1436. if (cv_mem->cv_VabstolMallocDone) {
  1437. N_VDestroy(Vabstol);
  1438. lrw -= lrw1;
  1439. liw -= liw1;
  1440. }
  1441. }
  1442. /*
  1443. * cvInitialSetup
  1444. *
  1445. * This routine performs input consistency checks at the first step.
  1446. * If needed, it also checks the linear solver module and calls the
  1447. * linear solver initialization routine.
  1448. */
  1449. static int cvInitialSetup(CVodeMem cv_mem)
  1450. {
  1451. int ier;
  1452. /* Did the user specify tolerances? */
  1453. if (itol == CV_NN) {
  1454. cvProcessError(cv_mem, CV_ILL_INPUT, "CVODE", "cvInitialSetup", MSGCV_NO_TOLS);
  1455. return(CV_ILL_INPUT);
  1456. }
  1457. /* Set data for efun */
  1458. if (cv_mem->cv_user_efun) e_data = user_data;
  1459. else e_data = cv_mem;
  1460. /* Load initial error weights */
  1461. ier = efun(zn[0], ewt, e_data);
  1462. if (ier != 0) {
  1463. if (itol == CV_WF)
  1464. cvProcessError(cv_mem, CV_ILL_INPUT, "CVODE", "cvInitialSetup", MSGCV_EWT_FAIL);
  1465. else
  1466. cvProcessError(cv_mem, CV_ILL_INPUT, "CVODE", "cvInitialSetup", MSGCV_BAD_EWT);
  1467. return(CV_ILL_INPUT);
  1468. }
  1469. /* Check if lsolve function exists (if needed) and call linit function (if it exists) */
  1470. if (iter == CV_NEWTON) {
  1471. if (lsolve == NULL) {
  1472. cvProcessError(cv_mem, CV_ILL_INPUT, "CVODE", "cvInitialSetup", MSGCV_LSOLVE_NULL);
  1473. return(CV_ILL_INPUT);
  1474. }
  1475. if (linit != NULL) {
  1476. ier = linit(cv_mem);
  1477. if (ier != 0) {
  1478. cvProcessError(cv_mem, CV_LINIT_FAIL, "CVODE", "cvInitialSetup", MSGCV_LINIT_FAIL);
  1479. return(CV_LINIT_FAIL);
  1480. }
  1481. }
  1482. }
  1483. return(CV_SUCCESS);
  1484. }
  1485. /*
  1486. * -----------------------------------------------------------------
  1487. * PRIVATE FUNCTIONS FOR CVODE
  1488. * -----------------------------------------------------------------
  1489. */
  1490. /*
  1491. * cvHin
  1492. *
  1493. * This routine computes a tentative initial step size h0.
  1494. * If tout is too close to tn (= t0), then cvHin returns CV_TOO_CLOSE
  1495. * and h remains uninitialized. Note that here tout is either the value
  1496. * passed to CVode at the first call or the value of tstop (if tstop is
  1497. * enabled and it is closer to t0=tn than tout).
  1498. * If the RHS function fails unrecoverably, cvHin returns CV_RHSFUNC_FAIL.
  1499. * If the RHS function fails recoverably too many times and recovery is
  1500. * not possible, cvHin returns CV_REPTD_RHSFUNC_ERR.
  1501. * Otherwise, cvHin sets h to the chosen value h0 and returns CV_SUCCESS.
  1502. *
  1503. * The algorithm used seeks to find h0 as a solution of
  1504. * (WRMS norm of (h0^2 ydd / 2)) = 1,
  1505. * where ydd = estimated second derivative of y.
  1506. *
  1507. * We start with an initial estimate equal to the geometric mean of the
  1508. * lower and upper bounds on the step size.
  1509. *
  1510. * Loop up to MAX_ITERS times to find h0.
  1511. * Stop if new and previous values differ by a factor < 2.
  1512. * Stop if hnew/hg > 2 after one iteration, as this probably means
  1513. * that the ydd value is bad because of cancellation error.
  1514. *
  1515. * For each new proposed hg, we allow MAX_ITERS attempts to
  1516. * resolve a possible recoverable failure from f() by reducing
  1517. * the proposed stepsize by a factor of 0.2. If a legal stepsize
  1518. * still cannot be found, fall back on a previous value if possible,
  1519. * or else return CV_REPTD_RHSFUNC_ERR.
  1520. *
  1521. * Finally, we apply a bias (0.5) and verify that h0 is within bounds.
  1522. */
  1523. static int cvHin(CVodeMem cv_mem, realtype tout)
  1524. {
  1525. int retval, sign, count1, count2;
  1526. realtype tdiff, tdist, tround, hlb, hub;
  1527. realtype hg, hgs, hs, hnew, hrat, h0, yddnrm;
  1528. booleantype hgOK, hnewOK;
  1529. /* If tout is too close to tn, give up */
  1530. if ((tdiff = tout-tn) == ZERO) return(CV_TOO_CLOSE);
  1531. sign = (tdiff > ZERO) ? 1 : -1;
  1532. tdist = SUNRabs(tdiff);
  1533. tround = uround * SUNMAX(SUNRabs(tn), SUNRabs(tout));
  1534. if (tdist < TWO*tround) return(CV_TOO_CLOSE);
  1535. /*
  1536. Set lower and upper bounds on h0, and take geometric mean
  1537. as first trial value.
  1538. Exit with this value if the bounds cross each other.
  1539. */
  1540. hlb = HLB_FACTOR * tround;
  1541. hub = cvUpperBoundH0(cv_mem, tdist);
  1542. hg = SUNRsqrt(hlb*hub);
  1543. if (hub < hlb) {
  1544. if (sign == -1) h = -hg;
  1545. else h = hg;
  1546. return(CV_SUCCESS);
  1547. }
  1548. /* Outer loop */
  1549. hnewOK = FALSE;
  1550. hs = hg; /* safeguard against 'uninitialized variable' warning */
  1551. for(count1 = 1; count1 <= MAX_ITERS; count1++) {
  1552. /* Attempts to estimate ydd */
  1553. hgOK = FALSE;
  1554. for (count2 = 1; count2 <= MAX_ITERS; count2++) {
  1555. hgs = hg*sign;
  1556. retval = cvYddNorm(cv_mem, hgs, &yddnrm);
  1557. /* If f() failed unrecoverably, give up */
  1558. if (retval < 0) return(CV_RHSFUNC_FAIL);
  1559. /* If successful, we can use ydd */
  1560. if (retval == CV_SUCCESS) {hgOK = TRUE; break;}
  1561. /* f() failed recoverably; cut step size and test it again */
  1562. hg *= POINT2;
  1563. }
  1564. /* If f() failed recoverably MAX_ITERS times */
  1565. if (!hgOK) {
  1566. /* Exit if this is the first or second pass. No recovery possible */
  1567. if (count1 <= 2) return(CV_REPTD_RHSFUNC_ERR);
  1568. /* We have a fall-back option. The value hs is a previous hnew which
  1569. passed through f(). Use it and break */
  1570. hnew = hs;
  1571. break;
  1572. }
  1573. /* The proposed step size is feasible. Save it. */
  1574. hs = hg;
  1575. /* If the stopping criteria was met, or if this is the last pass, stop */
  1576. if ( (hnewOK) || (count1 == MAX_ITERS)) {hnew = hg; break;}
  1577. /* Propose new step size */
  1578. hnew = (yddnrm*hub*hub > TWO) ? SUNRsqrt(TWO/yddnrm) : SUNRsqrt(hg*hub);
  1579. hrat = hnew/hg;
  1580. /* Accept hnew if it does not differ from hg by more than a factor of 2 */
  1581. if ((hrat > HALF) && (hrat < TWO)) {
  1582. hnewOK = TRUE;
  1583. }
  1584. /* After one pass, if ydd seems to be bad, use fall-back value. */
  1585. if ((count1 > 1) && (hrat > TWO)) {
  1586. hnew = hg;
  1587. hnewOK = TRUE;
  1588. }
  1589. /* Send this value back through f() */
  1590. hg = hnew;
  1591. }
  1592. /* Apply bounds, bias factor, and attach sign */
  1593. h0 = H_BIAS*hnew;
  1594. if (h0 < hlb) h0 = hlb;
  1595. if (h0 > hub) h0 = hub;
  1596. if (sign == -1) h0 = -h0;
  1597. h = h0;
  1598. return(CV_SUCCESS);
  1599. }
  1600. /*
  1601. * cvUpperBoundH0
  1602. *
  1603. * This routine sets an upper bound on abs(h0) based on
  1604. * tdist = tn - t0 and the values of y[i]/y'[i].
  1605. */
  1606. static realtype cvUpperBoundH0(CVodeMem cv_mem, realtype tdist)
  1607. {
  1608. realtype hub_inv, hub;
  1609. N_Vector temp1, temp2;
  1610. /*
  1611. * Bound based on |y0|/|y0'| -- allow at most an increase of
  1612. * HUB_FACTOR in y0 (based on a forward Euler step). The weight
  1613. * factor is used as a safeguard against zero components in y0.
  1614. */
  1615. temp1 = tempv;
  1616. temp2 = acor;
  1617. N_VAbs(zn[0], temp2);
  1618. efun(zn[0], temp1, e_data);
  1619. N_VInv(temp1, temp1);
  1620. N_VLinearSum(HUB_FACTOR, temp2, ONE, temp1, temp1);
  1621. N_VAbs(zn[1], temp2);
  1622. N_VDiv(temp2, temp1, temp1);
  1623. hub_inv = N_VMaxNorm(temp1);
  1624. /*
  1625. * bound based on tdist -- allow at most a step of magnitude
  1626. * HUB_FACTOR * tdist
  1627. */
  1628. hub = HUB_FACTOR*tdist;
  1629. /* Use the smaler of the two */
  1630. if (hub*hub_inv > ONE) hub = ONE/hub_inv;
  1631. return(hub);
  1632. }
  1633. /*
  1634. * cvYddNorm
  1635. *
  1636. * This routine computes an estimate of the second derivative of y
  1637. * using a difference quotient, and returns its WRMS norm.
  1638. */
  1639. static int cvYddNorm(CVodeMem cv_mem, realtype hg, realtype *yddnrm)
  1640. {
  1641. int retval;
  1642. N_VLinearSum(hg, zn[1], ONE, zn[0], y);
  1643. retval = f(tn+hg, y, tempv, user_data);
  1644. nfe++;
  1645. if (retval < 0) return(CV_RHSFUNC_FAIL);
  1646. if (retval > 0) return(RHSFUNC_RECVR);
  1647. N_VLinearSum(ONE, tempv, -ONE, zn[1], tempv);
  1648. N_VScale(ONE/hg, tempv, tempv);
  1649. *yddnrm = N_VWrmsNorm(tempv, ewt);
  1650. return(CV_SUCCESS);
  1651. }
  1652. /*
  1653. * cvStep
  1654. *
  1655. * This routine performs one internal cvode step, from tn to tn + h.
  1656. * It calls other routines to do all the work.
  1657. *
  1658. * The main operations done here are as follows:
  1659. * - preliminary adjustments if a new step size was chosen;
  1660. * - prediction of the Nordsieck history array zn at tn + h;
  1661. * - setting of multistep method coefficients and test quantities;
  1662. * - solution of the nonlinear system;
  1663. * - testing the local error;
  1664. * - updating zn and other state data if successful;
  1665. * - resetting stepsize and order for the next step.
  1666. * - if SLDET is on, check for stability, reduce order if necessary.
  1667. * On a failure in the nonlinear system solution or error test, the
  1668. * step may be reattempted, depending on the nature of the failure.
  1669. */
  1670. static int cvStep(CVodeMem cv_mem)
  1671. {
  1672. realtype saved_t, dsm;
  1673. int ncf, nef;
  1674. int nflag, kflag, eflag;
  1675. saved_t = tn;
  1676. ncf = nef = 0;
  1677. nflag = FIRST_CALL;
  1678. if ((nst > 0) && (hprime != h)) cvAdjustParams(cv_mem);
  1679. /* Looping point for attempts to take a step */
  1680. loop {
  1681. cvPredict(cv_mem);
  1682. cvSet(cv_mem);
  1683. nflag = cvNls(cv_mem, nflag);
  1684. kflag = cvHandleNFlag(cv_mem, &nflag, saved_t, &ncf);
  1685. /* Go back in loop if we need to predict again (nflag=PREV_CONV_FAIL)*/
  1686. if (kflag == PREDICT_AGAIN) continue;
  1687. /* Return if nonlinear solve failed and recovery not possible. */
  1688. if (kflag != DO_ERROR_TEST) return(kflag);
  1689. /* Perform error test (nflag=CV_SUCCESS) */
  1690. eflag = cvDoErrorTest(cv_mem, &nflag, saved_t, &nef, &dsm);
  1691. /* Go back in loop if we need to predict again (nflag=PREV_ERR_FAIL) */
  1692. if (eflag == CV_TRY_AGAIN) continue;
  1693. /* Return if error test failed and recovery not possible. */
  1694. if (eflag != CV_SUCCESS) return(eflag);
  1695. /* Error test passed (eflag=CV_SUCCESS), break from loop */
  1696. break;
  1697. }
  1698. /* Nonlinear system solve and error test were both successful.
  1699. Update data, and consider change of step and/or order. */
  1700. cvCompleteStep(cv_mem);
  1701. cvPrepareNextStep(cv_mem, dsm);
  1702. /* If Stablilty Limit Detection is turned on, call stability limit
  1703. detection routine for possible order reduction. */
  1704. if (sldeton) cvBDFStab(cv_mem);
  1705. etamax = (nst <= SMALL_NST) ? ETAMX2 : ETAMX3;
  1706. /* Finally, we rescale the acor array to be the
  1707. estimated local error vector. */
  1708. N_VScale(tq[2], acor, acor);
  1709. return(CV_SUCCESS);
  1710. }
  1711. /*
  1712. * cvAdjustParams
  1713. *
  1714. * This routine is called when a change in step size was decided upon,
  1715. * and it handles the required adjustments to the history array zn.
  1716. * If there is to be a change in order, we call cvAdjustOrder and reset
  1717. * q, L = q+1, and qwait. Then in any case, we call cvRescale, which
  1718. * resets h and rescales the Nordsieck array.
  1719. */
  1720. static void cvAdjustParams(CVodeMem cv_mem)
  1721. {
  1722. if (qprime != q) {
  1723. cvAdjustOrder(cv_mem, qprime-q);
  1724. q = qprime;
  1725. L = q+1;
  1726. qwait = L;
  1727. }
  1728. cvRescale(cv_mem);
  1729. }
  1730. /*
  1731. * cvAdjustOrder
  1732. *
  1733. * This routine is a high level routine which handles an order
  1734. * change by an amount deltaq (= +1 or -1). If a decrease in order
  1735. * is requested and q==2, then the routine returns immediately.
  1736. * Otherwise cvAdjustAdams or cvAdjustBDF is called to handle the
  1737. * order change (depending on the value of lmm).
  1738. */
  1739. static void cvAdjustOrder(CVodeMem cv_mem, int deltaq)
  1740. {
  1741. if ((q==2) && (deltaq != 1)) return;
  1742. switch(lmm){
  1743. case CV_ADAMS:
  1744. cvAdjustAdams(cv_mem, deltaq);
  1745. break;
  1746. case CV_BDF:
  1747. cvAdjustBDF(cv_mem, deltaq);
  1748. break;
  1749. }
  1750. }
  1751. /*
  1752. * cvAdjustAdams
  1753. *
  1754. * This routine adjusts the history array on a change of order q by
  1755. * deltaq, in the case that lmm == CV_ADAMS.
  1756. */
  1757. static void cvAdjustAdams(CVodeMem cv_mem, int deltaq)
  1758. {
  1759. int i, j;
  1760. realtype xi, hsum;
  1761. /* On an order increase, set new column of zn to zero and return */
  1762. if (deltaq==1) {
  1763. N_VConst(ZERO, zn[L]);
  1764. return;
  1765. }
  1766. /*
  1767. * On an order decrease, each zn[j] is adjusted by a multiple of zn[q].
  1768. * The coeffs. in the adjustment are the coeffs. of the polynomial:
  1769. * x
  1770. * q * INT { u * ( u + xi_1 ) * ... * ( u + xi_{q-2} ) } du
  1771. * 0
  1772. * where xi_j = [t_n - t_(n-j)]/h => xi_0 = 0
  1773. */
  1774. for (i=0; i <= qmax; i++) l[i] = ZERO;
  1775. l[1] = ONE;
  1776. hsum = ZERO;
  1777. for (j=1; j <= q-2; j++) {
  1778. hsum += tau[j];
  1779. xi = hsum / hscale;
  1780. for (i=j+1; i >= 1; i--) l[i] = l[i]*xi + l[i-1];
  1781. }
  1782. for (j=1; j <= q-2; j++) l[j+1] = q * (l[j] / (j+1));
  1783. for (j=2; j < q; j++)
  1784. N_VLinearSum(-l[j], zn[q], ONE, zn[j], zn[j]);
  1785. }
  1786. /*
  1787. * cvAdjustBDF
  1788. *
  1789. * This is a high level routine which handles adjustments to the
  1790. * history array on a change of order by deltaq in the case that
  1791. * lmm == CV_BDF. cvAdjustBDF calls cvIncreaseBDF if deltaq = +1 and
  1792. * cvDecreaseBDF if deltaq = -1 to do the actual work.
  1793. */
  1794. static void cvAdjustBDF(CVodeMem cv_mem, int deltaq)
  1795. {
  1796. switch(deltaq) {
  1797. case 1:
  1798. cvIncreaseBDF(cv_mem);
  1799. return;
  1800. case -1:
  1801. cvDecreaseBDF(cv_mem);
  1802. return;
  1803. }
  1804. }
  1805. /*
  1806. * cvIncreaseBDF
  1807. *
  1808. * This routine adjusts the history array on an increase in the
  1809. * order q in the case that lmm == CV_BDF.
  1810. * A new column zn[q+1] is set equal to a multiple of the saved
  1811. * vector (= acor) in zn[indx_acor]. Then each zn[j] is adjusted by
  1812. * a multiple of zn[q+1]. The coefficients in the adjustment are the
  1813. * coefficients of the polynomial x*x*(x+xi_1)*...*(x+xi_j),
  1814. * where xi_j = [t_n - t_(n-j)]/h.
  1815. */
  1816. static void cvIncreaseBDF(CVodeMem cv_mem)
  1817. {
  1818. realtype alpha0, alpha1, prod, xi, xiold, hsum, A1;
  1819. int i, j;
  1820. for (i=0; i <= qmax; i++) l[i] = ZERO;
  1821. l[2] = alpha1 = prod = xiold = ONE;
  1822. alpha0 = -ONE;
  1823. hsum = hscale;
  1824. if (q > 1) {
  1825. for (j=1; j < q; j++) {
  1826. hsum += tau[j+1];
  1827. xi = hsum / hscale;
  1828. prod *= xi;
  1829. alpha0 -= ONE / (j+1);
  1830. alpha1 += ONE / xi;
  1831. for (i=j+2; i >= 2; i--) l[i] = l[i]*xiold + l[i-1];
  1832. xiold = xi;
  1833. }
  1834. }
  1835. A1 = (-alpha0 - alpha1) / prod;
  1836. N_VScale(A1, zn[indx_acor], zn[L]);
  1837. for (j=2; j <= q; j++)
  1838. N_VLinearSum(l[j], zn[L], ONE, zn[j], zn[j]);
  1839. }
  1840. /*
  1841. * cvDecreaseBDF
  1842. *
  1843. * This routine adjusts the history array on a decrease in the
  1844. * order q in the case that lmm == CV_BDF.
  1845. * Each zn[j] is adjusted by a multiple of zn[q]. The coefficients
  1846. * in the adjustment are the coefficients of the polynomial
  1847. * x*x*(x+xi_1)*...*(x+xi_j), where xi_j = [t_n - t_(n-j)]/h.
  1848. */
  1849. static void cvDecreaseBDF(CVodeMem cv_mem)
  1850. {
  1851. realtype hsum, xi;
  1852. int i, j;
  1853. for (i=0; i <= qmax; i++) l[i] = ZERO;
  1854. l[2] = ONE;
  1855. hsum = ZERO;
  1856. for (j=1; j <= q-2; j++) {
  1857. hsum += tau[j];
  1858. xi = hsum /hscale;
  1859. for (i=j+2; i >= 2; i--) l[i] = l[i]*xi + l[i-1];
  1860. }
  1861. for (j=2; j < q; j++)
  1862. N_VLinearSum(-l[j], zn[q], ONE, zn[j], zn[j]);
  1863. }
  1864. /*
  1865. * cvRescale
  1866. *
  1867. * This routine rescales the Nordsieck array by multiplying the
  1868. * jth column zn[j] by eta^j, j = 1, ..., q. Then the value of
  1869. * h is rescaled by eta, and hscale is reset to h.
  1870. */
  1871. static void cvRescale(CVodeMem cv_mem)
  1872. {
  1873. int j;
  1874. realtype factor;
  1875. factor = eta;
  1876. for (j=1; j <= q; j++) {
  1877. N_VScale(factor, zn[j], zn[j]);
  1878. factor *= eta;
  1879. }
  1880. h = hscale * eta;
  1881. next_h = h;
  1882. hscale = h;
  1883. nscon = 0;
  1884. }
  1885. /*
  1886. * cvPredict
  1887. *
  1888. * This routine advances tn by the tentative step size h, and computes
  1889. * the predicted array z_n(0), which is overwritten on zn. The
  1890. * prediction of zn is done by repeated additions.
  1891. * If tstop is enabled, it is possible for tn + h to be past tstop by roundoff,
  1892. * and in that case, we reset tn (after incrementing by h) to tstop.
  1893. */
  1894. static void cvPredict(CVodeMem cv_mem)
  1895. {
  1896. int j, k;
  1897. tn += h;
  1898. if (tstopset) {
  1899. if ((tn - tstop)*h > ZERO) tn = tstop;
  1900. }
  1901. for (k = 1; k <= q; k++)
  1902. for (j = q; j >= k; j--)
  1903. N_VLinearSum(ONE, zn[j-1], ONE, zn[j], zn[j-1]);
  1904. }
  1905. /*
  1906. * cvSet
  1907. *
  1908. * This routine is a high level routine which calls cvSetAdams or
  1909. * cvSetBDF to set the polynomial l, the test quantity array tq,
  1910. * and the related variables rl1, gamma, and gamrat.
  1911. *
  1912. * The array tq is loaded with constants used in the control of estimated
  1913. * local errors and in the nonlinear convergence test. Specifically, while
  1914. * running at order q, the components of tq are as follows:
  1915. * tq[1] = a coefficient used to get the est. local error at order q-1
  1916. * tq[2] = a coefficient used to get the est. local error at order q
  1917. * tq[3] = a coefficient used to get the est. local error at order q+1
  1918. * tq[4] = constant used in nonlinear iteration convergence test
  1919. * tq[5] = coefficient used to get the order q+2 derivative vector used in
  1920. * the est. local error at order q+1
  1921. */
  1922. static void cvSet(CVodeMem cv_mem)
  1923. {
  1924. switch(lmm) {
  1925. case CV_ADAMS:
  1926. cvSetAdams(cv_mem);
  1927. break;
  1928. case CV_BDF:
  1929. cvSetBDF(cv_mem);
  1930. break;
  1931. }
  1932. rl1 = ONE / l[1];
  1933. gamma = h * rl1;
  1934. if (nst == 0) gammap = gamma;
  1935. gamrat = (nst > 0) ? gamma / gammap : ONE; /* protect x / x != 1.0 */
  1936. }
  1937. /*
  1938. * cvSetAdams
  1939. *
  1940. * This routine handles the computation of l and tq for the
  1941. * case lmm == CV_ADAMS.
  1942. *
  1943. * The components of the array l are the coefficients of a
  1944. * polynomial Lambda(x) = l_0 + l_1 x + ... + l_q x^q, given by
  1945. * q-1
  1946. * (d/dx) Lambda(x) = c * PRODUCT (1 + x / xi_i) , where
  1947. * i=1
  1948. * Lambda(-1) = 0, Lambda(0) = 1, and c is a normalization factor.
  1949. * Here xi_i = [t_n - t_(n-i)] / h.
  1950. *
  1951. * The array tq is set to test quantities used in the convergence
  1952. * test, the error test, and the selection of h at a new order.
  1953. */
  1954. static void cvSetAdams(CVodeMem cv_mem)
  1955. {
  1956. realtype m[L_MAX], M[3], hsum;
  1957. if (q == 1) {
  1958. l[0] = l[1] = tq[1] = tq[5] = ONE;
  1959. tq[2] = HALF;
  1960. tq[3] = ONE/TWELVE;
  1961. tq[4] = nlscoef / tq[2]; /* = 0.1 / tq[2] */
  1962. return;
  1963. }
  1964. hsum = cvAdamsStart(cv_mem, m);
  1965. M[0] = cvAltSum(q-1, m, 1);
  1966. M[1] = cvAltSum(q-1, m, 2);
  1967. cvAdamsFinish(cv_mem, m, M, hsum);
  1968. }
  1969. /*
  1970. * cvAdamsStart
  1971. *
  1972. * This routine generates in m[] the coefficients of the product
  1973. * polynomial needed for the Adams l and tq coefficients for q > 1.
  1974. */
  1975. static realtype cvAdamsStart(CVodeMem cv_mem, realtype m[])
  1976. {
  1977. realtype hsum, xi_inv, sum;
  1978. int i, j;
  1979. hsum = h;
  1980. m[0] = ONE;
  1981. for (i=1; i <= q; i++) m[i] = ZERO;
  1982. for (j=1; j < q; j++) {
  1983. if ((j==q-1) && (qwait == 1)) {
  1984. sum = cvAltSum(q-2, m, 2);
  1985. tq[1] = q * sum / m[q-2];
  1986. }
  1987. xi_inv = h / hsum;
  1988. for (i=j; i >= 1; i--) m[i] += m[i-1] * xi_inv;
  1989. hsum += tau[j];
  1990. /* The m[i] are coefficients of product(1 to j) (1 + x/xi_i) */
  1991. }
  1992. return(hsum);
  1993. }
  1994. /*
  1995. * cvAdamsFinish
  1996. *
  1997. * This routine completes the calculation of the Adams l and tq.
  1998. */
  1999. static void cvAdamsFinish(CVodeMem cv_mem, realtype m[], realtype M[], realtype hsum)
  2000. {
  2001. int i;
  2002. realtype M0_inv, xi, xi_inv;
  2003. M0_inv = ONE / M[0];
  2004. l[0] = ONE;
  2005. for (i=1; i <= q; i++) l[i] = M0_inv * (m[i-1] / i);
  2006. xi = hsum / h;
  2007. xi_inv = ONE / xi;
  2008. tq[2] = M[1] * M0_inv / xi;
  2009. tq[5] = xi / l[q];
  2010. if (qwait == 1) {
  2011. for (i=q; i >= 1; i--) m[i] += m[i-1] * xi_inv;
  2012. M[2] = cvAltSum(q, m, 2);
  2013. tq[3] = M[2] * M0_inv / L;
  2014. }
  2015. tq[4] = nlscoef / tq[2];
  2016. }
  2017. /*
  2018. * cvAltSum
  2019. *
  2020. * cvAltSum returns the value of the alternating sum
  2021. * sum (i= 0 ... iend) [ (-1)^i * (a[i] / (i + k)) ].
  2022. * If iend < 0 then cvAltSum returns 0.
  2023. * This operation is needed to compute the integral, from -1 to 0,
  2024. * of a polynomial x^(k-1) M(x) given the coefficients of M(x).
  2025. */
  2026. static realtype cvAltSum(int iend, realtype a[], int k)
  2027. {
  2028. int i, sign;
  2029. realtype sum;
  2030. if (iend < 0) return(ZERO);
  2031. sum = ZERO;
  2032. sign = 1;
  2033. for (i=0; i <= iend; i++) {
  2034. sum += sign * (a[i] / (i+k));
  2035. sign = -sign;
  2036. }
  2037. return(sum);
  2038. }
  2039. /*
  2040. * cvSetBDF
  2041. *
  2042. * This routine computes the coefficients l and tq in the case
  2043. * lmm == CV_BDF. cvSetBDF calls cvSetTqBDF to set the test
  2044. * quantity array tq.
  2045. *
  2046. * The components of the array l are the coefficients of a
  2047. * polynomial Lambda(x) = l_0 + l_1 x + ... + l_q x^q, given by
  2048. * q-1
  2049. * Lambda(x) = (1 + x / xi*_q) * PRODUCT (1 + x / xi_i) , where
  2050. * i=1
  2051. * xi_i = [t_n - t_(n-i)] / h.
  2052. *
  2053. * The array tq is set to test quantities used in the convergence
  2054. * test, the error test, and the selection of h at a new order.
  2055. */
  2056. static void cvSetBDF(CVodeMem cv_mem)
  2057. {
  2058. realtype alpha0, alpha0_hat, xi_inv, xistar_inv, hsum;
  2059. int i,j;
  2060. l[0] = l[1] = xi_inv = xistar_inv = ONE;
  2061. for (i=2; i <= q; i++) l[i] = ZERO;
  2062. alpha0 = alpha0_hat = -ONE;
  2063. hsum = h;
  2064. if (q > 1) {
  2065. for (j=2; j < q; j++) {
  2066. hsum += tau[j-1];
  2067. xi_inv = h / hsum;
  2068. alpha0 -= ONE / j;
  2069. for (i=j; i >= 1; i--) l[i] += l[i-1]*xi_inv;
  2070. /* The l[i] are coefficients of product(1 to j) (1 + x/xi_i) */
  2071. }
  2072. /* j = q */
  2073. alpha0 -= ONE / q;
  2074. xistar_inv = -l[1] - alpha0;
  2075. hsum += tau[q-1];
  2076. xi_inv = h / hsum;
  2077. alpha0_hat = -l[1] - xi_inv;
  2078. for (i=q; i >= 1; i--) l[i] += l[i-1]*xistar_inv;
  2079. }
  2080. cvSetTqBDF(cv_mem, hsum, alpha0, alpha0_hat, xi_inv, xistar_inv);
  2081. }
  2082. /*
  2083. * cvSetTqBDF
  2084. *
  2085. * This routine sets the test quantity array tq in the case
  2086. * lmm == CV_BDF.
  2087. */
  2088. static void cvSetTqBDF(CVodeMem cv_mem, realtype hsum, realtype alpha0,
  2089. realtype alpha0_hat, realtype xi_inv, realtype xistar_inv)
  2090. {
  2091. realtype A1, A2, A3, A4, A5, A6;
  2092. realtype C, Cpinv, Cppinv;
  2093. A1 = ONE - alpha0_hat + alpha0;
  2094. A2 = ONE + q * A1;
  2095. tq[2] = SUNRabs(A1 / (alpha0 * A2));
  2096. tq[5] = SUNRabs(A2 * xistar_inv / (l[q] * xi_inv));
  2097. if (qwait == 1) {
  2098. if (q > 1) {
  2099. C = xistar_inv / l[q];
  2100. A3 = alpha0 + ONE / q;
  2101. A4 = alpha0_hat + xi_inv;
  2102. Cpinv = (ONE - A4 + A3) / A3;
  2103. tq[1] = SUNRabs(C * Cpinv);
  2104. }
  2105. else tq[1] = ONE;
  2106. hsum += tau[q];
  2107. xi_inv = h / hsum;
  2108. A5 = alpha0 - (ONE / (q+1));
  2109. A6 = alpha0_hat - xi_inv;
  2110. Cppinv = (ONE - A6 + A5) / A2;
  2111. tq[3] = SUNRabs(Cppinv / (xi_inv * (q+2) * A5));
  2112. }
  2113. tq[4] = nlscoef / tq[2];
  2114. }
  2115. /*
  2116. * cvNls
  2117. *
  2118. * This routine attempts to solve the nonlinear system associated
  2119. * with a single implicit step of the linear multistep method.
  2120. * Depending on iter, it calls cvNlsFunctional or cvNlsNewton
  2121. * to do the work.
  2122. */
  2123. static int cvNls(CVodeMem cv_mem, int nflag)
  2124. {
  2125. int flag = CV_SUCCESS;
  2126. switch(iter) {
  2127. case CV_FUNCTIONAL:
  2128. flag = cvNlsFunctional(cv_mem);
  2129. break;
  2130. case CV_NEWTON:
  2131. flag = cvNlsNewton(cv_mem, nflag);
  2132. break;
  2133. }
  2134. return(flag);
  2135. }
  2136. /*
  2137. * cvNlsFunctional
  2138. *
  2139. * This routine attempts to solve the nonlinear system using
  2140. * functional iteration (no matrices involved).
  2141. *
  2142. * Possible return values are:
  2143. *
  2144. * CV_SUCCESS ---> continue with error test
  2145. *
  2146. * CV_RHSFUNC_FAIL ---> halt the integration
  2147. *
  2148. * CONV_FAIL -+
  2149. * RHSFUNC_RECVR -+-> predict again or stop if too many
  2150. *
  2151. */
  2152. static int cvNlsFunctional(CVodeMem cv_mem)
  2153. {
  2154. int retval, m;
  2155. realtype del, delp, dcon;
  2156. /* Initialize counter and evaluate f at predicted y */
  2157. crate = ONE;
  2158. m = 0;
  2159. retval = f(tn, zn[0], tempv, user_data);
  2160. nfe++;
  2161. if (retval < 0) return(CV_RHSFUNC_FAIL);
  2162. if (retval > 0) return(RHSFUNC_RECVR);
  2163. N_VConst(ZERO, acor);
  2164. /* Initialize delp to avoid compiler warning message */
  2165. del = delp = ZERO;
  2166. /* Loop until convergence; accumulate corrections in acor */
  2167. loop {
  2168. nni++;
  2169. /* Correct y directly from the last f value */
  2170. N_VLinearSum(h, tempv, -ONE, zn[1], tempv);
  2171. N_VScale(rl1, tempv, tempv);
  2172. N_VLinearSum(ONE, zn[0], ONE, tempv, y);
  2173. /* Get WRMS norm of current correction to use in convergence test */
  2174. N_VLinearSum(ONE, tempv, -ONE, acor, acor);
  2175. del = N_VWrmsNorm(acor, ewt);
  2176. N_VScale(ONE, tempv, acor);
  2177. /* Test for convergence. If m > 0, an estimate of the convergence
  2178. rate constant is stored in crate, and used in the test. */
  2179. if (m > 0) crate = SUNMAX(CRDOWN * crate, del / delp);
  2180. dcon = del * SUNMIN(ONE, crate) / tq[4];
  2181. if (dcon <= ONE) {
  2182. acnrm = (m == 0) ? del : N_VWrmsNorm(acor, ewt);
  2183. return(CV_SUCCESS); /* Convergence achieved */
  2184. }
  2185. /* Stop at maxcor iterations or if iter. seems to be diverging */
  2186. m++;
  2187. if ((m==maxcor) || ((m >= 2) && (del > RDIV * delp))) return(CONV_FAIL);
  2188. /* Save norm of correction, evaluate f, and loop again */
  2189. delp = del;
  2190. retval = f(tn, y, tempv, user_data);
  2191. nfe++;
  2192. if (retval < 0) return(CV_RHSFUNC_FAIL);
  2193. if (retval > 0) return(RHSFUNC_RECVR);
  2194. }
  2195. }
  2196. /*
  2197. * cvNlsNewton
  2198. *
  2199. * This routine handles the Newton iteration. It calls lsetup if
  2200. * indicated, calls cvNewtonIteration to perform the iteration, and
  2201. * retries a failed attempt at Newton iteration if that is indicated.
  2202. *
  2203. * Possible return values:
  2204. *
  2205. * CV_SUCCESS ---> continue with error test
  2206. *
  2207. * CV_RHSFUNC_FAIL -+
  2208. * CV_LSETUP_FAIL |-> halt the integration
  2209. * CV_LSOLVE_FAIL -+
  2210. *
  2211. * CONV_FAIL -+
  2212. * RHSFUNC_RECVR -+-> predict again or stop if too many
  2213. *
  2214. */
  2215. static int cvNlsNewton(CVodeMem cv_mem, int nflag)
  2216. {
  2217. N_Vector vtemp1, vtemp2, vtemp3;
  2218. int convfail, retval, ier;
  2219. booleantype callSetup;
  2220. vtemp1 = acor; /* rename acor as vtemp1 for readability */
  2221. vtemp2 = y; /* rename y as vtemp2 for readability */
  2222. vtemp3 = tempv; /* rename tempv as vtemp3 for readability */
  2223. /* Set flag convfail, input to lsetup for its evaluation decision */
  2224. convfail = ((nflag == FIRST_CALL) || (nflag == PREV_ERR_FAIL)) ?
  2225. CV_NO_FAILURES : CV_FAIL_OTHER;
  2226. /* Decide whether or not to call setup routine (if one exists) */
  2227. if (setupNonNull) {
  2228. callSetup = (nflag == PREV_CONV_FAIL) || (nflag == PREV_ERR_FAIL) ||
  2229. (nst == 0) || (nst >= nstlp + MSBP) || (SUNRabs(gamrat-ONE) > DGMAX);
  2230. } else {
  2231. crate = ONE;
  2232. callSetup = FALSE;
  2233. }
  2234. /* Looping point for the solution of the nonlinear system.
  2235. Evaluate f at the predicted y, call lsetup if indicated, and
  2236. call cvNewtonIteration for the Newton iteration itself. */
  2237. loop {
  2238. retval = f(tn, zn[0], ftemp, user_data);
  2239. nfe++;
  2240. if (retval < 0) return(CV_RHSFUNC_FAIL);
  2241. if (retval > 0) return(RHSFUNC_RECVR);
  2242. if (callSetup) {
  2243. ier = lsetup(cv_mem, convfail, zn[0], ftemp, &jcur,
  2244. vtemp1, vtemp2, vtemp3);
  2245. nsetups++;
  2246. callSetup = FALSE;
  2247. gamrat = crate = ONE;
  2248. gammap = gamma;
  2249. nstlp = nst;
  2250. /* Return if lsetup failed */
  2251. if (ier < 0) return(CV_LSETUP_FAIL);
  2252. if (ier > 0) return(CONV_FAIL);
  2253. }
  2254. /* Set acor to zero and load prediction into y vector */
  2255. N_VConst(ZERO, acor);
  2256. N_VScale(ONE, zn[0], y);
  2257. /* Do the Newton iteration */
  2258. ier = cvNewtonIteration(cv_mem);
  2259. /* If there is a convergence failure and the Jacobian-related
  2260. data appears not to be current, loop again with a call to lsetup
  2261. in which convfail=CV_FAIL_BAD_J. Otherwise return. */
  2262. if (ier != CV_TRY_AGAIN) return(ier);
  2263. callSetup = TRUE;
  2264. convfail = CV_FAIL_BAD_J;
  2265. }
  2266. }
  2267. /*
  2268. * cvNewtonIteration
  2269. *
  2270. * This routine performs the Newton iteration. If the iteration succeeds,
  2271. * it returns the value CV_SUCCESS. If not, it may signal the cvNlsNewton
  2272. * routine to call lsetup again and reattempt the iteration, by
  2273. * returning the value TRY_AGAIN. (In this case, cvNlsNewton must set
  2274. * convfail to CV_FAIL_BAD_J before calling setup again).
  2275. * Otherwise, this routine returns one of the appropriate values
  2276. * CV_LSOLVE_FAIL, CV_RHSFUNC_FAIL, CONV_FAIL, or RHSFUNC_RECVR back
  2277. * to cvNlsNewton.
  2278. */
  2279. static int cvNewtonIteration(CVodeMem cv_mem)
  2280. {
  2281. int m, retval;
  2282. realtype del, delp, dcon;
  2283. N_Vector b;
  2284. mnewt = m = 0;
  2285. /* Initialize delp to avoid compiler warning message */
  2286. del = delp = ZERO;
  2287. /* Looping point for Newton iteration */
  2288. loop {
  2289. /* Evaluate the residual of the nonlinear system */
  2290. N_VLinearSum(rl1, zn[1], ONE, acor, tempv);
  2291. N_VLinearSum(gamma, ftemp, -ONE, tempv, tempv);
  2292. /* Call the lsolve function */
  2293. b = tempv;
  2294. retval = lsolve(cv_mem, b, ewt, y, ftemp);
  2295. nni++;
  2296. if (retval < 0) return(CV_LSOLVE_FAIL);
  2297. /* If lsolve had a recoverable failure and Jacobian data is
  2298. not current, signal to try the solution again */
  2299. if (retval > 0) {
  2300. if ((!jcur) && (setupNonNull)) return(CV_TRY_AGAIN);
  2301. else return(CONV_FAIL);
  2302. }
  2303. /* Get WRMS norm of correction; add correction to acor and y */
  2304. del = N_VWrmsNorm(b, ewt);
  2305. N_VLinearSum(ONE, acor, ONE, b, acor);
  2306. N_VLinearSum(ONE, zn[0], ONE, acor, y);
  2307. /* Test for convergence. If m > 0, an estimate of the convergence
  2308. rate constant is stored in crate, and used in the test. */
  2309. if (m > 0) {
  2310. crate = SUNMAX(CRDOWN * crate, del/delp);
  2311. }
  2312. dcon = del * SUNMIN(ONE, crate) / tq[4];
  2313. if (dcon <= ONE) {
  2314. acnrm = (m==0) ? del : N_VWrmsNorm(acor, ewt);
  2315. jcur = FALSE;
  2316. return(CV_SUCCESS); /* Nonlinear system was solved successfully */
  2317. }
  2318. mnewt = ++m;
  2319. /* Stop at maxcor iterations or if iter. seems to be diverging.
  2320. If still not converged and Jacobian data is not current,
  2321. signal to try the solution again */
  2322. if ((m == maxcor) || ((m >= 2) && (del > RDIV*delp))) {
  2323. if ((!jcur) && (setupNonNull)) return(CV_TRY_AGAIN);
  2324. else return(CONV_FAIL);
  2325. }
  2326. /* Save norm of correction, evaluate f, and loop again */
  2327. delp = del;
  2328. retval = f(tn, y, ftemp, user_data);
  2329. nfe++;
  2330. if (retval < 0) return(CV_RHSFUNC_FAIL);
  2331. if (retval > 0) {
  2332. if ((!jcur) && (setupNonNull)) return(CV_TRY_AGAIN);
  2333. else return(RHSFUNC_RECVR);
  2334. }
  2335. } /* end loop */
  2336. }
  2337. /*
  2338. * cvHandleNFlag
  2339. *
  2340. * This routine takes action on the return value nflag = *nflagPtr
  2341. * returned by cvNls, as follows:
  2342. *
  2343. * If cvNls succeeded in solving the nonlinear system, then
  2344. * cvHandleNFlag returns the constant DO_ERROR_TEST, which tells cvStep
  2345. * to perform the error test.
  2346. *
  2347. * If the nonlinear system was not solved successfully, then ncfn and
  2348. * ncf = *ncfPtr are incremented and Nordsieck array zn is restored.
  2349. *
  2350. * If the solution of the nonlinear system failed due to an
  2351. * unrecoverable failure by setup, we return the value CV_LSETUP_FAIL.
  2352. *
  2353. * If it failed due to an unrecoverable failure in solve, then we return
  2354. * the value CV_LSOLVE_FAIL.
  2355. *
  2356. * If it failed due to an unrecoverable failure in rhs, then we return
  2357. * the value CV_RHSFUNC_FAIL.
  2358. *
  2359. * Otherwise, a recoverable failure occurred when solving the
  2360. * nonlinear system (cvNls returned nflag == CONV_FAIL or RHSFUNC_RECVR).
  2361. * In this case, if ncf is now equal to maxncf or |h| = hmin,
  2362. * we return the value CV_CONV_FAILURE (if nflag=CONV_FAIL) or
  2363. * CV_REPTD_RHSFUNC_ERR (if nflag=RHSFUNC_RECVR).
  2364. * If not, we set *nflagPtr = PREV_CONV_FAIL and return the value
  2365. * PREDICT_AGAIN, telling cvStep to reattempt the step.
  2366. *
  2367. */
  2368. static int cvHandleNFlag(CVodeMem cv_mem, int *nflagPtr, realtype saved_t,
  2369. int *ncfPtr)
  2370. {
  2371. int nflag;
  2372. nflag = *nflagPtr;
  2373. if (nflag == CV_SUCCESS) return(DO_ERROR_TEST);
  2374. /* The nonlinear soln. failed; increment ncfn and restore zn */
  2375. ncfn++;
  2376. cvRestore(cv_mem, saved_t);
  2377. /* Return if lsetup, lsolve, or rhs failed unrecoverably */
  2378. if (nflag == CV_LSETUP_FAIL) return(CV_LSETUP_FAIL);
  2379. if (nflag == CV_LSOLVE_FAIL) return(CV_LSOLVE_FAIL);
  2380. if (nflag == CV_RHSFUNC_FAIL) return(CV_RHSFUNC_FAIL);
  2381. /* At this point, nflag = CONV_FAIL or RHSFUNC_RECVR; increment ncf */
  2382. (*ncfPtr)++;
  2383. etamax = ONE;
  2384. /* If we had maxncf failures or |h| = hmin,
  2385. return CV_CONV_FAILURE or CV_REPTD_RHSFUNC_ERR. */
  2386. if ((SUNRabs(h) <= hmin*ONEPSM) || (*ncfPtr == maxncf)) {
  2387. if (nflag == CONV_FAIL) return(CV_CONV_FAILURE);
  2388. if (nflag == RHSFUNC_RECVR) return(CV_REPTD_RHSFUNC_ERR);
  2389. }
  2390. /* Reduce step size; return to reattempt the step */
  2391. eta = SUNMAX(ETACF, hmin / SUNRabs(h));
  2392. *nflagPtr = PREV_CONV_FAIL;
  2393. cvRescale(cv_mem);
  2394. return(PREDICT_AGAIN);
  2395. }
  2396. /*
  2397. * cvRestore
  2398. *
  2399. * This routine restores the value of tn to saved_t and undoes the
  2400. * prediction. After execution of cvRestore, the Nordsieck array zn has
  2401. * the same values as before the call to cvPredict.
  2402. */
  2403. static void cvRestore(CVodeMem cv_mem, realtype saved_t)
  2404. {
  2405. int j, k;
  2406. tn = saved_t;
  2407. for (k = 1; k <= q; k++)
  2408. for (j = q; j >= k; j--)
  2409. N_VLinearSum(ONE, zn[j-1], -ONE, zn[j], zn[j-1]);
  2410. }
  2411. /*
  2412. * cvDoErrorTest
  2413. *
  2414. * This routine performs the local error test.
  2415. * The weighted local error norm dsm is loaded into *dsmPtr, and
  2416. * the test dsm ?<= 1 is made.
  2417. *
  2418. * If the test passes, cvDoErrorTest returns CV_SUCCESS.
  2419. *
  2420. * If the test fails, we undo the step just taken (call cvRestore) and
  2421. *
  2422. * - if maxnef error test failures have occurred or if SUNRabs(h) = hmin,
  2423. * we return CV_ERR_FAILURE.
  2424. *
  2425. * - if more than MXNEF1 error test failures have occurred, an order
  2426. * reduction is forced. If already at order 1, restart by reloading
  2427. * zn from scratch. If f() fails we return either CV_RHSFUNC_FAIL
  2428. * or CV_UNREC_RHSFUNC_ERR (no recovery is possible at this stage).
  2429. *
  2430. * - otherwise, set *nflagPtr to PREV_ERR_FAIL, and return CV_TRY_AGAIN.
  2431. *
  2432. */
  2433. static booleantype cvDoErrorTest(CVodeMem cv_mem, int *nflagPtr,
  2434. realtype saved_t, int *nefPtr, realtype *dsmPtr)
  2435. {
  2436. realtype dsm;
  2437. int retval;
  2438. dsm = acnrm * tq[2];
  2439. /* If est. local error norm dsm passes test, return CV_SUCCESS */
  2440. *dsmPtr = dsm;
  2441. if (dsm <= ONE) return(CV_SUCCESS);
  2442. /* Test failed; increment counters, set nflag, and restore zn array */
  2443. (*nefPtr)++;
  2444. netf++;
  2445. *nflagPtr = PREV_ERR_FAIL;
  2446. cvRestore(cv_mem, saved_t);
  2447. /* At maxnef failures or |h| = hmin, return CV_ERR_FAILURE */
  2448. if ((SUNRabs(h) <= hmin*ONEPSM) || (*nefPtr == maxnef)) return(CV_ERR_FAILURE);
  2449. /* Set etamax = 1 to prevent step size increase at end of this step */
  2450. etamax = ONE;
  2451. /* Set h ratio eta from dsm, rescale, and return for retry of step */
  2452. if (*nefPtr <= MXNEF1) {
  2453. eta = ONE / (SUNRpowerR(BIAS2*dsm,ONE/L) + ADDON);
  2454. eta = SUNMAX(ETAMIN, SUNMAX(eta, hmin / SUNRabs(h)));
  2455. if (*nefPtr >= SMALL_NEF) eta = SUNMIN(eta, ETAMXF);
  2456. cvRescale(cv_mem);
  2457. return(CV_TRY_AGAIN);
  2458. }
  2459. /* After MXNEF1 failures, force an order reduction and retry step */
  2460. if (q > 1) {
  2461. eta = SUNMAX(ETAMIN, hmin / SUNRabs(h));
  2462. cvAdjustOrder(cv_mem,-1);
  2463. L = q;
  2464. q--;
  2465. qwait = L;
  2466. cvRescale(cv_mem);
  2467. return(CV_TRY_AGAIN);
  2468. }
  2469. /* If already at order 1, restart: reload zn from scratch */
  2470. eta = SUNMAX(ETAMIN, hmin / SUNRabs(h));
  2471. h *= eta;
  2472. next_h = h;
  2473. hscale = h;
  2474. qwait = LONG_WAIT;
  2475. nscon = 0;
  2476. retval = f(tn, zn[0], tempv, user_data);
  2477. nfe++;
  2478. if (retval < 0) return(CV_RHSFUNC_FAIL);
  2479. if (retval > 0) return(CV_UNREC_RHSFUNC_ERR);
  2480. N_VScale(h, tempv, zn[1]);
  2481. return(CV_TRY_AGAIN);
  2482. }
  2483. /*
  2484. * -----------------------------------------------------------------
  2485. * Functions called after succesful step
  2486. * -----------------------------------------------------------------
  2487. */
  2488. /*
  2489. * cvCompleteStep
  2490. *
  2491. * This routine performs various update operations when the solution
  2492. * to the nonlinear system has passed the local error test.
  2493. * We increment the step counter nst, record the values hu and qu,
  2494. * update the tau array, and apply the corrections to the zn array.
  2495. * The tau[i] are the last q values of h, with tau[1] the most recent.
  2496. * The counter qwait is decremented, and if qwait == 1 (and q < qmax)
  2497. * we save acor and tq[5] for a possible order increase.
  2498. */
  2499. static void cvCompleteStep(CVodeMem cv_mem)
  2500. {
  2501. int i, j;
  2502. nst++;
  2503. nscon++;
  2504. hu = h;
  2505. qu = q;
  2506. for (i=q; i >= 2; i--) tau[i] = tau[i-1];
  2507. if ((q==1) && (nst > 1)) tau[2] = tau[1];
  2508. tau[1] = h;
  2509. /* Apply correction to column j of zn: l_j * Delta_n */
  2510. for (j=0; j <= q; j++)
  2511. N_VLinearSum(l[j], acor, ONE, zn[j], zn[j]);
  2512. qwait--;
  2513. if ((qwait == 1) && (q != qmax)) {
  2514. N_VScale(ONE, acor, zn[qmax]);
  2515. saved_tq5 = tq[5];
  2516. indx_acor = qmax;
  2517. }
  2518. }
  2519. /*
  2520. * cvPrepareNextStep
  2521. *
  2522. * This routine handles the setting of stepsize and order for the
  2523. * next step -- hprime and qprime. Along with hprime, it sets the
  2524. * ratio eta = hprime/h. It also updates other state variables
  2525. * related to a change of step size or order.
  2526. */
  2527. static void cvPrepareNextStep(CVodeMem cv_mem, realtype dsm)
  2528. {
  2529. /* If etamax = 1, defer step size or order changes */
  2530. if (etamax == ONE) {
  2531. qwait = SUNMAX(qwait, 2);
  2532. qprime = q;
  2533. hprime = h;
  2534. eta = ONE;
  2535. return;
  2536. }
  2537. /* etaq is the ratio of new to old h at the current order */
  2538. etaq = ONE /(SUNRpowerR(BIAS2*dsm,ONE/L) + ADDON);
  2539. /* If no order change, adjust eta and acor in cvSetEta and return */
  2540. if (qwait != 0) {
  2541. eta = etaq;
  2542. qprime = q;
  2543. cvSetEta(cv_mem);
  2544. return;
  2545. }
  2546. /* If qwait = 0, consider an order change. etaqm1 and etaqp1 are
  2547. the ratios of new to old h at orders q-1 and q+1, respectively.
  2548. cvChooseEta selects the largest; cvSetEta adjusts eta and acor */
  2549. qwait = 2;
  2550. etaqm1 = cvComputeEtaqm1(cv_mem);
  2551. etaqp1 = cvComputeEtaqp1(cv_mem);
  2552. cvChooseEta(cv_mem);
  2553. cvSetEta(cv_mem);
  2554. }
  2555. /*
  2556. * cvSetEta
  2557. *
  2558. * This routine adjusts the value of eta according to the various
  2559. * heuristic limits and the optional input hmax.
  2560. */
  2561. static void cvSetEta(CVodeMem cv_mem)
  2562. {
  2563. /* If eta below the threshhold THRESH, reject a change of step size */
  2564. if (eta < THRESH) {
  2565. eta = ONE;
  2566. hprime = h;
  2567. } else {
  2568. /* Limit eta by etamax and hmax, then set hprime */
  2569. eta = SUNMIN(eta, etamax);
  2570. eta /= SUNMAX(ONE, SUNRabs(h)*hmax_inv*eta);
  2571. hprime = h * eta;
  2572. if (qprime < q) nscon = 0;
  2573. }
  2574. }
  2575. /*
  2576. * cvComputeEtaqm1
  2577. *
  2578. * This routine computes and returns the value of etaqm1 for a
  2579. * possible decrease in order by 1.
  2580. */
  2581. static realtype cvComputeEtaqm1(CVodeMem cv_mem)
  2582. {
  2583. realtype ddn;
  2584. etaqm1 = ZERO;
  2585. if (q > 1) {
  2586. ddn = N_VWrmsNorm(zn[q], ewt) * tq[1];
  2587. etaqm1 = ONE/(SUNRpowerR(BIAS1*ddn, ONE/q) + ADDON);
  2588. }
  2589. return(etaqm1);
  2590. }
  2591. /*
  2592. * cvComputeEtaqp1
  2593. *
  2594. * This routine computes and returns the value of etaqp1 for a
  2595. * possible increase in order by 1.
  2596. */
  2597. static realtype cvComputeEtaqp1(CVodeMem cv_mem)
  2598. {
  2599. realtype dup, cquot;
  2600. etaqp1 = ZERO;
  2601. if (q != qmax) {
  2602. if (saved_tq5 == ZERO) return(etaqp1);
  2603. cquot = (tq[5] / saved_tq5) * SUNRpowerI(h/tau[2], L);
  2604. N_VLinearSum(-cquot, zn[qmax], ONE, acor, tempv);
  2605. dup = N_VWrmsNorm(tempv, ewt) * tq[3];
  2606. etaqp1 = ONE / (SUNRpowerR(BIAS3*dup, ONE/(L+1)) + ADDON);
  2607. }
  2608. return(etaqp1);
  2609. }
  2610. /*
  2611. * cvChooseEta
  2612. * Given etaqm1, etaq, etaqp1 (the values of eta for qprime =
  2613. * q - 1, q, or q + 1, respectively), this routine chooses the
  2614. * maximum eta value, sets eta to that value, and sets qprime to the
  2615. * corresponding value of q. If there is a tie, the preference
  2616. * order is to (1) keep the same order, then (2) decrease the order,
  2617. * and finally (3) increase the order. If the maximum eta value
  2618. * is below the threshhold THRESH, the order is kept unchanged and
  2619. * eta is set to 1.
  2620. */
  2621. static void cvChooseEta(CVodeMem cv_mem)
  2622. {
  2623. realtype etam;
  2624. etam = SUNMAX(etaqm1, SUNMAX(etaq, etaqp1));
  2625. if (etam < THRESH) {
  2626. eta = ONE;
  2627. qprime = q;
  2628. return;
  2629. }
  2630. if (etam == etaq) {
  2631. eta = etaq;
  2632. qprime = q;
  2633. } else if (etam == etaqm1) {
  2634. eta = etaqm1;
  2635. qprime = q - 1;
  2636. } else {
  2637. eta = etaqp1;
  2638. qprime = q + 1;
  2639. if (lmm == CV_BDF) {
  2640. /*
  2641. * Store Delta_n in zn[qmax] to be used in order increase
  2642. *
  2643. * This happens at the last step of order q before an increase
  2644. * to order q+1, so it represents Delta_n in the ELTE at q+1
  2645. */
  2646. N_VScale(ONE, acor, zn[qmax]);
  2647. }
  2648. }
  2649. }
  2650. /*
  2651. * cvHandleFailure
  2652. *
  2653. * This routine prints error messages for all cases of failure by
  2654. * cvHin and cvStep.
  2655. * It returns to CVode the value that CVode is to return to the user.
  2656. */
  2657. static int cvHandleFailure(CVodeMem cv_mem, int flag)
  2658. {
  2659. /* Set vector of absolute weighted local errors */
  2660. /*
  2661. N_VProd(acor, ewt, tempv);
  2662. N_VAbs(tempv, tempv);
  2663. */
  2664. /* Depending on flag, print error message and return error flag */
  2665. switch (flag) {
  2666. case CV_ERR_FAILURE:
  2667. cvProcessError(cv_mem, CV_ERR_FAILURE, "CVODE", "CVode", MSGCV_ERR_FAILS, tn, h);
  2668. break;
  2669. case CV_CONV_FAILURE:
  2670. cvProcessError(cv_mem, CV_CONV_FAILURE, "CVODE", "CVode", MSGCV_CONV_FAILS, tn, h);
  2671. break;
  2672. case CV_LSETUP_FAIL:
  2673. cvProcessError(cv_mem, CV_LSETUP_FAIL, "CVODE", "CVode", MSGCV_SETUP_FAILED, tn);
  2674. break;
  2675. case CV_LSOLVE_FAIL:
  2676. cvProcessError(cv_mem, CV_LSOLVE_FAIL, "CVODE", "CVode", MSGCV_SOLVE_FAILED, tn);
  2677. break;
  2678. case CV_RHSFUNC_FAIL:
  2679. cvProcessError(cv_mem, CV_RHSFUNC_FAIL, "CVODE", "CVode", MSGCV_RHSFUNC_FAILED, tn);
  2680. break;
  2681. case CV_UNREC_RHSFUNC_ERR:
  2682. cvProcessError(cv_mem, CV_UNREC_RHSFUNC_ERR, "CVODE", "CVode", MSGCV_RHSFUNC_UNREC, tn);
  2683. break;
  2684. case CV_REPTD_RHSFUNC_ERR:
  2685. cvProcessError(cv_mem, CV_REPTD_RHSFUNC_ERR, "CVODE", "CVode", MSGCV_RHSFUNC_REPTD, tn);
  2686. break;
  2687. case CV_RTFUNC_FAIL:
  2688. cvProcessError(cv_mem, CV_RTFUNC_FAIL, "CVODE", "CVode", MSGCV_RTFUNC_FAILED, tn);
  2689. break;
  2690. case CV_TOO_CLOSE:
  2691. cvProcessError(cv_mem, CV_TOO_CLOSE, "CVODE", "CVode", MSGCV_TOO_CLOSE);
  2692. break;
  2693. default:
  2694. return(CV_SUCCESS);
  2695. }
  2696. return(flag);
  2697. }
  2698. /*
  2699. * -----------------------------------------------------------------
  2700. * Functions for BDF Stability Limit Detection
  2701. * -----------------------------------------------------------------
  2702. */
  2703. /*
  2704. * cvBDFStab
  2705. *
  2706. * This routine handles the BDF Stability Limit Detection Algorithm
  2707. * STALD. It is called if lmm = CV_BDF and the SLDET option is on.
  2708. * If the order is 3 or more, the required norm data is saved.
  2709. * If a decision to reduce order has not already been made, and
  2710. * enough data has been saved, cvSLdet is called. If it signals
  2711. * a stability limit violation, the order is reduced, and the step
  2712. * size is reset accordingly.
  2713. */
  2714. static void cvBDFStab(CVodeMem cv_mem)
  2715. {
  2716. int i,k, ldflag, factorial;
  2717. realtype sq, sqm1, sqm2;
  2718. /* If order is 3 or greater, then save scaled derivative data,
  2719. push old data down in i, then add current values to top. */
  2720. if (q >= 3) {
  2721. for (k = 1; k <= 3; k++)
  2722. for (i = 5; i >= 2; i--)
  2723. ssdat[i][k] = ssdat[i-1][k];
  2724. factorial = 1;
  2725. for (i = 1; i <= q-1; i++) factorial *= i;
  2726. sq = factorial*q*(q+1)*acnrm/SUNMAX(tq[5],TINY);
  2727. sqm1 = factorial*q*N_VWrmsNorm(zn[q], ewt);
  2728. sqm2 = factorial*N_VWrmsNorm(zn[q-1], ewt);
  2729. ssdat[1][1] = sqm2*sqm2;
  2730. ssdat[1][2] = sqm1*sqm1;
  2731. ssdat[1][3] = sq*sq;
  2732. }
  2733. if (qprime >= q) {
  2734. /* If order is 3 or greater, and enough ssdat has been saved,
  2735. nscon >= q+5, then call stability limit detection routine. */
  2736. if ( (q >= 3) && (nscon >= q+5) ) {
  2737. ldflag = cvSLdet(cv_mem);
  2738. if (ldflag > 3) {
  2739. /* A stability limit violation is indicated by
  2740. a return flag of 4, 5, or 6.
  2741. Reduce new order. */
  2742. qprime = q-1;
  2743. eta = etaqm1;
  2744. eta = SUNMIN(eta,etamax);
  2745. eta = eta/SUNMAX(ONE,SUNRabs(h)*hmax_inv*eta);
  2746. hprime = h*eta;
  2747. nor = nor + 1;
  2748. }
  2749. }
  2750. }
  2751. else {
  2752. /* Otherwise, let order increase happen, and
  2753. reset stability limit counter, nscon. */
  2754. nscon = 0;
  2755. }
  2756. }
  2757. /*
  2758. * cvSLdet
  2759. *
  2760. * This routine detects stability limitation using stored scaled
  2761. * derivatives data. cvSLdet returns the magnitude of the
  2762. * dominate characteristic root, rr. The presents of a stability
  2763. * limit is indicated by rr > "something a little less then 1.0",
  2764. * and a positive kflag. This routine should only be called if
  2765. * order is greater than or equal to 3, and data has been collected
  2766. * for 5 time steps.
  2767. *
  2768. * Returned values:
  2769. * kflag = 1 -> Found stable characteristic root, normal matrix case
  2770. * kflag = 2 -> Found stable characteristic root, quartic solution
  2771. * kflag = 3 -> Found stable characteristic root, quartic solution,
  2772. * with Newton correction
  2773. * kflag = 4 -> Found stability violation, normal matrix case
  2774. * kflag = 5 -> Found stability violation, quartic solution
  2775. * kflag = 6 -> Found stability violation, quartic solution,
  2776. * with Newton correction
  2777. *
  2778. * kflag < 0 -> No stability limitation,
  2779. * or could not compute limitation.
  2780. *
  2781. * kflag = -1 -> Min/max ratio of ssdat too small.
  2782. * kflag = -2 -> For normal matrix case, vmax > vrrt2*vrrt2
  2783. * kflag = -3 -> For normal matrix case, The three ratios
  2784. * are inconsistent.
  2785. * kflag = -4 -> Small coefficient prevents elimination of quartics.
  2786. * kflag = -5 -> R value from quartics not consistent.
  2787. * kflag = -6 -> No corrected root passes test on qk values
  2788. * kflag = -7 -> Trouble solving for sigsq.
  2789. * kflag = -8 -> Trouble solving for B, or R via B.
  2790. * kflag = -9 -> R via sigsq[k] disagrees with R from data.
  2791. */
  2792. static int cvSLdet(CVodeMem cv_mem)
  2793. {
  2794. int i, k, j, it, kmin = 0, kflag = 0;
  2795. realtype rat[5][4], rav[4], qkr[4], sigsq[4], smax[4], ssmax[4];
  2796. realtype drr[4], rrc[4],sqmx[4], qjk[4][4], vrat[5], qc[6][4], qco[6][4];
  2797. realtype rr, rrcut, vrrtol, vrrt2, sqtol, rrtol;
  2798. realtype smink, smaxk, sumrat, sumrsq, vmin, vmax, drrmax, adrr;
  2799. realtype tem, sqmax, saqk, qp, s, sqmaxk, saqj, sqmin;
  2800. realtype rsa, rsb, rsc, rsd, rd1a, rd1b, rd1c;
  2801. realtype rd2a, rd2b, rd3a, cest1, corr1;
  2802. realtype ratp, ratm, qfac1, qfac2, bb, rrb;
  2803. /* The following are cutoffs and tolerances used by this routine */
  2804. rrcut = RCONST(0.98);
  2805. vrrtol = RCONST(1.0e-4);
  2806. vrrt2 = RCONST(5.0e-4);
  2807. sqtol = RCONST(1.0e-3);
  2808. rrtol = RCONST(1.0e-2);
  2809. rr = ZERO;
  2810. /* Index k corresponds to the degree of the interpolating polynomial. */
  2811. /* k = 1 -> q-1 */
  2812. /* k = 2 -> q */
  2813. /* k = 3 -> q+1 */
  2814. /* Index i is a backward-in-time index, i = 1 -> current time, */
  2815. /* i = 2 -> previous step, etc */
  2816. /* get maxima, minima, and variances, and form quartic coefficients */
  2817. for (k=1; k<=3; k++) {
  2818. smink = ssdat[1][k];
  2819. smaxk = ZERO;
  2820. for (i=1; i<=5; i++) {
  2821. smink = SUNMIN(smink,ssdat[i][k]);
  2822. smaxk = SUNMAX(smaxk,ssdat[i][k]);
  2823. }
  2824. if (smink < TINY*smaxk) {
  2825. kflag = -1;
  2826. return(kflag);
  2827. }
  2828. smax[k] = smaxk;
  2829. ssmax[k] = smaxk*smaxk;
  2830. sumrat = ZERO;
  2831. sumrsq = ZERO;
  2832. for (i=1; i<=4; i++) {
  2833. rat[i][k] = ssdat[i][k]/ssdat[i+1][k];
  2834. sumrat = sumrat + rat[i][k];
  2835. sumrsq = sumrsq + rat[i][k]*rat[i][k];
  2836. }
  2837. rav[k] = FOURTH*sumrat;
  2838. vrat[k] = SUNRabs(FOURTH*sumrsq - rav[k]*rav[k]);
  2839. qc[5][k] = ssdat[1][k]*ssdat[3][k] - ssdat[2][k]*ssdat[2][k];
  2840. qc[4][k] = ssdat[2][k]*ssdat[3][k] - ssdat[1][k]*ssdat[4][k];
  2841. qc[3][k] = ZERO;
  2842. qc[2][k] = ssdat[2][k]*ssdat[5][k] - ssdat[3][k]*ssdat[4][k];
  2843. qc[1][k] = ssdat[4][k]*ssdat[4][k] - ssdat[3][k]*ssdat[5][k];
  2844. for (i=1; i<=5; i++) {
  2845. qco[i][k] = qc[i][k];
  2846. }
  2847. } /* End of k loop */
  2848. /* Isolate normal or nearly-normal matrix case. Three quartic will
  2849. have common or nearly-common roots in this case.
  2850. Return a kflag = 1 if this procedure works. If three root
  2851. differ more than vrrt2, return error kflag = -3. */
  2852. vmin = SUNMIN(vrat[1],SUNMIN(vrat[2],vrat[3]));
  2853. vmax = SUNMAX(vrat[1],SUNMAX(vrat[2],vrat[3]));
  2854. if (vmin < vrrtol*vrrtol) {
  2855. if (vmax > vrrt2*vrrt2) {
  2856. kflag = -2;
  2857. return(kflag);
  2858. } else {
  2859. rr = (rav[1] + rav[2] + rav[3])/THREE;
  2860. drrmax = ZERO;
  2861. for (k = 1;k<=3;k++) {
  2862. adrr = SUNRabs(rav[k] - rr);
  2863. drrmax = SUNMAX(drrmax, adrr);
  2864. }
  2865. if (drrmax > vrrt2) kflag = -3;
  2866. kflag = 1;
  2867. /* can compute charactistic root, drop to next section */
  2868. }
  2869. } else {
  2870. /* use the quartics to get rr. */
  2871. if (SUNRabs(qco[1][1]) < TINY*ssmax[1]) {
  2872. kflag = -4;
  2873. return(kflag);
  2874. }
  2875. tem = qco[1][2]/qco[1][1];
  2876. for (i=2; i<=5; i++) {
  2877. qco[i][2] = qco[i][2] - tem*qco[i][1];
  2878. }
  2879. qco[1][2] = ZERO;
  2880. tem = qco[1][3]/qco[1][1];
  2881. for (i=2; i<=5; i++) {
  2882. qco[i][3] = qco[i][3] - tem*qco[i][1];
  2883. }
  2884. qco[1][3] = ZERO;
  2885. if (SUNRabs(qco[2][2]) < TINY*ssmax[2]) {
  2886. kflag = -4;
  2887. return(kflag);
  2888. }
  2889. tem = qco[2][3]/qco[2][2];
  2890. for (i=3; i<=5; i++) {
  2891. qco[i][3] = qco[i][3] - tem*qco[i][2];
  2892. }
  2893. if (SUNRabs(qco[4][3]) < TINY*ssmax[3]) {
  2894. kflag = -4;
  2895. return(kflag);
  2896. }
  2897. rr = -qco[5][3]/qco[4][3];
  2898. if (rr < TINY || rr > HUNDRED) {
  2899. kflag = -5;
  2900. return(kflag);
  2901. }
  2902. for (k=1; k<=3; k++)
  2903. qkr[k] = qc[5][k] + rr*(qc[4][k] + rr*rr*(qc[2][k] + rr*qc[1][k]));
  2904. sqmax = ZERO;
  2905. for (k=1; k<=3; k++) {
  2906. saqk = SUNRabs(qkr[k])/ssmax[k];
  2907. if (saqk > sqmax) sqmax = saqk;
  2908. }
  2909. if (sqmax < sqtol) {
  2910. kflag = 2;
  2911. /* can compute charactistic root, drop to "given rr,etc" */
  2912. } else {
  2913. /* do Newton corrections to improve rr. */
  2914. for (it=1; it<=3; it++) {
  2915. for (k=1; k<=3; k++) {
  2916. qp = qc[4][k] + rr*rr*(THREE*qc[2][k] + rr*FOUR*qc[1][k]);
  2917. drr[k] = ZERO;
  2918. if (SUNRabs(qp) > TINY*ssmax[k]) drr[k] = -qkr[k]/qp;
  2919. rrc[k] = rr + drr[k];
  2920. }
  2921. for (k=1; k<=3; k++) {
  2922. s = rrc[k];
  2923. sqmaxk = ZERO;
  2924. for (j=1; j<=3; j++) {
  2925. qjk[j][k] = qc[5][j] + s*(qc[4][j] + s*s*(qc[2][j] + s*qc[1][j]));
  2926. saqj = SUNRabs(qjk[j][k])/ssmax[j];
  2927. if (saqj > sqmaxk) sqmaxk = saqj;
  2928. }
  2929. sqmx[k] = sqmaxk;
  2930. }
  2931. sqmin = sqmx[1] + ONE;
  2932. for (k=1; k<=3; k++) {
  2933. if (sqmx[k] < sqmin) {
  2934. kmin = k;
  2935. sqmin = sqmx[k];
  2936. }
  2937. }
  2938. rr = rrc[kmin];
  2939. if (sqmin < sqtol) {
  2940. kflag = 3;
  2941. /* can compute charactistic root */
  2942. /* break out of Newton correction loop and drop to "given rr,etc" */
  2943. break;
  2944. } else {
  2945. for (j=1; j<=3; j++) {
  2946. qkr[j] = qjk[j][kmin];
  2947. }
  2948. }
  2949. } /* end of Newton correction loop */
  2950. if (sqmin > sqtol) {
  2951. kflag = -6;
  2952. return(kflag);
  2953. }
  2954. } /* end of if (sqmax < sqtol) else */
  2955. } /* end of if (vmin < vrrtol*vrrtol) else, quartics to get rr. */
  2956. /* given rr, find sigsq[k] and verify rr. */
  2957. /* All positive kflag drop to this section */
  2958. for (k=1; k<=3; k++) {
  2959. rsa = ssdat[1][k];
  2960. rsb = ssdat[2][k]*rr;
  2961. rsc = ssdat[3][k]*rr*rr;
  2962. rsd = ssdat[4][k]*rr*rr*rr;
  2963. rd1a = rsa - rsb;
  2964. rd1b = rsb - rsc;
  2965. rd1c = rsc - rsd;
  2966. rd2a = rd1a - rd1b;
  2967. rd2b = rd1b - rd1c;
  2968. rd3a = rd2a - rd2b;
  2969. if (SUNRabs(rd1b) < TINY*smax[k]) {
  2970. kflag = -7;
  2971. return(kflag);
  2972. }
  2973. cest1 = -rd3a/rd1b;
  2974. if (cest1 < TINY || cest1 > FOUR) {
  2975. kflag = -7;
  2976. return(kflag);
  2977. }
  2978. corr1 = (rd2b/cest1)/(rr*rr);
  2979. sigsq[k] = ssdat[3][k] + corr1;
  2980. }
  2981. if (sigsq[2] < TINY) {
  2982. kflag = -8;
  2983. return(kflag);
  2984. }
  2985. ratp = sigsq[3]/sigsq[2];
  2986. ratm = sigsq[1]/sigsq[2];
  2987. qfac1 = FOURTH*(q*q - ONE);
  2988. qfac2 = TWO/(q - ONE);
  2989. bb = ratp*ratm - ONE - qfac1*ratp;
  2990. tem = ONE - qfac2*bb;
  2991. if (SUNRabs(tem) < TINY) {
  2992. kflag = -8;
  2993. return(kflag);
  2994. }
  2995. rrb = ONE/tem;
  2996. if (SUNRabs(rrb - rr) > rrtol) {
  2997. kflag = -9;
  2998. return(kflag);
  2999. }
  3000. /* Check to see if rr is above cutoff rrcut */
  3001. if (rr > rrcut) {
  3002. if (kflag == 1) kflag = 4;
  3003. if (kflag == 2) kflag = 5;
  3004. if (kflag == 3) kflag = 6;
  3005. }
  3006. /* All positive kflag returned at this point */
  3007. return(kflag);
  3008. }
  3009. /*
  3010. * -----------------------------------------------------------------
  3011. * Functions for rootfinding
  3012. * -----------------------------------------------------------------
  3013. */
  3014. /*
  3015. * cvRcheck1
  3016. *
  3017. * This routine completes the initialization of rootfinding memory
  3018. * information, and checks whether g has a zero both at and very near
  3019. * the initial point of the IVP.
  3020. *
  3021. * This routine returns an int equal to:
  3022. * CV_RTFUNC_FAIL < 0 if the g function failed, or
  3023. * CV_SUCCESS = 0 otherwise.
  3024. */
  3025. static int cvRcheck1(CVodeMem cv_mem)
  3026. {
  3027. int i, retval;
  3028. realtype smallh, hratio, tplus;
  3029. booleantype zroot;
  3030. for (i = 0; i < nrtfn; i++) iroots[i] = 0;
  3031. tlo = tn;
  3032. ttol = (SUNRabs(tn) + SUNRabs(h))*uround*HUNDRED;
  3033. /* Evaluate g at initial t and check for zero values. */
  3034. retval = gfun(tlo, zn[0], glo, user_data);
  3035. nge = 1;
  3036. if (retval != 0) return(CV_RTFUNC_FAIL);
  3037. zroot = FALSE;
  3038. for (i = 0; i < nrtfn; i++) {
  3039. if (SUNRabs(glo[i]) == ZERO) {
  3040. zroot = TRUE;
  3041. gactive[i] = FALSE;
  3042. }
  3043. }
  3044. if (!zroot) return(CV_SUCCESS);
  3045. /* Some g_i is zero at t0; look at g at t0+(small increment). */
  3046. hratio = SUNMAX(ttol/SUNRabs(h), PT1);
  3047. smallh = hratio*h;
  3048. tplus = tlo + smallh;
  3049. N_VLinearSum(ONE, zn[0], hratio, zn[1], y);
  3050. retval = gfun(tplus, y, ghi, user_data);
  3051. nge++;
  3052. if (retval != 0) return(CV_RTFUNC_FAIL);
  3053. /* We check now only the components of g which were exactly 0.0 at t0
  3054. * to see if we can 'activate' them. */
  3055. for (i = 0; i < nrtfn; i++) {
  3056. if (!gactive[i] && SUNRabs(ghi[i]) != ZERO) {
  3057. gactive[i] = TRUE;
  3058. glo[i] = ghi[i];
  3059. }
  3060. }
  3061. return(CV_SUCCESS);
  3062. }
  3063. /*
  3064. * cvRcheck2
  3065. *
  3066. * This routine checks for exact zeros of g at the last root found,
  3067. * if the last return was a root. It then checks for a close pair of
  3068. * zeros (an error condition), and for a new root at a nearby point.
  3069. * The array glo = g(tlo) at the left endpoint of the search interval
  3070. * is adjusted if necessary to assure that all g_i are nonzero
  3071. * there, before returning to do a root search in the interval.
  3072. *
  3073. * On entry, tlo = tretlast is the last value of tret returned by
  3074. * CVode. This may be the previous tn, the previous tout value,
  3075. * or the last root location.
  3076. *
  3077. * This routine returns an int equal to:
  3078. * CV_RTFUNC_FAIL < 0 if the g function failed, or
  3079. * CLOSERT = 3 if a close pair of zeros was found, or
  3080. * RTFOUND = 1 if a new zero of g was found near tlo, or
  3081. * CV_SUCCESS = 0 otherwise.
  3082. */
  3083. static int cvRcheck2(CVodeMem cv_mem)
  3084. {
  3085. int i, retval;
  3086. realtype smallh, hratio, tplus;
  3087. booleantype zroot;
  3088. if (irfnd == 0) return(CV_SUCCESS);
  3089. (void) CVodeGetDky(cv_mem, tlo, 0, y);
  3090. retval = gfun(tlo, y, glo, user_data);
  3091. nge++;
  3092. if (retval != 0) return(CV_RTFUNC_FAIL);
  3093. zroot = FALSE;
  3094. for (i = 0; i < nrtfn; i++) iroots[i] = 0;
  3095. for (i = 0; i < nrtfn; i++) {
  3096. if (!gactive[i]) continue;
  3097. if (SUNRabs(glo[i]) == ZERO) {
  3098. zroot = TRUE;
  3099. iroots[i] = 1;
  3100. }
  3101. }
  3102. if (!zroot) return(CV_SUCCESS);
  3103. /* One or more g_i has a zero at tlo. Check g at tlo+smallh. */
  3104. ttol = (SUNRabs(tn) + SUNRabs(h))*uround*HUNDRED;
  3105. smallh = (h > ZERO) ? ttol : -ttol;
  3106. tplus = tlo + smallh;
  3107. if ( (tplus - tn)*h >= ZERO) {
  3108. hratio = smallh/h;
  3109. N_VLinearSum(ONE, y, hratio, zn[1], y);
  3110. } else {
  3111. (void) CVodeGetDky(cv_mem, tplus, 0, y);
  3112. }
  3113. retval = gfun(tplus, y, ghi, user_data);
  3114. nge++;
  3115. if (retval != 0) return(CV_RTFUNC_FAIL);
  3116. /* Check for close roots (error return), for a new zero at tlo+smallh,
  3117. and for a g_i that changed from zero to nonzero. */
  3118. zroot = FALSE;
  3119. for (i = 0; i < nrtfn; i++) {
  3120. if (!gactive[i]) continue;
  3121. if (SUNRabs(ghi[i]) == ZERO) {
  3122. if (iroots[i] == 1) return(CLOSERT);
  3123. zroot = TRUE;
  3124. iroots[i] = 1;
  3125. } else {
  3126. if (iroots[i] == 1) glo[i] = ghi[i];
  3127. }
  3128. }
  3129. if (zroot) return(RTFOUND);
  3130. return(CV_SUCCESS);
  3131. }
  3132. /*
  3133. * cvRcheck3
  3134. *
  3135. * This routine interfaces to cvRootfind to look for a root of g
  3136. * between tlo and either tn or tout, whichever comes first.
  3137. * Only roots beyond tlo in the direction of integration are sought.
  3138. *
  3139. * This routine returns an int equal to:
  3140. * CV_RTFUNC_FAIL < 0 if the g function failed, or
  3141. * RTFOUND = 1 if a root of g was found, or
  3142. * CV_SUCCESS = 0 otherwise.
  3143. */
  3144. static int cvRcheck3(CVodeMem cv_mem)
  3145. {
  3146. int i, ier, retval;
  3147. /* Set thi = tn or tout, whichever comes first; set y = y(thi). */
  3148. if (taskc == CV_ONE_STEP) {
  3149. thi = tn;
  3150. N_VScale(ONE, zn[0], y);
  3151. }
  3152. if (taskc == CV_NORMAL) {
  3153. if ( (toutc - tn)*h >= ZERO) {
  3154. thi = tn;
  3155. N_VScale(ONE, zn[0], y);
  3156. } else {
  3157. thi = toutc;
  3158. (void) CVodeGetDky(cv_mem, thi, 0, y);
  3159. }
  3160. }
  3161. /* Set ghi = g(thi) and call cvRootfind to search (tlo,thi) for roots. */
  3162. retval = gfun(thi, y, ghi, user_data);
  3163. nge++;
  3164. if (retval != 0) return(CV_RTFUNC_FAIL);
  3165. ttol = (SUNRabs(tn) + SUNRabs(h))*uround*HUNDRED;
  3166. ier = cvRootfind(cv_mem);
  3167. if (ier == CV_RTFUNC_FAIL) return(CV_RTFUNC_FAIL);
  3168. for(i=0; i<nrtfn; i++) {
  3169. if(!gactive[i] && grout[i] != ZERO) gactive[i] = TRUE;
  3170. }
  3171. tlo = trout;
  3172. for (i = 0; i < nrtfn; i++) glo[i] = grout[i];
  3173. /* If no root found, return CV_SUCCESS. */
  3174. if (ier == CV_SUCCESS) return(CV_SUCCESS);
  3175. /* If a root was found, interpolate to get y(trout) and return. */
  3176. (void) CVodeGetDky(cv_mem, trout, 0, y);
  3177. return(RTFOUND);
  3178. }
  3179. /*
  3180. * cvRootfind
  3181. *
  3182. * This routine solves for a root of g(t) between tlo and thi, if
  3183. * one exists. Only roots of odd multiplicity (i.e. with a change
  3184. * of sign in one of the g_i), or exact zeros, are found.
  3185. * Here the sign of tlo - thi is arbitrary, but if multiple roots
  3186. * are found, the one closest to tlo is returned.
  3187. *
  3188. * The method used is the Illinois algorithm, a modified secant method.
  3189. * Reference: Kathie L. Hiebert and Lawrence F. Shampine, Implicitly
  3190. * Defined Output Points for Solutions of ODEs, Sandia National
  3191. * Laboratory Report SAND80-0180, February 1980.
  3192. *
  3193. * This routine uses the following parameters for communication:
  3194. *
  3195. * nrtfn = number of functions g_i, or number of components of
  3196. * the vector-valued function g(t). Input only.
  3197. *
  3198. * gfun = user-defined function for g(t). Its form is
  3199. * (void) gfun(t, y, gt, user_data)
  3200. *
  3201. * rootdir = in array specifying the direction of zero-crossings.
  3202. * If rootdir[i] > 0, search for roots of g_i only if
  3203. * g_i is increasing; if rootdir[i] < 0, search for
  3204. * roots of g_i only if g_i is decreasing; otherwise
  3205. * always search for roots of g_i.
  3206. *
  3207. * gactive = array specifying whether a component of g should
  3208. * or should not be monitored. gactive[i] is initially
  3209. * set to TRUE for all i=0,...,nrtfn-1, but it may be
  3210. * reset to FALSE if at the first step g[i] is 0.0
  3211. * both at the I.C. and at a small perturbation of them.
  3212. * gactive[i] is then set back on TRUE only after the
  3213. * corresponding g function moves away from 0.0.
  3214. *
  3215. * nge = cumulative counter for gfun calls.
  3216. *
  3217. * ttol = a convergence tolerance for trout. Input only.
  3218. * When a root at trout is found, it is located only to
  3219. * within a tolerance of ttol. Typically, ttol should
  3220. * be set to a value on the order of
  3221. * 100 * UROUND * max (SUNRabs(tlo), SUNRabs(thi))
  3222. * where UROUND is the unit roundoff of the machine.
  3223. *
  3224. * tlo, thi = endpoints of the interval in which roots are sought.
  3225. * On input, these must be distinct, but tlo - thi may
  3226. * be of either sign. The direction of integration is
  3227. * assumed to be from tlo to thi. On return, tlo and thi
  3228. * are the endpoints of the final relevant interval.
  3229. *
  3230. * glo, ghi = arrays of length nrtfn containing the vectors g(tlo)
  3231. * and g(thi) respectively. Input and output. On input,
  3232. * none of the glo[i] should be zero.
  3233. *
  3234. * trout = root location, if a root was found, or thi if not.
  3235. * Output only. If a root was found other than an exact
  3236. * zero of g, trout is the endpoint thi of the final
  3237. * interval bracketing the root, with size at most ttol.
  3238. *
  3239. * grout = array of length nrtfn containing g(trout) on return.
  3240. *
  3241. * iroots = int array of length nrtfn with root information.
  3242. * Output only. If a root was found, iroots indicates
  3243. * which components g_i have a root at trout. For
  3244. * i = 0, ..., nrtfn-1, iroots[i] = 1 if g_i has a root
  3245. * and g_i is increasing, iroots[i] = -1 if g_i has a
  3246. * root and g_i is decreasing, and iroots[i] = 0 if g_i
  3247. * has no roots or g_i varies in the direction opposite
  3248. * to that indicated by rootdir[i].
  3249. *
  3250. * This routine returns an int equal to:
  3251. * CV_RTFUNC_FAIL < 0 if the g function failed, or
  3252. * RTFOUND = 1 if a root of g was found, or
  3253. * CV_SUCCESS = 0 otherwise.
  3254. */
  3255. static int cvRootfind(CVodeMem cv_mem)
  3256. {
  3257. realtype alph, tmid, gfrac, maxfrac, fracint, fracsub;
  3258. int i, retval, imax, side, sideprev;
  3259. booleantype zroot, sgnchg;
  3260. imax = 0;
  3261. /* First check for change in sign in ghi or for a zero in ghi. */
  3262. maxfrac = ZERO;
  3263. zroot = FALSE;
  3264. sgnchg = FALSE;
  3265. for (i = 0; i < nrtfn; i++) {
  3266. if(!gactive[i]) continue;
  3267. if (SUNRabs(ghi[i]) == ZERO) {
  3268. if(rootdir[i]*glo[i] <= ZERO) {
  3269. zroot = TRUE;
  3270. }
  3271. } else {
  3272. if ( (glo[i]*ghi[i] < ZERO) && (rootdir[i]*glo[i] <= ZERO) ) {
  3273. gfrac = SUNRabs(ghi[i]/(ghi[i] - glo[i]));
  3274. if (gfrac > maxfrac) {
  3275. sgnchg = TRUE;
  3276. maxfrac = gfrac;
  3277. imax = i;
  3278. }
  3279. }
  3280. }
  3281. }
  3282. /* If no sign change was found, reset trout and grout. Then return
  3283. CV_SUCCESS if no zero was found, or set iroots and return RTFOUND. */
  3284. if (!sgnchg) {
  3285. trout = thi;
  3286. for (i = 0; i < nrtfn; i++) grout[i] = ghi[i];
  3287. if (!zroot) return(CV_SUCCESS);
  3288. for (i = 0; i < nrtfn; i++) {
  3289. iroots[i] = 0;
  3290. if(!gactive[i]) continue;
  3291. if ( (SUNRabs(ghi[i]) == ZERO) && (rootdir[i]*glo[i] <= ZERO) )
  3292. iroots[i] = glo[i] > 0 ? -1:1;
  3293. }
  3294. return(RTFOUND);
  3295. }
  3296. /* Initialize alph to avoid compiler warning */
  3297. alph = ONE;
  3298. /* A sign change was found. Loop to locate nearest root. */
  3299. side = 0; sideprev = -1;
  3300. loop { /* Looping point */
  3301. /* If interval size is already less than tolerance ttol, break. */
  3302. if (SUNRabs(thi - tlo) <= ttol) break;
  3303. /* Set weight alph.
  3304. On the first two passes, set alph = 1. Thereafter, reset alph
  3305. according to the side (low vs high) of the subinterval in which
  3306. the sign change was found in the previous two passes.
  3307. If the sides were opposite, set alph = 1.
  3308. If the sides were the same, then double alph (if high side),
  3309. or halve alph (if low side).
  3310. The next guess tmid is the secant method value if alph = 1, but
  3311. is closer to tlo if alph < 1, and closer to thi if alph > 1. */
  3312. if (sideprev == side) {
  3313. alph = (side == 2) ? alph*TWO : alph*HALF;
  3314. } else {
  3315. alph = ONE;
  3316. }
  3317. /* Set next root approximation tmid and get g(tmid).
  3318. If tmid is too close to tlo or thi, adjust it inward,
  3319. by a fractional distance that is between 0.1 and 0.5. */
  3320. tmid = thi - (thi - tlo)*ghi[imax]/(ghi[imax] - alph*glo[imax]);
  3321. if (SUNRabs(tmid - tlo) < HALF*ttol) {
  3322. fracint = SUNRabs(thi - tlo)/ttol;
  3323. fracsub = (fracint > FIVE) ? PT1 : HALF/fracint;
  3324. tmid = tlo + fracsub*(thi - tlo);
  3325. }
  3326. if (SUNRabs(thi - tmid) < HALF*ttol) {
  3327. fracint = SUNRabs(thi - tlo)/ttol;
  3328. fracsub = (fracint > FIVE) ? PT1 : HALF/fracint;
  3329. tmid = thi - fracsub*(thi - tlo);
  3330. }
  3331. (void) CVodeGetDky(cv_mem, tmid, 0, y);
  3332. retval = gfun(tmid, y, grout, user_data);
  3333. nge++;
  3334. if (retval != 0) return(CV_RTFUNC_FAIL);
  3335. /* Check to see in which subinterval g changes sign, and reset imax.
  3336. Set side = 1 if sign change is on low side, or 2 if on high side. */
  3337. maxfrac = ZERO;
  3338. zroot = FALSE;
  3339. sgnchg = FALSE;
  3340. sideprev = side;
  3341. for (i = 0; i < nrtfn; i++) {
  3342. if(!gactive[i]) continue;
  3343. if (SUNRabs(grout[i]) == ZERO) {
  3344. if(rootdir[i]*glo[i] <= ZERO) zroot = TRUE;
  3345. } else {
  3346. if ( (glo[i]*grout[i] < ZERO) && (rootdir[i]*glo[i] <= ZERO) ) {
  3347. gfrac = SUNRabs(grout[i]/(grout[i] - glo[i]));
  3348. if (gfrac > maxfrac) {
  3349. sgnchg = TRUE;
  3350. maxfrac = gfrac;
  3351. imax = i;
  3352. }
  3353. }
  3354. }
  3355. }
  3356. if (sgnchg) {
  3357. /* Sign change found in (tlo,tmid); replace thi with tmid. */
  3358. thi = tmid;
  3359. for (i = 0; i < nrtfn; i++) ghi[i] = grout[i];
  3360. side = 1;
  3361. /* Stop at root thi if converged; otherwise loop. */
  3362. if (SUNRabs(thi - tlo) <= ttol) break;
  3363. continue; /* Return to looping point. */
  3364. }
  3365. if (zroot) {
  3366. /* No sign change in (tlo,tmid), but g = 0 at tmid; return root tmid. */
  3367. thi = tmid;
  3368. for (i = 0; i < nrtfn; i++) ghi[i] = grout[i];
  3369. break;
  3370. }
  3371. /* No sign change in (tlo,tmid), and no zero at tmid.
  3372. Sign change must be in (tmid,thi). Replace tlo with tmid. */
  3373. tlo = tmid;
  3374. for (i = 0; i < nrtfn; i++) glo[i] = grout[i];
  3375. side = 2;
  3376. /* Stop at root thi if converged; otherwise loop back. */
  3377. if (SUNRabs(thi - tlo) <= ttol) break;
  3378. } /* End of root-search loop */
  3379. /* Reset trout and grout, set iroots, and return RTFOUND. */
  3380. trout = thi;
  3381. for (i = 0; i < nrtfn; i++) {
  3382. grout[i] = ghi[i];
  3383. iroots[i] = 0;
  3384. if(!gactive[i]) continue;
  3385. if ( (SUNRabs(ghi[i]) == ZERO) && (rootdir[i]*glo[i] <= ZERO) )
  3386. iroots[i] = glo[i] > 0 ? -1:1;
  3387. if ( (glo[i]*ghi[i] < ZERO) && (rootdir[i]*glo[i] <= ZERO) )
  3388. iroots[i] = glo[i] > 0 ? -1:1;
  3389. }
  3390. return(RTFOUND);
  3391. }
  3392. /*
  3393. * =================================================================
  3394. * Internal EWT function
  3395. * =================================================================
  3396. */
  3397. /*
  3398. * cvEwtSet
  3399. *
  3400. * This routine is responsible for setting the error weight vector ewt,
  3401. * according to tol_type, as follows:
  3402. *
  3403. * (1) ewt[i] = 1 / (reltol * SUNRabs(ycur[i]) + *abstol), i=0,...,neq-1
  3404. * if tol_type = CV_SS
  3405. * (2) ewt[i] = 1 / (reltol * SUNRabs(ycur[i]) + abstol[i]), i=0,...,neq-1
  3406. * if tol_type = CV_SV
  3407. *
  3408. * cvEwtSet returns 0 if ewt is successfully set as above to a
  3409. * positive vector and -1 otherwise. In the latter case, ewt is
  3410. * considered undefined.
  3411. *
  3412. * All the real work is done in the routines cvEwtSetSS, cvEwtSetSV.
  3413. */
  3414. SUNDIALS_EXPORT int cvEwtSet(N_Vector ycur, N_Vector weight, void *data)
  3415. {
  3416. CVodeMem cv_mem;
  3417. int flag = 0;
  3418. /* data points to cv_mem here */
  3419. cv_mem = (CVodeMem) data;
  3420. switch(itol) {
  3421. case CV_SS:
  3422. flag = cvEwtSetSS(cv_mem, ycur, weight);
  3423. break;
  3424. case CV_SV:
  3425. flag = cvEwtSetSV(cv_mem, ycur, weight);
  3426. break;
  3427. }
  3428. return(flag);
  3429. }
  3430. /*
  3431. * cvEwtSetSS
  3432. *
  3433. * This routine sets ewt as decribed above in the case tol_type = CV_SS.
  3434. * It tests for non-positive components before inverting. cvEwtSetSS
  3435. * returns 0 if ewt is successfully set to a positive vector
  3436. * and -1 otherwise. In the latter case, ewt is considered undefined.
  3437. */
  3438. static int cvEwtSetSS(CVodeMem cv_mem, N_Vector ycur, N_Vector weight)
  3439. {
  3440. N_VAbs(ycur, tempv);
  3441. N_VScale(reltol, tempv, tempv);
  3442. N_VAddConst(tempv, Sabstol, tempv);
  3443. if (N_VMin(tempv) <= ZERO) return(-1);
  3444. N_VInv(tempv, weight);
  3445. return(0);
  3446. }
  3447. /*
  3448. * cvEwtSetSV
  3449. *
  3450. * This routine sets ewt as decribed above in the case tol_type = CV_SV.
  3451. * It tests for non-positive components before inverting. cvEwtSetSV
  3452. * returns 0 if ewt is successfully set to a positive vector
  3453. * and -1 otherwise. In the latter case, ewt is considered undefined.
  3454. */
  3455. static int cvEwtSetSV(CVodeMem cv_mem, N_Vector ycur, N_Vector weight)
  3456. {
  3457. N_VAbs(ycur, tempv);
  3458. N_VLinearSum(reltol, tempv, ONE, Vabstol, tempv);
  3459. if (N_VMin(tempv) <= ZERO) return(-1);
  3460. N_VInv(tempv, weight);
  3461. return(0);
  3462. }
  3463. /*
  3464. * -----------------------------------------------------------------
  3465. * Error message handling functions
  3466. * -----------------------------------------------------------------
  3467. */
  3468. /*
  3469. * cvProcessError is a high level error handling function.
  3470. * - If cv_mem==NULL it prints the error message to stderr.
  3471. * - Otherwise, it sets up and calls the error handling function
  3472. * pointed to by cv_ehfun.
  3473. */
  3474. #define ehfun (cv_mem->cv_ehfun)
  3475. #define eh_data (cv_mem->cv_eh_data)
  3476. SUNDIALS_EXPORT void cvProcessError(CVodeMem cv_mem,
  3477. int error_code, const char *module, const char *fname,
  3478. const char *msgfmt, ...)
  3479. {
  3480. va_list ap;
  3481. char msg[256];
  3482. /* Initialize the argument pointer variable
  3483. (msgfmt is the last required argument to cvProcessError) */
  3484. va_start(ap, msgfmt);
  3485. /* Compose the message */
  3486. vsprintf(msg, msgfmt, ap);
  3487. if (cv_mem == NULL) { /* We write to stderr */
  3488. #ifndef NO_FPRINTF_OUTPUT
  3489. fprintf(stderr, "\n[%s ERROR] %s\n ", module, fname);
  3490. fprintf(stderr, "%s\n\n", msg);
  3491. #endif
  3492. } else { /* We can call ehfun */
  3493. ehfun(error_code, module, fname, msg, eh_data);
  3494. }
  3495. /* Finalize argument processing */
  3496. va_end(ap);
  3497. return;
  3498. }
  3499. /*
  3500. * cvErrHandler is the default error handling function.
  3501. * It sends the error message to the stream pointed to by cv_errfp.
  3502. */
  3503. #define errfp (cv_mem->cv_errfp)
  3504. SUNDIALS_EXPORT void cvErrHandler(int error_code, const char *module,
  3505. const char *function, char *msg, void *data)
  3506. {
  3507. CVodeMem cv_mem;
  3508. char err_type[10];
  3509. /* data points to cv_mem here */
  3510. cv_mem = (CVodeMem) data;
  3511. if (error_code == CV_WARNING)
  3512. sprintf(err_type,"WARNING");
  3513. else
  3514. sprintf(err_type,"ERROR");
  3515. #ifndef NO_FPRINTF_OUTPUT
  3516. if (errfp!=NULL) {
  3517. fprintf(errfp,"\n[%s %s] %s\n",module,err_type,function);
  3518. fprintf(errfp," %s\n\n",msg);
  3519. }
  3520. #endif
  3521. return;
  3522. }
  3523. /* undefine to be able to compile all source code files in a single compilation unit, added by 3ds.com */
  3524. #undef f
  3525. #undef user_data
  3526. #undef efun
  3527. #undef e_data
  3528. #undef qmax
  3529. #undef mxstep
  3530. #undef mxhnil
  3531. #undef sldeton
  3532. #undef hin
  3533. #undef hmin
  3534. #undef hmax_inv
  3535. #undef tstop
  3536. #undef tstopset
  3537. #undef maxnef
  3538. #undef maxncf
  3539. #undef maxcor
  3540. #undef nlscoef
  3541. #undef itol
  3542. #undef reltol
  3543. #undef Sabstol
  3544. #undef Vabstol
  3545. #undef uround
  3546. #undef zn
  3547. #undef ewt
  3548. #undef y
  3549. #undef acor
  3550. #undef tempv
  3551. #undef ftemp
  3552. #undef q
  3553. #undef qprime
  3554. #undef next_q
  3555. #undef qwait
  3556. #undef L
  3557. #undef h
  3558. #undef hprime
  3559. #undef next_h
  3560. #undef eta
  3561. #undef etaqm1
  3562. #undef etaq
  3563. #undef etaqp1
  3564. #undef nscon
  3565. #undef hscale
  3566. #undef tn
  3567. #undef tau
  3568. #undef tq
  3569. #undef l
  3570. #undef rl1
  3571. #undef gamma
  3572. #undef gammap
  3573. #undef gamrat
  3574. #undef crate
  3575. #undef acnrm
  3576. #undef mnewt
  3577. #undef etamax
  3578. #undef nst
  3579. #undef nfe
  3580. #undef ncfn
  3581. #undef netf
  3582. #undef nni
  3583. #undef nsetups
  3584. #undef nhnil
  3585. #undef linit
  3586. #undef lsetup
  3587. #undef lsolve
  3588. #undef lfree
  3589. #undef lmem
  3590. #undef qu
  3591. #undef nstlp
  3592. #undef h0u
  3593. #undef hu
  3594. #undef saved_tq5
  3595. #undef indx_acor
  3596. #undef jcur
  3597. #undef tolsf
  3598. #undef setupNonNull
  3599. #undef nor
  3600. #undef ssdat
  3601. #undef nrtfn
  3602. #undef tlo
  3603. #undef thi
  3604. #undef tretlast
  3605. #undef toutc
  3606. #undef trout
  3607. #undef ttol
  3608. #undef taskc
  3609. #undef irfnd
  3610. #undef nge
  3611. #undef ehfun
  3612. #undef eh_data
  3613. #undef errfp
  3614. #undef loop
  3615. #undef iter
  3616. #undef lmm
  3617. #undef lrw
  3618. #undef liw
  3619. #undef gfun
  3620. #undef glo
  3621. #undef ghi
  3622. #undef grout
  3623. #undef iroots
  3624. #undef rootdir
  3625. #undef gactive
  3626. #undef lrw1
  3627. #undef liw1