diskio_meat.hpp 110 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725
  1. // Copyright 2008-2016 Conrad Sanderson (http://conradsanderson.id.au)
  2. // Copyright 2008-2016 National ICT Australia (NICTA)
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // ------------------------------------------------------------------------
  15. //! \addtogroup diskio
  16. //! @{
  17. //! Generate the first line of the header used for saving matrices in text format.
  18. //! Format: "ARMA_MAT_TXT_ABXYZ".
  19. //! A is one of: I (for integral types) or F (for floating point types).
  20. //! B is one of: U (for unsigned types), S (for signed types), N (for not applicable) or C (for complex types).
  21. //! XYZ specifies the width of each element in terms of bytes, e.g. "008" indicates eight bytes.
  22. template<typename eT>
  23. inline
  24. arma_cold
  25. std::string
  26. diskio::gen_txt_header(const Mat<eT>&)
  27. {
  28. arma_type_check(( is_supported_elem_type<eT>::value == false ));
  29. if( is_u8<eT>::value) { return std::string("ARMA_MAT_TXT_IU001"); }
  30. else if( is_s8<eT>::value) { return std::string("ARMA_MAT_TXT_IS001"); }
  31. else if(is_u16<eT>::value) { return std::string("ARMA_MAT_TXT_IU002"); }
  32. else if(is_s16<eT>::value) { return std::string("ARMA_MAT_TXT_IS002"); }
  33. else if(is_u32<eT>::value) { return std::string("ARMA_MAT_TXT_IU004"); }
  34. else if(is_s32<eT>::value) { return std::string("ARMA_MAT_TXT_IS004"); }
  35. #if defined(ARMA_USE_U64S64)
  36. else if(is_u64<eT>::value) { return std::string("ARMA_MAT_TXT_IU008"); }
  37. else if(is_s64<eT>::value) { return std::string("ARMA_MAT_TXT_IS008"); }
  38. #endif
  39. #if defined(ARMA_ALLOW_LONG)
  40. else if(is_ulng_t_32<eT>::value) { return std::string("ARMA_MAT_TXT_IU004"); }
  41. else if(is_slng_t_32<eT>::value) { return std::string("ARMA_MAT_TXT_IS004"); }
  42. else if(is_ulng_t_64<eT>::value) { return std::string("ARMA_MAT_TXT_IU008"); }
  43. else if(is_slng_t_64<eT>::value) { return std::string("ARMA_MAT_TXT_IS008"); }
  44. #endif
  45. else if( is_float<eT>::value) { return std::string("ARMA_MAT_TXT_FN004"); }
  46. else if( is_double<eT>::value) { return std::string("ARMA_MAT_TXT_FN008"); }
  47. else if( is_cx_float<eT>::value) { return std::string("ARMA_MAT_TXT_FC008"); }
  48. else if(is_cx_double<eT>::value) { return std::string("ARMA_MAT_TXT_FC016"); }
  49. return std::string();
  50. }
  51. //! Generate the first line of the header used for saving matrices in binary format.
  52. //! Format: "ARMA_MAT_BIN_ABXYZ".
  53. //! A is one of: I (for integral types) or F (for floating point types).
  54. //! B is one of: U (for unsigned types), S (for signed types), N (for not applicable) or C (for complex types).
  55. //! XYZ specifies the width of each element in terms of bytes, e.g. "008" indicates eight bytes.
  56. template<typename eT>
  57. inline
  58. arma_cold
  59. std::string
  60. diskio::gen_bin_header(const Mat<eT>&)
  61. {
  62. arma_type_check(( is_supported_elem_type<eT>::value == false ));
  63. if( is_u8<eT>::value) { return std::string("ARMA_MAT_BIN_IU001"); }
  64. else if( is_s8<eT>::value) { return std::string("ARMA_MAT_BIN_IS001"); }
  65. else if(is_u16<eT>::value) { return std::string("ARMA_MAT_BIN_IU002"); }
  66. else if(is_s16<eT>::value) { return std::string("ARMA_MAT_BIN_IS002"); }
  67. else if(is_u32<eT>::value) { return std::string("ARMA_MAT_BIN_IU004"); }
  68. else if(is_s32<eT>::value) { return std::string("ARMA_MAT_BIN_IS004"); }
  69. #if defined(ARMA_USE_U64S64)
  70. else if(is_u64<eT>::value) { return std::string("ARMA_MAT_BIN_IU008"); }
  71. else if(is_s64<eT>::value) { return std::string("ARMA_MAT_BIN_IS008"); }
  72. #endif
  73. #if defined(ARMA_ALLOW_LONG)
  74. else if(is_ulng_t_32<eT>::value) { return std::string("ARMA_MAT_BIN_IU004"); }
  75. else if(is_slng_t_32<eT>::value) { return std::string("ARMA_MAT_BIN_IS004"); }
  76. else if(is_ulng_t_64<eT>::value) { return std::string("ARMA_MAT_BIN_IU008"); }
  77. else if(is_slng_t_64<eT>::value) { return std::string("ARMA_MAT_BIN_IS008"); }
  78. #endif
  79. else if( is_float<eT>::value) { return std::string("ARMA_MAT_BIN_FN004"); }
  80. else if( is_double<eT>::value) { return std::string("ARMA_MAT_BIN_FN008"); }
  81. else if( is_cx_float<eT>::value) { return std::string("ARMA_MAT_BIN_FC008"); }
  82. else if(is_cx_double<eT>::value) { return std::string("ARMA_MAT_BIN_FC016"); }
  83. return std::string();
  84. }
  85. //! Generate the first line of the header used for saving matrices in binary format.
  86. //! Format: "ARMA_SPM_BIN_ABXYZ".
  87. //! A is one of: I (for integral types) or F (for floating point types).
  88. //! B is one of: U (for unsigned types), S (for signed types), N (for not applicable) or C (for complex types).
  89. //! XYZ specifies the width of each element in terms of bytes, e.g. "008" indicates eight bytes.
  90. template<typename eT>
  91. inline
  92. arma_cold
  93. std::string
  94. diskio::gen_bin_header(const SpMat<eT>&)
  95. {
  96. arma_type_check(( is_supported_elem_type<eT>::value == false ));
  97. if( is_u8<eT>::value) { return std::string("ARMA_SPM_BIN_IU001"); }
  98. else if( is_s8<eT>::value) { return std::string("ARMA_SPM_BIN_IS001"); }
  99. else if(is_u16<eT>::value) { return std::string("ARMA_SPM_BIN_IU002"); }
  100. else if(is_s16<eT>::value) { return std::string("ARMA_SPM_BIN_IS002"); }
  101. else if(is_u32<eT>::value) { return std::string("ARMA_SPM_BIN_IU004"); }
  102. else if(is_s32<eT>::value) { return std::string("ARMA_SPM_BIN_IS004"); }
  103. #if defined(ARMA_USE_U64S64)
  104. else if(is_u64<eT>::value) { return std::string("ARMA_SPM_BIN_IU008"); }
  105. else if(is_s64<eT>::value) { return std::string("ARMA_SPM_BIN_IS008"); }
  106. #endif
  107. #if defined(ARMA_ALLOW_LONG)
  108. else if(is_ulng_t_32<eT>::value) { return std::string("ARMA_SPM_BIN_IU004"); }
  109. else if(is_slng_t_32<eT>::value) { return std::string("ARMA_SPM_BIN_IS004"); }
  110. else if(is_ulng_t_64<eT>::value) { return std::string("ARMA_SPM_BIN_IU008"); }
  111. else if(is_slng_t_64<eT>::value) { return std::string("ARMA_SPM_BIN_IS008"); }
  112. #endif
  113. else if( is_float<eT>::value) { return std::string("ARMA_SPM_BIN_FN004"); }
  114. else if( is_double<eT>::value) { return std::string("ARMA_SPM_BIN_FN008"); }
  115. else if( is_cx_float<eT>::value) { return std::string("ARMA_SPM_BIN_FC008"); }
  116. else if(is_cx_double<eT>::value) { return std::string("ARMA_SPM_BIN_FC016"); }
  117. return std::string();
  118. }
  119. //! Generate the first line of the header used for saving cubes in text format.
  120. //! Format: "ARMA_CUB_TXT_ABXYZ".
  121. //! A is one of: I (for integral types) or F (for floating point types).
  122. //! B is one of: U (for unsigned types), S (for signed types), N (for not applicable) or C (for complex types).
  123. //! XYZ specifies the width of each element in terms of bytes, e.g. "008" indicates eight bytes.
  124. template<typename eT>
  125. inline
  126. arma_cold
  127. std::string
  128. diskio::gen_txt_header(const Cube<eT>&)
  129. {
  130. arma_type_check(( is_supported_elem_type<eT>::value == false ));
  131. if( is_u8<eT>::value) { return std::string("ARMA_CUB_TXT_IU001"); }
  132. else if( is_s8<eT>::value) { return std::string("ARMA_CUB_TXT_IS001"); }
  133. else if(is_u16<eT>::value) { return std::string("ARMA_CUB_TXT_IU002"); }
  134. else if(is_s16<eT>::value) { return std::string("ARMA_CUB_TXT_IS002"); }
  135. else if(is_u32<eT>::value) { return std::string("ARMA_CUB_TXT_IU004"); }
  136. else if(is_s32<eT>::value) { return std::string("ARMA_CUB_TXT_IS004"); }
  137. #if defined(ARMA_USE_U64S64)
  138. else if(is_u64<eT>::value) { return std::string("ARMA_CUB_TXT_IU008"); }
  139. else if(is_s64<eT>::value) { return std::string("ARMA_CUB_TXT_IS008"); }
  140. #endif
  141. #if defined(ARMA_ALLOW_LONG)
  142. else if(is_ulng_t_32<eT>::value) { return std::string("ARMA_CUB_TXT_IU004"); }
  143. else if(is_slng_t_32<eT>::value) { return std::string("ARMA_CUB_TXT_IS004"); }
  144. else if(is_ulng_t_64<eT>::value) { return std::string("ARMA_CUB_TXT_IU008"); }
  145. else if(is_slng_t_64<eT>::value) { return std::string("ARMA_CUB_TXT_IS008"); }
  146. #endif
  147. else if( is_float<eT>::value) { return std::string("ARMA_CUB_TXT_FN004"); }
  148. else if( is_double<eT>::value) { return std::string("ARMA_CUB_TXT_FN008"); }
  149. else if( is_cx_float<eT>::value) { return std::string("ARMA_CUB_TXT_FC008"); }
  150. else if(is_cx_double<eT>::value) { return std::string("ARMA_CUB_TXT_FC016"); }
  151. return std::string();
  152. }
  153. //! Generate the first line of the header used for saving cubes in binary format.
  154. //! Format: "ARMA_CUB_BIN_ABXYZ".
  155. //! A is one of: I (for integral types) or F (for floating point types).
  156. //! B is one of: U (for unsigned types), S (for signed types), N (for not applicable) or C (for complex types).
  157. //! XYZ specifies the width of each element in terms of bytes, e.g. "008" indicates eight bytes.
  158. template<typename eT>
  159. inline
  160. arma_cold
  161. std::string
  162. diskio::gen_bin_header(const Cube<eT>&)
  163. {
  164. arma_type_check(( is_supported_elem_type<eT>::value == false ));
  165. if( is_u8<eT>::value) { return std::string("ARMA_CUB_BIN_IU001"); }
  166. else if( is_s8<eT>::value) { return std::string("ARMA_CUB_BIN_IS001"); }
  167. else if(is_u16<eT>::value) { return std::string("ARMA_CUB_BIN_IU002"); }
  168. else if(is_s16<eT>::value) { return std::string("ARMA_CUB_BIN_IS002"); }
  169. else if(is_u32<eT>::value) { return std::string("ARMA_CUB_BIN_IU004"); }
  170. else if(is_s32<eT>::value) { return std::string("ARMA_CUB_BIN_IS004"); }
  171. #if defined(ARMA_USE_U64S64)
  172. else if(is_u64<eT>::value) { return std::string("ARMA_CUB_BIN_IU008"); }
  173. else if(is_s64<eT>::value) { return std::string("ARMA_CUB_BIN_IS008"); }
  174. #endif
  175. #if defined(ARMA_ALLOW_LONG)
  176. else if(is_ulng_t_32<eT>::value) { return std::string("ARMA_CUB_BIN_IU004"); }
  177. else if(is_slng_t_32<eT>::value) { return std::string("ARMA_CUB_BIN_IS004"); }
  178. else if(is_ulng_t_64<eT>::value) { return std::string("ARMA_CUB_BIN_IU008"); }
  179. else if(is_slng_t_64<eT>::value) { return std::string("ARMA_CUB_BIN_IS008"); }
  180. #endif
  181. else if( is_float<eT>::value) { return std::string("ARMA_CUB_BIN_FN004"); }
  182. else if( is_double<eT>::value) { return std::string("ARMA_CUB_BIN_FN008"); }
  183. else if( is_cx_float<eT>::value) { return std::string("ARMA_CUB_BIN_FC008"); }
  184. else if(is_cx_double<eT>::value) { return std::string("ARMA_CUB_BIN_FC016"); }
  185. return std::string();
  186. }
  187. inline
  188. arma_deprecated
  189. file_type
  190. diskio::guess_file_type(std::istream& f)
  191. {
  192. arma_extra_debug_sigprint();
  193. return diskio::guess_file_type_internal(f);
  194. }
  195. inline
  196. arma_cold
  197. file_type
  198. diskio::guess_file_type_internal(std::istream& f)
  199. {
  200. arma_extra_debug_sigprint();
  201. f.clear();
  202. const std::fstream::pos_type pos1 = f.tellg();
  203. f.clear();
  204. f.seekg(0, ios::end);
  205. f.clear();
  206. const std::fstream::pos_type pos2 = f.tellg();
  207. const uword N_max = ( (pos1 >= 0) && (pos2 >= 0) && (pos2 > pos1) ) ? uword(pos2 - pos1) : uword(0);
  208. f.clear();
  209. f.seekg(pos1);
  210. if(N_max == 0) { return file_type_unknown; }
  211. const uword N_use = (std::min)(N_max, uword(4096));
  212. podarray<unsigned char> data(N_use);
  213. data.zeros();
  214. unsigned char* data_mem = data.memptr();
  215. f.clear();
  216. f.read( reinterpret_cast<char*>(data_mem), std::streamsize(N_use) );
  217. const bool load_okay = f.good();
  218. f.clear();
  219. f.seekg(pos1);
  220. if(load_okay == false) { return file_type_unknown; }
  221. bool has_binary = false;
  222. bool has_bracket = false;
  223. bool has_comma = false;
  224. for(uword i=0; i<N_use; ++i)
  225. {
  226. const unsigned char val = data_mem[i];
  227. if( (val <= 8) || (val >= 123) ) { has_binary = true; break; } // the range checking can be made more elaborate
  228. if( (val == '(') || (val == ')') ) { has_bracket = true; }
  229. if( (val == ',') ) { has_comma = true; }
  230. }
  231. if(has_binary) { return raw_binary; }
  232. if(has_comma && (has_bracket == false)) { return csv_ascii; }
  233. return raw_ascii;
  234. }
  235. //! Append a quasi-random string to the given filename.
  236. //! Avoiding use of rand() to preserve its state.
  237. inline
  238. arma_cold
  239. std::string
  240. diskio::gen_tmp_name(const std::string& x)
  241. {
  242. union { uword val; void* ptr; } u;
  243. u.val = uword(0);
  244. u.ptr = const_cast<std::string*>(&x);
  245. const u16 a = u16( (u.val >> 8) & 0xFFFF );
  246. const u16 b = u16( (std::clock()) & 0xFFFF );
  247. std::ostringstream ss;
  248. ss << x << ".tmp_";
  249. ss.setf(std::ios_base::hex, std::ios_base::basefield);
  250. ss.width(4);
  251. ss.fill('0');
  252. ss << a;
  253. ss.width(4);
  254. ss.fill('0');
  255. ss << b;
  256. return ss.str();
  257. }
  258. //! Safely rename a file.
  259. //! Before renaming, test if we can write to the final file.
  260. //! This should prevent:
  261. //! (i) overwriting files that are write protected,
  262. //! (ii) overwriting directories.
  263. inline
  264. arma_cold
  265. bool
  266. diskio::safe_rename(const std::string& old_name, const std::string& new_name)
  267. {
  268. const char* new_name_c_str = new_name.c_str();
  269. std::fstream f(new_name_c_str, std::fstream::out | std::fstream::app);
  270. f.put(' ');
  271. if(f.good()) { f.close(); } else { return false; }
  272. if(std::remove( new_name_c_str) != 0) { return false; }
  273. if(std::rename(old_name.c_str(), new_name_c_str) != 0) { return false; }
  274. return true;
  275. }
  276. template<typename eT>
  277. inline
  278. bool
  279. diskio::convert_token(eT& val, const std::string& token)
  280. {
  281. const size_t N = size_t(token.length());
  282. if(N == 0) { val = eT(0); return true; }
  283. const char* str = token.c_str();
  284. if( (N == 3) || (N == 4) )
  285. {
  286. const bool neg = (str[0] == '-');
  287. const bool pos = (str[0] == '+');
  288. const size_t offset = ( (neg || pos) && (N == 4) ) ? 1 : 0;
  289. const char sig_a = str[offset ];
  290. const char sig_b = str[offset+1];
  291. const char sig_c = str[offset+2];
  292. if( ((sig_a == 'i') || (sig_a == 'I')) && ((sig_b == 'n') || (sig_b == 'N')) && ((sig_c == 'f') || (sig_c == 'F')) )
  293. {
  294. val = neg ? cond_rel< is_signed<eT>::value >::make_neg(Datum<eT>::inf) : Datum<eT>::inf;
  295. return true;
  296. }
  297. else
  298. if( ((sig_a == 'n') || (sig_a == 'N')) && ((sig_b == 'a') || (sig_b == 'A')) && ((sig_c == 'n') || (sig_c == 'N')) )
  299. {
  300. val = Datum<eT>::nan;
  301. return true;
  302. }
  303. }
  304. char* endptr = NULL;
  305. if(is_real<eT>::value)
  306. {
  307. val = eT( std::strtod(str, &endptr) );
  308. }
  309. else
  310. {
  311. if(is_signed<eT>::value)
  312. {
  313. // signed integer
  314. #if defined(ARMA_USE_CXX11) || (defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 200112L))
  315. {
  316. val = eT( std::strtoll(str, &endptr, 10) );
  317. }
  318. #else
  319. {
  320. val = eT( std::strtol(str, &endptr, 10) );
  321. }
  322. #endif
  323. }
  324. else
  325. {
  326. // unsigned integer
  327. if(str[0] == '-') { val = eT(0); return true; }
  328. #if defined(ARMA_USE_CXX11) || (defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 200112L))
  329. {
  330. val = eT( std::strtoull(str, &endptr, 10) );
  331. }
  332. #else
  333. {
  334. val = eT( std::strtoul(str, &endptr, 10) );
  335. }
  336. #endif
  337. }
  338. }
  339. if(str == endptr) { return false; }
  340. return true;
  341. }
  342. template<typename T>
  343. inline
  344. bool
  345. diskio::convert_token(std::complex<T>& val, const std::string& token)
  346. {
  347. const size_t N = size_t(token.length());
  348. const size_t Nm1 = N-1;
  349. if(N == 0) { val = std::complex<T>(0); return true; }
  350. const char* str = token.c_str();
  351. // valid complex number formats:
  352. // (real,imag)
  353. // (real)
  354. // ()
  355. if( (token[0] != '(') || (token[Nm1] != ')') )
  356. {
  357. // no brackets, so treat the token as a non-complex number
  358. T val_real;
  359. const bool state = diskio::convert_token(val_real, token); // use the non-complex version of this function
  360. val = std::complex<T>(val_real);
  361. return state;
  362. }
  363. // does the token contain only the () brackets?
  364. if(N <= 2) { val = std::complex<T>(0); return true; }
  365. size_t comma_loc = 0;
  366. bool comma_found = false;
  367. for(size_t i=0; i<N; ++i) { if(str[i] == ',') { comma_loc = i; comma_found = true; break; } }
  368. bool state = false;
  369. if(comma_found == false)
  370. {
  371. // only the real part is available
  372. const std::string token_real( &(str[1]), (Nm1 - 1) );
  373. T val_real;
  374. state = diskio::convert_token(val_real, token_real); // use the non-complex version of this function
  375. val = std::complex<T>(val_real);
  376. }
  377. else
  378. {
  379. const std::string token_real( &(str[1]), (comma_loc - 1 ) );
  380. const std::string token_imag( &(str[comma_loc+1]), (Nm1 - 1 - comma_loc) );
  381. T val_real;
  382. T val_imag;
  383. const bool state_real = diskio::convert_token(val_real, token_real);
  384. const bool state_imag = diskio::convert_token(val_imag, token_imag);
  385. state = ((state_real == true) && (state_imag == true));
  386. val = std::complex<T>(val_real, val_imag);
  387. }
  388. return state;
  389. }
  390. template<typename eT>
  391. inline
  392. std::streamsize
  393. diskio::prepare_stream(std::ostream& f)
  394. {
  395. std::streamsize cell_width = f.width();
  396. if(is_real<eT>::value)
  397. {
  398. f.unsetf(ios::fixed);
  399. f.setf(ios::scientific);
  400. f.fill(' ');
  401. f.precision(16);
  402. cell_width = 24;
  403. // NOTE: for 'float' the optimum settings are f.precision(8) and cell_width = 15
  404. // NOTE: however, to avoid introducing errors in case single precision data is loaded as double precision,
  405. // NOTE: the same settings must be used for both 'float' and 'double'
  406. }
  407. else
  408. if(is_cx<eT>::value)
  409. {
  410. f.unsetf(ios::fixed);
  411. f.setf(ios::scientific);
  412. f.precision(16);
  413. }
  414. return cell_width;
  415. }
  416. //! Save a matrix as raw text (no header, human readable).
  417. //! Matrices can be loaded in Matlab and Octave, as long as they don't have complex elements.
  418. template<typename eT>
  419. inline
  420. bool
  421. diskio::save_raw_ascii(const Mat<eT>& x, const std::string& final_name)
  422. {
  423. arma_extra_debug_sigprint();
  424. const std::string tmp_name = diskio::gen_tmp_name(final_name);
  425. std::fstream f(tmp_name.c_str(), std::fstream::out);
  426. bool save_okay = f.is_open();
  427. if(save_okay)
  428. {
  429. save_okay = diskio::save_raw_ascii(x, f);
  430. f.flush();
  431. f.close();
  432. if(save_okay) { save_okay = diskio::safe_rename(tmp_name, final_name); }
  433. }
  434. return save_okay;
  435. }
  436. //! Save a matrix as raw text (no header, human readable).
  437. //! Matrices can be loaded in Matlab and Octave, as long as they don't have complex elements.
  438. template<typename eT>
  439. inline
  440. bool
  441. diskio::save_raw_ascii(const Mat<eT>& x, std::ostream& f)
  442. {
  443. arma_extra_debug_sigprint();
  444. const arma_ostream_state stream_state(f);
  445. const std::streamsize cell_width = diskio::prepare_stream<eT>(f);
  446. for(uword row=0; row < x.n_rows; ++row)
  447. {
  448. for(uword col=0; col < x.n_cols; ++col)
  449. {
  450. f.put(' ');
  451. if(is_real<eT>::value) { f.width(cell_width); }
  452. arma_ostream::raw_print_elem(f, x.at(row,col));
  453. }
  454. f.put('\n');
  455. }
  456. const bool save_okay = f.good();
  457. stream_state.restore(f);
  458. return save_okay;
  459. }
  460. //! Save a matrix as raw binary (no header)
  461. template<typename eT>
  462. inline
  463. bool
  464. diskio::save_raw_binary(const Mat<eT>& x, const std::string& final_name)
  465. {
  466. arma_extra_debug_sigprint();
  467. const std::string tmp_name = diskio::gen_tmp_name(final_name);
  468. std::ofstream f(tmp_name.c_str(), std::fstream::binary);
  469. bool save_okay = f.is_open();
  470. if(save_okay)
  471. {
  472. save_okay = diskio::save_raw_binary(x, f);
  473. f.flush();
  474. f.close();
  475. if(save_okay) { save_okay = diskio::safe_rename(tmp_name, final_name); }
  476. }
  477. return save_okay;
  478. }
  479. template<typename eT>
  480. inline
  481. bool
  482. diskio::save_raw_binary(const Mat<eT>& x, std::ostream& f)
  483. {
  484. arma_extra_debug_sigprint();
  485. f.write( reinterpret_cast<const char*>(x.mem), std::streamsize(x.n_elem*sizeof(eT)) );
  486. return f.good();
  487. }
  488. //! Save a matrix in text format (human readable),
  489. //! with a header that indicates the matrix type as well as its dimensions
  490. template<typename eT>
  491. inline
  492. bool
  493. diskio::save_arma_ascii(const Mat<eT>& x, const std::string& final_name)
  494. {
  495. arma_extra_debug_sigprint();
  496. const std::string tmp_name = diskio::gen_tmp_name(final_name);
  497. std::ofstream f(tmp_name.c_str());
  498. bool save_okay = f.is_open();
  499. if(save_okay)
  500. {
  501. save_okay = diskio::save_arma_ascii(x, f);
  502. f.flush();
  503. f.close();
  504. if(save_okay) { save_okay = diskio::safe_rename(tmp_name, final_name); }
  505. }
  506. return save_okay;
  507. }
  508. //! Save a matrix in text format (human readable),
  509. //! with a header that indicates the matrix type as well as its dimensions
  510. template<typename eT>
  511. inline
  512. bool
  513. diskio::save_arma_ascii(const Mat<eT>& x, std::ostream& f)
  514. {
  515. arma_extra_debug_sigprint();
  516. const arma_ostream_state stream_state(f);
  517. f << diskio::gen_txt_header(x) << '\n';
  518. f << x.n_rows << ' ' << x.n_cols << '\n';
  519. const std::streamsize cell_width = diskio::prepare_stream<eT>(f);
  520. for(uword row=0; row < x.n_rows; ++row)
  521. {
  522. for(uword col=0; col < x.n_cols; ++col)
  523. {
  524. f.put(' ');
  525. if(is_real<eT>::value) { f.width(cell_width); }
  526. arma_ostream::raw_print_elem(f, x.at(row,col));
  527. }
  528. f.put('\n');
  529. }
  530. const bool save_okay = f.good();
  531. stream_state.restore(f);
  532. return save_okay;
  533. }
  534. //! Save a matrix in CSV text format (human readable)
  535. template<typename eT>
  536. inline
  537. bool
  538. diskio::save_csv_ascii(const Mat<eT>& x, const std::string& final_name, const field<std::string>& header, const bool with_header)
  539. {
  540. arma_extra_debug_sigprint();
  541. const std::string tmp_name = diskio::gen_tmp_name(final_name);
  542. std::ofstream f(tmp_name.c_str());
  543. bool save_okay = f.is_open();
  544. if(save_okay == false) { return false; }
  545. if(with_header)
  546. {
  547. arma_extra_debug_print("diskio::save_csv_ascii(): writing header");
  548. for(uword i=0; i < header.n_elem; ++i)
  549. {
  550. f << header.at(i);
  551. if(i != (header.n_elem-1)) { f.put(','); }
  552. }
  553. f.put('\n');
  554. save_okay = f.good();
  555. }
  556. if(save_okay) { save_okay = diskio::save_csv_ascii(x, f); }
  557. f.flush();
  558. f.close();
  559. if(save_okay) { save_okay = diskio::safe_rename(tmp_name, final_name); }
  560. return save_okay;
  561. }
  562. //! Save a matrix in CSV text format (human readable)
  563. template<typename eT>
  564. inline
  565. bool
  566. diskio::save_csv_ascii(const Mat<eT>& x, std::ostream& f)
  567. {
  568. arma_extra_debug_sigprint();
  569. const arma_ostream_state stream_state(f);
  570. diskio::prepare_stream<eT>(f);
  571. uword x_n_rows = x.n_rows;
  572. uword x_n_cols = x.n_cols;
  573. for(uword row=0; row < x_n_rows; ++row)
  574. {
  575. for(uword col=0; col < x_n_cols; ++col)
  576. {
  577. arma_ostream::raw_print_elem(f, x.at(row,col));
  578. if( col < (x_n_cols-1) ) { f.put(','); }
  579. }
  580. f.put('\n');
  581. }
  582. const bool save_okay = f.good();
  583. stream_state.restore(f);
  584. return save_okay;
  585. }
  586. //! Save a matrix in CSV text format (human readable); complex numbers stored in "a+bi" format
  587. template<typename T>
  588. inline
  589. bool
  590. diskio::save_csv_ascii(const Mat< std::complex<T> >& x, std::ostream& f)
  591. {
  592. arma_extra_debug_sigprint();
  593. typedef typename std::complex<T> eT;
  594. const arma_ostream_state stream_state(f);
  595. diskio::prepare_stream<eT>(f);
  596. uword x_n_rows = x.n_rows;
  597. uword x_n_cols = x.n_cols;
  598. for(uword row=0; row < x_n_rows; ++row)
  599. {
  600. for(uword col=0; col < x_n_cols; ++col)
  601. {
  602. const eT& val = x.at(row,col);
  603. const T tmp_r = std::real(val);
  604. const T tmp_i = std::imag(val);
  605. const T tmp_i_abs = (tmp_i < T(0)) ? T(-tmp_i) : T(tmp_i);
  606. const char tmp_sign = (tmp_i < T(0)) ? char('-') : char('+');
  607. arma_ostream::raw_print_elem(f, tmp_r );
  608. f.put(tmp_sign);
  609. arma_ostream::raw_print_elem(f, tmp_i_abs);
  610. f.put('i');
  611. if( col < (x_n_cols-1) ) { f.put(','); }
  612. }
  613. f.put('\n');
  614. }
  615. const bool save_okay = f.good();
  616. stream_state.restore(f);
  617. return save_okay;
  618. }
  619. //! Save a matrix in binary format,
  620. //! with a header that stores the matrix type as well as its dimensions
  621. template<typename eT>
  622. inline
  623. bool
  624. diskio::save_arma_binary(const Mat<eT>& x, const std::string& final_name)
  625. {
  626. arma_extra_debug_sigprint();
  627. const std::string tmp_name = diskio::gen_tmp_name(final_name);
  628. std::ofstream f(tmp_name.c_str(), std::fstream::binary);
  629. bool save_okay = f.is_open();
  630. if(save_okay)
  631. {
  632. save_okay = diskio::save_arma_binary(x, f);
  633. f.flush();
  634. f.close();
  635. if(save_okay) { save_okay = diskio::safe_rename(tmp_name, final_name); }
  636. }
  637. return save_okay;
  638. }
  639. //! Save a matrix in binary format,
  640. //! with a header that stores the matrix type as well as its dimensions
  641. template<typename eT>
  642. inline
  643. bool
  644. diskio::save_arma_binary(const Mat<eT>& x, std::ostream& f)
  645. {
  646. arma_extra_debug_sigprint();
  647. f << diskio::gen_bin_header(x) << '\n';
  648. f << x.n_rows << ' ' << x.n_cols << '\n';
  649. f.write( reinterpret_cast<const char*>(x.mem), std::streamsize(x.n_elem*sizeof(eT)) );
  650. return f.good();
  651. }
  652. //! Save a matrix as a PGM greyscale image
  653. template<typename eT>
  654. inline
  655. bool
  656. diskio::save_pgm_binary(const Mat<eT>& x, const std::string& final_name)
  657. {
  658. arma_extra_debug_sigprint();
  659. const std::string tmp_name = diskio::gen_tmp_name(final_name);
  660. std::fstream f(tmp_name.c_str(), std::fstream::out | std::fstream::binary);
  661. bool save_okay = f.is_open();
  662. if(save_okay)
  663. {
  664. save_okay = diskio::save_pgm_binary(x, f);
  665. f.flush();
  666. f.close();
  667. if(save_okay) { save_okay = diskio::safe_rename(tmp_name, final_name); }
  668. }
  669. return save_okay;
  670. }
  671. //
  672. // TODO:
  673. // add functionality to save the image in a normalised format,
  674. // i.e. scaled so that every value falls in the [0,255] range.
  675. //! Save a matrix as a PGM greyscale image
  676. template<typename eT>
  677. inline
  678. bool
  679. diskio::save_pgm_binary(const Mat<eT>& x, std::ostream& f)
  680. {
  681. arma_extra_debug_sigprint();
  682. f << "P5" << '\n';
  683. f << x.n_cols << ' ' << x.n_rows << '\n';
  684. f << 255 << '\n';
  685. const uword n_elem = x.n_rows * x.n_cols;
  686. podarray<u8> tmp(n_elem);
  687. uword i = 0;
  688. for(uword row=0; row < x.n_rows; ++row)
  689. for(uword col=0; col < x.n_cols; ++col)
  690. {
  691. tmp[i] = u8( x.at(row,col) ); // TODO: add round() ?
  692. ++i;
  693. }
  694. f.write(reinterpret_cast<const char*>(tmp.mem), std::streamsize(n_elem) );
  695. return f.good();
  696. }
  697. //! Save a matrix as a PGM greyscale image
  698. template<typename T>
  699. inline
  700. bool
  701. diskio::save_pgm_binary(const Mat< std::complex<T> >& x, const std::string& final_name)
  702. {
  703. arma_extra_debug_sigprint();
  704. const uchar_mat tmp = conv_to<uchar_mat>::from(x);
  705. return diskio::save_pgm_binary(tmp, final_name);
  706. }
  707. //! Save a matrix as a PGM greyscale image
  708. template<typename T>
  709. inline
  710. bool
  711. diskio::save_pgm_binary(const Mat< std::complex<T> >& x, std::ostream& f)
  712. {
  713. arma_extra_debug_sigprint();
  714. const uchar_mat tmp = conv_to<uchar_mat>::from(x);
  715. return diskio::save_pgm_binary(tmp, f);
  716. }
  717. //! Save a matrix as part of a HDF5 file
  718. template<typename eT>
  719. inline
  720. bool
  721. diskio::save_hdf5_binary(const Mat<eT>& x, const hdf5_name& spec, std::string& err_msg)
  722. {
  723. arma_extra_debug_sigprint();
  724. #if defined(ARMA_USE_HDF5)
  725. {
  726. hdf5_misc::hdf5_suspend_printing_errors hdf5_print_suspender;
  727. bool save_okay = false;
  728. const bool append = bool(spec.opts.flags & hdf5_opts::flag_append);
  729. const bool replace = bool(spec.opts.flags & hdf5_opts::flag_replace);
  730. const bool use_existing_file = ((append || replace) && (arma_H5Fis_hdf5(spec.filename.c_str()) > 0));
  731. const std::string tmp_name = (use_existing_file) ? std::string() : diskio::gen_tmp_name(spec.filename);
  732. // Set up the file according to HDF5's preferences
  733. hid_t file = (use_existing_file) ? arma_H5Fopen(spec.filename.c_str(), H5F_ACC_RDWR, H5P_DEFAULT) : arma_H5Fcreate(tmp_name.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
  734. if(file < 0) { return false; }
  735. // We need to create a dataset, datatype, and dataspace
  736. hsize_t dims[2];
  737. dims[1] = x.n_rows;
  738. dims[0] = x.n_cols;
  739. hid_t dataspace = arma_H5Screate_simple(2, dims, NULL); // treat the matrix as a 2d array dataspace
  740. hid_t datatype = hdf5_misc::get_hdf5_type<eT>();
  741. // If this returned something invalid, well, it's time to crash.
  742. arma_check(datatype == -1, "Mat::save(): unknown datatype for HDF5");
  743. // MATLAB forces the users to specify a name at save time for HDF5;
  744. // Octave will use the default of 'dataset' unless otherwise specified.
  745. // If the user hasn't specified a dataset name, we will use 'dataset'
  746. // We may have to split out the group name from the dataset name.
  747. std::vector<hid_t> groups;
  748. std::string full_name = spec.dsname;
  749. size_t loc;
  750. while ((loc = full_name.find("/")) != std::string::npos)
  751. {
  752. // Create another group...
  753. if (loc != 0) // Ignore the first /, if there is a leading /.
  754. {
  755. hid_t gid = arma_H5Gcreate((groups.size() == 0) ? file : groups[groups.size() - 1], full_name.substr(0, loc).c_str(), H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
  756. if((gid < 0) && use_existing_file)
  757. {
  758. gid = arma_H5Gopen((groups.size() == 0) ? file : groups[groups.size() - 1], full_name.substr(0, loc).c_str(), H5P_DEFAULT);
  759. }
  760. groups.push_back(gid);
  761. }
  762. full_name = full_name.substr(loc + 1);
  763. }
  764. const std::string dataset_name = full_name.empty() ? std::string("dataset") : full_name;
  765. const hid_t last_group = (groups.size() == 0) ? file : groups[groups.size() - 1];
  766. if(use_existing_file && replace)
  767. {
  768. arma_H5Ldelete(last_group, dataset_name.c_str(), H5P_DEFAULT);
  769. // NOTE: H5Ldelete() in HDF5 v1.8 doesn't reclaim the deleted space; use h5repack to reclaim space: h5repack oldfile.h5 newfile.h5
  770. // NOTE: has this behaviour changed in HDF5 1.10 ?
  771. // NOTE: https://lists.hdfgroup.org/pipermail/hdf-forum_lists.hdfgroup.org/2017-August/010482.html
  772. // NOTE: https://lists.hdfgroup.org/pipermail/hdf-forum_lists.hdfgroup.org/2017-August/010486.html
  773. }
  774. hid_t dataset = arma_H5Dcreate(last_group, dataset_name.c_str(), datatype, dataspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
  775. if(dataset < 0)
  776. {
  777. save_okay = false;
  778. err_msg = "couldn't create dataset in ";
  779. }
  780. else
  781. {
  782. save_okay = (arma_H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, x.mem) >= 0);
  783. arma_H5Dclose(dataset);
  784. }
  785. arma_H5Tclose(datatype);
  786. arma_H5Sclose(dataspace);
  787. for (size_t i = 0; i < groups.size(); ++i) { arma_H5Gclose(groups[i]); }
  788. arma_H5Fclose(file);
  789. if((use_existing_file == false) && (save_okay == true)) { save_okay = diskio::safe_rename(tmp_name, spec.filename); }
  790. return save_okay;
  791. }
  792. #else
  793. {
  794. arma_ignore(x);
  795. arma_ignore(spec);
  796. arma_ignore(err_msg);
  797. arma_stop_logic_error("Mat::save(): use of HDF5 must be enabled");
  798. return false;
  799. }
  800. #endif
  801. }
  802. //! Load a matrix as raw text (no header, human readable).
  803. //! Can read matrices saved as text in Matlab and Octave.
  804. //! NOTE: this is much slower than reading a file with a header.
  805. template<typename eT>
  806. inline
  807. bool
  808. diskio::load_raw_ascii(Mat<eT>& x, const std::string& name, std::string& err_msg)
  809. {
  810. arma_extra_debug_sigprint();
  811. std::fstream f;
  812. f.open(name.c_str(), std::fstream::in);
  813. bool load_okay = f.is_open();
  814. if(load_okay)
  815. {
  816. load_okay = diskio::load_raw_ascii(x, f, err_msg);
  817. f.close();
  818. }
  819. return load_okay;
  820. }
  821. //! Load a matrix as raw text (no header, human readable).
  822. //! Can read matrices saved as text in Matlab and Octave.
  823. //! NOTE: this is much slower than reading a file with a header.
  824. template<typename eT>
  825. inline
  826. bool
  827. diskio::load_raw_ascii(Mat<eT>& x, std::istream& f, std::string& err_msg)
  828. {
  829. arma_extra_debug_sigprint();
  830. bool load_okay = f.good();
  831. f.clear();
  832. const std::fstream::pos_type pos1 = f.tellg();
  833. //
  834. // work out the size
  835. uword f_n_rows = 0;
  836. uword f_n_cols = 0;
  837. bool f_n_cols_found = false;
  838. std::string line_string;
  839. std::stringstream line_stream;
  840. std::string token;
  841. while( f.good() && load_okay )
  842. {
  843. std::getline(f, line_string);
  844. // TODO: does it make sense to stop processing the file if an empty line is found ?
  845. if(line_string.size() == 0) { break; }
  846. line_stream.clear();
  847. line_stream.str(line_string);
  848. uword line_n_cols = 0;
  849. while (line_stream >> token) { ++line_n_cols; }
  850. if(f_n_cols_found == false)
  851. {
  852. f_n_cols = line_n_cols;
  853. f_n_cols_found = true;
  854. }
  855. else
  856. {
  857. if(line_n_cols != f_n_cols)
  858. {
  859. load_okay = false;
  860. err_msg = "inconsistent number of columns in ";
  861. }
  862. }
  863. ++f_n_rows;
  864. }
  865. if(load_okay)
  866. {
  867. f.clear();
  868. f.seekg(pos1);
  869. x.set_size(f_n_rows, f_n_cols);
  870. for(uword row=0; ((row < x.n_rows) && load_okay); ++row)
  871. for(uword col=0; ((col < x.n_cols) && load_okay); ++col)
  872. {
  873. f >> token;
  874. if(diskio::convert_token(x.at(row,col), token) == false)
  875. {
  876. load_okay = false;
  877. err_msg = "couldn't interpret data in ";
  878. }
  879. }
  880. }
  881. // an empty file indicates an empty matrix
  882. if( (f_n_cols_found == false) && (load_okay == true) ) { x.reset(); }
  883. return load_okay;
  884. }
  885. //! Load a matrix in binary format (no header);
  886. //! the matrix is assumed to have one column
  887. template<typename eT>
  888. inline
  889. bool
  890. diskio::load_raw_binary(Mat<eT>& x, const std::string& name, std::string& err_msg)
  891. {
  892. arma_extra_debug_sigprint();
  893. std::ifstream f;
  894. f.open(name.c_str(), std::fstream::binary);
  895. bool load_okay = f.is_open();
  896. if(load_okay)
  897. {
  898. load_okay = diskio::load_raw_binary(x, f, err_msg);
  899. f.close();
  900. }
  901. return load_okay;
  902. }
  903. template<typename eT>
  904. inline
  905. bool
  906. diskio::load_raw_binary(Mat<eT>& x, std::istream& f, std::string& err_msg)
  907. {
  908. arma_extra_debug_sigprint();
  909. arma_ignore(err_msg);
  910. f.clear();
  911. const std::streampos pos1 = f.tellg();
  912. f.clear();
  913. f.seekg(0, ios::end);
  914. f.clear();
  915. const std::streampos pos2 = f.tellg();
  916. const uword N = ( (pos1 >= 0) && (pos2 >= 0) ) ? uword(pos2 - pos1) : 0;
  917. f.clear();
  918. //f.seekg(0, ios::beg);
  919. f.seekg(pos1);
  920. x.set_size(N / uword(sizeof(eT)), 1);
  921. f.clear();
  922. f.read( reinterpret_cast<char *>(x.memptr()), std::streamsize(x.n_elem * uword(sizeof(eT))) );
  923. return f.good();
  924. }
  925. //! Load a matrix in text format (human readable),
  926. //! with a header that indicates the matrix type as well as its dimensions
  927. template<typename eT>
  928. inline
  929. bool
  930. diskio::load_arma_ascii(Mat<eT>& x, const std::string& name, std::string& err_msg)
  931. {
  932. arma_extra_debug_sigprint();
  933. std::ifstream f(name.c_str());
  934. bool load_okay = f.is_open();
  935. if(load_okay)
  936. {
  937. load_okay = diskio::load_arma_ascii(x, f, err_msg);
  938. f.close();
  939. }
  940. return load_okay;
  941. }
  942. //! Load a matrix in text format (human readable),
  943. //! with a header that indicates the matrix type as well as its dimensions
  944. template<typename eT>
  945. inline
  946. bool
  947. diskio::load_arma_ascii(Mat<eT>& x, std::istream& f, std::string& err_msg)
  948. {
  949. arma_extra_debug_sigprint();
  950. std::streampos pos = f.tellg();
  951. bool load_okay = true;
  952. std::string f_header;
  953. uword f_n_rows;
  954. uword f_n_cols;
  955. f >> f_header;
  956. f >> f_n_rows;
  957. f >> f_n_cols;
  958. if(f_header == diskio::gen_txt_header(x))
  959. {
  960. x.zeros(f_n_rows, f_n_cols);
  961. std::string token;
  962. for(uword row=0; row < x.n_rows; ++row)
  963. for(uword col=0; col < x.n_cols; ++col)
  964. {
  965. f >> token;
  966. diskio::convert_token( x.at(row,col), token );
  967. }
  968. load_okay = f.good();
  969. }
  970. else
  971. {
  972. load_okay = false;
  973. err_msg = "incorrect header in ";
  974. }
  975. // allow automatic conversion of u32/s32 matrices into u64/s64 matrices
  976. if(load_okay == false)
  977. {
  978. if( (sizeof(eT) == 8) && is_same_type<uword,eT>::yes )
  979. {
  980. Mat<u32> tmp;
  981. std::string junk;
  982. f.clear();
  983. f.seekg(pos);
  984. load_okay = diskio::load_arma_ascii(tmp, f, junk);
  985. if(load_okay) { x = conv_to< Mat<eT> >::from(tmp); }
  986. }
  987. else
  988. if( (sizeof(eT) == 8) && is_same_type<sword,eT>::yes )
  989. {
  990. Mat<s32> tmp;
  991. std::string junk;
  992. f.clear();
  993. f.seekg(pos);
  994. load_okay = diskio::load_arma_ascii(tmp, f, junk);
  995. if(load_okay) { x = conv_to< Mat<eT> >::from(tmp); }
  996. }
  997. }
  998. return load_okay;
  999. }
  1000. //! Load a matrix in CSV text format (human readable)
  1001. template<typename eT>
  1002. inline
  1003. bool
  1004. diskio::load_csv_ascii(Mat<eT>& x, const std::string& name, std::string& err_msg, field<std::string>& header, const bool with_header)
  1005. {
  1006. arma_extra_debug_sigprint();
  1007. std::fstream f;
  1008. f.open(name.c_str(), std::fstream::in);
  1009. bool load_okay = f.is_open();
  1010. if(load_okay == false) { return false; }
  1011. if(with_header)
  1012. {
  1013. arma_extra_debug_print("diskio::load_csv_ascii(): reading header");
  1014. std::string header_line;
  1015. std::stringstream header_stream;
  1016. std::vector<std::string> header_tokens;
  1017. std::getline(f, header_line);
  1018. load_okay = f.good();
  1019. if(load_okay)
  1020. {
  1021. std::string token;
  1022. header_stream.clear();
  1023. header_stream.str(header_line);
  1024. uword header_n_tokens = 0;
  1025. while(header_stream.good())
  1026. {
  1027. std::getline(header_stream, token, ',');
  1028. ++header_n_tokens;
  1029. header_tokens.push_back(token);
  1030. }
  1031. if(header_n_tokens == uword(0))
  1032. {
  1033. header.reset();
  1034. }
  1035. else
  1036. {
  1037. header.set_size(1,header_n_tokens);
  1038. for(uword i=0; i < header_n_tokens; ++i) { header.at(i) = header_tokens[i]; }
  1039. }
  1040. }
  1041. }
  1042. if(load_okay)
  1043. {
  1044. load_okay = diskio::load_csv_ascii(x, f, err_msg);
  1045. }
  1046. f.close();
  1047. return load_okay;
  1048. }
  1049. //! Load a matrix in CSV text format (human readable)
  1050. template<typename eT>
  1051. inline
  1052. bool
  1053. diskio::load_csv_ascii(Mat<eT>& x, std::istream& f, std::string&)
  1054. {
  1055. arma_extra_debug_sigprint();
  1056. // TODO: replace with more efficient implementation
  1057. bool load_okay = f.good();
  1058. f.clear();
  1059. const std::fstream::pos_type pos1 = f.tellg();
  1060. //
  1061. // work out the size
  1062. uword f_n_rows = 0;
  1063. uword f_n_cols = 0;
  1064. std::string line_string;
  1065. std::stringstream line_stream;
  1066. std::string token;
  1067. while( f.good() && load_okay )
  1068. {
  1069. std::getline(f, line_string);
  1070. if(line_string.size() == 0) { break; }
  1071. line_stream.clear();
  1072. line_stream.str(line_string);
  1073. uword line_n_cols = 0;
  1074. while(line_stream.good())
  1075. {
  1076. std::getline(line_stream, token, ',');
  1077. ++line_n_cols;
  1078. }
  1079. if(f_n_cols < line_n_cols) { f_n_cols = line_n_cols; }
  1080. ++f_n_rows;
  1081. }
  1082. f.clear();
  1083. f.seekg(pos1);
  1084. x.zeros(f_n_rows, f_n_cols);
  1085. uword row = 0;
  1086. while(f.good())
  1087. {
  1088. std::getline(f, line_string);
  1089. if(line_string.size() == 0) { break; }
  1090. line_stream.clear();
  1091. line_stream.str(line_string);
  1092. uword col = 0;
  1093. while(line_stream.good())
  1094. {
  1095. std::getline(line_stream, token, ',');
  1096. diskio::convert_token( x.at(row,col), token );
  1097. ++col;
  1098. }
  1099. ++row;
  1100. }
  1101. return load_okay;
  1102. }
  1103. //! Load a matrix in CSV text format (human readable); complex numbers stored in "a+bi" format
  1104. template<typename T>
  1105. inline
  1106. bool
  1107. diskio::load_csv_ascii(Mat< std::complex<T> >& x, std::istream& f, std::string&)
  1108. {
  1109. arma_extra_debug_sigprint();
  1110. // TODO: replace with more efficient implementation
  1111. bool load_okay = f.good();
  1112. f.clear();
  1113. const std::fstream::pos_type pos1 = f.tellg();
  1114. //
  1115. // work out the size
  1116. uword f_n_rows = 0;
  1117. uword f_n_cols = 0;
  1118. std::string line_string;
  1119. std::stringstream line_stream;
  1120. std::string token;
  1121. while( f.good() && load_okay )
  1122. {
  1123. std::getline(f, line_string);
  1124. if(line_string.size() == 0) { break; }
  1125. line_stream.clear();
  1126. line_stream.str(line_string);
  1127. uword line_n_cols = 0;
  1128. while(line_stream.good())
  1129. {
  1130. std::getline(line_stream, token, ',');
  1131. ++line_n_cols;
  1132. }
  1133. if(f_n_cols < line_n_cols) { f_n_cols = line_n_cols; }
  1134. ++f_n_rows;
  1135. }
  1136. f.clear();
  1137. f.seekg(pos1);
  1138. x.zeros(f_n_rows, f_n_cols);
  1139. uword row = 0;
  1140. std::string str_real;
  1141. std::string str_imag;
  1142. while(f.good())
  1143. {
  1144. std::getline(f, line_string);
  1145. if(line_string.size() == 0) { break; }
  1146. line_stream.clear();
  1147. line_stream.str(line_string);
  1148. uword col = 0;
  1149. while(line_stream.good())
  1150. {
  1151. std::getline(line_stream, token, ',');
  1152. const size_t token_len = size_t( token.length() );
  1153. if(token_len == 0) { col++; continue; }
  1154. // handle special cases: inf and nan, without the imaginary part
  1155. if( (token_len == 3) || (token_len == 4) )
  1156. {
  1157. const char* str = token.c_str();
  1158. const bool neg = (str[0] == '-');
  1159. const bool pos = (str[0] == '+');
  1160. const size_t offset = ( (neg || pos) && (token_len == 4) ) ? 1 : 0;
  1161. const char sig_a = str[offset ];
  1162. const char sig_b = str[offset+1];
  1163. const char sig_c = str[offset+2];
  1164. bool found_val_real = false;
  1165. T val_real = T(0);
  1166. if( ((sig_a == 'i') || (sig_a == 'I')) && ((sig_b == 'n') || (sig_b == 'N')) && ((sig_c == 'f') || (sig_c == 'F')) )
  1167. {
  1168. val_real = (neg) ? -(Datum<T>::inf) : Datum<T>::inf;
  1169. found_val_real = true;
  1170. }
  1171. else
  1172. if( ((sig_a == 'n') || (sig_a == 'N')) && ((sig_b == 'a') || (sig_b == 'A')) && ((sig_c == 'n') || (sig_c == 'N')) )
  1173. {
  1174. val_real = Datum<T>::nan;
  1175. found_val_real = true;
  1176. }
  1177. if(found_val_real)
  1178. {
  1179. x.at(row,col) = std::complex<T>(val_real, T(0));
  1180. col++; continue; // get next token
  1181. }
  1182. }
  1183. bool found_x = false;
  1184. std::string::size_type loc_x = 0; // location of the separator (+ or -) between the real and imaginary part
  1185. std::string::size_type loc_i = token.find_last_of('i'); // location of the imaginary part indicator
  1186. if(loc_i == std::string::npos)
  1187. {
  1188. str_real = token;
  1189. str_imag.clear();
  1190. }
  1191. else
  1192. {
  1193. bool found_plus = false;
  1194. bool found_minus = false;
  1195. std::string::size_type loc_plus = token.find_last_of('+');
  1196. if(loc_plus != std::string::npos)
  1197. {
  1198. if(loc_plus >= 1)
  1199. {
  1200. const char prev_char = token.at(loc_plus-1);
  1201. // make sure we're not looking at the sign of the exponent
  1202. if( (prev_char != 'e') && (prev_char != 'E') )
  1203. {
  1204. found_plus = true;
  1205. }
  1206. else
  1207. {
  1208. // search again, omitting the exponent
  1209. loc_plus = token.find_last_of('+', loc_plus-1);
  1210. if(loc_plus != std::string::npos) { found_plus = true; }
  1211. }
  1212. }
  1213. else
  1214. {
  1215. // loc_plus == 0, meaning we're at the start of the string
  1216. found_plus = true;
  1217. }
  1218. }
  1219. std::string::size_type loc_minus = token.find_last_of('-');
  1220. if(loc_minus != std::string::npos)
  1221. {
  1222. if(loc_minus >= 1)
  1223. {
  1224. const char prev_char = token.at(loc_minus-1);
  1225. // make sure we're not looking at the sign of the exponent
  1226. if( (prev_char != 'e') && (prev_char != 'E') )
  1227. {
  1228. found_minus = true;
  1229. }
  1230. else
  1231. {
  1232. // search again, omitting the exponent
  1233. loc_minus = token.find_last_of('-', loc_minus-1);
  1234. if(loc_minus != std::string::npos) { found_minus = true; }
  1235. }
  1236. }
  1237. else
  1238. {
  1239. // loc_minus == 0, meaning we're at the start of the string
  1240. found_minus = true;
  1241. }
  1242. }
  1243. if(found_plus && found_minus)
  1244. {
  1245. if( (loc_i > loc_plus) && (loc_i > loc_minus) )
  1246. {
  1247. // choose the sign closest to the "i" to be the separator between the real and imaginary part
  1248. loc_x = ( (loc_i - loc_plus) < (loc_i - loc_minus) ) ? loc_plus : loc_minus;
  1249. found_x = true;
  1250. }
  1251. }
  1252. else if(found_plus ) { loc_x = loc_plus; found_x = true; }
  1253. else if(found_minus) { loc_x = loc_minus; found_x = true; }
  1254. if(found_x)
  1255. {
  1256. if( loc_x > 0 ) { str_real = token.substr(0,loc_x); } else { str_real.clear(); }
  1257. if((loc_x+1) < token.size()) { str_imag = token.substr(loc_x, token.size()-loc_x-1); } else { str_imag.clear(); }
  1258. }
  1259. else
  1260. {
  1261. str_real.clear();
  1262. str_imag.clear();
  1263. }
  1264. }
  1265. T val_real = T(0);
  1266. T val_imag = T(0);
  1267. diskio::convert_token(val_real, str_real);
  1268. diskio::convert_token(val_imag, str_imag);
  1269. x.at(row,col) = std::complex<T>(val_real, val_imag);
  1270. ++col;
  1271. }
  1272. ++row;
  1273. }
  1274. return load_okay;
  1275. }
  1276. //! Load a matrix in binary format,
  1277. //! with a header that indicates the matrix type as well as its dimensions
  1278. template<typename eT>
  1279. inline
  1280. bool
  1281. diskio::load_arma_binary(Mat<eT>& x, const std::string& name, std::string& err_msg)
  1282. {
  1283. arma_extra_debug_sigprint();
  1284. std::ifstream f;
  1285. f.open(name.c_str(), std::fstream::binary);
  1286. bool load_okay = f.is_open();
  1287. if(load_okay)
  1288. {
  1289. load_okay = diskio::load_arma_binary(x, f, err_msg);
  1290. f.close();
  1291. }
  1292. return load_okay;
  1293. }
  1294. template<typename eT>
  1295. inline
  1296. bool
  1297. diskio::load_arma_binary(Mat<eT>& x, std::istream& f, std::string& err_msg)
  1298. {
  1299. arma_extra_debug_sigprint();
  1300. std::streampos pos = f.tellg();
  1301. bool load_okay = true;
  1302. std::string f_header;
  1303. uword f_n_rows;
  1304. uword f_n_cols;
  1305. f >> f_header;
  1306. f >> f_n_rows;
  1307. f >> f_n_cols;
  1308. if(f_header == diskio::gen_bin_header(x))
  1309. {
  1310. //f.seekg(1, ios::cur); // NOTE: this may not be portable, as on a Windows machine a newline could be two characters
  1311. f.get();
  1312. x.set_size(f_n_rows,f_n_cols);
  1313. f.read( reinterpret_cast<char *>(x.memptr()), std::streamsize(x.n_elem*sizeof(eT)) );
  1314. load_okay = f.good();
  1315. }
  1316. else
  1317. {
  1318. load_okay = false;
  1319. err_msg = "incorrect header in ";
  1320. }
  1321. // allow automatic conversion of u32/s32 matrices into u64/s64 matrices
  1322. if(load_okay == false)
  1323. {
  1324. if( (sizeof(eT) == 8) && is_same_type<uword,eT>::yes )
  1325. {
  1326. Mat<u32> tmp;
  1327. std::string junk;
  1328. f.clear();
  1329. f.seekg(pos);
  1330. load_okay = diskio::load_arma_binary(tmp, f, junk);
  1331. if(load_okay) { x = conv_to< Mat<eT> >::from(tmp); }
  1332. }
  1333. else
  1334. if( (sizeof(eT) == 8) && is_same_type<sword,eT>::yes )
  1335. {
  1336. Mat<s32> tmp;
  1337. std::string junk;
  1338. f.clear();
  1339. f.seekg(pos);
  1340. load_okay = diskio::load_arma_binary(tmp, f, junk);
  1341. if(load_okay) { x = conv_to< Mat<eT> >::from(tmp); }
  1342. }
  1343. }
  1344. return load_okay;
  1345. }
  1346. inline
  1347. void
  1348. diskio::pnm_skip_comments(std::istream& f)
  1349. {
  1350. while( isspace(f.peek()) )
  1351. {
  1352. while( isspace(f.peek()) ) { f.get(); }
  1353. if(f.peek() == '#')
  1354. {
  1355. while( (f.peek() != '\r') && (f.peek() != '\n') ) { f.get(); }
  1356. }
  1357. }
  1358. }
  1359. //! Load a PGM greyscale image as a matrix
  1360. template<typename eT>
  1361. inline
  1362. bool
  1363. diskio::load_pgm_binary(Mat<eT>& x, const std::string& name, std::string& err_msg)
  1364. {
  1365. arma_extra_debug_sigprint();
  1366. std::fstream f;
  1367. f.open(name.c_str(), std::fstream::in | std::fstream::binary);
  1368. bool load_okay = f.is_open();
  1369. if(load_okay)
  1370. {
  1371. load_okay = diskio::load_pgm_binary(x, f, err_msg);
  1372. f.close();
  1373. }
  1374. return load_okay;
  1375. }
  1376. //! Load a PGM greyscale image as a matrix
  1377. template<typename eT>
  1378. inline
  1379. bool
  1380. diskio::load_pgm_binary(Mat<eT>& x, std::istream& f, std::string& err_msg)
  1381. {
  1382. bool load_okay = true;
  1383. std::string f_header;
  1384. f >> f_header;
  1385. if(f_header == "P5")
  1386. {
  1387. uword f_n_rows = 0;
  1388. uword f_n_cols = 0;
  1389. int f_maxval = 0;
  1390. diskio::pnm_skip_comments(f);
  1391. f >> f_n_cols;
  1392. diskio::pnm_skip_comments(f);
  1393. f >> f_n_rows;
  1394. diskio::pnm_skip_comments(f);
  1395. f >> f_maxval;
  1396. f.get();
  1397. if( (f_maxval > 0) && (f_maxval <= 65535) )
  1398. {
  1399. x.set_size(f_n_rows,f_n_cols);
  1400. if(f_maxval <= 255)
  1401. {
  1402. const uword n_elem = f_n_cols*f_n_rows;
  1403. podarray<u8> tmp(n_elem);
  1404. f.read( reinterpret_cast<char*>(tmp.memptr()), std::streamsize(n_elem) );
  1405. uword i = 0;
  1406. //cout << "f_n_cols = " << f_n_cols << endl;
  1407. //cout << "f_n_rows = " << f_n_rows << endl;
  1408. for(uword row=0; row < f_n_rows; ++row)
  1409. for(uword col=0; col < f_n_cols; ++col)
  1410. {
  1411. x.at(row,col) = eT(tmp[i]);
  1412. ++i;
  1413. }
  1414. }
  1415. else
  1416. {
  1417. const uword n_elem = f_n_cols*f_n_rows;
  1418. podarray<u16> tmp(n_elem);
  1419. f.read( reinterpret_cast<char *>(tmp.memptr()), std::streamsize(n_elem*2) );
  1420. uword i = 0;
  1421. for(uword row=0; row < f_n_rows; ++row)
  1422. for(uword col=0; col < f_n_cols; ++col)
  1423. {
  1424. x.at(row,col) = eT(tmp[i]);
  1425. ++i;
  1426. }
  1427. }
  1428. }
  1429. else
  1430. {
  1431. load_okay = false;
  1432. err_msg = "functionality unimplemented to handle loading ";
  1433. }
  1434. if(f.good() == false) { load_okay = false; }
  1435. }
  1436. else
  1437. {
  1438. load_okay = false;
  1439. err_msg = "unsupported header in ";
  1440. }
  1441. return load_okay;
  1442. }
  1443. //! Load a PGM greyscale image as a matrix
  1444. template<typename T>
  1445. inline
  1446. bool
  1447. diskio::load_pgm_binary(Mat< std::complex<T> >& x, const std::string& name, std::string& err_msg)
  1448. {
  1449. arma_extra_debug_sigprint();
  1450. uchar_mat tmp;
  1451. const bool load_okay = diskio::load_pgm_binary(tmp, name, err_msg);
  1452. x = conv_to< Mat< std::complex<T> > >::from(tmp);
  1453. return load_okay;
  1454. }
  1455. //! Load a PGM greyscale image as a matrix
  1456. template<typename T>
  1457. inline
  1458. bool
  1459. diskio::load_pgm_binary(Mat< std::complex<T> >& x, std::istream& is, std::string& err_msg)
  1460. {
  1461. arma_extra_debug_sigprint();
  1462. uchar_mat tmp;
  1463. const bool load_okay = diskio::load_pgm_binary(tmp, is, err_msg);
  1464. x = conv_to< Mat< std::complex<T> > >::from(tmp);
  1465. return load_okay;
  1466. }
  1467. //! Load a HDF5 file as a matrix
  1468. template<typename eT>
  1469. inline
  1470. bool
  1471. diskio::load_hdf5_binary(Mat<eT>& x, const hdf5_name& spec, std::string& err_msg)
  1472. {
  1473. arma_extra_debug_sigprint();
  1474. #if defined(ARMA_USE_HDF5)
  1475. {
  1476. hdf5_misc::hdf5_suspend_printing_errors hdf5_print_suspender;
  1477. bool load_okay = false;
  1478. hid_t fid = arma_H5Fopen(spec.filename.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);
  1479. if(fid >= 0)
  1480. {
  1481. // MATLAB HDF5 dataset names are user-specified;
  1482. // Octave tends to store the datasets in a group, with the actual dataset being referred to as "value".
  1483. // If the user hasn't specified a dataset, we will search for "dataset" and "value",
  1484. // and if those are not found we will take the first dataset we do find.
  1485. std::vector<std::string> searchNames;
  1486. const bool exact = (spec.dsname.empty() == false);
  1487. if(exact)
  1488. {
  1489. searchNames.push_back(spec.dsname);
  1490. }
  1491. else
  1492. {
  1493. searchNames.push_back("dataset");
  1494. searchNames.push_back("value" );
  1495. }
  1496. hid_t dataset = hdf5_misc::search_hdf5_file(searchNames, fid, 2, exact);
  1497. if(dataset >= 0)
  1498. {
  1499. hid_t filespace = arma_H5Dget_space(dataset);
  1500. // This must be <= 2 due to our search rules.
  1501. const int ndims = arma_H5Sget_simple_extent_ndims(filespace);
  1502. hsize_t dims[2];
  1503. const herr_t query_status = arma_H5Sget_simple_extent_dims(filespace, dims, NULL);
  1504. // arma_check(query_status < 0, "Mat::load(): cannot get size of HDF5 dataset");
  1505. if(query_status < 0)
  1506. {
  1507. err_msg = "cannot get size of HDF5 dataset in ";
  1508. arma_H5Sclose(filespace);
  1509. arma_H5Dclose(dataset);
  1510. arma_H5Fclose(fid);
  1511. return false;
  1512. }
  1513. if(ndims == 1) { dims[1] = 1; } // Vector case; fake second dimension (one column).
  1514. x.set_size(dims[1], dims[0]);
  1515. // Now we have to see what type is stored to figure out how to load it.
  1516. hid_t datatype = arma_H5Dget_type(dataset);
  1517. hid_t mat_type = hdf5_misc::get_hdf5_type<eT>();
  1518. // If these are the same type, it is simple.
  1519. if(arma_H5Tequal(datatype, mat_type) > 0)
  1520. {
  1521. // Load directly; H5S_ALL used so that we load the entire dataset.
  1522. hid_t read_status = arma_H5Dread(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, void_ptr(x.memptr()));
  1523. if(read_status >= 0) { load_okay = true; }
  1524. }
  1525. else
  1526. {
  1527. // Load into another array and convert its type accordingly.
  1528. hid_t read_status = hdf5_misc::load_and_convert_hdf5(x.memptr(), dataset, datatype, x.n_elem);
  1529. if(read_status >= 0) { load_okay = true; }
  1530. }
  1531. // Now clean up.
  1532. arma_H5Tclose(datatype);
  1533. arma_H5Tclose(mat_type);
  1534. arma_H5Sclose(filespace);
  1535. }
  1536. arma_H5Dclose(dataset);
  1537. arma_H5Fclose(fid);
  1538. if(load_okay == false)
  1539. {
  1540. err_msg = "unsupported or missing HDF5 data in ";
  1541. }
  1542. }
  1543. else
  1544. {
  1545. err_msg = "cannot open file ";
  1546. }
  1547. return load_okay;
  1548. }
  1549. #else
  1550. {
  1551. arma_ignore(x);
  1552. arma_ignore(spec);
  1553. arma_ignore(err_msg);
  1554. arma_stop_logic_error("Mat::load(): use of HDF5 must be enabled");
  1555. return false;
  1556. }
  1557. #endif
  1558. }
  1559. //! Try to load a matrix by automatically determining its type
  1560. template<typename eT>
  1561. inline
  1562. bool
  1563. diskio::load_auto_detect(Mat<eT>& x, const std::string& name, std::string& err_msg)
  1564. {
  1565. arma_extra_debug_sigprint();
  1566. #if defined(ARMA_USE_HDF5)
  1567. // We're currently using the C bindings for the HDF5 library, which don't support C++ streams
  1568. if( arma_H5Fis_hdf5(name.c_str()) ) { return load_hdf5_binary(x, name, err_msg); }
  1569. #endif
  1570. std::fstream f;
  1571. f.open(name.c_str(), std::fstream::in | std::fstream::binary);
  1572. bool load_okay = f.is_open();
  1573. if(load_okay)
  1574. {
  1575. load_okay = diskio::load_auto_detect(x, f, err_msg);
  1576. f.close();
  1577. }
  1578. return load_okay;
  1579. }
  1580. //! Try to load a matrix by automatically determining its type
  1581. template<typename eT>
  1582. inline
  1583. bool
  1584. diskio::load_auto_detect(Mat<eT>& x, std::istream& f, std::string& err_msg)
  1585. {
  1586. arma_extra_debug_sigprint();
  1587. const char* ARMA_MAT_TXT_str = "ARMA_MAT_TXT";
  1588. const char* ARMA_MAT_BIN_str = "ARMA_MAT_BIN";
  1589. const char* P5_str = "P5";
  1590. const uword ARMA_MAT_TXT_len = uword(12);
  1591. const uword ARMA_MAT_BIN_len = uword(12);
  1592. const uword P5_len = uword(2);
  1593. podarray<char> header(ARMA_MAT_TXT_len + 1);
  1594. char* header_mem = header.memptr();
  1595. std::streampos pos = f.tellg();
  1596. f.read( header_mem, std::streamsize(ARMA_MAT_TXT_len) );
  1597. f.clear();
  1598. f.seekg(pos);
  1599. header_mem[ARMA_MAT_TXT_len] = '\0';
  1600. if( std::strncmp(ARMA_MAT_TXT_str, header_mem, size_t(ARMA_MAT_TXT_len)) == 0 )
  1601. {
  1602. return load_arma_ascii(x, f, err_msg);
  1603. }
  1604. else
  1605. if( std::strncmp(ARMA_MAT_BIN_str, header_mem, size_t(ARMA_MAT_BIN_len)) == 0 )
  1606. {
  1607. return load_arma_binary(x, f, err_msg);
  1608. }
  1609. else
  1610. if( std::strncmp(P5_str, header_mem, size_t(P5_len)) == 0 )
  1611. {
  1612. return load_pgm_binary(x, f, err_msg);
  1613. }
  1614. else
  1615. {
  1616. const file_type ft = guess_file_type_internal(f);
  1617. switch(ft)
  1618. {
  1619. case csv_ascii:
  1620. return load_csv_ascii(x, f, err_msg);
  1621. break;
  1622. case raw_binary:
  1623. return load_raw_binary(x, f, err_msg);
  1624. break;
  1625. case raw_ascii:
  1626. return load_raw_ascii(x, f, err_msg);
  1627. break;
  1628. default:
  1629. err_msg = "unknown data in ";
  1630. return false;
  1631. }
  1632. }
  1633. return false;
  1634. }
  1635. //
  1636. // sparse matrices
  1637. //
  1638. //! Save a sparse matrix in CSV format
  1639. template<typename eT>
  1640. inline
  1641. bool
  1642. diskio::save_csv_ascii(const SpMat<eT>& x, const std::string& final_name, const field<std::string>& header, const bool with_header)
  1643. {
  1644. arma_extra_debug_sigprint();
  1645. const std::string tmp_name = diskio::gen_tmp_name(final_name);
  1646. std::ofstream f(tmp_name.c_str());
  1647. bool save_okay = f.is_open();
  1648. if(save_okay == false) { return false; }
  1649. if(with_header)
  1650. {
  1651. arma_extra_debug_print("diskio::save_csv_ascii(): writing header");
  1652. for(uword i=0; i < header.n_elem; ++i)
  1653. {
  1654. f << header(i);
  1655. if(i != (header.n_elem-1)) { f.put(','); }
  1656. }
  1657. f.put('\n');
  1658. save_okay = f.good();
  1659. }
  1660. if(save_okay) { save_okay = diskio::save_csv_ascii(x, f); }
  1661. f.flush();
  1662. f.close();
  1663. if(save_okay) { save_okay = diskio::safe_rename(tmp_name, final_name); }
  1664. return save_okay;
  1665. }
  1666. //! Save a sparse matrix in CSV format
  1667. template<typename eT>
  1668. inline
  1669. bool
  1670. diskio::save_csv_ascii(const SpMat<eT>& x, std::ostream& f)
  1671. {
  1672. arma_extra_debug_sigprint();
  1673. const arma_ostream_state stream_state(f);
  1674. diskio::prepare_stream<eT>(f);
  1675. x.sync();
  1676. uword x_n_rows = x.n_rows;
  1677. uword x_n_cols = x.n_cols;
  1678. for(uword row=0; row < x_n_rows; ++row)
  1679. {
  1680. for(uword col=0; col < x_n_cols; ++col)
  1681. {
  1682. const eT val = x.at(row,col);
  1683. if(val != eT(0)) { arma_ostream::raw_print_elem(f, val); }
  1684. if( col < (x_n_cols-1) ) { f.put(','); }
  1685. }
  1686. f.put('\n');
  1687. }
  1688. const bool save_okay = f.good();
  1689. stream_state.restore(f);
  1690. return save_okay;
  1691. }
  1692. //! Save a sparse matrix in CSV format (complex numbers)
  1693. template<typename T>
  1694. inline
  1695. bool
  1696. diskio::save_csv_ascii(const SpMat< std::complex<T> >& x, std::ostream& f)
  1697. {
  1698. arma_extra_debug_sigprint();
  1699. arma_ignore(x);
  1700. arma_ignore(f);
  1701. arma_warn("saving complex sparse matrices as csv_ascii not yet implemented");
  1702. return false;
  1703. }
  1704. //! Save a matrix in ASCII coord format
  1705. template<typename eT>
  1706. inline
  1707. bool
  1708. diskio::save_coord_ascii(const SpMat<eT>& x, const std::string& final_name)
  1709. {
  1710. arma_extra_debug_sigprint();
  1711. const std::string tmp_name = diskio::gen_tmp_name(final_name);
  1712. std::ofstream f(tmp_name.c_str());
  1713. bool save_okay = f.is_open();
  1714. if(save_okay)
  1715. {
  1716. save_okay = diskio::save_coord_ascii(x, f);
  1717. f.flush();
  1718. f.close();
  1719. if(save_okay) { save_okay = diskio::safe_rename(tmp_name, final_name); }
  1720. }
  1721. return save_okay;
  1722. }
  1723. //! Save a matrix in ASCII coord format
  1724. template<typename eT>
  1725. inline
  1726. bool
  1727. diskio::save_coord_ascii(const SpMat<eT>& x, std::ostream& f)
  1728. {
  1729. arma_extra_debug_sigprint();
  1730. const arma_ostream_state stream_state(f);
  1731. diskio::prepare_stream<eT>(f);
  1732. typename SpMat<eT>::const_iterator iter = x.begin();
  1733. typename SpMat<eT>::const_iterator iter_end = x.end();
  1734. for(; iter != iter_end; ++iter)
  1735. {
  1736. const eT val = (*iter);
  1737. f << iter.row() << ' ' << iter.col() << ' ' << val << '\n';
  1738. }
  1739. // make sure it's possible to figure out the matrix size later
  1740. if( (x.n_rows > 0) && (x.n_cols > 0) )
  1741. {
  1742. const uword max_row = (x.n_rows > 0) ? x.n_rows-1 : 0;
  1743. const uword max_col = (x.n_cols > 0) ? x.n_cols-1 : 0;
  1744. if( x.at(max_row, max_col) == eT(0) )
  1745. {
  1746. f << max_row << ' ' << max_col << " 0\n";
  1747. }
  1748. }
  1749. const bool save_okay = f.good();
  1750. stream_state.restore(f);
  1751. return save_okay;
  1752. }
  1753. //! Save a matrix in ASCII coord format (complex numbers)
  1754. template<typename T>
  1755. inline
  1756. bool
  1757. diskio::save_coord_ascii(const SpMat< std::complex<T> >& x, std::ostream& f)
  1758. {
  1759. arma_extra_debug_sigprint();
  1760. typedef typename std::complex<T> eT;
  1761. const arma_ostream_state stream_state(f);
  1762. diskio::prepare_stream<eT>(f);
  1763. typename SpMat<eT>::const_iterator iter = x.begin();
  1764. typename SpMat<eT>::const_iterator iter_end = x.end();
  1765. for(; iter != iter_end; ++iter)
  1766. {
  1767. const eT val = (*iter);
  1768. f << iter.row() << ' ' << iter.col() << ' ' << val.real() << ' ' << val.imag() << '\n';
  1769. }
  1770. // make sure it's possible to figure out the matrix size later
  1771. if( (x.n_rows > 0) && (x.n_cols > 0) )
  1772. {
  1773. const uword max_row = (x.n_rows > 0) ? x.n_rows-1 : 0;
  1774. const uword max_col = (x.n_cols > 0) ? x.n_cols-1 : 0;
  1775. if( x.at(max_row, max_col) == eT(0) )
  1776. {
  1777. f << max_row << ' ' << max_col << " 0 0\n";
  1778. }
  1779. }
  1780. const bool save_okay = f.good();
  1781. stream_state.restore(f);
  1782. return save_okay;
  1783. }
  1784. //! Save a matrix in binary format,
  1785. //! with a header that stores the matrix type as well as its dimensions
  1786. template<typename eT>
  1787. inline
  1788. bool
  1789. diskio::save_arma_binary(const SpMat<eT>& x, const std::string& final_name)
  1790. {
  1791. arma_extra_debug_sigprint();
  1792. const std::string tmp_name = diskio::gen_tmp_name(final_name);
  1793. std::ofstream f(tmp_name.c_str(), std::fstream::binary);
  1794. bool save_okay = f.is_open();
  1795. if(save_okay)
  1796. {
  1797. save_okay = diskio::save_arma_binary(x, f);
  1798. f.flush();
  1799. f.close();
  1800. if(save_okay) { save_okay = diskio::safe_rename(tmp_name, final_name); }
  1801. }
  1802. return save_okay;
  1803. }
  1804. //! Save a matrix in binary format,
  1805. //! with a header that stores the matrix type as well as its dimensions
  1806. template<typename eT>
  1807. inline
  1808. bool
  1809. diskio::save_arma_binary(const SpMat<eT>& x, std::ostream& f)
  1810. {
  1811. arma_extra_debug_sigprint();
  1812. f << diskio::gen_bin_header(x) << '\n';
  1813. f << x.n_rows << ' ' << x.n_cols << ' ' << x.n_nonzero << '\n';
  1814. f.write( reinterpret_cast<const char*>(x.values), std::streamsize(x.n_nonzero*sizeof(eT)) );
  1815. f.write( reinterpret_cast<const char*>(x.row_indices), std::streamsize(x.n_nonzero*sizeof(uword)) );
  1816. f.write( reinterpret_cast<const char*>(x.col_ptrs), std::streamsize((x.n_cols+1)*sizeof(uword)) );
  1817. return f.good();
  1818. }
  1819. template<typename eT>
  1820. inline
  1821. bool
  1822. diskio::load_csv_ascii(SpMat<eT>& x, const std::string& name, std::string& err_msg, field<std::string>& header, const bool with_header)
  1823. {
  1824. arma_extra_debug_sigprint();
  1825. std::fstream f;
  1826. f.open(name.c_str(), std::fstream::in);
  1827. bool load_okay = f.is_open();
  1828. if(load_okay == false) { return false; }
  1829. if(with_header)
  1830. {
  1831. arma_extra_debug_print("diskio::load_csv_ascii(): reading header");
  1832. std::string header_line;
  1833. std::stringstream header_stream;
  1834. std::vector<std::string> header_tokens;
  1835. std::getline(f, header_line);
  1836. load_okay = f.good();
  1837. if(load_okay)
  1838. {
  1839. std::string token;
  1840. header_stream.clear();
  1841. header_stream.str(header_line);
  1842. uword header_n_tokens = 0;
  1843. while(header_stream.good())
  1844. {
  1845. std::getline(header_stream, token, ',');
  1846. ++header_n_tokens;
  1847. header_tokens.push_back(token);
  1848. }
  1849. if(header_n_tokens == uword(0))
  1850. {
  1851. header.reset();
  1852. }
  1853. else
  1854. {
  1855. header.set_size(1,header_n_tokens);
  1856. for(uword i=0; i < header_n_tokens; ++i) { header.at(i) = header_tokens[i]; }
  1857. }
  1858. }
  1859. }
  1860. if(load_okay)
  1861. {
  1862. load_okay = diskio::load_csv_ascii(x, f, err_msg);
  1863. }
  1864. f.close();
  1865. return load_okay;
  1866. }
  1867. template<typename eT>
  1868. inline
  1869. bool
  1870. diskio::load_csv_ascii(SpMat<eT>& x, std::istream& f, std::string& err_msg)
  1871. {
  1872. arma_extra_debug_sigprint();
  1873. arma_ignore(err_msg);
  1874. // TODO: replace with more efficient implementation
  1875. bool load_okay = f.good();
  1876. f.clear();
  1877. const std::fstream::pos_type pos1 = f.tellg();
  1878. //
  1879. // work out the size
  1880. uword f_n_rows = 0;
  1881. uword f_n_cols = 0;
  1882. std::string line_string;
  1883. std::stringstream line_stream;
  1884. std::string token;
  1885. while( f.good() && load_okay )
  1886. {
  1887. std::getline(f, line_string);
  1888. if(line_string.size() == 0) { break; }
  1889. line_stream.clear();
  1890. line_stream.str(line_string);
  1891. uword line_n_cols = 0;
  1892. while(line_stream.good())
  1893. {
  1894. std::getline(line_stream, token, ',');
  1895. ++line_n_cols;
  1896. }
  1897. if(f_n_cols < line_n_cols) { f_n_cols = line_n_cols; }
  1898. ++f_n_rows;
  1899. }
  1900. f.clear();
  1901. f.seekg(pos1);
  1902. x.zeros(f_n_rows, f_n_cols);
  1903. uword row = 0;
  1904. while(f.good())
  1905. {
  1906. std::getline(f, line_string);
  1907. if(line_string.size() == 0) { break; }
  1908. line_stream.clear();
  1909. line_stream.str(line_string);
  1910. uword col = 0;
  1911. while(line_stream.good())
  1912. {
  1913. std::getline(line_stream, token, ',');
  1914. eT val = eT(0);
  1915. diskio::convert_token( val, token );
  1916. if(val != eT(0)) { x(row,col) = val; }
  1917. ++col;
  1918. }
  1919. ++row;
  1920. }
  1921. return load_okay;
  1922. }
  1923. template<typename T>
  1924. inline
  1925. bool
  1926. diskio::load_csv_ascii(SpMat< std::complex<T> >& x, std::istream& f, std::string& err_msg)
  1927. {
  1928. arma_extra_debug_sigprint();
  1929. arma_ignore(x);
  1930. arma_ignore(f);
  1931. arma_ignore(err_msg);
  1932. arma_warn("loading complex sparse matrices as csv_ascii not yet implemented");
  1933. return false;
  1934. }
  1935. template<typename eT>
  1936. inline
  1937. bool
  1938. diskio::load_coord_ascii(SpMat<eT>& x, const std::string& name, std::string& err_msg)
  1939. {
  1940. arma_extra_debug_sigprint();
  1941. std::fstream f;
  1942. f.open(name.c_str(), std::fstream::in | std::fstream::binary);
  1943. bool load_okay = f.is_open();
  1944. if(load_okay)
  1945. {
  1946. load_okay = diskio::load_coord_ascii(x, f, err_msg);
  1947. f.close();
  1948. }
  1949. return load_okay;
  1950. }
  1951. template<typename eT>
  1952. inline
  1953. bool
  1954. diskio::load_coord_ascii(SpMat<eT>& x, std::istream& f, std::string& err_msg)
  1955. {
  1956. arma_extra_debug_sigprint();
  1957. arma_ignore(err_msg);
  1958. bool load_okay = f.good();
  1959. f.clear();
  1960. const std::fstream::pos_type pos1 = f.tellg();
  1961. // work out the size
  1962. uword f_n_rows = 0;
  1963. uword f_n_cols = 0;
  1964. bool size_found = false;
  1965. std::string line_string;
  1966. std::stringstream line_stream;
  1967. std::string token;
  1968. while( f.good() && load_okay )
  1969. {
  1970. std::getline(f, line_string);
  1971. if(line_string.size() == 0) { break; }
  1972. line_stream.clear();
  1973. line_stream.str(line_string);
  1974. uword line_row = 0;
  1975. uword line_col = 0;
  1976. // a valid line in co-ord format has at least 2 entries
  1977. line_stream >> line_row;
  1978. if(line_stream.good() == false) { load_okay = false; break; }
  1979. line_stream >> line_col;
  1980. size_found = true;
  1981. if(f_n_rows < line_row) { f_n_rows = line_row; }
  1982. if(f_n_cols < line_col) { f_n_cols = line_col; }
  1983. }
  1984. // take into account that indices start at 0
  1985. if(size_found) { ++f_n_rows; ++f_n_cols; }
  1986. if(load_okay)
  1987. {
  1988. f.clear();
  1989. f.seekg(pos1);
  1990. MapMat<eT> tmp(f_n_rows, f_n_cols);
  1991. while(f.good())
  1992. {
  1993. std::getline(f, line_string);
  1994. if(line_string.size() == 0) { break; }
  1995. line_stream.clear();
  1996. line_stream.str(line_string);
  1997. uword line_row = 0;
  1998. uword line_col = 0;
  1999. line_stream >> line_row;
  2000. line_stream >> line_col;
  2001. eT val = eT(0);
  2002. line_stream >> token;
  2003. if(line_stream.fail() == false)
  2004. {
  2005. diskio::convert_token( val, token );
  2006. }
  2007. if(val != eT(0)) { tmp(line_row,line_col) = val; }
  2008. }
  2009. x = tmp;
  2010. }
  2011. return load_okay;
  2012. }
  2013. template<typename T>
  2014. inline
  2015. bool
  2016. diskio::load_coord_ascii(SpMat< std::complex<T> >& x, std::istream& f, std::string& err_msg)
  2017. {
  2018. arma_extra_debug_sigprint();
  2019. arma_ignore(err_msg);
  2020. bool load_okay = f.good();
  2021. f.clear();
  2022. const std::fstream::pos_type pos1 = f.tellg();
  2023. // work out the size
  2024. uword f_n_rows = 0;
  2025. uword f_n_cols = 0;
  2026. bool size_found = false;
  2027. std::string line_string;
  2028. std::stringstream line_stream;
  2029. std::string token_real;
  2030. std::string token_imag;
  2031. while( f.good() && load_okay )
  2032. {
  2033. std::getline(f, line_string);
  2034. if(line_string.size() == 0) { break; }
  2035. line_stream.clear();
  2036. line_stream.str(line_string);
  2037. uword line_row = 0;
  2038. uword line_col = 0;
  2039. // a valid line in co-ord format has at least 2 entries
  2040. line_stream >> line_row;
  2041. if(line_stream.good() == false) { load_okay = false; break; }
  2042. line_stream >> line_col;
  2043. size_found = true;
  2044. if(f_n_rows < line_row) f_n_rows = line_row;
  2045. if(f_n_cols < line_col) f_n_cols = line_col;
  2046. }
  2047. // take into account that indices start at 0
  2048. if(size_found) { ++f_n_rows; ++f_n_cols; }
  2049. if(load_okay)
  2050. {
  2051. f.clear();
  2052. f.seekg(pos1);
  2053. MapMat< std::complex<T> > tmp(f_n_rows, f_n_cols);
  2054. while(f.good())
  2055. {
  2056. std::getline(f, line_string);
  2057. if(line_string.size() == 0) { break; }
  2058. line_stream.clear();
  2059. line_stream.str(line_string);
  2060. uword line_row = 0;
  2061. uword line_col = 0;
  2062. line_stream >> line_row;
  2063. line_stream >> line_col;
  2064. T val_real = T(0);
  2065. T val_imag = T(0);
  2066. line_stream >> token_real;
  2067. if(line_stream.fail() == false)
  2068. {
  2069. diskio::convert_token( val_real, token_real );
  2070. }
  2071. line_stream >> token_imag;
  2072. if(line_stream.fail() == false)
  2073. {
  2074. diskio::convert_token( val_imag, token_imag );
  2075. }
  2076. if( (val_real != T(0)) || (val_imag != T(0)) )
  2077. {
  2078. tmp(line_row,line_col) = std::complex<T>(val_real, val_imag);
  2079. }
  2080. }
  2081. x = tmp;
  2082. }
  2083. return load_okay;
  2084. }
  2085. //! Load a matrix in binary format,
  2086. //! with a header that indicates the matrix type as well as its dimensions
  2087. template<typename eT>
  2088. inline
  2089. bool
  2090. diskio::load_arma_binary(SpMat<eT>& x, const std::string& name, std::string& err_msg)
  2091. {
  2092. arma_extra_debug_sigprint();
  2093. std::ifstream f;
  2094. f.open(name.c_str(), std::fstream::binary);
  2095. bool load_okay = f.is_open();
  2096. if(load_okay)
  2097. {
  2098. load_okay = diskio::load_arma_binary(x, f, err_msg);
  2099. f.close();
  2100. }
  2101. return load_okay;
  2102. }
  2103. template<typename eT>
  2104. inline
  2105. bool
  2106. diskio::load_arma_binary(SpMat<eT>& x, std::istream& f, std::string& err_msg)
  2107. {
  2108. arma_extra_debug_sigprint();
  2109. bool load_okay = true;
  2110. std::string f_header;
  2111. f >> f_header;
  2112. if(f_header == diskio::gen_bin_header(x))
  2113. {
  2114. uword f_n_rows;
  2115. uword f_n_cols;
  2116. uword f_n_nz;
  2117. f >> f_n_rows;
  2118. f >> f_n_cols;
  2119. f >> f_n_nz;
  2120. //f.seekg(1, ios::cur); // NOTE: this may not be portable, as on a Windows machine a newline could be two characters
  2121. f.get();
  2122. x.reserve(f_n_rows, f_n_cols, f_n_nz);
  2123. f.read( reinterpret_cast<char*>(access::rwp(x.values)), std::streamsize(x.n_nonzero*sizeof(eT)) );
  2124. std::streampos pos = f.tellg();
  2125. f.read( reinterpret_cast<char*>(access::rwp(x.row_indices)), std::streamsize(x.n_nonzero*sizeof(uword)) );
  2126. f.read( reinterpret_cast<char*>(access::rwp(x.col_ptrs)), std::streamsize((x.n_cols+1)*sizeof(uword)) );
  2127. bool check1 = true; for(uword i=0; i < x.n_nonzero; ++i) { if(x.values[i] == eT(0)) { check1 = false; break; } }
  2128. bool check2 = true; for(uword i=0; i < x.n_cols; ++i) { if(x.col_ptrs[i+1] < x.col_ptrs[i]) { check2 = false; break; } }
  2129. bool check3 = (x.col_ptrs[x.n_cols] == x.n_nonzero);
  2130. if((check1 == true) && ((check2 == false) || (check3 == false)))
  2131. {
  2132. if(sizeof(uword) == 8)
  2133. {
  2134. arma_extra_debug_print("detected inconsistent data while loading; re-reading integer parts as u32");
  2135. // inconstency could be due to a different uword size used during saving,
  2136. // so try loading the row_indices and col_ptrs under the assumption of 32 bit unsigned integers
  2137. f.clear();
  2138. f.seekg(pos);
  2139. podarray<u32> tmp_a(x.n_nonzero ); tmp_a.zeros();
  2140. podarray<u32> tmp_b(x.n_cols + 1); tmp_b.zeros();
  2141. f.read( reinterpret_cast<char*>(tmp_a.memptr()), std::streamsize( x.n_nonzero * sizeof(u32)) );
  2142. f.read( reinterpret_cast<char*>(tmp_b.memptr()), std::streamsize((x.n_cols + 1) * sizeof(u32)) );
  2143. check2 = true; for(uword i=0; i < x.n_cols; ++i) { if(tmp_b[i+1] < tmp_b[i]) { check2 = false; break; } }
  2144. check3 = (tmp_b[x.n_cols] == x.n_nonzero);
  2145. load_okay = f.good();
  2146. if( load_okay && (check2 == true) && (check3 == true) )
  2147. {
  2148. arma_extra_debug_print("reading integer parts as u32 succeeded");
  2149. arrayops::convert(access::rwp(x.row_indices), tmp_a.memptr(), x.n_nonzero );
  2150. arrayops::convert(access::rwp(x.col_ptrs), tmp_b.memptr(), x.n_cols + 1);
  2151. }
  2152. else
  2153. {
  2154. arma_extra_debug_print("reading integer parts as u32 failed");
  2155. }
  2156. }
  2157. }
  2158. if((check1 == false) || (check2 == false) || (check3 == false))
  2159. {
  2160. load_okay = false;
  2161. err_msg = "inconsistent data in ";
  2162. }
  2163. else
  2164. {
  2165. load_okay = f.good();
  2166. }
  2167. }
  2168. else
  2169. {
  2170. load_okay = false;
  2171. err_msg = "incorrect header in ";
  2172. }
  2173. return load_okay;
  2174. }
  2175. // cubes
  2176. //! Save a cube as raw text (no header, human readable).
  2177. template<typename eT>
  2178. inline
  2179. bool
  2180. diskio::save_raw_ascii(const Cube<eT>& x, const std::string& final_name)
  2181. {
  2182. arma_extra_debug_sigprint();
  2183. const std::string tmp_name = diskio::gen_tmp_name(final_name);
  2184. std::fstream f(tmp_name.c_str(), std::fstream::out);
  2185. bool save_okay = f.is_open();
  2186. if(save_okay)
  2187. {
  2188. save_okay = save_raw_ascii(x, f);
  2189. f.flush();
  2190. f.close();
  2191. if(save_okay) { save_okay = diskio::safe_rename(tmp_name, final_name); }
  2192. }
  2193. return save_okay;
  2194. }
  2195. //! Save a cube as raw text (no header, human readable).
  2196. template<typename eT>
  2197. inline
  2198. bool
  2199. diskio::save_raw_ascii(const Cube<eT>& x, std::ostream& f)
  2200. {
  2201. arma_extra_debug_sigprint();
  2202. const arma_ostream_state stream_state(f);
  2203. const std::streamsize cell_width = diskio::prepare_stream<eT>(f);
  2204. for(uword slice=0; slice < x.n_slices; ++slice)
  2205. {
  2206. for(uword row=0; row < x.n_rows; ++row)
  2207. {
  2208. for(uword col=0; col < x.n_cols; ++col)
  2209. {
  2210. f.put(' ');
  2211. if(is_real<eT>::value) { f.width(cell_width); }
  2212. arma_ostream::raw_print_elem(f, x.at(row,col,slice));
  2213. }
  2214. f.put('\n');
  2215. }
  2216. }
  2217. const bool save_okay = f.good();
  2218. stream_state.restore(f);
  2219. return save_okay;
  2220. }
  2221. //! Save a cube as raw binary (no header)
  2222. template<typename eT>
  2223. inline
  2224. bool
  2225. diskio::save_raw_binary(const Cube<eT>& x, const std::string& final_name)
  2226. {
  2227. arma_extra_debug_sigprint();
  2228. const std::string tmp_name = diskio::gen_tmp_name(final_name);
  2229. std::ofstream f(tmp_name.c_str(), std::fstream::binary);
  2230. bool save_okay = f.is_open();
  2231. if(save_okay)
  2232. {
  2233. save_okay = diskio::save_raw_binary(x, f);
  2234. f.flush();
  2235. f.close();
  2236. if(save_okay) { save_okay = diskio::safe_rename(tmp_name, final_name); }
  2237. }
  2238. return save_okay;
  2239. }
  2240. template<typename eT>
  2241. inline
  2242. bool
  2243. diskio::save_raw_binary(const Cube<eT>& x, std::ostream& f)
  2244. {
  2245. arma_extra_debug_sigprint();
  2246. f.write( reinterpret_cast<const char*>(x.mem), std::streamsize(x.n_elem*sizeof(eT)) );
  2247. return f.good();
  2248. }
  2249. //! Save a cube in text format (human readable),
  2250. //! with a header that indicates the cube type as well as its dimensions
  2251. template<typename eT>
  2252. inline
  2253. bool
  2254. diskio::save_arma_ascii(const Cube<eT>& x, const std::string& final_name)
  2255. {
  2256. arma_extra_debug_sigprint();
  2257. const std::string tmp_name = diskio::gen_tmp_name(final_name);
  2258. std::ofstream f(tmp_name.c_str());
  2259. bool save_okay = f.is_open();
  2260. if(save_okay)
  2261. {
  2262. save_okay = diskio::save_arma_ascii(x, f);
  2263. f.flush();
  2264. f.close();
  2265. if(save_okay) { save_okay = diskio::safe_rename(tmp_name, final_name); }
  2266. }
  2267. return save_okay;
  2268. }
  2269. //! Save a cube in text format (human readable),
  2270. //! with a header that indicates the cube type as well as its dimensions
  2271. template<typename eT>
  2272. inline
  2273. bool
  2274. diskio::save_arma_ascii(const Cube<eT>& x, std::ostream& f)
  2275. {
  2276. arma_extra_debug_sigprint();
  2277. const arma_ostream_state stream_state(f);
  2278. f << diskio::gen_txt_header(x) << '\n';
  2279. f << x.n_rows << ' ' << x.n_cols << ' ' << x.n_slices << '\n';
  2280. const std::streamsize cell_width = diskio::prepare_stream<eT>(f);
  2281. for(uword slice=0; slice < x.n_slices; ++slice)
  2282. {
  2283. for(uword row=0; row < x.n_rows; ++row)
  2284. {
  2285. for(uword col=0; col < x.n_cols; ++col)
  2286. {
  2287. f.put(' ');
  2288. if(is_real<eT>::value) { f.width(cell_width); }
  2289. arma_ostream::raw_print_elem(f, x.at(row,col,slice));
  2290. }
  2291. f.put('\n');
  2292. }
  2293. }
  2294. const bool save_okay = f.good();
  2295. stream_state.restore(f);
  2296. return save_okay;
  2297. }
  2298. //! Save a cube in binary format,
  2299. //! with a header that stores the cube type as well as its dimensions
  2300. template<typename eT>
  2301. inline
  2302. bool
  2303. diskio::save_arma_binary(const Cube<eT>& x, const std::string& final_name)
  2304. {
  2305. arma_extra_debug_sigprint();
  2306. const std::string tmp_name = diskio::gen_tmp_name(final_name);
  2307. std::ofstream f(tmp_name.c_str(), std::fstream::binary);
  2308. bool save_okay = f.is_open();
  2309. if(save_okay)
  2310. {
  2311. save_okay = diskio::save_arma_binary(x, f);
  2312. f.flush();
  2313. f.close();
  2314. if(save_okay) { save_okay = diskio::safe_rename(tmp_name, final_name); }
  2315. }
  2316. return save_okay;
  2317. }
  2318. //! Save a cube in binary format,
  2319. //! with a header that stores the cube type as well as its dimensions
  2320. template<typename eT>
  2321. inline
  2322. bool
  2323. diskio::save_arma_binary(const Cube<eT>& x, std::ostream& f)
  2324. {
  2325. arma_extra_debug_sigprint();
  2326. f << diskio::gen_bin_header(x) << '\n';
  2327. f << x.n_rows << ' ' << x.n_cols << ' ' << x.n_slices << '\n';
  2328. f.write( reinterpret_cast<const char*>(x.mem), std::streamsize(x.n_elem*sizeof(eT)) );
  2329. return f.good();
  2330. }
  2331. //! Save a cube as part of a HDF5 file
  2332. template<typename eT>
  2333. inline
  2334. bool
  2335. diskio::save_hdf5_binary(const Cube<eT>& x, const hdf5_name& spec, std::string& err_msg)
  2336. {
  2337. arma_extra_debug_sigprint();
  2338. #if defined(ARMA_USE_HDF5)
  2339. {
  2340. hdf5_misc::hdf5_suspend_printing_errors hdf5_print_suspender;
  2341. bool save_okay = false;
  2342. const bool append = bool(spec.opts.flags & hdf5_opts::flag_append);
  2343. const bool replace = bool(spec.opts.flags & hdf5_opts::flag_replace);
  2344. const bool use_existing_file = ((append || replace) && (arma_H5Fis_hdf5(spec.filename.c_str()) > 0));
  2345. const std::string tmp_name = (use_existing_file) ? std::string() : diskio::gen_tmp_name(spec.filename);
  2346. // Set up the file according to HDF5's preferences
  2347. hid_t file = (use_existing_file) ? arma_H5Fopen(spec.filename.c_str(), H5F_ACC_RDWR, H5P_DEFAULT) : arma_H5Fcreate(tmp_name.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
  2348. if(file < 0) { return false; }
  2349. // We need to create a dataset, datatype, and dataspace
  2350. hsize_t dims[3];
  2351. dims[2] = x.n_rows;
  2352. dims[1] = x.n_cols;
  2353. dims[0] = x.n_slices;
  2354. hid_t dataspace = arma_H5Screate_simple(3, dims, NULL); // treat the cube as a 3d array dataspace
  2355. hid_t datatype = hdf5_misc::get_hdf5_type<eT>();
  2356. // If this returned something invalid, well, it's time to crash.
  2357. arma_check(datatype == -1, "Cube::save(): unknown datatype for HDF5");
  2358. // MATLAB forces the users to specify a name at save time for HDF5;
  2359. // Octave will use the default of 'dataset' unless otherwise specified.
  2360. // If the user hasn't specified a dataset name, we will use 'dataset'
  2361. // We may have to split out the group name from the dataset name.
  2362. std::vector<hid_t> groups;
  2363. std::string full_name = spec.dsname;
  2364. size_t loc;
  2365. while ((loc = full_name.find("/")) != std::string::npos)
  2366. {
  2367. // Create another group...
  2368. if (loc != 0) // Ignore the first /, if there is a leading /.
  2369. {
  2370. hid_t gid = arma_H5Gcreate((groups.size() == 0) ? file : groups[groups.size() - 1], full_name.substr(0, loc).c_str(), H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
  2371. if((gid < 0) && use_existing_file)
  2372. {
  2373. gid = arma_H5Gopen((groups.size() == 0) ? file : groups[groups.size() - 1], full_name.substr(0, loc).c_str(), H5P_DEFAULT);
  2374. }
  2375. groups.push_back(gid);
  2376. }
  2377. full_name = full_name.substr(loc + 1);
  2378. }
  2379. const std::string dataset_name = full_name.empty() ? std::string("dataset") : full_name;
  2380. const hid_t last_group = (groups.size() == 0) ? file : groups[groups.size() - 1];
  2381. if(use_existing_file && replace)
  2382. {
  2383. arma_H5Ldelete(last_group, dataset_name.c_str(), H5P_DEFAULT);
  2384. // NOTE: H5Ldelete() in HDF5 v1.8 doesn't reclaim the deleted space; use h5repack to reclaim space: h5repack oldfile.h5 newfile.h5
  2385. // NOTE: has this behaviour changed in HDF5 1.10 ?
  2386. // NOTE: https://lists.hdfgroup.org/pipermail/hdf-forum_lists.hdfgroup.org/2017-August/010482.html
  2387. // NOTE: https://lists.hdfgroup.org/pipermail/hdf-forum_lists.hdfgroup.org/2017-August/010486.html
  2388. }
  2389. hid_t dataset = arma_H5Dcreate(last_group, dataset_name.c_str(), datatype, dataspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
  2390. if(dataset < 0)
  2391. {
  2392. save_okay = false;
  2393. err_msg = "couldn't create dataset in ";
  2394. }
  2395. else
  2396. {
  2397. save_okay = (arma_H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, x.mem) >= 0);
  2398. arma_H5Dclose(dataset);
  2399. }
  2400. arma_H5Tclose(datatype);
  2401. arma_H5Sclose(dataspace);
  2402. for (size_t i = 0; i < groups.size(); ++i) { arma_H5Gclose(groups[i]); }
  2403. arma_H5Fclose(file);
  2404. if((use_existing_file == false) && (save_okay == true)) { save_okay = diskio::safe_rename(tmp_name, spec.filename); }
  2405. return save_okay;
  2406. }
  2407. #else
  2408. {
  2409. arma_ignore(x);
  2410. arma_ignore(spec);
  2411. arma_ignore(err_msg);
  2412. arma_stop_logic_error("Cube::save(): use of HDF5 must be enabled");
  2413. return false;
  2414. }
  2415. #endif
  2416. }
  2417. //! Load a cube as raw text (no header, human readable).
  2418. //! NOTE: this is much slower than reading a file with a header.
  2419. template<typename eT>
  2420. inline
  2421. bool
  2422. diskio::load_raw_ascii(Cube<eT>& x, const std::string& name, std::string& err_msg)
  2423. {
  2424. arma_extra_debug_sigprint();
  2425. Mat<eT> tmp;
  2426. const bool load_okay = diskio::load_raw_ascii(tmp, name, err_msg);
  2427. if(load_okay)
  2428. {
  2429. if(tmp.is_empty() == false)
  2430. {
  2431. x.set_size(tmp.n_rows, tmp.n_cols, 1);
  2432. x.slice(0) = tmp;
  2433. }
  2434. else
  2435. {
  2436. x.reset();
  2437. }
  2438. }
  2439. return load_okay;
  2440. }
  2441. //! Load a cube as raw text (no header, human readable).
  2442. //! NOTE: this is much slower than reading a file with a header.
  2443. template<typename eT>
  2444. inline
  2445. bool
  2446. diskio::load_raw_ascii(Cube<eT>& x, std::istream& f, std::string& err_msg)
  2447. {
  2448. arma_extra_debug_sigprint();
  2449. Mat<eT> tmp;
  2450. const bool load_okay = diskio::load_raw_ascii(tmp, f, err_msg);
  2451. if(load_okay)
  2452. {
  2453. if(tmp.is_empty() == false)
  2454. {
  2455. x.set_size(tmp.n_rows, tmp.n_cols, 1);
  2456. x.slice(0) = tmp;
  2457. }
  2458. else
  2459. {
  2460. x.reset();
  2461. }
  2462. }
  2463. return load_okay;
  2464. }
  2465. //! Load a cube in binary format (no header);
  2466. //! the cube is assumed to have one slice with one column
  2467. template<typename eT>
  2468. inline
  2469. bool
  2470. diskio::load_raw_binary(Cube<eT>& x, const std::string& name, std::string& err_msg)
  2471. {
  2472. arma_extra_debug_sigprint();
  2473. std::ifstream f;
  2474. f.open(name.c_str(), std::fstream::binary);
  2475. bool load_okay = f.is_open();
  2476. if(load_okay)
  2477. {
  2478. load_okay = diskio::load_raw_binary(x, f, err_msg);
  2479. f.close();
  2480. }
  2481. return load_okay;
  2482. }
  2483. template<typename eT>
  2484. inline
  2485. bool
  2486. diskio::load_raw_binary(Cube<eT>& x, std::istream& f, std::string& err_msg)
  2487. {
  2488. arma_extra_debug_sigprint();
  2489. arma_ignore(err_msg);
  2490. f.clear();
  2491. const std::streampos pos1 = f.tellg();
  2492. f.clear();
  2493. f.seekg(0, ios::end);
  2494. f.clear();
  2495. const std::streampos pos2 = f.tellg();
  2496. const uword N = ( (pos1 >= 0) && (pos2 >= 0) ) ? uword(pos2 - pos1) : 0;
  2497. f.clear();
  2498. //f.seekg(0, ios::beg);
  2499. f.seekg(pos1);
  2500. x.set_size(N / uword(sizeof(eT)), 1, 1);
  2501. f.clear();
  2502. f.read( reinterpret_cast<char *>(x.memptr()), std::streamsize(x.n_elem * uword(sizeof(eT))) );
  2503. return f.good();
  2504. }
  2505. //! Load a cube in text format (human readable),
  2506. //! with a header that indicates the cube type as well as its dimensions
  2507. template<typename eT>
  2508. inline
  2509. bool
  2510. diskio::load_arma_ascii(Cube<eT>& x, const std::string& name, std::string& err_msg)
  2511. {
  2512. arma_extra_debug_sigprint();
  2513. std::ifstream f(name.c_str());
  2514. bool load_okay = f.is_open();
  2515. if(load_okay)
  2516. {
  2517. load_okay = diskio::load_arma_ascii(x, f, err_msg);
  2518. f.close();
  2519. }
  2520. return load_okay;
  2521. }
  2522. //! Load a cube in text format (human readable),
  2523. //! with a header that indicates the cube type as well as its dimensions
  2524. template<typename eT>
  2525. inline
  2526. bool
  2527. diskio::load_arma_ascii(Cube<eT>& x, std::istream& f, std::string& err_msg)
  2528. {
  2529. arma_extra_debug_sigprint();
  2530. std::streampos pos = f.tellg();
  2531. bool load_okay = true;
  2532. std::string f_header;
  2533. uword f_n_rows;
  2534. uword f_n_cols;
  2535. uword f_n_slices;
  2536. f >> f_header;
  2537. f >> f_n_rows;
  2538. f >> f_n_cols;
  2539. f >> f_n_slices;
  2540. if(f_header == diskio::gen_txt_header(x))
  2541. {
  2542. x.set_size(f_n_rows, f_n_cols, f_n_slices);
  2543. for(uword slice = 0; slice < x.n_slices; ++slice)
  2544. for(uword row = 0; row < x.n_rows; ++row )
  2545. for(uword col = 0; col < x.n_cols; ++col )
  2546. {
  2547. f >> x.at(row,col,slice);
  2548. }
  2549. load_okay = f.good();
  2550. }
  2551. else
  2552. {
  2553. load_okay = false;
  2554. err_msg = "incorrect header in ";
  2555. }
  2556. // allow automatic conversion of u32/s32 cubes into u64/s64 cubes
  2557. if(load_okay == false)
  2558. {
  2559. if( (sizeof(eT) == 8) && is_same_type<uword,eT>::yes )
  2560. {
  2561. Cube<u32> tmp;
  2562. std::string junk;
  2563. f.clear();
  2564. f.seekg(pos);
  2565. load_okay = diskio::load_arma_ascii(tmp, f, junk);
  2566. if(load_okay) { x = conv_to< Cube<eT> >::from(tmp); }
  2567. }
  2568. else
  2569. if( (sizeof(eT) == 8) && is_same_type<sword,eT>::yes )
  2570. {
  2571. Cube<s32> tmp;
  2572. std::string junk;
  2573. f.clear();
  2574. f.seekg(pos);
  2575. load_okay = diskio::load_arma_ascii(tmp, f, junk);
  2576. if(load_okay) { x = conv_to< Cube<eT> >::from(tmp); }
  2577. }
  2578. }
  2579. return load_okay;
  2580. }
  2581. //! Load a cube in binary format,
  2582. //! with a header that indicates the cube type as well as its dimensions
  2583. template<typename eT>
  2584. inline
  2585. bool
  2586. diskio::load_arma_binary(Cube<eT>& x, const std::string& name, std::string& err_msg)
  2587. {
  2588. arma_extra_debug_sigprint();
  2589. std::ifstream f;
  2590. f.open(name.c_str(), std::fstream::binary);
  2591. bool load_okay = f.is_open();
  2592. if(load_okay)
  2593. {
  2594. load_okay = diskio::load_arma_binary(x, f, err_msg);
  2595. f.close();
  2596. }
  2597. return load_okay;
  2598. }
  2599. template<typename eT>
  2600. inline
  2601. bool
  2602. diskio::load_arma_binary(Cube<eT>& x, std::istream& f, std::string& err_msg)
  2603. {
  2604. arma_extra_debug_sigprint();
  2605. std::streampos pos = f.tellg();
  2606. bool load_okay = true;
  2607. std::string f_header;
  2608. uword f_n_rows;
  2609. uword f_n_cols;
  2610. uword f_n_slices;
  2611. f >> f_header;
  2612. f >> f_n_rows;
  2613. f >> f_n_cols;
  2614. f >> f_n_slices;
  2615. if(f_header == diskio::gen_bin_header(x))
  2616. {
  2617. //f.seekg(1, ios::cur); // NOTE: this may not be portable, as on a Windows machine a newline could be two characters
  2618. f.get();
  2619. x.set_size(f_n_rows, f_n_cols, f_n_slices);
  2620. f.read( reinterpret_cast<char *>(x.memptr()), std::streamsize(x.n_elem*sizeof(eT)) );
  2621. load_okay = f.good();
  2622. }
  2623. else
  2624. {
  2625. load_okay = false;
  2626. err_msg = "incorrect header in ";
  2627. }
  2628. // allow automatic conversion of u32/s32 cubes into u64/s64 cubes
  2629. if(load_okay == false)
  2630. {
  2631. if( (sizeof(eT) == 8) && is_same_type<uword,eT>::yes )
  2632. {
  2633. Cube<u32> tmp;
  2634. std::string junk;
  2635. f.clear();
  2636. f.seekg(pos);
  2637. load_okay = diskio::load_arma_binary(tmp, f, junk);
  2638. if(load_okay) { x = conv_to< Cube<eT> >::from(tmp); }
  2639. }
  2640. else
  2641. if( (sizeof(eT) == 8) && is_same_type<sword,eT>::yes )
  2642. {
  2643. Cube<s32> tmp;
  2644. std::string junk;
  2645. f.clear();
  2646. f.seekg(pos);
  2647. load_okay = diskio::load_arma_binary(tmp, f, junk);
  2648. if(load_okay) { x = conv_to< Cube<eT> >::from(tmp); }
  2649. }
  2650. }
  2651. return load_okay;
  2652. }
  2653. //! Load a HDF5 file as a cube
  2654. template<typename eT>
  2655. inline
  2656. bool
  2657. diskio::load_hdf5_binary(Cube<eT>& x, const hdf5_name& spec, std::string& err_msg)
  2658. {
  2659. arma_extra_debug_sigprint();
  2660. #if defined(ARMA_USE_HDF5)
  2661. {
  2662. hdf5_misc::hdf5_suspend_printing_errors hdf5_print_suspender;
  2663. bool load_okay = false;
  2664. hid_t fid = arma_H5Fopen(spec.filename.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);
  2665. if(fid >= 0)
  2666. {
  2667. // MATLAB HDF5 dataset names are user-specified;
  2668. // Octave tends to store the datasets in a group, with the actual dataset being referred to as "value".
  2669. // If the user hasn't specified a dataset, we will search for "dataset" and "value",
  2670. // and if those are not found we will take the first dataset we do find.
  2671. std::vector<std::string> searchNames;
  2672. const bool exact = (spec.dsname.empty() == false);
  2673. if(exact)
  2674. {
  2675. searchNames.push_back(spec.dsname);
  2676. }
  2677. else
  2678. {
  2679. searchNames.push_back("dataset");
  2680. searchNames.push_back("value" );
  2681. }
  2682. hid_t dataset = hdf5_misc::search_hdf5_file(searchNames, fid, 3, exact);
  2683. if(dataset >= 0)
  2684. {
  2685. hid_t filespace = arma_H5Dget_space(dataset);
  2686. // This must be <= 3 due to our search rules.
  2687. const int ndims = arma_H5Sget_simple_extent_ndims(filespace);
  2688. hsize_t dims[3];
  2689. const herr_t query_status = arma_H5Sget_simple_extent_dims(filespace, dims, NULL);
  2690. // arma_check(query_status < 0, "Cube::load(): cannot get size of HDF5 dataset");
  2691. if(query_status < 0)
  2692. {
  2693. err_msg = "cannot get size of HDF5 dataset in ";
  2694. arma_H5Sclose(filespace);
  2695. arma_H5Dclose(dataset);
  2696. arma_H5Fclose(fid);
  2697. return false;
  2698. }
  2699. if (ndims == 1) { dims[1] = 1; dims[2] = 1; } // Vector case; one row/colum, several slices
  2700. if (ndims == 2) { dims[2] = 1; } // Matrix case; one column, several rows/slices
  2701. x.set_size(dims[2], dims[1], dims[0]);
  2702. // Now we have to see what type is stored to figure out how to load it.
  2703. hid_t datatype = arma_H5Dget_type(dataset);
  2704. hid_t mat_type = hdf5_misc::get_hdf5_type<eT>();
  2705. // If these are the same type, it is simple.
  2706. if(arma_H5Tequal(datatype, mat_type) > 0)
  2707. {
  2708. // Load directly; H5S_ALL used so that we load the entire dataset.
  2709. hid_t read_status = arma_H5Dread(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, void_ptr(x.memptr()));
  2710. if(read_status >= 0) { load_okay = true; }
  2711. }
  2712. else
  2713. {
  2714. // Load into another array and convert its type accordingly.
  2715. hid_t read_status = hdf5_misc::load_and_convert_hdf5(x.memptr(), dataset, datatype, x.n_elem);
  2716. if(read_status >= 0) { load_okay = true; }
  2717. }
  2718. // Now clean up.
  2719. arma_H5Tclose(datatype);
  2720. arma_H5Tclose(mat_type);
  2721. arma_H5Sclose(filespace);
  2722. }
  2723. arma_H5Dclose(dataset);
  2724. arma_H5Fclose(fid);
  2725. if(load_okay == false)
  2726. {
  2727. err_msg = "unsupported or missing HDF5 data in ";
  2728. }
  2729. }
  2730. else
  2731. {
  2732. err_msg = "cannot open file ";
  2733. }
  2734. return load_okay;
  2735. }
  2736. #else
  2737. {
  2738. arma_ignore(x);
  2739. arma_ignore(spec);
  2740. arma_ignore(err_msg);
  2741. arma_stop_logic_error("Cube::load(): use of HDF5 must be enabled");
  2742. return false;
  2743. }
  2744. #endif
  2745. }
  2746. //! Try to load a cube by automatically determining its type
  2747. template<typename eT>
  2748. inline
  2749. bool
  2750. diskio::load_auto_detect(Cube<eT>& x, const std::string& name, std::string& err_msg)
  2751. {
  2752. arma_extra_debug_sigprint();
  2753. #if defined(ARMA_USE_HDF5)
  2754. // We're currently using the C bindings for the HDF5 library, which don't support C++ streams
  2755. if( arma_H5Fis_hdf5(name.c_str()) ) { return load_hdf5_binary(x, name, err_msg); }
  2756. #endif
  2757. std::fstream f;
  2758. f.open(name.c_str(), std::fstream::in | std::fstream::binary);
  2759. bool load_okay = f.is_open();
  2760. if(load_okay)
  2761. {
  2762. load_okay = diskio::load_auto_detect(x, f, err_msg);
  2763. f.close();
  2764. }
  2765. return load_okay;
  2766. }
  2767. //! Try to load a cube by automatically determining its type
  2768. template<typename eT>
  2769. inline
  2770. bool
  2771. diskio::load_auto_detect(Cube<eT>& x, std::istream& f, std::string& err_msg)
  2772. {
  2773. arma_extra_debug_sigprint();
  2774. const char* ARMA_CUB_TXT_str = "ARMA_CUB_TXT";
  2775. const char* ARMA_CUB_BIN_str = "ARMA_CUB_BIN";
  2776. const char* P6_str = "P6";
  2777. const uword ARMA_CUB_TXT_len = uword(12);
  2778. const uword ARMA_CUB_BIN_len = uword(12);
  2779. const uword P6_len = uword(2);
  2780. podarray<char> header(ARMA_CUB_TXT_len + 1);
  2781. char* header_mem = header.memptr();
  2782. std::streampos pos = f.tellg();
  2783. f.read( header_mem, std::streamsize(ARMA_CUB_TXT_len) );
  2784. f.clear();
  2785. f.seekg(pos);
  2786. header_mem[ARMA_CUB_TXT_len] = '\0';
  2787. if( std::strncmp(ARMA_CUB_TXT_str, header_mem, size_t(ARMA_CUB_TXT_len)) == 0 )
  2788. {
  2789. return load_arma_ascii(x, f, err_msg);
  2790. }
  2791. else
  2792. if( std::strncmp(ARMA_CUB_BIN_str, header_mem, size_t(ARMA_CUB_BIN_len)) == 0 )
  2793. {
  2794. return load_arma_binary(x, f, err_msg);
  2795. }
  2796. else
  2797. if( std::strncmp(P6_str, header_mem, size_t(P6_len)) == 0 )
  2798. {
  2799. return load_ppm_binary(x, f, err_msg);
  2800. }
  2801. else
  2802. {
  2803. const file_type ft = guess_file_type_internal(f);
  2804. switch(ft)
  2805. {
  2806. // case csv_ascii:
  2807. // return load_csv_ascii(x, f, err_msg);
  2808. // break;
  2809. case raw_binary:
  2810. return load_raw_binary(x, f, err_msg);
  2811. break;
  2812. case raw_ascii:
  2813. return load_raw_ascii(x, f, err_msg);
  2814. break;
  2815. default:
  2816. err_msg = "unknown data in ";
  2817. return false;
  2818. }
  2819. }
  2820. return false;
  2821. }
  2822. // fields
  2823. template<typename T1>
  2824. inline
  2825. bool
  2826. diskio::save_arma_binary(const field<T1>& x, const std::string& final_name)
  2827. {
  2828. arma_extra_debug_sigprint();
  2829. const std::string tmp_name = diskio::gen_tmp_name(final_name);
  2830. std::ofstream f( tmp_name.c_str(), std::fstream::binary );
  2831. bool save_okay = f.is_open();
  2832. if(save_okay)
  2833. {
  2834. save_okay = diskio::save_arma_binary(x, f);
  2835. f.flush();
  2836. f.close();
  2837. if(save_okay) { save_okay = diskio::safe_rename(tmp_name, final_name); }
  2838. }
  2839. return save_okay;
  2840. }
  2841. template<typename T1>
  2842. inline
  2843. bool
  2844. diskio::save_arma_binary(const field<T1>& x, std::ostream& f)
  2845. {
  2846. arma_extra_debug_sigprint();
  2847. arma_type_check(( (is_Mat<T1>::value == false) && (is_Cube<T1>::value == false) ));
  2848. if(x.n_slices <= 1)
  2849. {
  2850. f << "ARMA_FLD_BIN" << '\n';
  2851. f << x.n_rows << '\n';
  2852. f << x.n_cols << '\n';
  2853. }
  2854. else
  2855. {
  2856. f << "ARMA_FL3_BIN" << '\n';
  2857. f << x.n_rows << '\n';
  2858. f << x.n_cols << '\n';
  2859. f << x.n_slices << '\n';
  2860. }
  2861. bool save_okay = true;
  2862. for(uword i=0; i<x.n_elem; ++i)
  2863. {
  2864. save_okay = diskio::save_arma_binary(x[i], f);
  2865. if(save_okay == false) { break; }
  2866. }
  2867. return save_okay;
  2868. }
  2869. template<typename T1>
  2870. inline
  2871. bool
  2872. diskio::load_arma_binary(field<T1>& x, const std::string& name, std::string& err_msg)
  2873. {
  2874. arma_extra_debug_sigprint();
  2875. std::ifstream f( name.c_str(), std::fstream::binary );
  2876. bool load_okay = f.is_open();
  2877. if(load_okay)
  2878. {
  2879. load_okay = diskio::load_arma_binary(x, f, err_msg);
  2880. f.close();
  2881. }
  2882. return load_okay;
  2883. }
  2884. template<typename T1>
  2885. inline
  2886. bool
  2887. diskio::load_arma_binary(field<T1>& x, std::istream& f, std::string& err_msg)
  2888. {
  2889. arma_extra_debug_sigprint();
  2890. arma_type_check(( (is_Mat<T1>::value == false) && (is_Cube<T1>::value == false) ));
  2891. bool load_okay = true;
  2892. std::string f_type;
  2893. f >> f_type;
  2894. if(f_type == "ARMA_FLD_BIN")
  2895. {
  2896. uword f_n_rows;
  2897. uword f_n_cols;
  2898. f >> f_n_rows;
  2899. f >> f_n_cols;
  2900. x.set_size(f_n_rows, f_n_cols);
  2901. f.get();
  2902. for(uword i=0; i<x.n_elem; ++i)
  2903. {
  2904. load_okay = diskio::load_arma_binary(x[i], f, err_msg);
  2905. if(load_okay == false) { break; }
  2906. }
  2907. }
  2908. else
  2909. if(f_type == "ARMA_FL3_BIN")
  2910. {
  2911. uword f_n_rows;
  2912. uword f_n_cols;
  2913. uword f_n_slices;
  2914. f >> f_n_rows;
  2915. f >> f_n_cols;
  2916. f >> f_n_slices;
  2917. x.set_size(f_n_rows, f_n_cols, f_n_slices);
  2918. f.get();
  2919. for(uword i=0; i<x.n_elem; ++i)
  2920. {
  2921. load_okay = diskio::load_arma_binary(x[i], f, err_msg);
  2922. if(load_okay == false) { break; }
  2923. }
  2924. }
  2925. else
  2926. {
  2927. load_okay = false;
  2928. err_msg = "unsupported field type in ";
  2929. }
  2930. return load_okay;
  2931. }
  2932. inline
  2933. bool
  2934. diskio::save_std_string(const field<std::string>& x, const std::string& final_name)
  2935. {
  2936. arma_extra_debug_sigprint();
  2937. const std::string tmp_name = diskio::gen_tmp_name(final_name);
  2938. std::ofstream f( tmp_name.c_str(), std::fstream::binary );
  2939. bool save_okay = f.is_open();
  2940. if(save_okay)
  2941. {
  2942. save_okay = diskio::save_std_string(x, f);
  2943. f.flush();
  2944. f.close();
  2945. if(save_okay) { save_okay = diskio::safe_rename(tmp_name, final_name); }
  2946. }
  2947. return save_okay;
  2948. }
  2949. inline
  2950. bool
  2951. diskio::save_std_string(const field<std::string>& x, std::ostream& f)
  2952. {
  2953. arma_extra_debug_sigprint();
  2954. for(uword row=0; row<x.n_rows; ++row)
  2955. for(uword col=0; col<x.n_cols; ++col)
  2956. {
  2957. f << x.at(row,col);
  2958. if(col < x.n_cols-1)
  2959. {
  2960. f << ' ';
  2961. }
  2962. else
  2963. {
  2964. f << '\n';
  2965. }
  2966. }
  2967. return f.good();
  2968. }
  2969. inline
  2970. bool
  2971. diskio::load_std_string(field<std::string>& x, const std::string& name, std::string& err_msg)
  2972. {
  2973. arma_extra_debug_sigprint();
  2974. std::ifstream f( name.c_str() );
  2975. bool load_okay = f.is_open();
  2976. if(load_okay)
  2977. {
  2978. load_okay = diskio::load_std_string(x, f, err_msg);
  2979. f.close();
  2980. }
  2981. return load_okay;
  2982. }
  2983. inline
  2984. bool
  2985. diskio::load_std_string(field<std::string>& x, std::istream& f, std::string& err_msg)
  2986. {
  2987. arma_extra_debug_sigprint();
  2988. bool load_okay = true;
  2989. //
  2990. // work out the size
  2991. uword f_n_rows = 0;
  2992. uword f_n_cols = 0;
  2993. bool f_n_cols_found = false;
  2994. std::string line_string;
  2995. std::string token;
  2996. while( f.good() && load_okay )
  2997. {
  2998. std::getline(f, line_string);
  2999. if(line_string.size() == 0) { break; }
  3000. std::stringstream line_stream(line_string);
  3001. uword line_n_cols = 0;
  3002. while (line_stream >> token) { line_n_cols++; }
  3003. if(f_n_cols_found == false)
  3004. {
  3005. f_n_cols = line_n_cols;
  3006. f_n_cols_found = true;
  3007. }
  3008. else
  3009. {
  3010. if(line_n_cols != f_n_cols)
  3011. {
  3012. load_okay = false;
  3013. err_msg = "inconsistent number of columns in ";
  3014. }
  3015. }
  3016. ++f_n_rows;
  3017. }
  3018. if(load_okay)
  3019. {
  3020. f.clear();
  3021. f.seekg(0, ios::beg);
  3022. //f.seekg(start);
  3023. x.set_size(f_n_rows, f_n_cols);
  3024. for(uword row=0; row < x.n_rows; ++row)
  3025. for(uword col=0; col < x.n_cols; ++col)
  3026. {
  3027. f >> x.at(row,col);
  3028. }
  3029. }
  3030. if(f.good() == false) { load_okay = false; }
  3031. return load_okay;
  3032. }
  3033. //! Try to load a field by automatically determining its type
  3034. template<typename T1>
  3035. inline
  3036. bool
  3037. diskio::load_auto_detect(field<T1>& x, const std::string& name, std::string& err_msg)
  3038. {
  3039. arma_extra_debug_sigprint();
  3040. std::fstream f;
  3041. f.open(name.c_str(), std::fstream::in | std::fstream::binary);
  3042. bool load_okay = f.is_open();
  3043. if(load_okay)
  3044. {
  3045. load_okay = diskio::load_auto_detect(x, f, err_msg);
  3046. f.close();
  3047. }
  3048. return load_okay;
  3049. }
  3050. //! Try to load a field by automatically determining its type
  3051. template<typename T1>
  3052. inline
  3053. bool
  3054. diskio::load_auto_detect(field<T1>& x, std::istream& f, std::string& err_msg)
  3055. {
  3056. arma_extra_debug_sigprint();
  3057. arma_type_check(( is_Mat<T1>::value == false ));
  3058. static const std::string ARMA_FLD_BIN = "ARMA_FLD_BIN";
  3059. static const std::string ARMA_FL3_BIN = "ARMA_FL3_BIN";
  3060. static const std::string P6 = "P6";
  3061. podarray<char> raw_header(uword(ARMA_FLD_BIN.length()) + 1);
  3062. std::streampos pos = f.tellg();
  3063. f.read( raw_header.memptr(), std::streamsize(ARMA_FLD_BIN.length()) );
  3064. f.clear();
  3065. f.seekg(pos);
  3066. raw_header[uword(ARMA_FLD_BIN.length())] = '\0';
  3067. const std::string header = raw_header.mem;
  3068. if(ARMA_FLD_BIN == header.substr(0, ARMA_FLD_BIN.length()))
  3069. {
  3070. return load_arma_binary(x, f, err_msg);
  3071. }
  3072. else
  3073. if(ARMA_FL3_BIN == header.substr(0, ARMA_FL3_BIN.length()))
  3074. {
  3075. return load_arma_binary(x, f, err_msg);
  3076. }
  3077. else
  3078. if(P6 == header.substr(0, P6.length()))
  3079. {
  3080. return load_ppm_binary(x, f, err_msg);
  3081. }
  3082. else
  3083. {
  3084. err_msg = "unsupported header in ";
  3085. return false;
  3086. }
  3087. }
  3088. //
  3089. // handling of PPM images by cubes
  3090. template<typename eT>
  3091. inline
  3092. bool
  3093. diskio::load_ppm_binary(Cube<eT>& x, const std::string& name, std::string& err_msg)
  3094. {
  3095. arma_extra_debug_sigprint();
  3096. std::fstream f;
  3097. f.open(name.c_str(), std::fstream::in | std::fstream::binary);
  3098. bool load_okay = f.is_open();
  3099. if(load_okay)
  3100. {
  3101. load_okay = diskio::load_ppm_binary(x, f, err_msg);
  3102. f.close();
  3103. }
  3104. return load_okay;
  3105. }
  3106. template<typename eT>
  3107. inline
  3108. bool
  3109. diskio::load_ppm_binary(Cube<eT>& x, std::istream& f, std::string& err_msg)
  3110. {
  3111. arma_extra_debug_sigprint();
  3112. bool load_okay = true;
  3113. std::string f_header;
  3114. f >> f_header;
  3115. if(f_header == "P6")
  3116. {
  3117. uword f_n_rows = 0;
  3118. uword f_n_cols = 0;
  3119. int f_maxval = 0;
  3120. diskio::pnm_skip_comments(f);
  3121. f >> f_n_cols;
  3122. diskio::pnm_skip_comments(f);
  3123. f >> f_n_rows;
  3124. diskio::pnm_skip_comments(f);
  3125. f >> f_maxval;
  3126. f.get();
  3127. if( (f_maxval > 0) && (f_maxval <= 65535) )
  3128. {
  3129. x.set_size(f_n_rows, f_n_cols, 3);
  3130. if(f_maxval <= 255)
  3131. {
  3132. const uword n_elem = 3*f_n_cols*f_n_rows;
  3133. podarray<u8> tmp(n_elem);
  3134. f.read( reinterpret_cast<char*>(tmp.memptr()), std::streamsize(n_elem) );
  3135. uword i = 0;
  3136. //cout << "f_n_cols = " << f_n_cols << endl;
  3137. //cout << "f_n_rows = " << f_n_rows << endl;
  3138. for(uword row=0; row < f_n_rows; ++row)
  3139. for(uword col=0; col < f_n_cols; ++col)
  3140. {
  3141. x.at(row,col,0) = eT(tmp[i+0]);
  3142. x.at(row,col,1) = eT(tmp[i+1]);
  3143. x.at(row,col,2) = eT(tmp[i+2]);
  3144. i+=3;
  3145. }
  3146. }
  3147. else
  3148. {
  3149. const uword n_elem = 3*f_n_cols*f_n_rows;
  3150. podarray<u16> tmp(n_elem);
  3151. f.read( reinterpret_cast<char *>(tmp.memptr()), std::streamsize(2*n_elem) );
  3152. uword i = 0;
  3153. for(uword row=0; row < f_n_rows; ++row)
  3154. for(uword col=0; col < f_n_cols; ++col)
  3155. {
  3156. x.at(row,col,0) = eT(tmp[i+0]);
  3157. x.at(row,col,1) = eT(tmp[i+1]);
  3158. x.at(row,col,2) = eT(tmp[i+2]);
  3159. i+=3;
  3160. }
  3161. }
  3162. }
  3163. else
  3164. {
  3165. load_okay = false;
  3166. err_msg = "currently no code available to handle loading ";
  3167. }
  3168. if(f.good() == false) { load_okay = false; }
  3169. }
  3170. else
  3171. {
  3172. load_okay = false;
  3173. err_msg = "unsupported header in ";
  3174. }
  3175. return load_okay;
  3176. }
  3177. template<typename eT>
  3178. inline
  3179. bool
  3180. diskio::save_ppm_binary(const Cube<eT>& x, const std::string& final_name)
  3181. {
  3182. arma_extra_debug_sigprint();
  3183. const std::string tmp_name = diskio::gen_tmp_name(final_name);
  3184. std::ofstream f( tmp_name.c_str(), std::fstream::binary );
  3185. bool save_okay = f.is_open();
  3186. if(save_okay)
  3187. {
  3188. save_okay = diskio::save_ppm_binary(x, f);
  3189. f.flush();
  3190. f.close();
  3191. if(save_okay) { save_okay = diskio::safe_rename(tmp_name, final_name); }
  3192. }
  3193. return save_okay;
  3194. }
  3195. template<typename eT>
  3196. inline
  3197. bool
  3198. diskio::save_ppm_binary(const Cube<eT>& x, std::ostream& f)
  3199. {
  3200. arma_extra_debug_sigprint();
  3201. arma_debug_check( (x.n_slices != 3), "diskio::save_ppm_binary(): given cube must have exactly 3 slices" );
  3202. const uword n_elem = 3 * x.n_rows * x.n_cols;
  3203. podarray<u8> tmp(n_elem);
  3204. uword i = 0;
  3205. for(uword row=0; row < x.n_rows; ++row)
  3206. {
  3207. for(uword col=0; col < x.n_cols; ++col)
  3208. {
  3209. tmp[i+0] = u8( access::tmp_real( x.at(row,col,0) ) );
  3210. tmp[i+1] = u8( access::tmp_real( x.at(row,col,1) ) );
  3211. tmp[i+2] = u8( access::tmp_real( x.at(row,col,2) ) );
  3212. i+=3;
  3213. }
  3214. }
  3215. f << "P6" << '\n';
  3216. f << x.n_cols << '\n';
  3217. f << x.n_rows << '\n';
  3218. f << 255 << '\n';
  3219. f.write( reinterpret_cast<const char*>(tmp.mem), std::streamsize(n_elem) );
  3220. return f.good();
  3221. }
  3222. //
  3223. // handling of PPM images by fields
  3224. template<typename T1>
  3225. inline
  3226. bool
  3227. diskio::load_ppm_binary(field<T1>& x, const std::string& name, std::string& err_msg)
  3228. {
  3229. arma_extra_debug_sigprint();
  3230. std::fstream f;
  3231. f.open(name.c_str(), std::fstream::in | std::fstream::binary);
  3232. bool load_okay = f.is_open();
  3233. if(load_okay)
  3234. {
  3235. load_okay = diskio::load_ppm_binary(x, f, err_msg);
  3236. f.close();
  3237. }
  3238. return load_okay;
  3239. }
  3240. template<typename T1>
  3241. inline
  3242. bool
  3243. diskio::load_ppm_binary(field<T1>& x, std::istream& f, std::string& err_msg)
  3244. {
  3245. arma_extra_debug_sigprint();
  3246. arma_type_check(( is_Mat<T1>::value == false ));
  3247. typedef typename T1::elem_type eT;
  3248. bool load_okay = true;
  3249. std::string f_header;
  3250. f >> f_header;
  3251. if(f_header == "P6")
  3252. {
  3253. uword f_n_rows = 0;
  3254. uword f_n_cols = 0;
  3255. int f_maxval = 0;
  3256. diskio::pnm_skip_comments(f);
  3257. f >> f_n_cols;
  3258. diskio::pnm_skip_comments(f);
  3259. f >> f_n_rows;
  3260. diskio::pnm_skip_comments(f);
  3261. f >> f_maxval;
  3262. f.get();
  3263. if( (f_maxval > 0) && (f_maxval <= 65535) )
  3264. {
  3265. x.set_size(3);
  3266. Mat<eT>& R = x(0);
  3267. Mat<eT>& G = x(1);
  3268. Mat<eT>& B = x(2);
  3269. R.set_size(f_n_rows,f_n_cols);
  3270. G.set_size(f_n_rows,f_n_cols);
  3271. B.set_size(f_n_rows,f_n_cols);
  3272. if(f_maxval <= 255)
  3273. {
  3274. const uword n_elem = 3*f_n_cols*f_n_rows;
  3275. podarray<u8> tmp(n_elem);
  3276. f.read( reinterpret_cast<char*>(tmp.memptr()), std::streamsize(n_elem) );
  3277. uword i = 0;
  3278. //cout << "f_n_cols = " << f_n_cols << endl;
  3279. //cout << "f_n_rows = " << f_n_rows << endl;
  3280. for(uword row=0; row < f_n_rows; ++row)
  3281. {
  3282. for(uword col=0; col < f_n_cols; ++col)
  3283. {
  3284. R.at(row,col) = eT(tmp[i+0]);
  3285. G.at(row,col) = eT(tmp[i+1]);
  3286. B.at(row,col) = eT(tmp[i+2]);
  3287. i+=3;
  3288. }
  3289. }
  3290. }
  3291. else
  3292. {
  3293. const uword n_elem = 3*f_n_cols*f_n_rows;
  3294. podarray<u16> tmp(n_elem);
  3295. f.read( reinterpret_cast<char *>(tmp.memptr()), std::streamsize(2*n_elem) );
  3296. uword i = 0;
  3297. for(uword row=0; row < f_n_rows; ++row)
  3298. for(uword col=0; col < f_n_cols; ++col)
  3299. {
  3300. R.at(row,col) = eT(tmp[i+0]);
  3301. G.at(row,col) = eT(tmp[i+1]);
  3302. B.at(row,col) = eT(tmp[i+2]);
  3303. i+=3;
  3304. }
  3305. }
  3306. }
  3307. else
  3308. {
  3309. load_okay = false;
  3310. err_msg = "currently no code available to handle loading ";
  3311. }
  3312. if(f.good() == false) { load_okay = false; }
  3313. }
  3314. else
  3315. {
  3316. load_okay = false;
  3317. err_msg = "unsupported header in ";
  3318. }
  3319. return load_okay;
  3320. }
  3321. template<typename T1>
  3322. inline
  3323. bool
  3324. diskio::save_ppm_binary(const field<T1>& x, const std::string& final_name)
  3325. {
  3326. arma_extra_debug_sigprint();
  3327. const std::string tmp_name = diskio::gen_tmp_name(final_name);
  3328. std::ofstream f( tmp_name.c_str(), std::fstream::binary );
  3329. bool save_okay = f.is_open();
  3330. if(save_okay)
  3331. {
  3332. save_okay = diskio::save_ppm_binary(x, f);
  3333. f.flush();
  3334. f.close();
  3335. if(save_okay) { save_okay = diskio::safe_rename(tmp_name, final_name); }
  3336. }
  3337. return save_okay;
  3338. }
  3339. template<typename T1>
  3340. inline
  3341. bool
  3342. diskio::save_ppm_binary(const field<T1>& x, std::ostream& f)
  3343. {
  3344. arma_extra_debug_sigprint();
  3345. arma_type_check(( is_Mat<T1>::value == false ));
  3346. typedef typename T1::elem_type eT;
  3347. arma_debug_check( (x.n_elem != 3), "diskio::save_ppm_binary(): given field must have exactly 3 matrices of equal size" );
  3348. bool same_size = true;
  3349. for(uword i=1; i<3; ++i)
  3350. {
  3351. if( (x(0).n_rows != x(i).n_rows) || (x(0).n_cols != x(i).n_cols) )
  3352. {
  3353. same_size = false;
  3354. break;
  3355. }
  3356. }
  3357. arma_debug_check( (same_size != true), "diskio::save_ppm_binary(): given field must have exactly 3 matrices of equal size" );
  3358. const Mat<eT>& R = x(0);
  3359. const Mat<eT>& G = x(1);
  3360. const Mat<eT>& B = x(2);
  3361. f << "P6" << '\n';
  3362. f << R.n_cols << '\n';
  3363. f << R.n_rows << '\n';
  3364. f << 255 << '\n';
  3365. const uword n_elem = 3 * R.n_rows * R.n_cols;
  3366. podarray<u8> tmp(n_elem);
  3367. uword i = 0;
  3368. for(uword row=0; row < R.n_rows; ++row)
  3369. for(uword col=0; col < R.n_cols; ++col)
  3370. {
  3371. tmp[i+0] = u8( access::tmp_real( R.at(row,col) ) );
  3372. tmp[i+1] = u8( access::tmp_real( G.at(row,col) ) );
  3373. tmp[i+2] = u8( access::tmp_real( B.at(row,col) ) );
  3374. i+=3;
  3375. }
  3376. f.write( reinterpret_cast<const char*>(tmp.mem), std::streamsize(n_elem) );
  3377. return f.good();
  3378. }
  3379. //! @}