blib/lib/PDL/IO/Matlab.pm

filter: Statementstmt 93.7% 15 / 16 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 94.7% 18 / 19 CC 1 SCAR 0.0
CC
1
Cov
94%
BEGIN
1.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« convert_matvar_pdl.c ↑ Summary
1 #
2 # GENERATED WITH PDL::PP from matlab.pd! Don't modify!
3 #
4 package PDL::IO::Matlab;
5  
6 1 our @EXPORT_OK = qw(matlab_read matlab_write matlab_print_info );
7 1 our %EXPORT_TAGS = (Func=>\@EXPORT_OK);
8  
9 1 ▶use PDL::Core;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use PDL::Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use DynaLoader;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13  
14 1 our $VERSION = '0.008';
15 1 our @ISA = ( 'PDL::Exporter','DynaLoader' );
16 1 push @PDL::Core::PP, __PACKAGE__;
17 1 bootstrap PDL::IO::Matlab $VERSION;
18  
19  
20  
21  
22  
23  
24  
25  
26 #line 39 "matlab.pd"
27  
28 =head1 NAME
29  
30 PDL::IO::Matlab -- Read and write Matlab format data files.
31  
32 =head1 DESCRIPTION
33  
34 This module provides routines to read and write pdls to and from
35 data files in Matlab formats. The module uses the matio C library.
36 Both functional and OO interface are provided.
37  
38 Only real, multi-dimensional arrays corresponding to PDL data types are supported.
39 Compression for both reading and writing is supported.
40  
41 See the section L</CAVEATS> for important information on potential problems when using
42 this module.
43  
44 =head1 SYNOPSIS
45  
46 use PDL;
47 use PDL::IO::Matlab qw( matlab_read matlab_write matlab_print_info);
48  
49 # write two pdls in matlab 5 format
50 matlab_write('file.dat', $x, $y);
51  
52 # read an array of ndarrays
53 # from file in matlab 4, 5, or 7.3 format.
54 my @pdls = matlab_read('file.dat');
55  
56 # write pdl in matlab 7.3 format.
57 matlab_write('file.dat', 'MAT73', $x);
58  
59 matlab_print_info('file.dat');
60  
61 =cut
62  
63 $PDL::onlinedoc->scan(__FILE__) if $PDL::onlinedoc;
64  
65 use strict;
66 use warnings;
67  
68 use PDL::LiteF;
69 use PDL::NiceSlice;
70 use PDL::Options;
71 use Data::Dumper;
72  
73 #line 88 "matlab.pd"
74 my %Format_list = (
75 MAT73 => 0,
76 MAT5 => 1,
77 MAT4 => 2
78 );
79  
80 my %Inv_format_list = (
81 0 => 'MAT73',
82 1 => 'MAT5',
83 2 => 'MAT4'
84 );
85  
86 # non-OO functions
87  
88 =head1 FUNCTIONS
89  
90 The functional interface.
91  
92 =head2 B<matlab_read>
93  
94 =head3 Usage
95  
96 Return all arrays in C<$filename>
97  
98 @pdls = matlab_read($filename);
99 @pdls = matlab_read($filename, {OPTIONS});
100  
101 Return first array in C<$filename>
102  
103 $x = matlab_read($filename);
104  
105 Do not automatically convert C<1xn> and C<nx1> arrays
106 to 1-d arrays.
107  
108 @pdls = matlab_read($filename, { onedr => 0 } );
109  
110 Reads all data in the file C<$filename>.
111 Formats 4, 5, and 7.3 are supported. Options
112 are passed to L</B<new>>.
113  
114 =cut
115  
116 sub matlab_read {
117 my ($filename,$opts) = @_;
118 my $mat = PDL::IO::Matlab->new($filename, '<', $opts || {});
119 my @res = $mat->read_all;
120 $mat->close;
121 wantarray ? @res : $res[0];
122 }
123  
124 =head2 B<matlab_write>
125  
126 =head3 Usage
127  
128 matlab_write($filename,$x1,$x2,...);
129 matlab_write($filename,$format,$x1,$x2,...);
130  
131 Automatically convert C<n> element, 1-d ndarrays to C<1xn> matlab
132 variables.
133  
134 matlab_write($filename,$x1,$x2,..., {onedw => 1} );
135  
136 Automatically convert to C<nx1> matlab
137 variables.
138  
139 matlab_write($filename,$x1,$x2,..., {onedw => 2} );
140  
141 Use zlib compression
142  
143 matlab_write($filename,$x1,$x2,..., {compress => 1} );
144  
145 This method writes pdls C<$x1>, C<$x2>,.... If present, C<$format>
146 must be either C<'MAT5'> or C<'MAT73'>.
147  
148 =cut
149  
150 sub matlab_write {
151 my @strings;
152 my @hashes;
153 my @refs;
154 while(@_) {
155 my $v = shift;
156 if ( ref($v) ) {
157 if ( ref($v) eq 'HASH' ) {
158 push @hashes, $v;
159 }
160 else {
161 push @refs, $v;
162 }
163 }
164 else {
165 push @strings, $v;
166 }
167 }
168 barf 'matlab_write: ' . scalar(@strings) .
169 ' string arguments given. One or two expected.'
170 if @strings < 1 or @strings > 2 ;
171 my $filename = $strings[0];
172 my $format = $strings[1] || 'MAT5';
173 my $opth = { format => $format };
174 foreach (keys %{$hashes[0]}) { $opth->{$_} = $hashes[0]->{$_} }
175 #line 192 "matlab.pd"
176 my $mat = PDL::IO::Matlab->new($filename, '>', $opth);
177 $mat->write(@refs) if @refs;
178 $mat->close;
179 scalar(@refs);
180 }
181  
182 =head2 B<matlab_print_info>
183  
184 =head3 Usage
185  
186 # print names and dimensions of variables.
187 matlab_print_info($filename);
188 # also print a small amount of the data.
189 matlab_print_info($filename, { data => 1 });
190 # This does the same thing.
191 matlab_print_info($filename, data => 1 );
192  
193 Print information about the contents of the matlab file C<$filename>,
194 including the name, dimension and class type of the variables.
195  
196 =cut
197  
198 sub matlab_print_info {
199 my $name = shift;
200 my $mat = PDL::IO::Matlab->new($name, '<');
201 $mat->print_all_var_info(@_);
202 $mat->close;
203 }
204  
205 =head1 METHODS
206  
207 =head2 B<new>
208  
209 =head3 Usage
210  
211 # open for writing
212 $mat = PDL::IO::Matlab->new('file.dat', '>', {format => 'MAT5'});
213  
214 # default format is MAT5
215 $mat = PDL::IO::Matlab->new('file.dat', '>');
216  
217 # may use 'w' or '>'
218 $mat = PDL::IO::Matlab->new('file.dat', 'w');
219  
220 # supply header
221 $mat = PDL::IO::Matlab->new('file.dat', '>', { header => 'some text'} );
222  
223 # read-write with rw or <>
224 $mat = PDL::IO::Matlab->new('file.dat', 'rw');
225  
226 # open for reading
227 $mat = PDL::IO::Matlab->new('file.dat', '<');
228  
229 =head3 Options
230  
231 =over
232  
233 =item format
234  
235 Either C<'MAT5'> or C<'MAT73'>.
236  
237 =item compress
238  
239 Either C<1> for yes, or C<0> for no.
240  
241 =item header
242  
243 A header (a string) to write into the file.
244  
245 =item namekey
246  
247 A hash key that will be used to store the matlab name
248 for a variable read from a file in the header of an ndarray.
249 The default value is 'NAME'. Thus, the name can be accessed
250 via C<< $pdl->hdr->{NAME} >>.
251  
252 =item varbasew
253  
254 The base of the default matlab variable name that will be
255 written in the matlab file along with each ndarray. An
256 integer will be appended to the base name. This integer is
257 initialized to zero and is incremented after writing each
258 variable.
259  
260 =back
261  
262 The option C<compress> enables zlib compression if the zlib library
263 is available and if the data file format is C<'MAT5'>.
264  
265 =cut
266  
267 sub new {
268 my $class = shift;
269 my ($filename,$mode,$iopts) = @_;
270 my $opt = new PDL::Options(
271 {
272 format => undef,
273 header => undef,
274 namekey => 'NAME',
275 varbasew => 'variable',
276 onedw => 1,
277 onedr => 1,
278 compress => 0
279 });
280 $iopts ||= {};
281  
282 my $obj = $opt->options($iopts);
283  
284 my %exobj = (
285 filename => undef,
286 mode => undef,
287 handle => undef,
288 wvarnum => 0,
289 );
290  
291 foreach (keys %exobj) { $obj->{$_} = $exobj{$_} };
292  
293 bless $obj, $class;
294  
295 $obj->set_filename($filename) if $filename;
296  
297 if ( defined $mode ) {
298 if ($mode eq 'r' or $mode eq '<') {
299 $obj->set_mode('r');
300 }
301 elsif ($mode eq 'w' or $mode eq '>') {
302 $obj->set_mode('w');
303 }
304 elsif ($mode eq 'rw' or $mode eq '<>') {
305 $obj->set_mode('rw');
306 }
307 else {
308 barf "PDL::IO::Matlab::open unknown mode '$mode'";
309 }
310 }
311 elsif (defined $filename) {
312 barf("PDL::IO::Matlab::new filename given, but no access mode.");
313 }
314 barf("PDL::IO::Matlab::new unknown file format")
315 if defined $obj->{format} and not exists $Format_list{$obj->{format}};
316 $obj->open() if defined $filename;
317 $obj;
318 }
319  
320 # may want to keep track of state at some point,
321 # an automatically close.
322 sub DESTROY {
323 my $self = shift;
324 # $self->close;
325 }
326  
327 sub open {
328 my $self = shift;
329 my $mode = $self->get_mode();
330 my $filename = $self->get_filename();
331 my $handle;
332 if ( $mode eq 'r' ) {
333 $handle = _mat_open_read($filename);
334 }
335 elsif ( $mode eq 'w' ) {
336 $self->get_format || $self->set_format('MAT5');
337 my $header = $self->get_header();
338 my $header_flag = defined $header ? 1 : 0;
339 $header = '' unless defined $header;
340 $handle = _mat_create_ver(
341 $filename, $header, $Format_list{$self->get_format}, $header_flag);
342 }
343 elsif ( $mode eq 'rw' ) {
344 $handle = _mat_open_read_write($filename);
345 }
346 else {
347 barf "PDL::IO::Matlab::open unknown mode '$mode'";
348 }
349 barf "PDL::IO::Matlab::open Can't open '$filename' in mode $mode" unless $handle;
350 $self->set_handle($handle);
351 $self->get_format || $self->set_format($self->get_version);
352 $self;
353 }
354  
355 =head2 B<close>
356  
357 =head3 Usage
358  
359 $mat->close;
360  
361 Close matlab file and free memory associated with C<$mat>.
362  
363 =cut
364  
365 sub close {
366 my $self = shift;
367 _mat_close($self->get_handle() );
368 $self;
369 }
370  
371 =head2 B<read_next>
372  
373 =head3 Usage
374  
375 my $x = $mat->read_next;
376 print "End of file\n" unless ref($x);
377  
378 my ($err,$x) = $mat->read_next;
379 print "End of file\n" if $err;
380  
381 Read one pdl from file associated with object C<$mat>.
382  
383 =cut
384  
385 sub read_next {
386 my $self = shift;
387 my ($pdl,$matlab_name) = _convert_next_matvar_to_pdl($self->get_handle,
388 $self->get_onedr);
389 my $err = ref($pdl) ? 0 : 1;
390 $pdl->hdr->{$self->get_namekey} = $matlab_name if defined $matlab_name;
391 return ($err,$pdl);
392 }
393  
394 =head2 B<read_all>
395  
396 =head3 Usage
397  
398 my @pdls = $mat->read_all;
399  
400 Read all remaining pdls from file associated with object C<$mat>.
401  
402 =cut
403  
404 sub read_all {
405 my $self = shift;
406 my @res;
407 while(1) {
408 my ($err,$pdl) = read_next($self);
409 last if $err;
410 push @res, $pdl;
411 }
412 @res;
413 }
414  
415 =head2 B<write>
416  
417 =head3 Usage
418  
419 $x2->hdr->{NAME} = 'variablename';
420  
421 $mat->write($x1,$x2,...);
422  
423 $mat->write($x1,$x2,...,{OPTIONS});
424  
425 Append pdls to open file associated with C<$mat>.
426  
427 If an ndarray has a matlab name stored in the header
428 it will be used as the matlab name written to the file
429 with this ndarray. The key is in C<< $pdl->{namekey} >>,
430 with default value C<'NAME'>. If the name is not in
431 the ndarray's header, then a default value will be used.
432  
433 =head3 Options
434  
435 =over
436  
437 =item onedw
438  
439 In order to write a file that is compatible with Matlab and Octave,
440 C<onedw> must be either C<1> or C<2>. If C<onedw> is C<1> then a 1-d
441 pdl of length n is written as a as an C<nx1> pdl (a C<1xn> matlab
442 variable). If C<onedw> is C<2> then the output ndarray is C<1xn> and
443 the matlab variable C<nx1>. If C<onedw> is zero (the default), then
444 the 1-d pdl is written as a 1-d ndarray. In the last case, Octave will
445 print an error and fail to read the variable.
446  
447 =item compress
448  
449 If C<compress> is C<1> then zlib compression is used, if the library
450 is available and if the format is C<'MAT5'>.
451  
452 =back
453  
454 =cut
455  
456 sub _make_write_var_name {
457 my $self = shift;
458 my $varname = $self->get_varbasew . $self->get_wvarnum;
459 $self->set_wvarnum($self->get_wvarnum + 1);
460 $varname;
461 }
462  
463 sub write {
464 my $self = shift;
465 my @pdls;
466 my @hashes;
467 while (@_) {
468 my $arg = shift;
469 if (ref($arg) eq 'HASH') {
470 push @hashes, $arg;
471 }
472 else {
473 push @pdls, $arg;
474 }
475 }
476 # my %opts = parse( {onedw => 0 }, @hashes ? $hashes[0] : {} );
477 my $opts = @hashes ? $hashes[0] : {} ;
478 my $onedw = exists $opts->{onedw} ? $opts->{onedw} : $self->get_onedw;
479 $onedw = 1 if $onedw == 0 and $self->get_format eq 'MAT73'; # else crash
480 my $compress = exists $opts->{compress} ? $opts->{compress} : $self->get_compress;
481 foreach (@pdls) {
482 my $name = exists $_->hdr->{$self->get_namekey} ?
483 $_->hdr->{$self->get_namekey} : $self->_make_write_var_name;
484 _write_pdl_to_matlab_file($self->get_handle,$_, $name, $onedw, $compress);
485 }
486 return $self;
487 }
488  
489 =head2 B<rewind>
490  
491 =head3 Usage
492  
493 $mat->rewind
494  
495 Reset pointer to the head of the file.
496  
497 =cut
498  
499 sub rewind {
500 my $self = shift;
501 _mat_rewind($self->get_handle);
502 }
503  
504 =head2 B<get_filename>
505  
506 =head3 Usage
507  
508 $mat->get_filename
509  
510 Return name of file associated with C<$mat>.
511  
512 =cut
513  
514 =head2 B<get_header>
515  
516 =head3 Usage
517  
518 $mat->get_header
519  
520 Return the header string from the matlab data file associated with
521 C<$mat>.
522  
523 =cut
524  
525 sub get_header {
526 my $self = shift;
527 return defined $self->{header} ?
528 $self->{header} : defined $self->{handle} ?
529 _mat_get_header($self->{handle}) : undef;
530 }
531  
532 sub set_header {
533 my $self = shift;
534 $self->{header} = shift;
535 }
536  
537 =head2 B<get_format>
538  
539 =head3 Usage
540  
541 $mat->get_format
542  
543 Return matlab data file format for file associated with
544 C<$mat>. One of C<'MAT4'>, C<'MAT5'>, or C<'MAT73'>.
545  
546 =cut
547  
548 # I am not using this ??
549 # version here means file format, use get_format instead
550 sub get_version {
551 my $self = shift;
552 my $val = _mat_get_version($self->get_handle);
553 $Inv_format_list{$val};
554 }
555  
556 =head2 B<print_all_var_info>
557  
558 =head3 Usage
559  
560 $mat->print_all_var_info;
561  
562 # also print a small amount of data from each variable.
563 $mat->print_all_var_info( data => 1 );
564  
565 Print a summary of all data in the file associated
566 with C<$mat> (starting from the next unread variable.)
567  
568 =cut
569  
570 sub print_all_var_info {
571 my $self = shift;
572 my $len = scalar(@_);
573 my $user_options = {};
574 if ( $len == 1 ) {
575 $user_options = $_[0];
576 }
577 elsif ( $len > 1 ) {
578 my %user_option_hash = @_;
579 $user_options = \%user_option_hash;
580 }
581 my %opts = parse( {data => 0} , $user_options);
582 my $printdata = $opts{data} ? 1 : 0;
583 my $handle = $self->get_handle;
584 _extra_matio_print_all_var_info($handle,$printdata);
585 }
586  
587 #line 650 "matlab.pd"
588 sub get_handle {
589 my $self = shift;
590 barf 'PDL::IO::Matlab::get_handle: handle not defined.' unless
591 defined $self->{handle};
592 $self->{handle};
593 }
594  
595 sub set_handle {
596 my $self = shift;
597 $self->{handle} = shift;
598 }
599
600  
601 sub get_mode {
602 my $self = shift;
603 barf 'PDL::IO::Matlab::get_mode: mode not defined.' unless
604 defined $self->{mode};
605 $self->{mode};
606 }
607  
608 sub set_mode {
609 my $self = shift;
610 $self->{mode} = shift;
611 }
612
613  
614 sub get_filename {
615 my $self = shift;
616 barf 'PDL::IO::Matlab::get_filename: filename not defined.' unless
617 defined $self->{filename};
618 $self->{filename};
619 }
620  
621 sub set_filename {
622 my $self = shift;
623 $self->{filename} = shift;
624 }
625
626  
627 sub get_format {
628 my $self = shift;
629 $self->{format};
630 }
631  
632 sub set_format {
633 my $self = shift;
634 $self->{format} = shift;
635 }
636
637  
638 sub get_varbasew {
639 my $self = shift;
640 barf 'PDL::IO::Matlab::get_varbasew: varbasew not defined.' unless
641 defined $self->{varbasew};
642 $self->{varbasew};
643 }
644  
645 sub set_varbasew {
646 my $self = shift;
647 $self->{varbasew} = shift;
648 }
649
650  
651 sub get_onedw {
652 my $self = shift;
653 barf 'PDL::IO::Matlab::get_onedw: onedw not defined.' unless
654 defined $self->{onedw};
655 $self->{onedw};
656 }
657  
658 sub set_onedw {
659 my $self = shift;
660 $self->{onedw} = shift;
661 }
662
663  
664 sub get_onedr {
665 my $self = shift;
666 barf 'PDL::IO::Matlab::get_onedr: onedr not defined.' unless
667 defined $self->{onedr};
668 $self->{onedr};
669 }
670  
671 sub set_onedr {
672 my $self = shift;
673 $self->{onedr} = shift;
674 }
675
676  
677 sub get_namekey {
678 my $self = shift;
679 barf 'PDL::IO::Matlab::get_namekey: namekey not defined.' unless
680 defined $self->{namekey};
681 $self->{namekey};
682 }
683  
684 sub set_namekey {
685 my $self = shift;
686 $self->{namekey} = shift;
687 }
688
689  
690 sub get_wvarnum {
691 my $self = shift;
692 barf 'PDL::IO::Matlab::get_wvarnum: wvarnum not defined.' unless
693 defined $self->{wvarnum};
694 $self->{wvarnum};
695 }
696  
697 sub set_wvarnum {
698 my $self = shift;
699 $self->{wvarnum} = shift;
700 }
701
702  
703 sub get_compress {
704 my $self = shift;
705 barf 'PDL::IO::Matlab::get_compress: compress not defined.' unless
706 defined $self->{compress};
707 $self->{compress};
708 }
709  
710 sub set_compress {
711 my $self = shift;
712 $self->{compress} = shift;
713 }
714
715  
716 =head1 ACCESSOR METHODS
717  
718 The following are additional accessor methods for the matlab file objects
719 PDL::IO::Matlab.
720  
721 get_handle set_handle get_mode set_mode get_filename set_filename get_format set_format get_varbasew set_varbasew get_onedw set_onedw get_onedr set_onedr get_namekey set_namekey get_wvarnum set_wvarnum get_compress set_compress
722 =cut
723  
724 #line 654 "matlab.pd"
725  
726 =head1 CAVEATS
727  
728 =head2 complicating factors
729  
730 There are two complicating factors when using matlab files with PDL.
731 First, matlab does not support one-dimensional vectors. Thus, a 1-d pdl
732 must be represented as either a C<1 x n> of a C<n x 1> matlab variable. Second,
733 matlab stores matrices in column-major order, while pdl stores them
734 in row-major order.
735  
736 =over
737  
738 =item B<one-dimensional pdls>
739  
740 You can write 1-d pdls to a file with this module. This module can then read the
741 file. But, Octave will fail to read the file and print an error message.
742 See L</B<write>> for how this is handled.
743  
744 =item B<column- vs. row major>
745  
746 Data written by Octave (PDL) will be read by PDL (Octave) with indices transposed.
747 On the todo list is an option to physically or logically transpose the data on
748 reading and writing.
749  
750 =item B<Octave requires distinct matlab variable names>
751  
752 With this module, you may write more than one
753 variable, each with the same name, (the matlab name; not the
754 pdl identifier, or variable, name), to a file in MAT5
755 format. This module is then able to read all pdls from this file.
756 But, Octave, when reading this file, will overwrite all but
757 the last occurrence of the variable with the last
758 occurrence. See the method L</B<write>>.
759  
760 Trying to write two pdls with the same matlab variable name in MAT73 format will cause
761 an error.
762  
763 =back
764  
765 =head2 other missing features, bugs
766  
767 When trying to read an unsupported matlab data type from a file, this module will
768 throw an error. Supporting other data types or optionally skipping them is on
769 the todo list.
770  
771 Random access of variables in a file is on the todo list. The underlying B<matio>
772 library supports this.
773  
774 This module is currently built with some hardcoded data from a PDL installation, that
775 may contain platform-specific (linux) features. It may fail to
776 build or function correctly when used on other platforms.
777  
778 =head1 AUTHOR
779  
780 John Lapeyre, C<< <jlapeyre at cpan.org> >>
781  
782 The matio library was written by Christopher C. Hulbert.
783  
784 =head1 LICENSE AND COPYRIGHT
785  
786 Copyright 2012 John Lapeyre.
787  
788 This program is free software; you can redistribute it and/or modify it
789 under the terms of either: the GNU General Public License as published
790 by the Free Software Foundation; or the Artistic License.
791  
792 See http://dev.perl.org/licenses/ for more information.
793  
794 The matio library included here is
795 Copyright 2011 Christopher C. Hulbert. All rights reserved.
796 See the file matio-1.5/COPYING in the source distribution
797 of this module.
798  
799 =cut
800  
801 # broken
802 #sub print_all_var_info_new {
803 # my $self = shift;
804 # my $handle = $self->get_handle;
805 # _extra_matio_print_all_var_info($handle,1,10,10);
806 #}
807  
808 ###########################################################################
809 #line 810 "Matlab.pm"
810  
811 # Exit with OK status
812  
813 0 1;
« convert_matvar_pdl.c ↑ Summary