casacore
Loading...
Searching...
No Matches
Slicer.h
Go to the documentation of this file.
1// # Slicer.h: specify which elements to extract from an n-dimensional array
2// # Copyright (C) 1994,1995,1997,1999
3// # Associated Universities, Inc. Washington DC, USA.
4// #
5// # This library is free software; you can redistribute it and/or modify it
6// # under the terms of the GNU Library General Public License as published by
7// # the Free Software Foundation; either version 2 of the License, or (at your
8// # option) any later version.
9// #
10// # This library is distributed in the hope that it will be useful, but WITHOUT
11// # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12// # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
13// # License for more details.
14// #
15// # You should have received a copy of the GNU Library General Public License
16// # along with this library; if not, write to the Free Software Foundation,
17// # Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA.
18// #
19// # Correspondence concerning AIPS++ should be addressed as follows:
20// # Internet email: casa-feedback@nrao.edu.
21// # Postal address: AIPS++ Project Office
22// # National Radio Astronomy Observatory
23// # 520 Edgemont Road
24// # Charlottesville, VA 22903-2475 USA
25
26#ifndef CASA_SLICER_2_H
27#define CASA_SLICER_2_H
28
29// # Includes
30#include "IPosition.h"
31
32namespace casacore { // # NAMESPACE CASACORE - BEGIN
33
34// # Forward Declarations
35class Slice;
36
37// <summary>
38// Specify which elements to extract from an n-dimensional array
39// </summary>
40
41// <reviewed reviewer="Paul Shannon" date="1994/07/07" tests="tSlicer">
42// The review and modification of this class were undertaken, in part,
43// with the aim of making this class header an example -- this is what
44// the Casacore project thinks a class header should look like.
45// </reviewed>
46
47// <prerequisite>
48// You should have at least a preliminary understanding of these classes:
49// <li> <linkto class=IPosition>IPosition</linkto>
50// <li> <linkto class=Array>Array</linkto>
51// <li> <linkto class=Slice>Slice</linkto>
52// </prerequisite>
53
54// <etymology>
55// The class name "Slicer" may be thought of as a short form
56// of "n-Dimensional Slice Specifier." Some confusion is possible
57// between class "Slice" and this class.
58// </etymology>
59//
60// <synopsis>
61// If you need to extract or operate upon a portion of an array,
62// the Slicer class is the best way to specify the subarray you are
63// interested in.
64//
65// Slicer has many constructors. Of these, some require that the
66// programmer supply a full specification of the array elements he
67// wants to extract; other constructors make do with partial information.
68// In the latter case, the constructor will assume sensible default values or,
69// when directed, infer missing information from the array that's getting
70// sliced (hereafter, the "source" array).
71//
72// <h4> Constructing With Full Information </h4>
73//
74// To fully specify a subarray, you must supply three pieces of information
75// for each axis of the subarray:
76//
77// <ol>
78// <li> where to start
79// <li> how many elements to extract
80// <li> what stride (or "increment" or "interval") to use: a stride of
81// "n" means pick extract only every "nth" element along an axis
82// </ol>
83//
84// The most basic constructor for Slicer illustrates this. To create
85// an Slicer for getting selected elements from a 3D array:
86//
87// <srcblock>
88// IPosition start (3,0,0,0), length (3,10,10,10), stride (3,3,3,3);
89// Slicer slicer (start, length, stride);
90// // assume proper declarations, and meaningful values in the source array
91// subArray = sourceArray (slicer);
92// </srcblock>
93// It gets elements 0,3,6,9,12,15,18,21,24,27 for each dimension.
94//
95// <note role=caution> If you wish to extract elements from the array
96// at intervals, these intervals must be regular. The interval is one
97// constant integer for each dimension of the array: it cannot be a function.
98// </note>
99//
100// <note role=caution> "length", the second parameter to the Slicer
101// constructor above, may actually be used in two ways. In normal
102// (and default) use, it specifies how many elements to select from the
103// source. In the alternative use, it specifies the index of the last element
104// to extract from the source array. This ambiguity (does "end" mean
105// "length" or does it mean "last index"?) is handled by a default
106// fourth parameter to the constructor. This code fragment will
107// extract the same subarray as the example above:
108// <srcblock>
109// IPosition start (3,0,0,0), end (3,27,27,27), stride (3,3,3,3);
110// Slicer slicer (start, end, stride, Slicer::endIsLast);
111// subArray = sourceArray (slicer);
112// </srcblock>
113// Note that in this example end(3,28,29,28) gives the same result.
114// (We use "end" as the name of the formal parameter because it supports
115// both meanings -- "last index" or "length." You may wish to use a
116// clarifying name for the actual parameter in your code, as we have
117// above when we used "length".)
118// </note>
119// Similar to Python it is possible to address the start and/or end value
120// from the end by giving a negative value (-1 means the last value).
121// However, a length and stride cannot be negative.
122// Unlike Python the end value is inclusive (as discussed above).
123// For example,
124// <srcblock>
125// Slicer slicer (IPosition(1,-4), IPosition(1,-2), Slicer::endIsLast)
126// Slicer slicer (IPosition(1,6), IPosition(1,8), Slicer::endIsLast)
127// </srcblock>
128// Both Slicers give the same result when used on a Vector with length 10.
129//
130// <h4> Constructing with Partial Information </h4>
131//
132// Some of the constructors don't require complete information: Slicer
133// either calculates sensible default values or deduces them from the
134// source array. If you do not specify a "stride" argument, for example,
135// a value of 1 will be used for all dimensions. If you specify a "start"
136// but nothing else, a stride of 1, and (perhaps against expectation)
137// a length of 1 will be used.
138//
139// Note that using a negative start or end is also partial information.
140// The actual array shape is needed to derive the exact start or end value.
141//
142// To instruct the Slicer to get otherwise unspecified information
143// from the source array, you can create an IPosition like "end"
144// as shown here:
145//
146// <srcblock>
147// IPosition start (3,0,0,0), stride (3,3,3,3);
148// IPosition end (3,Slicer::MimicSource, Slicer::MimicSource,
149// Slicer::MimicSource);
150// Slicer smartSlicer (start, end, stride);
151// // assume proper declarations...
152// subArray = sourceArray (smartSlicer)
153// </srcblock>
154//
155// If you are a library programmer, and write a class that can be sliced
156// by the Slicer class, you need to understand the mechanism for
157// completing the information which the application programmer, in using
158// your class, specified incompletely. (If you are an application
159// programmer, who wants to slice a library class, this explanation will
160// be only of academic interest.)
161//
162// When the source array (the library class you provide) gets the Slicer --
163// which typically comes when the source array is asked to return a
164// reference to a subarray -- the source does a callback to the Slicer
165// object. The source array passes its own shape as one of the arguments
166// to the Slicer callback and asks the Slicer to fill in the missing
167// values from that shape.
168//
169// In use, and with an imagined class "MyVector", code would look
170// like this:
171// <srcblock>
172// // first, a fragment from the application program:
173// IPosition start (1,10), end (1, Slicer::MimicSource);
174// Slicer slicer (start, end);
175// MyVector <int> v0 (100);
176// MyVector <int> v1 = v0 (slicer);
177// //....
178// // second, a fragment from a constructor of the library class "MyVector":
179// // the MyVector class will construct v1 as a reference to
180// // selected elements of v0, using (among other things) a
181// // callback to the slicer it was passed (above, in the
182// // construction of v1.
183// //
184// IPosition start, end, stride;
185// fullSliceInformation =
186// slicer.inferShapeFromSource (MyVector::shape(), start, end, stride);
187// // now the MyVector instance knows everything it needs to
188// // construct the instance.
189// </srcblock>
190// Please note that v1 will have a length of 90, and refer to elements
191// 10-99 of v0.
192//
193// <note role=warning> An exception will be thrown if the positions
194// defined in the Slicer exceed the source array's shape.
195// </note>
196// </synopsis>
197//
198// <example>
199// Given a large image, 4k on a side, extract (by sampling) an image
200// 1k on a side, but covering the same region as the original.
201//
202// <srcblock>
203// Image <float> image ("N5364.fits"); // a 4-d VLA map, 4096 x 4096 x 3 x 1
204// IPosition start (4,0,0,0,0), stride (4,4,4,1,1);
205// IPosition end (4, Slicer::MimicSource, Slicer::MimicSource,
206// Slicer::MimicSource, Slicer::MimicSource);
207// Slicer smartSlicer (start, end, stride);
208// // assume proper declarations...
209// Image <float> subImage = image (smartSlicer);
210// </srcblock>
211//
212// </example>
213
214// <motivation>
215// Slicer is particularly convenient for designers of other library
216// classes: Array and Image, for example. (In fact, this convenience
217// was the original motivation for the class.) The benefit
218// is this: the application programmer, who needs a slice of an Array,
219// may provide slicing specifications in many different ways, but the
220// Array class author needs to provide only one member function to
221// return the slice. The Slicer class, in effect, and with its
222// many constructors, provides a way to funnel all of the variety
223// into a single member function call to the array or image class.
224//
225// For example, imagine a 100 x 100 x 100 array from which you want to
226// extract various subarrays. Here are some of the ways you might
227// specify the the subarray in the -absence- of Slicer.
228//
229// <srcblock>
230// // preliminaries: create a cube and assign values to all elements --
231// // this will be "source" array
232// Cube <int> bigCube (IPosition (3, 100, 100, 100));
233// assignValues (bigCube);
234// // declare a smaller cube, the destination array.
235// Cube <int> smallCube (IPosition (3, 10, 10, 10));
236//
237// // example 1: use Slice objects to extract a subcube -- the first
238// // ten elements along each axis
239// Slice xIndices (0,10,1), yIndices (0,10,1), zIndices (0,10,1);
240// smallCube = bigCube (xIndices, yIndices, zIndices);
241//
242// // example 2: get the same subcube using three IPosition arguments
243// IPosition start (3,0,0,0), end (3,10,10,10), stride (3,1,1,1);
244// smallCube = bigCube (start, end, stride);
245//
246// // example 3: use 2 IPositions, letting the 3rd (stride) default to
247// // IPosition (3,1,1,1)
248// smallCube = bigCube (start, end);
249// </srcblock>
250//
251// So the Cube class (together with its base class) must define three separate
252// member functions for the essentially identical operation of
253// extracting a subcube. The same replication is also required of
254// Image, Array, and the other Array subclasses (Matrix and Vector).
255//
256// The Slicer class collapses all of this into a single member
257// function per class:
258//
259// <srcblock>
260// Slicer slicer = (call the constructor that best suits your problem)
261// smallCube = bigCube (slicer);
262// </srcblock>
263//
264// Since there are many constructors available for Slicer, you
265// can still specify the subarray that you may want in a number of
266// different ways, by constructing the Slicer in the way most natural
267// to your circumstances. You then pass the Slicer to the array, and
268// you will get back the slice you want.
269//
270// This class also offers the application programmer considerable
271// flexibility by allowing the shape of the source array to determine
272// some of the slice specification. This benefit is explained and
273// demonstrated above.
274// </motivation>
275
276// <todo asof="1994/07/01">
277// <li> This class, and the TableArray, Array and Image classes,
278// could allow for the extraction of a subarray with fewer axes than the
279// source array. At present, for example, you cannot, directly slice
280// a matrix from a cube.
281// </todo>
282
283class Slicer {
284 public:
285 // Define the "MimicSource" value which defines the open start or end.
286 // This value should be different from MIN_INT in IPosition.h.
287 // It should also not be the lowest possible value, since that
288 // will probably be used as an undefined value.
289 // It must be a negative number.
290 enum { MimicSource = -2147483646 };
291
292 // Define the possible interpretations of the end-value.
294 // The end-values given in the constructor define the lengths.
296 // The end-values given in the constructor define the trc.
298 };
299
300 // Construct a 1-dimensional Slicer.
301 // Start and end are inferred from the source; stride=1.
302 // "endIsLength" and "endIsLast" are identical here, so there's
303 // no need to discriminate between them by using a default parameter.
305
306 // The member function <src>inferShapeFromSource</src>
307 // (invoked as a callback by the
308 // source array) will use the shape of the source array for the
309 // unspecified values: IPosition elements with the value
310 // Slicer::MimicSource
311 // <thrown>
312 // <li> ArraySlicerError
313 // </thrown>
314 // Create a Slicer with a given start, end (or length), and stride.
315 // An exception will be thrown if a negative length or non-positive
316 // stride is given or if the IPositions start, end, and stride
317 // do not have the same dimensionality.
318 // If length or stride is not given, they default to 1.
319 // <br> It is possible to leave values in start and end undefined
320 // by giving the value <src>MimicSource</src>. They can be filled
321 // in later with the actual array shape using function
322 // <src>inferShapeFromSource</src>.
323 // <group>
325 LengthOrLast endInterpretation = endIsLength);
327 LengthOrLast endInterpretation = endIsLength);
328 explicit Slicer(const IPosition& start);
329 // </group>
330
331 // Create a Slicer object from Slice objects.
332 // In a Slice object one defines the start, length, and stride for
333 // one axis.
334 // The default Slice constructor (called with no arguments) creates
335 // a Slice with start and length equal to zero, and an undefined stride.
336 // <group>
337 // Create a Slicer for a 1-dimensional array.
338 Slicer(const Slice& x, LengthOrLast endInterpretation = endIsLength);
339
340 // Create a Slicer for a 2-dim array.
341 Slicer(const Slice& x, const Slice& y, LengthOrLast endInterpretation = endIsLength);
342
343 // Create a Slicer for a 3-dim array.
344 Slicer(const Slice& x, const Slice& y, const Slice& z,
345 LengthOrLast endInterpretation = endIsLength);
346 // </group>
347
348 // Equality
349 bool operator==(const Slicer&) const;
350
351 // Return the number of dimensions of the Slicer.
352 size_t ndim() const;
353
354 // This function checks all of the start, length (or end),
355 // and stride IPositions, and fills in missing values by
356 // getting the corresponding values from the shape of the
357 // source array.
358 // These will first be resized, if necessary.
359 // If, for a given axis, (end < start) , it means that a
360 // length of zero was specified.
361 // An exception is thrown if the
362 // start, end, or length exceeds the array shape or if the
363 // dimensionality of the array and Slicer do not conform.
364 // <thrown>
365 // <li> ArraySlicerError
366 // </thrown>
368 IPosition& endResult, IPosition& strideResult) const;
369
370 // Report the defined starting position.
371 const IPosition& start() const;
372
373 // Report the defined ending position.
374 const IPosition& end() const;
375
376 // Report the defined stride.
377 const IPosition& stride() const;
378
379 // Report the length of the resulting axes.
380 const IPosition& length() const;
381
382 // Are all values fixed (i.e., no MimicSource given)?
383 bool isFixed() const;
384
385 // Set the start and end positions. No explicit checking is done that
386 // the input parameters make sense, so you must be certain if you
387 // call these. These are useful if you have a loop with many iterations
388 // and you do not wish the overhead of creating a new Slicer object
389 // for each iteration if the only thing you are doing is adjusting
390 // the start and end positions. Other than for performance reasons,
391 // these methods should not be called and you should prefer the
392 // error checking provided by constructing a new Slicer object.
393 // Note that the length is not updated, so in principle care should
394 // be taken that the length does not change.
395 // <group>
397 void setEnd(const IPosition& end) { end_p = end; }
398 // </group>
399
400 private:
405 IPosition len_p; // Length of input
406 bool fixed_p; // no MimicSource used
407
408 // Define a private constructor taking an ssize_t.
409 // This is to prevent the user from the unexpected and meaningless
410 // Slicer that would result when the ssize_t argument is promoted to
411 // an IPosition.
412 // Slicer (ssize_t);
413
414 // Check the given start, end/length and stride.
415 // Fill in the length or end.
416 // It also calls <src>fillFixed</src> to fill the fixed flag.
418
419 // Fill in start, len and stride from a Slice.
420 void fillSlice(const Slice&, ssize_t& start, ssize_t& length, ssize_t& stride);
421
422 // Fill the fixed flag.
423 void fillFixed();
424};
425
426// <summary>IO functions for Slicer's</summary>
427// <group name="Slicer IO">
428// Print the contents of the specified Slicer to the specified stream.
429std::ostream& operator<<(std::ostream& stream, const Slicer& slicer);
430// </group>
431std::string to_string(const Slicer& slicer);
432
433inline size_t Slicer::ndim() const { return start_p.nelements(); }
435inline const IPosition& Slicer::start() const { return start_p; }
436
437inline const IPosition& Slicer::end() const { return end_p; }
438
439inline const IPosition& Slicer::stride() const { return stride_p; }
440
441inline const IPosition& Slicer::length() const { return len_p; }
442
443inline bool Slicer::isFixed() const { return fixed_p; }
444
445} // namespace casacore
446
447#endif
size_t nelements() const
The number of elements in this IPosition.
Definition IPosition.h:551
const IPosition & length() const
Report the length of the resulting axes.
Definition Slicer.h:441
void setEnd(const IPosition &end)
Definition Slicer.h:397
const IPosition & end() const
Report the defined ending position.
Definition Slicer.h:437
Slicer(const IPosition &start, const IPosition &end, LengthOrLast endInterpretation=endIsLength)
Slicer(const Slice &x, const Slice &y, const Slice &z, LengthOrLast endInterpretation=endIsLength)
Create a Slicer for a 3-dim array.
Slicer(const Slice &x, LengthOrLast endInterpretation=endIsLength)
Create a Slicer object from Slice objects.
IPosition stride_p
Definition Slicer.h:404
const IPosition & stride() const
Report the defined stride.
Definition Slicer.h:439
Slicer(const Slice &x, const Slice &y, LengthOrLast endInterpretation=endIsLength)
Create a Slicer for a 2-dim array.
void fillSlice(const Slice &, ssize_t &start, ssize_t &length, ssize_t &stride)
Fill in start, len and stride from a Slice.
void fillEndLen()
Define a private constructor taking an ssize_t.
LengthOrLast asEnd_p
Definition Slicer.h:401
Slicer(const IPosition &start, const IPosition &end, const IPosition &stride, LengthOrLast endInterpretation=endIsLength)
The member function inferShapeFromSource (invoked as a callback by the source array) will use the sha...
IPosition start_p
Definition Slicer.h:402
const IPosition & start() const
Report the defined starting position.
Definition Slicer.h:435
void fillFixed()
Fill the fixed flag.
Slicer(const IPosition &start)
bool isFixed() const
Are all values fixed (i.e., no MimicSource given)?
Definition Slicer.h:443
IPosition len_p
Definition Slicer.h:405
Slicer()
Construct a 1-dimensional Slicer.
LengthOrLast
Define the possible interpretations of the end-value.
Definition Slicer.h:293
@ endIsLast
The end-values given in the constructor define the trc.
Definition Slicer.h:297
@ endIsLength
The end-values given in the constructor define the lengths.
Definition Slicer.h:295
bool operator==(const Slicer &) const
Equality.
IPosition end_p
Definition Slicer.h:403
size_t ndim() const
Return the number of dimensions of the Slicer.
Definition Slicer.h:434
IPosition inferShapeFromSource(const IPosition &shape, IPosition &startResult, IPosition &endResult, IPosition &strideResult) const
This function checks all of the start, length (or end), and stride IPositions, and fills in missing v...
void setStart(const IPosition &start)
Set the start and end positions.
Definition Slicer.h:396
For temporary backward namespace compatibility, use casa as alias for casacore.
Definition mainpage.dox:28
ostream & operator<<(ostream &os, const IComplex &)
Show on ostream.
IPosition shape(const RecordFieldId &) const
Get the actual shape of this field.
std::string to_string(const IPosition &ip)
IO functions for Slicer's .
Definition Slicer.h:429
std::ostream & operator<<(std::ostream &stream, const Slicer &slicer)
Print the contents of the specified Slicer to the specified stream.