changelog shortlog tags changeset files revisions annotate raw

src/ov-cell.cc

changeset 10289: 4b124317dc38
parent:829e69ec3110
author: John W. Eaton <jwe@octave.org>
date: Tue Feb 09 20:58:55 2010 -0500 (39 minutes ago)
permissions: -rw-r--r--
description: base_properties::set_children: account for hidden children
1/*
2
3Copyright (C) 1999, 2000, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
4 John W. Eaton
5
6This file is part of Octave.
7
8Octave is free software; you can redistribute it and/or modify it
9under the terms of the GNU General Public License as published by the
10Free Software Foundation; either version 3 of the License, or (at your
11option) any later version.
12
13Octave is distributed in the hope that it will be useful, but WITHOUT
14ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16for more details.
17
18You should have received a copy of the GNU General Public License
19along with Octave; see the file COPYING. If not, see
20<http://www.gnu.org/licenses/>.
21
22*/
23
24#ifdef HAVE_CONFIG_H
25#include <config.h>
26#endif
27
28#include <iomanip>
29#include <iostream>
30#include <sstream>
31#include <vector>
32#include <queue>
33
34#include "Array-util.h"
35#include "byte-swap.h"
36#include "lo-utils.h"
37#include "quit.h"
38#include "oct-locbuf.h"
39
40#include "defun.h"
41#include "error.h"
42#include "ov-cell.h"
43#include "oct-obj.h"
44#include "unwind-prot.h"
45#include "utils.h"
46#include "ov-base-mat.h"
47#include "ov-base-mat.cc"
48#include "ov-re-mat.h"
49#include "ov-scalar.h"
50#include "pr-output.h"
51#include "ov-scalar.h"
52#include "gripes.h"
53
54#include "ls-oct-ascii.h"
55#include "ls-oct-binary.h"
56#include "ls-hdf5.h"
57#include "ls-utils.h"
58
59// Cell is able to handle octave_value indexing by itself, so just forward
60// everything.
61
62template <>
63octave_value
64octave_base_matrix<Cell>::do_index_op (const octave_value_list& idx,
65 bool resize_ok)
66{
67 return matrix.index (idx, resize_ok);
68}
69
70template <>
71void
72octave_base_matrix<Cell>::assign (const octave_value_list& idx, const Cell& rhs)
73{
74 matrix.assign (idx, rhs);
75}
76
77template <>
78void
79octave_base_matrix<Cell>::assign (const octave_value_list& idx, octave_value rhs)
80{
81 // FIXME: Really?
82 if (rhs.is_cell ())
83 matrix.assign (idx, rhs.cell_value ());
84 else
85 matrix.assign (idx, Cell (rhs));
86}
87
88template <>
89void
90octave_base_matrix<Cell>::delete_elements (const octave_value_list& idx)
91{
92 matrix.delete_elements (idx);
93}
94
95template class octave_base_matrix<Cell>;
96
97DEFINE_OCTAVE_ALLOCATOR (octave_cell);
98
99DEFINE_OV_TYPEID_FUNCTIONS_AND_DATA (octave_cell, "cell", "cell");
100
101static void
102gripe_failed_assignment (void)
103{
104 error ("assignment to cell array failed");
105}
106
107octave_value_list
108octave_cell::subsref (const std::string& type,
109 const std::list<octave_value_list>& idx,
110 int nargout)
111{
112 octave_value_list retval;
113
114 switch (type[0])
115 {
116 case '(':
117 retval(0) = do_index_op (idx.front ());
118 break;
119
120 case '{':
121 {
122 octave_value tmp = do_index_op (idx.front ());
123
124 if (! error_state)
125 {
126 Cell tcell = tmp.cell_value ();
127
128 if (tcell.length () == 1)
129 retval(0) = tcell(0,0);
130 else
131 retval = octave_value (octave_value_list (tcell), true);
132 }
133 }
134 break;
135
136 case '.':
137 {
138 std::string nm = type_name ();
139 error ("%s cannot be indexed with %c", nm.c_str (), type[0]);
140 }
141 break;
142
143 default:
144 panic_impossible ();
145 }
146
147 // FIXME -- perhaps there should be an
148 // octave_value_list::next_subsref member function? See also
149 // octave_user_function::subsref.
150
151 if (idx.size () > 1)
152 retval = retval(0).next_subsref (nargout, type, idx);
153
154 return retval;
155}
156
157octave_value
158octave_cell::subsref (const std::string& type,
159 const std::list<octave_value_list>& idx,
160 bool auto_add)
161{
162 octave_value retval;
163
164 switch (type[0])
165 {
166 case '(':
167 retval = do_index_op (idx.front (), auto_add);
168 break;
169
170 case '{':
171 {
172 octave_value tmp = do_index_op (idx.front (), auto_add);
173
174 if (! error_state)
175 {
176 const Cell tcell = tmp.cell_value ();
177
178 if (tcell.length () == 1)
179 retval = tcell(0,0);
180 else
181 retval = octave_value (octave_value_list (tcell), true);
182 }
183 }
184 break;
185
186 case '.':
187 {
188 std::string nm = type_name ();
189 error ("%s cannot be indexed with %c", nm.c_str (), type[0]);
190 }
191 break;
192
193 default:
194 panic_impossible ();
195 }
196
197 // FIXME -- perhaps there should be an
198 // octave_value_list::next_subsref member function? See also
199 // octave_user_function::subsref.
200
201 if (idx.size () > 1)
202 retval = retval.next_subsref (auto_add, type, idx);
203
204 return retval;
205}
206
207octave_value
208octave_cell::subsasgn (const std::string& type,
209 const std::list<octave_value_list>& idx,
210 const octave_value& rhs)
211{
212 octave_value retval;
213
214 int n = type.length ();
215
216 octave_value t_rhs = rhs;
217
218 clear_cellstr_cache ();
219
220 if (idx.front ().empty ())
221 {
222 error ("missing index in indexed assignment");
223 return retval;
224 }
225
226 if (n > 1)
227 {
228 switch (type[0])
229 {
230 case '(':
231 {
232 if (is_empty () && type[1] == '.')
233 {
234 // Allow conversion of empty cell array to some other
235 // type in cases like
236 //
237 // x = []; x(i).f = rhs
238
239 octave_value tmp = octave_value::empty_conv (type, rhs);
240
241 return tmp.subsasgn (type, idx, rhs);
242 }
243 else
244 {
245 octave_value tmp = do_index_op (idx.front (), true);
246
247 if (! tmp.is_defined ())
248 tmp = octave_value::empty_conv (type.substr (1), rhs);
249
250 if (! error_state)
251 {
252 std::list<octave_value_list> next_idx (idx);
253
254 next_idx.erase (next_idx.begin ());
255
256 tmp.make_unique ();
257
258 t_rhs = tmp.subsasgn (type.substr (1), next_idx, rhs);
259 }
260 }
261 }
262 break;
263
264 case '{':
265 {
266 matrix.make_unique ();
267 Cell tmpc = matrix.index (idx.front (), true);
268
269 if (! error_state)
270 {
271 std::list<octave_value_list> next_idx (idx);
272
273 next_idx.erase (next_idx.begin ());
274
275 std::string next_type = type.substr (1);
276
277 if (tmpc.numel () == 1)
278 {
279 octave_value tmp = tmpc(0);
280 tmpc = Cell ();
281
282 if (! tmp.is_defined () || tmp.is_zero_by_zero ())
283 {
284 tmp = octave_value::empty_conv (type.substr (1), rhs);
285 tmp.make_unique (); // probably a no-op.
286 }
287 else
288 // optimization: ignore the copy still stored inside our array.
289 tmp.make_unique (1);
290
291 if (! error_state)
292 t_rhs = tmp.subsasgn (next_type, next_idx, rhs);
293 }
294 else
295 gripe_indexed_cs_list ();
296 }
297 }
298 break;
299
300 case '.':
301 {
302 std::string nm = type_name ();
303 error ("%s cannot be indexed with %c", nm.c_str (), type[0]);
304 }
305 break;
306
307 default:
308 panic_impossible ();
309 }
310 }
311
312 if (! error_state)
313 {
314 switch (type[0])
315 {
316 case '(':
317 {
318 octave_value_list i = idx.front ();
319
320 if (t_rhs.is_cell ())
321 octave_base_matrix<Cell>::assign (i, t_rhs.cell_value ());
322 else
323 if (t_rhs.is_null_value ())
324 octave_base_matrix<Cell>::delete_elements (i);
325 else
326 octave_base_matrix<Cell>::assign (i, Cell (t_rhs));
327
328 if (! error_state)
329 {
330 count++;
331 retval = octave_value (this);
332 }
333 else
334 gripe_failed_assignment ();
335 }
336 break;
337
338 case '{':
339 {
340 octave_value_list idxf = idx.front ();
341
342 if (t_rhs.is_cs_list ())
343 {
344 Cell tmp_cell = Cell (t_rhs.list_value ());
345
346 // Inquire the proper shape of the RHS.
347
348 dim_vector didx = dims ().redim (idxf.length ());
349 for (octave_idx_type k = 0; k < idxf.length (); k++)
350 if (! idxf(k).is_magic_colon ()) didx(k) = idxf(k).numel ();
351
352 if (didx.numel () == tmp_cell.numel ())
353 tmp_cell = tmp_cell.reshape (didx);
354
355
356 octave_base_matrix<Cell>::assign (idxf, tmp_cell);
357 }
358 else if (idxf.all_scalars () || do_index_op (idxf, true).numel () == 1)
359 // Regularize a null matrix if stored into a cell.
360 octave_base_matrix<Cell>::assign (idxf, Cell (t_rhs.storable_value ()));
361 else if (! error_state)
362 gripe_nonbraced_cs_list_assignment ();
363
364 if (! error_state)
365 {
366 count++;
367 retval = octave_value (this);
368 }
369 else
370 gripe_failed_assignment ();
371 }
372 break;
373
374 case '.':
375 {
376 std::string nm = type_name ();
377 error ("%s cannot be indexed with %c", nm.c_str (), type[0]);
378 }
379 break;
380
381 default:
382 panic_impossible ();
383 }
384 }
385
386 return retval;
387}
388
389bool
390octave_cell::is_cellstr (void) const
391{
392 bool retval;
393 if (cellstr_cache.get ())
394 retval = true;
395 else
396 {
397 retval = matrix.is_cellstr ();
398 // Allocate empty cache to mark that this is indeed a cellstr.
399 if (retval)
400 cellstr_cache.reset (new Array<std::string> ());
401 }
402
403 return retval;
404}
405
406void
407octave_cell::assign (const octave_value_list& idx, const Cell& rhs)
408{
409 clear_cellstr_cache ();
410 octave_base_matrix<Cell>::assign (idx, rhs);
411}
412
413void
414octave_cell::assign (const octave_value_list& idx, const octave_value& rhs)
415{
416 clear_cellstr_cache ();
417 octave_base_matrix<Cell>::assign (idx, rhs);
418}
419
420
421void
422octave_cell::delete_elements (const octave_value_list& idx)
423{
424 clear_cellstr_cache ();
425 octave_base_matrix<Cell>::delete_elements (idx);
426}
427
428size_t
429octave_cell::byte_size (void) const
430{
431 size_t retval = 0;
432
433 for (octave_idx_type i = 0; i < numel (); i++)
434 retval += matrix(i).byte_size ();
435
436 return retval;
437}
438
439octave_value
440octave_cell::sort (octave_idx_type dim, sortmode mode) const
441{
442 octave_value retval;
443
444 if (is_cellstr ())
445 {
446 Array<std::string> tmp = cellstr_value ();
447
448 tmp = tmp.sort (dim, mode);
449
450 // We already have the cache.
451 retval = new octave_cell (tmp);
452 }
453 else
454 error ("sort: only cell arrays of character strings may be sorted");
455
456 return retval;
457}
458
459octave_value
460octave_cell::sort (Array<octave_idx_type> &sidx, octave_idx_type dim,
461 sortmode mode) const
462{
463 octave_value retval;
464
465 if (is_cellstr ())
466 {
467 Array<std::string> tmp = cellstr_value ();
468
469 tmp = tmp.sort (sidx, dim, mode);
470
471 // We already have the cache.
472 retval = new octave_cell (tmp);
473 }
474 else
475 error ("sort: only cell arrays of character strings may be sorted");
476
477 return retval;
478}
479
480sortmode
481octave_cell::is_sorted (sortmode mode) const
482{
483 sortmode retval = UNSORTED;
484
485 if (is_cellstr ())
486 {
487 Array<std::string> tmp = cellstr_value ();
488
489 retval = tmp.is_sorted (mode);
490 }
491 else
492 error ("issorted: not a cell array of strings");
493
494 return retval;
495}
496
497
498Array<octave_idx_type>
499octave_cell::sort_rows_idx (sortmode mode) const
500{
501 Array<octave_idx_type> retval;
502
503 if (is_cellstr ())
504 {
505 Array<std::string> tmp = cellstr_value ();
506
507 retval = tmp.sort_rows_idx (mode);
508 }
509 else
510 error ("sortrows: only cell arrays of character strings may be sorted");
511
512 return retval;
513}
514
515sortmode
516octave_cell::is_sorted_rows (sortmode mode) const
517{
518 sortmode retval = UNSORTED;
519
520 if (is_cellstr ())
521 {
522 Array<std::string> tmp = cellstr_value ();
523
524 retval = tmp.is_sorted_rows (mode);
525 }
526 else
527 error ("issorted: not a cell array of strings");
528
529 return retval;
530}
531
532bool
533octave_cell::is_true (void) const
534{
535 error ("invalid conversion from cell array to logical value");
536 return false;
537}
538
539octave_value_list
540octave_cell::list_value (void) const
541{
542 return octave_value_list (matrix);
543}
544
545string_vector
546octave_cell::all_strings (bool pad) const
547{
548 string_vector retval;
549
550 octave_idx_type nel = numel ();
551
552 int n_elts = 0;
553
554 octave_idx_type max_len = 0;
555
556 std::queue<string_vector> strvec_queue;
557
558 for (octave_idx_type i = 0; i < nel; i++)
559 {
560 string_vector s = matrix(i).all_strings ();
561
562 if (error_state)
563 return retval;
564
565 octave_idx_type s_len = s.length ();
566
567 n_elts += s_len ? s_len : 1;
568
569 octave_idx_type s_max_len = s.max_length ();
570
571 if (s_max_len > max_len)
572 max_len = s_max_len;
573
574 strvec_queue.push (s);
575 }
576
577 retval = string_vector (n_elts);
578
579 octave_idx_type k = 0;
580
581 for (octave_idx_type i = 0; i < nel; i++)
582 {
583 const string_vector s = strvec_queue.front ();
584 strvec_queue.pop ();
585
586 octave_idx_type s_len = s.length ();
587
588 if (s_len)
589 {
590 for (octave_idx_type j = 0; j < s_len; j++)
591 {
592 std::string t = s[j];
593 int t_len = t.length ();
594
595 if (pad && max_len > t_len)
596 t += std::string (max_len - t_len, ' ');
597
598 retval[k++] = t;
599 }
600 }
601 else if (pad)
602 retval[k++] = std::string (max_len, ' ');
603 else
604 retval[k++] = std::string ();
605 }
606
607 return retval;
608}
609
610Array<std::string>
611octave_cell::cellstr_value (void) const
612{
613 Array<std::string> retval;
614
615 if (is_cellstr ())
616 {
617 if (cellstr_cache->is_empty ())
618 *cellstr_cache = matrix.cellstr_value ();
619
620 return *cellstr_cache;
621 }
622 else
623 error ("invalid conversion from cell array to array of strings");
624
625 return retval;
626}
627
628bool
629octave_cell::print_as_scalar (void) const
630{
631 return (ndims () > 2 || numel () == 0);
632}
633
634void
635octave_cell::print (std::ostream& os, bool) const
636{
637 print_raw (os);
638}
639
640void
641octave_cell::print_raw (std::ostream& os, bool) const
642{
643 int nd = matrix.ndims ();
644
645 if (nd == 2)
646 {
647 octave_idx_type nr = rows ();
648 octave_idx_type nc = columns ();
649
650 if (nr > 0 && nc > 0)
651 {
652 indent (os);
653 os << "{";
654 newline (os);
655
656 increment_indent_level ();
657
658 for (octave_idx_type j = 0; j < nc; j++)
659 {
660 for (octave_idx_type i = 0; i < nr; i++)
661 {
662 octave_quit ();
663
664 std::ostringstream buf;
665 buf << "[" << i+1 << "," << j+1 << "]";
666
667 octave_value val = matrix(i,j);
668
669 val.print_with_name (os, buf.str ());
670 }
671 }
672
673 decrement_indent_level ();
674
675 indent (os);
676 os << "}";
677 newline (os);
678 }
679 else
680 {
681 indent (os);
682 os << "{}";
683 if (Vprint_empty_dimensions)
684 os << "(" << nr << "x" << nc << ")";
685 newline (os);
686 }
687 }
688 else
689 {
690 indent (os);
691 dim_vector dv = matrix.dims ();
692 os << "{" << dv.str () << " Cell Array}";
693 newline (os);
694 }
695}
696
697#define CELL_ELT_TAG "<cell-element>"
698
699bool
700octave_cell::save_ascii (std::ostream& os)
701{
702 dim_vector d = dims ();
703 if (d.length () > 2)
704 {
705 os << "# ndims: " << d.length () << "\n";
706
707 for (int i = 0; i < d.length (); i++)
708 os << " " << d (i);
709 os << "\n";
710
711 Cell tmp = cell_value ();
712
713 for (octave_idx_type i = 0; i < d.numel (); i++)
714 {
715 octave_value o_val = tmp.elem (i);
716
717 // Recurse to print sub-value.
718 bool b = save_ascii_data (os, o_val, CELL_ELT_TAG, false, 0);
719
720 if (! b)
721 return os;
722 }
723 }
724 else
725 {
726 // Keep this case, rather than use generic code above for backward
727 // compatiability. Makes load_ascii much more complex!!
728 os << "# rows: " << rows () << "\n"
729 << "# columns: " << columns () << "\n";
730
731 Cell tmp = cell_value ();
732
733 for (octave_idx_type j = 0; j < tmp.cols (); j++)
734 {
735 for (octave_idx_type i = 0; i < tmp.rows (); i++)
736 {
737 octave_value o_val = tmp.elem (i, j);
738
739 // Recurse to print sub-value.
740 bool b = save_ascii_data (os, o_val, CELL_ELT_TAG, false, 0);
741
742 if (! b)
743 return os;
744 }
745
746 os << "\n";
747 }
748 }
749
750 return true;
751}
752
753bool
754octave_cell::load_ascii (std::istream& is)
755{
756 bool success = true;
757
758 clear_cellstr_cache ();
759
760 string_vector keywords(2);
761
762 keywords[0] = "ndims";
763 keywords[1] = "rows";
764
765 std::string kw;
766 octave_idx_type val = 0;
767
768 if (extract_keyword (is, keywords, kw, val, true))
769 {
770 if (kw == "ndims")
771 {
772 int mdims = static_cast<int> (val);
773
774 if (mdims >= 0)
775 {
776 dim_vector dv;
777 dv.resize (mdims);
778
779 for (int i = 0; i < mdims; i++)
780 is >> dv(i);
781
782 Cell tmp(dv);
783
784 for (octave_idx_type i = 0; i < dv.numel (); i++)
785 {
786 octave_value t2;
787 bool dummy;
788
789 // recurse to read cell elements
790 std::string nm = read_ascii_data (is, std::string (),
791 dummy, t2, i);
792
793 if (nm == CELL_ELT_TAG)
794 {
795 if (is)
796 tmp.elem (i) = t2;
797 }
798 else
799 {
800 error ("load: cell array element had unexpected name");
801 success = false;
802 break;
803 }
804 }
805
806 if (is)
807 matrix = tmp;
808 else
809 {
810 error ("load: failed to load matrix constant");
811 success = false;
812 }
813 }
814 else
815 {
816 error ("load: failed to extract number of rows and columns");
817 success = false;
818 }
819 }
820 else if (kw == "rows")
821 {
822 octave_idx_type nr = val;
823 octave_idx_type nc = 0;
824
825 if (nr >= 0 && extract_keyword (is, "columns", nc) && nc >= 0)
826 {
827 if (nr > 0 && nc > 0)
828 {
829 Cell tmp (nr, nc);
830
831 for (octave_idx_type j = 0; j < nc; j++)
832 {
833 for (octave_idx_type i = 0; i < nr; i++)
834 {
835 octave_value t2;
836 bool dummy;
837
838 // recurse to read cell elements
839 std::string nm = read_ascii_data (is, std::string (),
840 dummy, t2, i);
841
842 if (nm == CELL_ELT_TAG)
843 {
844 if (is)
845 tmp.elem (i, j) = t2;
846 }
847 else
848 {
849 error ("load: cell array element had unexpected name");
850 success = false;
851 goto cell_read_error;
852 }
853 }
854 }
855
856 cell_read_error:
857
858 if (is)
859 matrix = tmp;
860 else
861 {
862 error ("load: failed to load cell element");
863 success = false;
864 }
865 }
866 else if (nr == 0 || nc == 0)
867 matrix = Cell (nr, nc);
868 else
869 panic_impossible ();
870 }
871 else
872 {
873 error ("load: failed to extract number of rows and columns for cell array");
874 success = false;
875 }
876 }
877 else
878 panic_impossible ();
879 }
880 else
881 {
882 error ("load: failed to extract number of rows and columns");
883 success = false;
884 }
885
886 return success;
887}
888
889bool
890octave_cell::save_binary (std::ostream& os, bool& save_as_floats)
891{
892 dim_vector d = dims ();
893 if (d.length () < 1)
894 return false;
895
896 // Use negative value for ndims
897 int32_t di = - d.length();
898 os.write (reinterpret_cast<char *> (&di), 4);
899 for (int i = 0; i < d.length (); i++)
900 {
901 di = d(i);
902 os.write (reinterpret_cast<char *> (&di), 4);
903 }
904
905 Cell tmp = cell_value ();
906
907 for (octave_idx_type i = 0; i < d.numel (); i++)
908 {
909 octave_value o_val = tmp.elem (i);
910
911 // Recurse to print sub-value.
912 bool b = save_binary_data (os, o_val, CELL_ELT_TAG, "", 0,
913 save_as_floats);
914
915 if (! b)
916 return false;
917 }
918
919 return true;
920}
921
922bool
923octave_cell::load_binary (std::istream& is, bool swap,
924 oct_mach_info::float_format fmt)
925{
926 clear_cellstr_cache ();
927
928 bool success = true;
929 int32_t mdims;
930 if (! is.read (reinterpret_cast<char *> (&mdims), 4))
931 return false;
932 if (swap)
933 swap_bytes<4> (&mdims);
934 if (mdims >= 0)
935 return false;
936
937 mdims = -mdims;
938 int32_t di;
939 dim_vector dv;
940 dv.resize (mdims);
941
942 for (int i = 0; i < mdims; i++)
943 {
944 if (! is.read (reinterpret_cast<char *> (&di), 4))
945 return false;
946 if (swap)
947 swap_bytes<4> (&di);
948 dv(i) = di;
949 }
950
951 // Convert an array with a single dimension to be a row vector.
952 // Octave should never write files like this, other software
953 // might.
954
955 if (mdims == 1)
956 {
957 mdims = 2;
958 dv.resize (mdims);
959 dv(1) = dv(0);
960 dv(0) = 1;
961 }
962
963 octave_idx_type nel = dv.numel ();
964 Cell tmp(dv);
965
966 for (octave_idx_type i = 0; i < nel; i++)
967 {
968 octave_value t2;
969 bool dummy;
970 std::string doc;
971
972 // recurse to read cell elements
973 std::string nm = read_binary_data (is, swap, fmt, std::string (),
974 dummy, t2, doc);
975
976 if (nm == CELL_ELT_TAG)
977 {
978 if (is)
979 tmp.elem (i) = t2;
980 }
981 else
982 {
983 error ("load: cell array element had unexpected name");
984 success = false;
985 break;
986 }
987 }
988
989 if (is)
990 matrix = tmp;
991 else
992 {
993 error ("load: failed to load matrix constant");
994 success = false;
995 }
996
997 return success;
998}
999
1000void *
1001octave_cell::mex_get_data (void) const
1002{
1003 clear_cellstr_cache ();
1004 return matrix.mex_get_data ();
1005}
1006
1007#if defined (HAVE_HDF5)
1008
1009bool
1010octave_cell::save_hdf5 (hid_t loc_id, const char *name, bool save_as_floats)
1011{
1012 dim_vector dv = dims ();
1013 int empty = save_hdf5_empty (loc_id, name, dv);
1014 if (empty)
1015 return (empty > 0);
1016
1017 hsize_t rank = dv.length ();
1018 hid_t space_hid = -1, data_hid = -1, size_hid = -1;
1019
1020#if HAVE_HDF5_18
1021 data_hid = H5Gcreate (loc_id, name, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
1022#else
1023 data_hid = H5Gcreate (loc_id, name, 0);
1024#endif
1025
1026 if (data_hid < 0)
1027 return false;
1028
1029 // Have to save cell array shape, since can't have a
1030 // dataset of groups....
1031
1032 space_hid = H5Screate_simple (1, &rank, 0);
1033
1034 if (space_hid < 0)
1035 {
1036 H5Gclose (data_hid);
1037 return false;
1038 }
1039
1040 OCTAVE_LOCAL_BUFFER (octave_idx_type, hdims, rank);
1041
1042 // Octave uses column-major, while HDF5 uses row-major ordering
1043 for (hsize_t i = 0; i < rank; i++)
1044 hdims[i] = dv(rank-i-1);
1045
1046#if HAVE_HDF5_18
1047 size_hid = H5Dcreate (data_hid, "dims", H5T_NATIVE_IDX, space_hid,
1048 H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
1049#else
1050 size_hid = H5Dcreate (data_hid, "dims", H5T_NATIVE_IDX, space_hid,
1051 H5P_DEFAULT);
1052#endif
1053 if (size_hid < 0)
1054 {
1055 H5Sclose (space_hid);
1056 H5Gclose (data_hid);
1057 return false;
1058 }
1059
1060 if (H5Dwrite (size_hid, H5T_NATIVE_IDX, H5S_ALL, H5S_ALL,
1061 H5P_DEFAULT, hdims) < 0)
1062 {
1063 H5Dclose (size_hid);
1064 H5Sclose (space_hid);
1065 H5Gclose (data_hid);
1066 return false;
1067 }
1068
1069 H5Dclose (size_hid);
1070 H5Sclose (space_hid);
1071
1072 // Recursively add each element of the cell to this group.
1073
1074 Cell tmp = cell_value ();
1075
1076 octave_idx_type nel = dv.numel ();
1077
1078 for (octave_idx_type i = 0; i < nel; i++)
1079 {
1080 std::ostringstream buf;
1081 int digits = static_cast<int> (::floor (::log10 (static_cast<double> (nel)) + 1.0));
1082 buf << "_" << std::setw (digits) << std::setfill ('0') << i;
1083 std::string s = buf.str ();
1084
1085 if (! add_hdf5_data (data_hid, tmp.elem (i), s.c_str (), "", false,
1086 save_as_floats))
1087 {
1088 H5Gclose (data_hid);
1089 return false;
1090 }
1091 }
1092
1093 H5Gclose (data_hid);
1094
1095 return true;
1096}
1097
1098bool
1099octave_cell::load_hdf5 (hid_t loc_id, const char *name)
1100{
1101 clear_cellstr_cache ();
1102
1103 bool retval = false;
1104
1105 dim_vector dv;
1106 int empty = load_hdf5_empty (loc_id, name, dv);
1107 if (empty > 0)
1108 matrix.resize(dv);
1109 if (empty)
1110 return (empty > 0);
1111
1112#if HAVE_HDF5_18
1113 hid_t group_id = H5Gopen (loc_id, name, H5P_DEFAULT);
1114#else
1115 hid_t group_id = H5Gopen (loc_id, name);
1116#endif
1117
1118 if (group_id < 0)
1119 return false;
1120
1121#if HAVE_HDF5_18
1122 hid_t data_hid = H5Dopen (group_id, "dims", H5P_DEFAULT);
1123#else
1124 hid_t data_hid = H5Dopen (group_id, "dims");
1125#endif
1126 hid_t space_hid = H5Dget_space (data_hid);
1127 hsize_t rank = H5Sget_simple_extent_ndims (space_hid);
1128 if (rank != 1)
1129 {
1130 H5Dclose (data_hid);
1131 H5Gclose (group_id);
1132 return false;
1133 }
1134
1135 OCTAVE_LOCAL_BUFFER (hsize_t, hdims, rank);
1136 OCTAVE_LOCAL_BUFFER (hsize_t, maxdims, rank);
1137
1138 H5Sget_simple_extent_dims (space_hid, hdims, maxdims);
1139
1140 // Octave uses column-major, while HDF5 uses row-major ordering.
1141
1142 dv.resize (hdims[0]);
1143
1144 OCTAVE_LOCAL_BUFFER (octave_idx_type, tmp, hdims[0]);
1145
1146 if (H5Dread (data_hid, H5T_NATIVE_IDX, H5S_ALL, H5S_ALL,
1147 H5P_DEFAULT, tmp) < 0)
1148 {
1149 H5Dclose (data_hid);
1150 H5Gclose (group_id);
1151 return false;
1152 }
1153
1154 H5Dclose (data_hid);
1155 H5Gclose (group_id);
1156
1157 for (hsize_t i = 0, j = hdims[0] - 1; i < hdims[0]; i++, j--)
1158 dv(j) = tmp[i];
1159
1160 hdf5_callback_data dsub;
1161
1162 herr_t retval2 = -1;
1163
1164 Cell m (dv);
1165
1166 int current_item = 0;
1167
1168 hsize_t num_obj = 0;
1169#if HAVE_HDF5_18
1170 group_id = H5Gopen (loc_id, name, H5P_DEFAULT);
1171#else
1172 group_id = H5Gopen (loc_id, name);
1173#endif
1174 H5Gget_num_objs (group_id, &num_obj);
1175 H5Gclose (group_id);
1176
1177 for (octave_idx_type i = 0; i < dv.numel (); i++)
1178 {
1179
1180 if (current_item >= static_cast<int> (num_obj))
1181 retval2 = -1;
1182 else
1183 retval2 = H5Giterate (loc_id, name, &current_item,
1184 hdf5_read_next_data, &dsub);
1185
1186 if (retval2 <= 0)
1187 break;
1188
1189 octave_value ov = dsub.tc;
1190 m.elem (i) = ov;
1191
1192 }
1193
1194 if (retval2 >= 0)
1195 {
1196 matrix = m;
1197 retval = true;
1198 }
1199
1200 return retval;
1201}
1202
1203#endif
1204
1205DEFUN (iscell, args, ,
1206 "-*- texinfo -*-\n\
1207@deftypefn {Built-in Function} {} iscell (@var{x})\n\
1208Return true if @var{x} is a cell array object. Otherwise, return\n\
1209false.\n\
1210@end deftypefn")
1211{
1212 octave_value retval;
1213
1214 if (args.length () == 1)
1215 retval = args(0).is_cell ();
1216 else
1217 print_usage ();
1218
1219 return retval;
1220}
1221
1222DEFUN (cell, args, ,
1223 "-*- texinfo -*-\n\
1224@deftypefn {Built-in Function} {} cell (@var{x})\n\
1225@deftypefnx {Built-in Function} {} cell (@var{n}, @var{m})\n\
1226Create a new cell array object. If invoked with a single scalar\n\
1227argument, @code{cell} returns a square cell array with the dimension\n\
1228specified. If you supply two scalar arguments, @code{cell} takes\n\
1229them to be the number of rows and columns. If given a vector with two\n\
1230elements, @code{cell} uses the values of the elements as the number of\n\
1231rows and columns, respectively.\n\
1232@end deftypefn")
1233{
1234 octave_value retval;
1235
1236 int nargin = args.length ();
1237
1238 dim_vector dims;
1239
1240 switch (nargin)
1241 {
1242 case 0:
1243 dims = dim_vector (0, 0);
1244 break;
1245
1246 case 1:
1247 get_dimensions (args(0), "cell", dims);
1248 break;
1249
1250 default:
1251 {
1252 dims.resize (nargin);
1253
1254 for (int i = 0; i < nargin; i++)
1255 {
1256 dims(i) = args(i).is_empty () ? 0 : args(i).nint_value ();
1257
1258 if (error_state)
1259 {
1260 error ("cell: expecting scalar arguments");
1261 break;
1262 }
1263 }
1264 }
1265 break;
1266 }
1267
1268 if (! error_state)
1269 {
1270 dims.chop_trailing_singletons ();
1271
1272 check_dimensions (dims, "cell");
1273
1274 if (! error_state)
1275 retval = Cell (dims, Matrix ());
1276 }
1277
1278 return retval;
1279}
1280
1281DEFUN (iscellstr, args, ,
1282 "-*- texinfo -*-\n\
1283@deftypefn {Built-in Function} {} iscellstr (@var{cell})\n\
1284Return true if every element of the cell array @var{cell} is a\n\
1285character string\n\
1286@end deftypefn")
1287{
1288 octave_value retval;
1289
1290 if (args.length () == 1)
1291 retval = args(0).is_cellstr ();
1292 else
1293 print_usage ();
1294
1295 return retval;
1296}
1297
1298// Note that since Fcellstr calls Fiscellstr, we need to have
1299// Fiscellstr defined first (to provide a declaration) and also we
1300// should keep it in the same file (so we don't have to provide a
1301// declaration) and so we don't have to use feval to call it.
1302
1303DEFUN (cellstr, args, ,
1304 "-*- texinfo -*-\n\
1305@deftypefn {Built-in Function} {} cellstr (@var{string})\n\
1306Create a new cell array object from the elements of the string\n\
1307array @var{string}.\n\
1308@end deftypefn")
1309{
1310 octave_value retval;
1311
1312 if (args.length () == 1)
1313 {
1314 octave_value_list tmp = Fiscellstr (args, 1);
1315
1316 if (tmp(0).is_true ())
1317 retval = args(0);
1318 else
1319 {
1320 string_vector s = args(0).all_strings ();
1321
1322 if (! error_state)
1323 retval = (s.is_empty ()
1324 ? Cell (octave_value (std::string ()))
1325 : Cell (s, true));
1326 else
1327 error ("cellstr: expecting argument to be a 2-d character array");
1328 }
1329 }
1330 else
1331 print_usage ();
1332
1333 return retval;
1334}
1335
1336DEFUN (struct2cell, args, ,
1337 "-*- texinfo -*-\n\
1338@deftypefn {Built-in Function} {} struct2cell (@var{S})\n\
1339Create a new cell array from the objects stored in the struct object.\n\
1340If @var{f} is the number of fields in the structure, the resulting\n\
1341cell array will have a dimension vector corresponding to\n\
1342@code{[@var{F} size(@var{S})]}. For example:\n\
1343\n\
1344@example\n\
1345@group\n\
1346 s = struct('name', @{'Peter', 'Hannah', 'Robert'@}, 'age', @{23, 16, 3@});\n\
1347 c = struct2cell(s)\n\
1348 @result{} c = @{1x1x3 Cell Array@}\n\
1349 c(1,1,:)(:)\n\
1350 @result{} ans =\n\
1351 @{\n\
1352 [1,1] = Peter\n\
1353 [2,1] = Hannah\n\
1354 [3,1] = Robert\n\
1355 @}\n\
1356 c(2,1,:)(:)\n\
1357 @result{} ans =\n\
1358 @{\n\
1359 [1,1] = 23\n\
1360 [2,1] = 16\n\
1361 [3,1] = 3\n\
1362 @}\n\
1363@end group\n\
1364@end example\n\
1365\n\
1366@seealso{cell2struct, fieldnames}\n\
1367@end deftypefn")
1368{
1369 octave_value retval;
1370
1371 int nargin = args.length ();
1372
1373 if (nargin == 1)
1374 {
1375 Octave_map m = args(0).map_value ();
1376
1377 if (! error_state)
1378 {
1379 dim_vector m_dv = m.dims ();
1380
1381 string_vector keys = m.keys ();
1382
1383 octave_idx_type num_fields = keys.length ();
1384
1385 // The resulting dim_vector should have dimensions:
1386 // [numel(fields) size(struct)]
1387 // except if the struct is a column vector.
1388
1389 dim_vector result_dv;
1390 if (m_dv (m_dv.length () - 1) == 1)
1391 result_dv.resize (m_dv.length ());
1392 else
1393 result_dv.resize (m_dv.length () + 1); // Add 1 for the fields.
1394
1395 result_dv(0) = num_fields;
1396
1397 for (int i = 1; i < result_dv.length (); i++)
1398 result_dv(i) = m_dv(i-1);
1399
1400 Cell c (result_dv);
1401
1402 octave_idx_type n_elts = m.numel ();
1403
1404 for (octave_idx_type j = 0; j < num_fields; j++)
1405 {
1406 octave_idx_type k = j;
1407
1408 const Cell vals = m.contents (keys(j));
1409
1410 for (octave_idx_type i = 0; i < n_elts; i++)
1411 {
1412 c(k) = vals(i);
1413 k += num_fields;
1414 }
1415 }
1416
1417 retval = c;
1418 }
1419 else
1420 error ("struct2cell: expecting argument to be a cell array");
1421 }
1422 else
1423 print_usage ();
1424
1425 return retval;
1426}
1427
1428/*
1429%!test
1430%! keys = cellstr (char (floor (rand (11,10)*24+65)))';
1431%! vals = cellfun(@(x) mat2cell(rand (19,1), ones (19,1), 1), ...
1432%! mat2cell([1:11]', ones(11,1), 1), "uniformoutput", false)';
1433%! s = struct ([keys; vals]{:});
1434%! t = cell2struct ([vals{:}], keys, 2);
1435%! assert (s, t);
1436%! assert (struct2cell (s), [vals{:}]');
1437%! assert (fieldnames (s), keys');
1438*/
1439
1440mxArray *
1441octave_cell::as_mxArray (void) const
1442{
1443 mxArray *retval = new mxArray (dims ());
1444
1445 mxArray **elts = static_cast<mxArray **> (retval->get_data ());
1446
1447 mwSize nel = numel ();
1448
1449 const octave_value *p = matrix.data ();
1450
1451 for (mwIndex i = 0; i < nel; i++)
1452 elts[i] = new mxArray (p[i]);
1453
1454 return retval;
1455}
1456
1457octave_value
1458octave_cell::map (unary_mapper_t umap) const
1459{
1460 switch (umap)
1461 {
1462#define FORWARD_MAPPER(UMAP) \
1463 case umap_ ## UMAP: \
1464 return matrix.UMAP ()
1465 FORWARD_MAPPER (xisalnum);
1466 FORWARD_MAPPER (xisalpha);
1467 FORWARD_MAPPER (xisascii);
1468 FORWARD_MAPPER (xiscntrl);
1469 FORWARD_MAPPER (xisdigit);
1470 FORWARD_MAPPER (xisgraph);
1471 FORWARD_MAPPER (xislower);
1472 FORWARD_MAPPER (xisprint);
1473 FORWARD_MAPPER (xispunct);
1474 FORWARD_MAPPER (xisspace);
1475 FORWARD_MAPPER (xisupper);
1476 FORWARD_MAPPER (xisxdigit);
1477 FORWARD_MAPPER (xtoascii);
1478 FORWARD_MAPPER (xtolower);
1479 FORWARD_MAPPER (xtoupper);
1480
1481 default:
1482 return octave_base_value::map (umap);
1483 }
1484}