001/*-
002 *******************************************************************************
003 * Copyright (c) 2011, 2016 Diamond Light Source Ltd.
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *    Peter Chang - initial API and implementation and/or initial documentation
011 *******************************************************************************/
012
013package org.eclipse.january.dataset;
014
015import java.io.IOException;
016import java.io.Serializable;
017import java.lang.annotation.Annotation;
018import java.lang.reflect.Field;
019import java.util.ArrayList;
020import java.util.Arrays;
021import java.util.HashMap;
022import java.util.LinkedList;
023import java.util.List;
024import java.util.Map;
025import java.util.Objects;
026
027import org.eclipse.january.DatasetException;
028import org.eclipse.january.IMonitor;
029import org.eclipse.january.io.ILazyLoader;
030import org.eclipse.january.metadata.MetadataFactory;
031import org.eclipse.january.metadata.MetadataType;
032import org.eclipse.january.metadata.OriginMetadata;
033import org.eclipse.january.metadata.Reshapeable;
034import org.eclipse.january.metadata.Sliceable;
035import org.eclipse.january.metadata.Transposable;
036import org.slf4j.Logger;
037import org.slf4j.LoggerFactory;
038
039public class LazyDataset extends LazyDatasetBase implements Serializable, Cloneable {
040        private static final long serialVersionUID = 2467865859867440242L;
041
042        private static final Logger logger = LoggerFactory.getLogger(LazyDataset.class);
043
044        protected Map<Class<? extends MetadataType>, List<MetadataType>> oMetadata = null;
045        protected int[] oShape; // original shape
046        protected long  size;   // number of items
047        private Class<? extends Dataset> clazz = null;
048        protected int   isize;  // number of elements per item
049
050        protected ILazyLoader loader;
051
052        // relative to loader
053        protected int[] begSlice = null; // slice begin
054        protected int[] delSlice = null; // slice delta
055        /**
056         * @since 2.2
057         */
058        protected int[] sShape   = null; // sliced shape
059
060        /**
061         * @since 2.2
062         */
063        protected int[] padding = null; // differences in shape from original (or sliced) shape
064        protected int[] map; // transposition map (same length as current shape)
065
066        /**
067         * Create a lazy dataset
068         * @param loader lazy loader
069         * @param name of dataset
070         * @param elements item size
071         * @param clazz dataset sub-interface
072         * @param shape dataset shape
073         * @since 2.3
074         */
075        public LazyDataset(ILazyLoader loader, String name, int elements, Class<? extends Dataset> clazz, int... shape) {
076                this.loader = loader;
077                this.name = name;
078                this.isize = elements;
079                this.clazz = clazz;
080                this.shape = shape.clone();
081                this.oShape = this.shape;
082                try {
083                        size = ShapeUtils.calcLongSize(shape);
084                } catch (IllegalArgumentException e) {
085                        size = Long.MAX_VALUE; // this indicates that the entire dataset cannot be read in! 
086                }
087        }
088
089        /**
090         * Create a lazy dataset
091         * @param loader lazy loader
092         * @param name of dataset
093         * @param clazz dataset sub-interface
094         * @param shape dataset shape
095         * @since 2.3
096         */
097        public LazyDataset(ILazyLoader loader, String name, Class<? extends Dataset> clazz, int... shape) {
098                this(loader, name, 1, clazz, shape);
099        }
100
101        /**
102         * Create a lazy dataset
103         * @param name of dataset
104         * @param dtype dataset type
105         * @param elements item size
106         * @param shape dataset shape
107         * @param loader lazy loader
108         * @deprecated Use {@link #LazyDataset(ILazyLoader, String, int, Class, int[])}
109         */
110        @Deprecated
111        public LazyDataset(String name, int dtype, int elements, int[] shape, ILazyLoader loader) {
112                this(loader, name, elements, DTypeUtils.getInterface(dtype), shape);
113        }
114
115        /**
116         * Create a lazy dataset
117         * @param name of dataset
118         * @param dtype dataset type
119         * @param shape dataset shape
120         * @param loader lazy loader
121         * @deprecated Use {@link #LazyDataset(ILazyLoader, String, int, Class, int[])}
122         */
123        @Deprecated
124        public LazyDataset(String name, int dtype, int[] shape, ILazyLoader loader) {
125                this(name, dtype, 1, shape, loader);
126        }
127
128        LazyDataset(LazyDataset other) {
129                name  = other.name;
130                shape = other.shape.clone();
131                metadata  = other.copyMetadata();
132                oMetadata = other.oMetadata;
133                oShape = other.oShape;
134                size   = other.size;
135                clazz  = other.clazz;
136                isize  = other.isize;
137                loader = other.loader;
138
139                begSlice = other.begSlice;
140                delSlice = other.delSlice;
141                sShape   = other.sShape;
142                padding  = other.padding;
143                map      = other.map;
144        }
145
146        /**
147         * Create a lazy dataset based on in-memory data (handy for testing)
148         * @param dataset input
149         * @return lazy dataset
150         */
151        public static LazyDataset createLazyDataset(final Dataset dataset) {
152                return new LazyDataset(new ILazyLoader() {
153                        private static final long serialVersionUID = -6725268922780517523L;
154
155                        final Dataset d = dataset;
156
157                        @Override
158                        public boolean isFileReadable() {
159                                return true;
160                        }
161
162                        @Override
163                        public Dataset getDataset(IMonitor mon, SliceND slice) throws IOException {
164                                return d.getSlice(mon, slice);
165                        }
166                }, dataset.getName(), dataset.getElementsPerItem(), dataset.getClass(), dataset.getShapeRef());
167        }
168
169        @Override
170        public Class<?> getElementClass() {
171                return InterfaceUtils.getElementClass(clazz);
172        }
173
174        /**
175         * Can return -1 when dataset interface is not defined
176         */
177        @Override
178        public int getDType() {
179                return clazz == null ? -1 : DTypeUtils.getDType(clazz);
180        }
181
182        /**
183         * @return dataset interface that supports element class and number of elements. Can be null when undefined
184         * @since 2.3
185         */
186        public Class<? extends Dataset> getInterface() {
187                return clazz;
188        }
189
190        /**
191         * Set interface
192         * @param clazz dataset sub-interface
193         * @since 2.3
194         */
195        public void setInterface(Class<? extends Dataset> clazz) {
196                this.clazz = clazz;
197        }
198
199        /**
200         * Can return -1 for unknown
201         */
202        @Override
203        public int getElementsPerItem() {
204                return isize;
205        }
206
207        @Override
208        public int getSize() {
209                return (int) size;
210        }
211
212        @Override
213        public String toString() {
214                StringBuilder out = new StringBuilder();
215
216                if (name != null && name.length() > 0) {
217                        out.append("Lazy dataset '");
218                        out.append(name);
219                        out.append("' has shape [");
220                } else {
221                        out.append("Lazy dataset shape is [");
222                }
223                int rank = shape == null ? 0 : shape.length;
224
225                if (rank > 0 && shape[0] >= 0) {
226                        out.append(shape[0]);
227                }
228                for (int i = 1; i < rank; i++) {
229                        out.append(", " + shape[i]);
230                }
231                out.append(']');
232
233                return out.toString();
234        }
235
236        @Override
237        public int hashCode() {
238                final int prime = 31;
239                int result = super.hashCode();
240                result = prime * result + Arrays.hashCode(oShape);
241                result = prime * result + (int) (size ^ (size >>> 32));
242                result = prime * result + Objects.hashCode(clazz);
243                result = prime * result + isize;
244                result = prime * result + Objects.hashCode(loader);
245                result = prime * result + Arrays.hashCode(begSlice);
246                result = prime * result + Arrays.hashCode(delSlice);
247                result = prime * result + Arrays.hashCode(sShape);
248                result = prime * result + Arrays.hashCode(padding);
249                result = prime * result + Arrays.hashCode(map);
250                return result;
251        }
252
253        @Override
254        public boolean equals(Object obj) {
255                if (this == obj) {
256                        return true;
257                }
258                if (!super.equals(obj)) {
259                        return false;
260                }
261
262                LazyDataset other = (LazyDataset) obj;
263                if (!Arrays.equals(oShape, other.oShape)) {
264                        return false;
265                }
266                if (size != other.size) {
267                        return false;
268                }
269                if (!Objects.equals(clazz, other.clazz)) {
270                        return false;
271                }
272                if (isize != other.isize) {
273                        return false;
274                }
275
276                if (loader != other.loader) {
277                        return false;
278                }
279
280                if (!Arrays.equals(begSlice, other.begSlice)) {
281                        return false;
282                }
283                if (!Arrays.equals(delSlice, other.delSlice)) {
284                        return false;
285                }
286                if (!Arrays.equals(sShape, other.sShape)) {
287                        return false;
288                }
289                if (!Arrays.equals(padding, other.padding)) {
290                        return false;
291                }
292                if (!Arrays.equals(map, other.map)) {
293                        return false;
294                }
295
296                return true;
297        }
298
299        @Override
300        public LazyDataset clone() {
301                return new LazyDataset(this);
302        }
303
304        @Override
305        public void setShape(int... shape) {
306                setShapeInternal(shape.clone());
307        }
308
309        @Override
310        public LazyDataset squeezeEnds() {
311                setShapeInternal(ShapeUtils.squeezeShape(shape, true));
312                return this;
313        }
314
315        @Override
316        public Dataset getSlice(int[] start, int[] stop, int[] step) throws DatasetException {
317                return getSlice(null, start, stop, step);
318        }
319
320        @Override
321        public Dataset getSlice(Slice... slice) throws DatasetException {
322                if (slice == null || slice.length == 0) {
323                        return internalGetSlice(null, new SliceND(shape));
324                }
325                return internalGetSlice(null, new SliceND(shape, slice));
326        }
327
328        @Override
329        public Dataset getSlice(SliceND slice) throws DatasetException {
330                return getSlice(null, slice);
331        }
332
333        @Override
334        public Dataset getSlice(IMonitor monitor, Slice... slice) throws DatasetException {
335                if (slice == null || slice.length == 0) {
336                        return internalGetSlice(monitor, new SliceND(shape));
337                }
338                return internalGetSlice(monitor, new SliceND(shape, slice));
339        }
340
341        @Override
342        public LazyDataset getSliceView(Slice... slice) {
343                if (slice == null || slice.length == 0) {
344                        return getSliceView(new SliceND(shape));
345                }
346                return getSliceView(new SliceND(shape, slice));
347        }
348
349        /**
350         * @param nShape
351         */
352        private void setShapeInternal(int... nShape) {
353                // work out transposed (sliced) shape (instead of removing padding from current shape)
354                if (size != 0) {
355                        int[] pShape = calcTransposed(map, sShape == null ? oShape : sShape);
356                        padding = ShapeUtils.calcShapePadding(pShape, nShape);
357                }
358
359                if (metadata != null) {
360                        storeMetadata(metadata, Reshapeable.class);
361                        metadata = copyMetadata();
362                        reshapeMetadata(shape, nShape);
363                }
364                shape = nShape;
365        }
366
367        @Override
368        public LazyDataset getSliceView(int[] start, int[] stop, int[] step) {
369                return internalGetSliceView(new SliceND(shape, start, stop, step));
370        }
371
372        @Override
373        public LazyDataset getSliceView(SliceND slice) {
374                checkSliceND(slice);
375                return internalGetSliceView(slice);
376        }
377
378        protected LazyDataset internalGetSliceView(SliceND slice) {
379                LazyDataset view = clone();
380                if (slice == null || slice.isAll()) {
381                        return view;
382                }
383
384                SliceND nslice = calcTrueSlice(slice);
385                if (nslice != null) {
386                        view.begSlice = nslice.getStart();
387                        view.delSlice = nslice.getStep();
388                        view.sShape = nslice.getShape();
389                }
390                view.shape = slice.getShape();
391                view.size = ShapeUtils.calcLongSize(view.shape);
392                view.storeMetadata(metadata, Sliceable.class);
393
394                view.sliceMetadata(true, slice);
395                return view;
396        }
397
398        @Override
399        public Dataset getSlice(IMonitor monitor, int[] start, int[] stop, int[] step) throws DatasetException {
400                return internalGetSlice(monitor, new SliceND(shape, start, stop, step));
401        }
402
403        @Override
404        public Dataset getSlice(IMonitor monitor, SliceND slice) throws DatasetException {
405                checkSliceND(slice);
406
407                return internalGetSlice(monitor, slice);
408        }
409
410        protected Dataset internalGetSlice(IMonitor monitor, SliceND slice) throws DatasetException {
411                if (loader != null && !loader.isFileReadable()) {
412                        return null;
413                }
414
415                SliceND nslice = calcTrueSlice(slice);
416
417                Dataset a;
418                if (nslice == null) {
419                        Class<? extends Dataset> nClass = clazz == null ? DoubleDataset.class : clazz;
420                        a = DatasetFactory.zeros(nClass, slice == null ? shape : slice.getShape());
421                } else {
422                        try {
423                                a = DatasetUtils.convertToDataset(loader.getDataset(monitor, nslice));
424                        } catch (IOException e) {
425                                logger.error("Problem getting {}: {}", slice == null ? "all" : String.format("slice %s %s %s from %s", Arrays.toString(slice.getStart()), Arrays.toString(slice.getStop()),
426                                                                Arrays.toString(slice.getStep()), loader), e);
427                                throw new DatasetException(e);
428                        }
429                }
430                a.setName(name + AbstractDataset.BLOCK_OPEN + (nslice == null ?
431                                (slice == null ? "..." : slice) : nslice) + AbstractDataset.BLOCK_CLOSE);
432                if (metadata != null && a instanceof LazyDatasetBase) {
433                        LazyDatasetBase ba = (LazyDatasetBase) a;
434                        ba.metadata = copyMetadata();
435                        if (oMetadata != null) {
436                                ba.restoreMetadata(oMetadata);
437                        }
438                        // metadata axis may be larger than data
439                        if (nslice != null && (!nslice.isAll() || nslice.getMaxShape() != nslice.getShape())) {
440                                ba.sliceMetadata(true, nslice);
441                        }
442                }
443
444                if (nslice != null) {
445                        if (map != null) {
446                                a = a.getTransposedView(map);
447                        }
448                        if (padding != null) {
449                                a.setShape(slice == null ? shape : slice.getShape());
450                        }
451                }
452                a.addMetadata(MetadataFactory.createMetadata(OriginMetadata.class, this, nslice == null ?
453                                (slice == null ? null : slice.convertToSlice()) : nslice.convertToSlice(), oShape, null, name));
454
455                if (clazz == null) {
456                        clazz = a.getClass();
457                }
458                return a;
459        }
460
461        @Override
462        public LazyDataset getTransposedView(final int... axes) {
463                LazyDataset view = clone();
464
465                int[] naxes = checkPermutatedAxes(shape, axes);
466                if (naxes == null) {
467                        return view;
468                }
469
470                view.shape = calcTransposed(naxes, shape);
471                if (view.size != 0 && padding != null) { // work out transpose by reverting effect of padding
472                        int or = oShape.length;
473                        int nr = shape.length;
474                        int j = 0; // naxes index
475                        int[] mShape = calcTransposed(map, sShape == null ? oShape : sShape); // pre-padded shape
476                        int m = 0; // shape index
477                        int e = -1; // index of unit dimension
478                        final List<Integer> uaxes = new LinkedList<>();
479                        for (int a : naxes) {
480                                uaxes.add(a);
481                        }
482                        List<Integer> oList = new ArrayList<>(); // dimensions left out by padding (in order)
483                        int np = padding.length;
484                        for (int i = 0; i < np; i++) {
485                                int p = padding[i];
486                                if (p > 0) { // remove added dimensions
487                                        for (int k = 0; k < p; k++, j++) {
488                                                uaxes.remove((Integer) j);
489                                        }
490                                } else if (p == 0) { // leave alone
491                                        if (mShape[m] == 1) { // bump up last unit dimension index
492                                                e = m;
493                                        }
494                                        j++;
495                                        m++;
496                                } else { // add omitted dimensions to list
497                                        p = -p;
498                                        for (int k = 0; k < p; k++) {
499                                                e = find(mShape, 1, e + 1);
500                                                oList.add(e);
501                                        }
502                                }
503                        }
504                        
505                        int[] omitted = new int[oList.size()];
506                        j = 0;
507                        for (Integer o : oList) {
508                                omitted[j++] = o;
509                        }
510                        int[] used = new int[or - omitted.length]; // all dimensions not omitted in pre-padded shape
511                        j = 0;
512                        for (int i = 0; i < or; i++) {
513                                if (Arrays.binarySearch(omitted, i) < 0) {
514                                        used[j++] = i;
515                                }
516                        }
517
518                        int[] vaxes = new int[uaxes.size()];
519                        j = 0;
520                        for (int i = 0; i < nr; i++) { // remap dimension numbering
521                                int l = uaxes.indexOf(i);
522                                if (l >= 0) {
523                                        vaxes[l] = used[j++];
524                                }
525                        }
526                        int[] taxes = new int[or];
527                        j = 0;
528                        for (int i = 0; i < or; i++) { // reassemble map
529                                if (Arrays.binarySearch(omitted, i) >= 0) {
530                                        taxes[i] = i;
531                                } else {
532                                        taxes[i] = vaxes[j++];
533                                }
534                        }
535
536                        naxes = taxes;
537                }
538
539                view.map = map == null ? naxes : calcTransposed(naxes, map);
540                if (view.size != 0) {
541                        // work out transposed (sliced) shape
542                        int[] tShape = calcTransposed(view.map, sShape == null ? oShape : sShape);
543                        try {
544                                view.padding = ShapeUtils.calcShapePadding(tShape, view.shape);
545                        } catch (IllegalArgumentException e) {
546                                System.err.println(e.getMessage() + ": " + Arrays.toString(tShape) + " cf " + Arrays.toString(view.shape));
547                        }
548                }
549                view.storeMetadata(metadata, Transposable.class);
550                view.transposeMetadata(axes);
551                return view;
552        }
553
554        private static int find(int[] map, int m, int off) {
555                for (int i = off, imax = map.length; i < imax; i++) {
556                        if (map[i] == m) {
557                                return i;
558                        }
559                }
560                return -1;
561        }
562
563        private static int[] calcTransposed(int[] map, int[] values) {
564                if (values == null) {
565                        return null;
566                }
567                int r = values.length;
568                if (map == null || r < 2) {
569                        return values;
570                }
571                int[] ovalues = new int[r];
572                for (int i = 0; i < r; i++) {
573                        ovalues[i] = values[map[i]];
574                }
575                return ovalues;
576        }
577
578        /**
579         * Calculate absolute slice
580         * @param slice an n-D slice
581         * @return true slice or null if zero-sized
582         */
583        protected final SliceND calcTrueSlice(SliceND slice) {
584                /*
585                 * Lazy dataset operations: getTransposedView (T), getSliceView (G), setShape/squeezeEnds (S+/S-):
586                 * 
587                 *     . T sets shape, base, and map in new view
588                 *     . G sets shape, size, begSlice and delSlice in new view
589                 *     . S sets shape, shapePadding in current view
590                 * 
591                 * Then getSlice needs to interpret all info to find true slice, load data, get transposition (view)
592                 * and set shape. Therefore:
593                 *     . S needs to update shapePadding only
594                 *     . T needs to update shapePadding too
595                 *     . G needs to work out true slice to update
596                 * 
597                 * slice -> true slice
598                 *   adjusts for shape (S^-1) then remap dimensions (T^-1)
599                 */
600
601                if (slice == null) {
602                        slice = new SliceND(shape);
603                }
604
605                if (ShapeUtils.calcLongSize(slice.getShape()) == 0) {
606                        return null;
607                }
608
609                int[] nshape;
610                int[] nstart;
611                int[] nstep;
612
613                int r = oShape.length;
614                if (padding == null) {
615                        nshape = slice.getShape();
616                        nstart = slice.getStart();
617                        nstep = slice.getStep();
618                } else {
619                        final int[] lshape = slice.getShape();
620                        final int[] lstart = slice.getStart();
621                        final int[] lstep  = slice.getStep();
622
623                        nstart = new int[r];
624                        nstep = new int[r];
625                        nshape = new int[r];
626                        int i = 0;
627                        int j = 0;
628                        for (int p : padding) { // remove padding
629                                if (p == 0) {
630                                        nshape[i] = lshape[j];
631                                        nstart[i] = lstart[j];
632                                        nstep[i]  = lstep[j];
633                                        i++;
634                                        j++;
635                                } else if (p < 0) {
636                                        int imax = i - p;
637                                        while (i < imax) {
638                                                nshape[i] = 1;
639                                                nstep[i]  = 1;
640                                                i++;
641                                        }
642                                } else {
643                                        j += p;
644                                }
645                        }
646                }
647
648                if (map != null && r > 1) { // transpose dimensions
649                        int[] pshape = new int[r];
650                        int[] pstart = new int[r];
651                        int[] pstep = new int[r];
652                        for (int i = 0; i < r; i++) {
653                                int m = map[i];
654                                pshape[m] = nshape[i];
655                                pstart[m] = nstart[i];
656                                pstep[m]  = nstep[i];
657                        }
658
659                        nshape = pshape;
660                        nstart = pstart;
661                        nstep  = pstep;
662                }
663
664                int[] nstop = new int[r];
665                if (begSlice != null) { // find net slice
666                        for (int i = 0; i < r; i++) {
667                                int b = begSlice[i];
668                                int d = delSlice[i];
669                                nstart[i] = b + nstart[i] * d;
670                                int nd = nstep[i] * d;
671                                nstep[i] = nd;
672                                nstop[i]  = nstart[i] + (nshape[i] - 1) * nd + (nd >= 0 ? 1 : -1);
673                        }
674                } else {
675                        for (int i = 0; i < r; i++) {
676                                int d = nstep[i];
677                                nstop[i] = nstart[i] + (nshape[i] - 1) * d + (d >= 0 ? 1 : -1);
678                        }
679                }
680
681                return createSlice(nstart, nstop, nstep);
682        }
683
684        protected SliceND createSlice(int[] nstart, int[] nstop, int[] nstep) {
685                return SliceND.createSlice(oShape, null, nstart, nstop, nstep);
686        }
687
688        /**
689         * Transform data so that it can be used in setSlice of saver
690         * @param data input
691         * @param tslice true slice 
692         * @return data with dimensions adjusted and remapped 
693         */
694        final IDataset transformInput(IDataset data, SliceND tslice) {
695                if (padding != null) { // remove padding
696                        data = data.getSliceView();
697                        int[] nshape = tslice == null ? shape : tslice.getShape();
698                        data.setShape(nshape);
699                }
700
701                return map == null ? data : data.getTransposedView(map);
702        }
703
704        /**
705         * Store metadata items that has given annotation
706         * @param origMetadata original metadata
707         * @param aclazz annotation class
708         */
709        private void storeMetadata(Map<Class<? extends MetadataType>, List<MetadataType>> origMetadata, Class<? extends Annotation> aclazz) {
710                List<Class<? extends MetadataType>> mclazzes = findAnnotatedMetadata(aclazz);
711                if (mclazzes.size() == 0) {
712                        return;
713                }
714
715                if (oMetadata == null) {
716                        oMetadata = new HashMap<Class<? extends MetadataType>, List<MetadataType>>();
717                }
718                for (Class<? extends MetadataType> mc : mclazzes) {
719                        if (oMetadata.containsKey(mc)) {
720                                continue; // do not overwrite original
721                        }
722
723                        List<MetadataType> l = origMetadata.get(mc);
724                        List<MetadataType> nl = new ArrayList<MetadataType>(l.size());
725                        for (MetadataType m : l) {
726                                nl.add(m.clone());
727                        }
728                        oMetadata.put(mc, nl);
729                }
730        }
731
732        @SuppressWarnings("unchecked")
733        private List<Class<? extends MetadataType>> findAnnotatedMetadata(Class<? extends Annotation> aclazz) {
734                List<Class<? extends MetadataType>> mclazzes = new ArrayList<Class<? extends MetadataType>>();
735                if (metadata == null) {
736                        return mclazzes;
737                }
738
739                for (Class<? extends MetadataType> c : metadata.keySet()) {
740                        boolean hasAnn = false;
741                        for (MetadataType m : metadata.get(c)) {
742                                if (m == null) {
743                                        continue;
744                                }
745
746                                Class<? extends MetadataType> mc = m.getClass();
747                                do { // iterate over super-classes
748                                        for (Field f : mc.getDeclaredFields()) {
749                                                if (f.isAnnotationPresent(aclazz)) {
750                                                        hasAnn = true;
751                                                        break;
752                                                }
753                                        }
754                                        Class<?> sclazz = mc.getSuperclass();
755                                        if (!MetadataType.class.isAssignableFrom(sclazz)) {
756                                                break;
757                                        }
758                                        mc = (Class<? extends MetadataType>) sclazz;
759                                } while (!hasAnn);
760                                if (hasAnn) {
761                                        break;
762                                }
763                        }
764                        if (hasAnn) {
765                                mclazzes.add(c);
766                        }
767                }
768                return mclazzes;
769        }
770
771        /**
772         * Gets the maximum size of a slice of a dataset in a given dimension
773         * which should normally fit in memory. Note that it might be possible
774         * to get more in memory, this is a conservative estimate and seems to
775         * almost always work at the size returned; providing Xmx is less than
776         * the physical memory.
777         * 
778         * To get more in memory increase -Xmx setting or use an expression
779         * which calls a rolling function (like rmean) instead of slicing directly
780         * to memory.
781         * 
782         * @param lazySet lazy dataset
783         * @param dimension to slice along
784         * @return maximum size of dimension that can be sliced.
785         */
786        public static int getMaxSliceLength(ILazyDataset lazySet, int dimension) {
787                // size in bytes of each item
788                final double size = InterfaceUtils.getItemBytes(lazySet.getElementsPerItem(), InterfaceUtils.getInterface(lazySet));
789                
790                // Max in bytes takes into account our minimum requirement
791                final double max  = Math.max(Runtime.getRuntime().totalMemory(), Runtime.getRuntime().maxMemory());
792                
793                // Firstly if the whole dataset it likely to fit in memory, then we allow it.
794                // Space specified in bytes per item available
795                final double space = max/lazySet.getSize();
796
797                // If we have room for this whole dataset, then fine
798                int[] shape = lazySet.getShape();
799                if (space >= size) {
800                        return shape[dimension];
801                }
802
803                // Otherwise estimate what we can fit in, conservatively.
804                // First get size of one slice, see it that fits, if not, still return 1
805                double sizeOneSlice = size; // in bytes
806                for (int dim = 0; dim < shape.length; dim++) {
807                        if (dim == dimension) {
808                                continue;
809                        }
810                        sizeOneSlice *= shape[dim];
811                }
812                double avail = max / sizeOneSlice;
813                if (avail < 1) {
814                        return 1;
815                }
816
817                // We fudge this to leave some room
818                return (int) Math.floor(avail/4d);
819        }
820}