1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
use crate*;
/* #region reshape args */
/// Reshape arguments.
/* #endregion */
/* #region reshapeable */
/// Check if this tensor can be reshaped to a new shape without explicitly copying underlying data.
///
/// Please note this function returns `Result` instead of boolean.
///
/// - If shape not match, this function will raise error.
/// - If shape match but data need to be copied, return `Ok(None)`.
/// - If everything is fine, return `Ok(Some(layout_out))`.
///
/// For order, row-major and col-major behaves differently.
///
/// # See also
///
/// - [`reshape`]: the actual function for tensor reshaping.
/// - [`layout_reshapeable`]: The underlying function for checking layout compatibility for
/// reshaping, input by shape instead of tensor.
/* #endregion */
/* #region reshape_with_args */
/// Reshapes the given tensor to the specified shape, with argument specifying the order and whether
/// to copy data.
///
/// See also [`reshape_with_args`].
/// Reshapes the given tensor to the specified shape, with argument specifying the order and whether
/// to copy data.
///
/// See also [`reshape_with_args`].
/// Reshapes the given tensor to the specified shape, with argument specifying the order and whether
/// to copy data.
///
/// See also [`reshape_with_args`].
/// Reshapes the given tensor to the specified shape, with argument specifying the order and whether
/// to copy data.
///
/// See also [`reshape_with_args`].
/// Reshapes the given tensor to the specified shape, with argument specifying the order and whether
/// to copy data.
///
/// See also [`reshape_with_args`].
/// Reshapes the given tensor to the specified shape, with argument specifying the order and whether
/// to copy data.
///
/// For usual users, please consider using [`reshape`] (take reference of tensor) or [`into_shape`]
/// (take ownership of tensor) instead, which are simpler interfaces to reshaping.
///
/// <div class="warning">
///
/// **Row/Column Major Notice**
///
/// This function behaves differently on default orders ([`RowMajor`] and [`ColMajor`]) of device.
///
/// </div>
///
/// # Parameters
///
/// - `tensor`: [`TensorAny<R, T, B, D>`]
///
/// - The input tensor to be reshaped.
///
/// - `shape`: TryInto [`AxesIndex<isize>`]
///
/// - The new shape of the tensor.
/// - Can be a single integer, or a list/tuple of integers.
/// - Negative values are supported and indicate counting dimensions from the back.
/// - Overloads:
///
/// - integer: 1-D shape with a single dimension.
/// - vector/array/tuple of integers: N-D shape with N dimensions. For tuples,
/// mixed-signed/unsigned integers are supported.
///
/// - `args`: Into [`ReshapeArgs`]
///
/// - `order`: The indexing order for **reading** (similar to changing the default-order of
/// device). This also affects the order for writing. [`RowMajor`] and [`ColMajor`] are
/// supported. By default, the device's default order is used.
///
/// - `copy`: Whether to clone data when the new shape is not compatible with the original shape.
///
/// - True: The tensor will always be copied. The output tensor will be contiguous with the
/// specified order.
/// - False: Panic if the new shape is not compatible with the original shape.
/// - None (default): The tensor will be copied only if necessary. If copied, the output tensor
/// will be contiguous with the specified order. Copy will be avoided if the new shape is
/// compatible with the original layout, even if the tensor is not contiguous.
///
/// - Overloads:
///
/// - copy: [`bool`]
/// - copy: [`Option<bool>`] (None means default behavior)
/// - order: [`TensorOrder`]
/// - (order: [`TensorOrder`], copy: [`bool`])
/// - (order: [`TensorOrder`], copy: [`Option<bool>`])
///
/// # Examples
///
/// You can specify the order for reading the tensor by argument `order`.
///
/// Following is an example of row-major reshape. This is independent to the original default-layout
/// of device.
///
/// ```rust
/// # use rstsr::prelude::*;
/// # let mut device = DeviceCpu::default();
/// # device.set_default_order(RowMajor);
/// let a = rt::tensor_from_nested!([[0, 1, 2], [3, 4, 5]], &device);
/// println!("{a}");
/// // [[ 0 1 2]
/// // [ 3 4 5]]
/// let a_row = rt::tensor_from_nested!([[0, 1], [2, 3], [4, 5]], &device);
/// println!("{a_row}");
/// // [[ 0 1]
/// // [ 2 3]
/// // [ 4 5]]
/// ```
///
/// And here is an example of col-major reshape.
///
/// ```rust
/// # use rstsr::prelude::*;
/// # let mut device = DeviceCpu::default();
/// # device.set_default_order(RowMajor);
/// let a = rt::tensor_from_nested!([[0, 1, 2], [3, 4, 5]], &device);
/// println!("{a}");
/// // [[ 0 1 2]
/// // [ 3 4 5]]
/// let a_col = rt::tensor_from_nested!([[0, 4], [3, 2], [1, 5]], &device);
/// println!("{a_col}");
/// // [[ 0 4]
/// // [ 3 2]
/// // [ 1 5]]
/// ```
///
/// The following example shows that if `copy = false`, then an error will be raised when the new
/// shape is not compatible with the original shape. Given a strided tensor:
///
/// ```rust
/// # use rstsr::prelude::*;
/// # let mut device = DeviceCpu::default();
/// # device.set_default_order(RowMajor);
/// // shape: (4, 6, 9), stride: (72, 9, 1), not c-contiguous
/// // contiguous situation: (4, [6, 9]), or say the last two dimensions are contiguous
/// let a = rt::arange((288, &device)).into_shape([4, 8, 9]).into_slice((.., 0..6, ..));
/// assert_eq!(a.shape(), &[4, 6, 9]);
/// assert_eq!(a.stride(), &[72, 9, 1]);
/// assert!(!a.c_contig());
/// ```
///
/// The following example shows the reshaping does not explicitly clones data, and `copy = false`
/// does not raise error.
///
/// ```rust
/// # use rstsr::prelude::*;
/// # let mut device = DeviceCpu::default();
/// # device.set_default_order(RowMajor);
/// let a = rt::arange((288, &device)).into_shape([4, 8, 9]).into_slice((.., 0..6, ..));
/// // split a single dimension into multiple dimensions
/// assert!(a.reshape_with_args_f([2, 2, 6, 9], false).is_ok()); // (4, 6, 9) -> ([2, 2], 6, 9)
/// assert!(a.reshape_with_args_f([4, 3, 2, 9], false).is_ok()); // (4, 6, 9) -> (4, [3, 2], 9)
/// assert!(a.reshape_with_args_f([4, 2, 3, 3, 3], false).is_ok()); // (4, 6, 9) -> (4, [2, 3], [3, 3])
///
/// // merge contiguous dimensions into a single dimension
/// assert!(a.reshape_with_args_f([4, 54], false).is_ok()); // (4, 6, 9) -> (4, 6 * 9)
///
/// // merge contiguous dimensions and then split
/// assert!(a.reshape_with_args_f([4, 3, 6, 3], false).is_ok()); // (4, [6, 9]) -> (4, [3, 6, 3])
/// ```
///
/// However, the following example will raise error due to shape-incompatible. Using `copy = None`
/// or `copy = true` will work, but the data will be cloned.
///
/// ```rust
/// # use rstsr::prelude::*;
/// # let mut device = DeviceCpu::default();
/// # device.set_default_order(RowMajor);
/// let a = rt::arange((288, &device)).into_shape([4, 8, 9]).into_slice((.., 0..6, ..));
/// // merge non-contiguous dimensions
/// assert!(a.reshape_with_args_f([24, 9], false).is_err()); // (4, 6, 9) -> (4 * 6, 9)
/// assert!(a.reshape_with_args_f([-1], false).is_err()); // (4, 6, 9) -> (4 * 6 * 9)
/// assert!(a.reshape_with_args_f([12, 2, 9], false).is_err()); // (4, 6, 9) -> (4 * [3, 2], 9)
/// ```
///
/// # Notes of API accordance
///
/// - Array-API: `reshape(x, /, shape, *, copy=None)` ([`reshape`](https://data-apis.org/array-api/latest/API_specification/generated/array_api.reshape.html))
/// - NumPy: `reshape(a, /, shape, order='C', *, copy=False)` ([`numpy.reshape`](https://numpy.org/doc/stable/reference/generated/numpy.reshape.html)):
/// - RSTSR: `rt::reshape_with_args(tensor, shape, (order, copy))`
/// - RSTSR: `rt::reshape(tensor, shape)`
///
/// Please note that the `order` argument in RSTSR does not support NumPy's `'A'` (order='A' means
/// 'F' if the array is Fortran contiguous, 'C' otherwise in NumPy).
///
/// # See also
///
/// ## Similar function from other crates/libraries
///
/// - Python Array API standard: [`reshape`](https://data-apis.org/array-api/2024.12/API_specification/generated/array_api.reshape.html)
/// - NumPy: [`reshape`](https://numpy.org/doc/stable/reference/generated/numpy.reshape.html)
/// - ndarray: [`to_shape`](https://docs.rs/ndarray/latest/ndarray/struct.ArrayBase.html#method.to_shape)
///
/// ## Related functions in RSTSR
///
/// - [`reshape`]: simpler interface for reshaping.
/// - [`reshapeable_without_copy`]: Check whether the layout is compatible with the new shape.
/// - [`to_layout`]: Return a tensor with the specified layout.
/// - [`to_contig`]: Return an owned contiguous tensor.
///
/// ## Variants of this function
///
/// - [`reshape_with_args`] / [`reshape_with_args_f`]: Taking reference and returning Cow.
/// - [`into_shape_with_args`] / [`into_shape_with_args_f`]: Taking ownership and returning owned
/// tensor.
/// - [`change_shape_with_args`] / [`change_shape_with_args_f`]: Taking ownership and returning Cow.
/// - [`to_shape_with_args`] / [`to_shape_with_args_f`]: Alias to [`reshape_with_args`] /
/// [`reshape_with_args_f`].
/// - Associated methods on [`TensorAny`]:
///
/// - [`Tensor::reshape_with_args`] / [`Tensor::reshape_with_args_f`]
/// - [`Tensor::into_shape_with_args`] / [`Tensor::into_shape_with_args_f`]
/// - [`Tensor::change_shape_with_args`] / [`Tensor::change_shape_with_args_f`]
/// - [`Tensor::to_shape_with_args`] / [`Tensor::to_shape_with_args_f`]
pub use reshape_with_args as to_shape_with_args;
pub use reshape_with_args_f as to_shape_with_args_f;
/* #endregion */
/* #region reshape */
/// Reshapes the given tensor to the specified shape.
///
/// # See also [`reshape`], [`into_shape`], [`change_shape`] and [`reshape_with_args`].
/// Reshapes the given tensor to the specified shape.
///
/// This function is not intended to be used by usual users. Please consider using
/// [`reshape`] (take reference of tensor) or [`into_shape`] (take ownership of tensor)
/// instead.
///
/// <div class="warning">
///
/// **Row/Column Major Notice**
///
/// This function behaves differently on default orders ([`RowMajor`] and [`ColMajor`]) of device.
///
/// </div>
///
/// # Parameters
///
/// - `tensor`: [`TensorAny<R, T, B, D>`]
///
/// - The input tensor to be reshaped.
/// - Ownership of input tensor is taken.
///
/// - `shape`: TryInto [`AxesIndex<isize>`]
///
/// - Position in the expanded axes where the new axis (or axes) is placed.
/// - Can be a single integer, or a list/tuple of integers.
/// - Negative values are supported and indicate counting dimensions from the back.
///
/// # Returns
///
/// - [`TensorCow<'a, T, B, IxD>`](TensorCow)
///
/// - The reshaped tensor.
/// - This function will try to avoid data cloning if possible.
///
/// - If layout-compatible, depending on whether the input tensor is owned or other cases,
/// either a view or owned tensor will be returned.
/// - If layout-not-compatible, an owned tensor will be returned, cloning the data.
/// - Cow (Clone-on-Write) semantics is used for representing either view or owned tensor.
///
/// This function is different to [`reshape`], in that it takes ownership of the input
/// tensor.
///
/// This function is also different to [`into_shape`], in that it may return a view, if the input
/// tensor also have the ownership of tensor view, and the layout is compatible.
///
/// # See also
///
/// Refer to [`reshape`] for more details and examples.
/// Reshapes the given tensor to the specified shape.
///
/// # See also [`reshape`], [`into_shape`], [`change_shape`] and [`reshape_with_args`].
/// Reshapes the given tensor to the specified shape.
///
/// <div class="warning">
///
/// **Row/Column Major Notice**
///
/// This function behaves differently on default orders ([`RowMajor`] and [`ColMajor`]) of device.
///
/// </div>
///
/// # Parameters
///
/// - `tensor`: [`TensorAny<R, T, B, D>`]
///
/// - The input tensor to be reshaped.
/// - Ownership of input tensor is taken.
///
/// - `shape`: TryInto [`AxesIndex<isize>`]
///
/// - The new shape of the tensor.
/// - Can be a single integer, or a list/tuple of integers.
/// - Negative values are supported and indicate counting dimensions from the back.
/// - Overloads:
/// - integer: 1-D shape with a single dimension.
/// - vector/array/tuple of integers: N-D shape with N dimensions. For tuples,
/// mixed-signed/unsigned integers are supported.
///
/// # Returns
///
/// - [`Tensor<T, B, IxD>`]
///
/// - The reshaped tensor.
/// - This function will try to avoid data cloning if possible, but with strict conditions:
///
/// - Layout-compatible after reshaping;
/// - Input tensor owns the underlying data (i.e., not a view);
/// - The input tensor is compact in memory (i.e., the underlying data does not have redundant
/// elements; size of tensor exactly matches the length of underlying data).
///
/// This function is different to [`change_shape`](change_shape()) and [`reshape`], in
/// that it takes ownership of the input tensor, and always returns an owned tensor.
///
/// # Examples
///
/// ```rust
/// use rstsr::prelude::*;
/// let a = rt::arange(6).into_shape([2, 3]);
/// ```
///
/// # Elaborated examples
///
/// Here is some showcases that demonstrate when data cloning happens or not. All examples are
/// row-major.
///
/// A first case is a tensor that is not fully contiguous (containing negative strides), but the
/// tensor is compact (size of tensor is the same to the length of underlying data). In this case,
/// if the new shape is compatible, no data cloning happens:
///
/// ```rust
/// # use rstsr::prelude::*;
/// # let mut device = DeviceCpu::default();
/// # device.set_default_order(RowMajor);
/// // shape: (4, 6, 9), stride: (-54, 9, 1), not c-contiguous
/// // contiguous situation: (4, [6, 9]); the first dimension is reversed
/// let a = rt::arange((216, &device)).into_shape([4, 6, 9]).into_flip(0);
/// let a_ptr = a.raw().as_ptr();
/// let b = a.into_shape([4, 54]);
/// let b_ptr = b.raw().as_ptr();
/// assert_eq!(a_ptr, b_ptr); // contiguous dims merged, no data clone happened
/// ```
///
/// However, if the new shape is not compatible, data cloning will happen:
///
/// ```rust
/// # use rstsr::prelude::*;
/// # let mut device = DeviceCpu::default();
/// # device.set_default_order(RowMajor);
/// // shape: (4, 6, 9), stride: (-54, 9, 1), not c-contiguous
/// // contiguous situation: (4, [6, 9]); the first dimension is reversed
/// let a = rt::arange((216, &device)).into_shape([4, 6, 9]).into_flip(0);
/// let a_ptr = a.raw().as_ptr();
/// let b = a.into_shape([24, 9]);
/// let b_ptr = b.raw().as_ptr();
/// assert_ne!(a_ptr, b_ptr); // layout not compatible, data clone happened
/// ```
///
/// Another case is a tensor that is not compact (size of tensor is less than the length of
/// underlying data). In this case, even if the new shape is compatible, data cloning will happen:
///
/// ```rust
/// # use rstsr::prelude::*;
/// # let mut device = DeviceCpu::default();
/// # device.set_default_order(RowMajor);
/// // shape: (4, 6, 9), stride: (72, 9, 1), not c-contiguous
/// // contiguous situation: (4, [6, 9]), or say the last two dimensions are contiguous
/// let a = rt::arange((288, &device)).into_shape([4, 8, 9]).into_slice((.., 0..6, ..));
/// let a_ptr = a.raw().as_ptr();
/// let b = a.into_shape([4, 54]);
/// let b_ptr = b.raw().as_ptr();
/// assert_ne!(a_ptr, b_ptr); // layout-compatible, but input tensor is not compact (216 < 288)
/// ```
///
/// # See also
///
/// Refer to [`reshape`] for more details and examples.
/// Reshapes the given tensor to the specified shape.
///
/// # See also [`reshape`], [`into_shape`], [`change_shape`] and [`reshape_with_args`].
/// Reshapes the given tensor to the specified shape.
///
/// Advanced arguments can be specified by function [`reshape_with_args`] if you want to control the
/// order for reading the tensor, and whether to copy data.
///
/// <div class="warning">
///
/// **Row/Column Major Notice**
///
/// This function behaves differently on default orders ([`RowMajor`] and [`ColMajor`]) of device.
///
/// </div>
///
/// # Parameters
///
/// - `tensor`: [`&TensorAny<R, T, B, D>`](TensorAny)
///
/// - The input tensor to be reshaped.
///
/// - `shape`: TryInto [`AxesIndex<isize>`]
///
/// - The new shape of the tensor.
/// - Can be a single integer, or a list/tuple of integers.
/// - Negative values are supported and indicate counting dimensions from the back.
/// - Overloads:
/// - integer: 1-D shape with a single dimension.
/// - vector/array/tuple of integers: N-D shape with N dimensions. For tuples,
/// mixed-signed/unsigned integers are supported.
///
/// # Returns
///
/// - [`TensorCow<'a, T, B, IxD>`](TensorCow)
///
/// - The reshaped tensor.
/// - This function will try to avoid data cloning if possible.
///
/// - If layout-compatible, a view will be returned.
/// - If shape-not-compatible, an owned tensor will be returned, cloning the data.
/// - Cow (Clone-on-Write) semantics is used for representing either view or owned tensor.
///
/// # Examples
///
/// In row-major order, to reshape a vector of (6, ) to a matrix of (2, 3):
/// ```rust
/// # use rstsr::prelude::*;
/// # let mut device = DeviceCpu::default();
/// # device.set_default_order(RowMajor);
/// let a = rt::arange((6, &device));
/// let result = a.reshape([2, 3]);
/// println!("{result}");
/// // [[ 0 1 2]
/// // [ 3 4 5]]
/// ```
///
/// You can also use negative dimension, where -1 means "infer this dimension":
///
/// ```rust
/// # use rstsr::prelude::*;
/// # let mut device = DeviceCpu::default();
/// # device.set_default_order(RowMajor);
/// // in this case, unspecified axes length is inferred as 6 / 3 = 2
/// let a = rt::arange((6, &device));
/// let result = a.reshape([3, -1]);
/// println!("{result}");
/// // [[ 0 1]
/// // [ 2 3]
/// // [ 4 5]]
/// ```
///
/// # Ownership Semantics between [`reshape`], [`into_shape`] and [`change_shape`]
///
/// [`into_shape`] and [`change_shape`] take ownership of the input tensor. They are important
/// variants to this function [`reshape`].
///
/// | Function | Input Ownership | Output Ownership | Cloning Condition |
/// |--|--|--|--|
/// | [`reshape`] | Borrowed <br> [`&TensorAny`](TensorAny) | View <br> [`TensorCow`] with [`DataCow::Ref`] | not cloned (layout-compatible) |
/// | | | Owned <br> [`TensorCow`] with [`DataCow::Owned`] | cloned (layout-not-compatible) |
/// | [`into_shape`] | Owned <br> [`Tensor`] | Owned <br> [`Tensor`] | not cloned (layout-compatible, input tensor owns data, input tensor is compact) |
/// | | | Owned <br> [`Tensor`] | cloned (otherwise) |
/// | | Otherwise <br> [`TensorAny`] | Owned <br> [`Tensor`] | cloned (always) |
/// | [`change_shape`] | Owned <br> [`Tensor`] | Owned <br> [`TensorCow`] with [`DataCow::Owned`] | not cloned (layout-compatible, input tensor owns data, input tensor is compact) |
/// | | | Owned <br> [`TensorCow`] with [`DataCow::Owned`] | cloned (otherwise) |
/// | | Otherwise <br> [`TensorAny`] | View <br> [`TensorCow`] with [`DataCow::Ref`] | not cloned (layout-compatible) |
/// | | | Owned <br> [`TensorCow`] with [`DataCow::Owned`] | cloned (layout-not-compatible) |
///
/// # Tips on common compilation errors
///
/// You may encounter ownership problem when you try to assign a reshaped tensor like this:
///
/// ```compile_fail
/// # use rstsr::prelude::*;
/// # let mut device = DeviceCpu::default();
/// # device.set_default_order(RowMajor);
/// let a = rt::arange((6, &device)).reshape([2, 3]);
/// println!("a: {:?}", a);
/// ```
///
/// The compiler may give an error like:
///
/// ```text
/// 704 | let a = rt::arange((6, &device)).reshape([2, 3]);
/// | ^^^^^^^^^^^^^^^^^^^^^^^^ - temporary value is freed at the end of this statement
/// | |
/// | creates a temporary value which is freed while still in use
/// 705 | println!("a: {:?}", a);
/// | - borrow later used here
/// |
/// help: consider using a `let` binding to create a longer lived value
/// |
/// 704 ~ let binding = rt::arange((6, &device));
/// 705 ~ let a = binding.reshape([2, 3]);
/// |
/// ```
///
/// The suggestion by compiler is correct. However, you have another simpler way to solve this
/// problem by using [`into_shape`] variant that takes ownership:
///
/// ```rust
/// # use rstsr::prelude::*;
/// # let mut device = DeviceCpu::default();
/// # device.set_default_order(RowMajor);
/// let a = rt::arange((6, &device)).into_shape([2, 3]);
/// ```
///
/// # Notes of API accordance
///
/// - Array-API: `reshape(x, /, shape, *, copy=None)` ([`reshape`](https://data-apis.org/array-api/latest/API_specification/generated/array_api.reshape.html))
/// - NumPy: `reshape(a, /, shape, order='C', *, copy=False)` ([`numpy.reshape`](https://numpy.org/doc/stable/reference/generated/numpy.reshape.html)):
/// - RSTSR: `rt::reshape_with_args(tensor, shape, (order, copy))`
/// - RSTSR: `rt::reshape(tensor, shape)`
///
/// Please note this function does not support `order` and `copy` arguments in NumPy's `reshape`.
/// You can use function [`reshape_with_args`] to specify these arguments.
///
/// # Elaborated examples
///
/// ## Difference between [RowMajor] and [ColMajor]
///
/// Tensor can be uniquely iterated (into a 1-dimension vector), for either row-major or
/// column-major order.
///
/// **Reshape operation does not change the iterated sequence of a tensor**, by definition. In other
/// words, the following code always holds true:
///
/// ```rust
/// # use rstsr::prelude::*;
/// # let mut device = DeviceCpu::default();
/// # device.set_default_order(ColMajor);
/// let a = rt::tensor_from_nested!([[0, 1, 2], [3, 4, 5]], &device);
/// # let b = a.reshape([3, 2]);
/// // note iteration order of associated method `iter` depends on `device.default_order()`
///
/// // let b = a.reshape(... SOME SHAPE ...);
/// let a_vec = a.iter().collect::<Vec<_>>();
/// let b_vec = b.iter().collect::<Vec<_>>();
/// assert_eq!(a_vec, b_vec); // iterated sequence is the same
/// ```
///
/// For example, in row-major order, reshape a matrix of (2, 3) to (3, 2):
///
/// ```rust
/// # use rstsr::prelude::*;
/// # let mut device = DeviceCpu::default();
/// // set to row-major order
/// device.set_default_order(RowMajor);
/// // a: [[0, 1, 2], [3, 4, 5]]
/// // b: [[0, 1], [2, 3], [4, 5]]
/// // iterated sequence: [0, 1, 2, 3, 4, 5]
///
/// let a = rt::tensor_from_nested!([[0, 1, 2], [3, 4, 5]], &device);
/// println!("{a}");
/// // [[ 0 1 2]
/// // [ 3 4 5]]
/// let b = a.reshape([3, 2]);
/// println!("{b}");
/// // [[ 0 1]
/// // [ 2 3]
/// // [ 4 5]]
///
/// let a_vec = a.iter().cloned().collect::<Vec<_>>();
/// println!("{a_vec:?}");
/// // [0, 1, 2, 3, 4, 5]
/// let b_vec = b.iter().cloned().collect::<Vec<_>>();
/// println!("{b_vec:?}");
/// // [0, 1, 2, 3, 4, 5]
/// ```
///
/// In the column-major order, reshape the same matrix of (2, 3) to (3, 2) will yield a different
/// result:
///
/// ```rust
/// # use rstsr::prelude::*;
/// # let mut device = DeviceCpu::default();
/// // set to column-major order
/// device.set_default_order(ColMajor);
/// // a: [[0, 1, 2], [3, 4, 5]]
/// // b: [[0, 4], [3, 2], [1, 5]]
/// // iterated sequence: [0, 3, 1, 4, 2, 5]
///
/// let a = rt::tensor_from_nested!([[0, 1, 2], [3, 4, 5]], &device);
/// println!("{a}");
/// // [[ 0 1 2]
/// // [ 3 4 5]]
/// let b = a.reshape([3, 2]);
/// println!("{b}");
/// // [[ 0 4]
/// // [ 3 2]
/// // [ 1 5]]
///
/// let a_vec = a.iter().cloned().collect::<Vec<_>>();
/// println!("{a_vec:?}");
/// // [0, 3, 1, 4, 2, 5]
/// let b_vec = b.iter().cloned().collect::<Vec<_>>();
/// println!("{b_vec:?}");
/// // [0, 3, 1, 4, 2, 5]
/// ```
///
/// You can also use function [`reshape_with_args`]`(shape, order)` to specify the order for reading
/// the tensor.
///
/// ## Occasions of data cloning
///
/// The following discussion assumes the tensor is in row-major order. Similar discussion applies to
/// column-major order.
///
/// If the tensor to be reshaped is already in C-contiguous if the device is also row-major, or
/// F-contiguous if the device is column-major, then the reshape operation can be performed without
/// any data cloning.
///
/// Otherwise, whether data cloning is necessary depends. For example, consider a tensor of shape
/// (4, 6, 9) but with non-contiguous strides:
///
/// ```rust
/// # use rstsr::prelude::*;
/// # let mut device = DeviceCpu::default();
/// # device.set_default_order(RowMajor);
/// // contiguous situation: (4, [6, 9]), or say the last two dimensions are contiguous
/// let a = rt::arange((288, &device)).into_shape([4, 8, 9]).into_slice((.., 0..6, ..));
/// println!("{:?}", a.layout());
/// // 3-Dim (dyn), contiguous: c
/// // shape: [4, 6, 9], stride: [72, 9, 1], offset: 0
/// ```
///
/// Those cases will not require data cloning (returns a view, or [`DataCow::Ref`] internally):
///
/// ```rust
/// # use rstsr::prelude::*;
/// # let mut device = DeviceCpu::default();
/// # device.set_default_order(RowMajor);
/// let a = rt::arange((288, &device)).into_shape([4, 8, 9]).into_slice((.., 0..6, ..));
/// // split a single dimension into multiple dimensions
/// assert!(!a.reshape([2, 2, 6, 9]).is_owned()); // (4, 6, 9) -> ([2, 2], 6, 9)
/// assert!(!a.reshape([4, 3, 2, 9]).is_owned()); // (4, 6, 9) -> (4, [3, 2], 9)
/// assert!(!a.reshape([4, 2, 3, 3, 3]).is_owned()); // (4, 6, 9) -> (4, [2, 3], [3, 3])
///
/// // merge contiguous dimensions into a single dimension
/// assert!(!a.reshape([4, 54]).is_owned()); // (4, 6, 9) -> (4, 6 * 9)
///
/// // merge contiguous dimensions and then split
/// assert!(!a.reshape([4, 3, 6, 3]).is_owned()); // (4, [6, 9]) -> (4, [3, 6, 3])
/// ```
///
/// However, the following cases will require data cloning (returns an owned tensor, or
/// [`DataCow::Owned`] internally):
///
/// ```rust
/// # use rstsr::prelude::*;
/// # let mut device = DeviceCpu::default();
/// # device.set_default_order(RowMajor);
/// let a = rt::arange((288, &device)).into_shape([4, 8, 9]).into_slice((.., 0..6, ..));
/// assert!(a.reshape([24, 9]).is_owned()); // (4, 6, 9) -> (4 * 6, 9)
/// assert!(a.reshape(-1).is_owned()); // (4, 6, 9) -> (4 * 6 * 9)
/// assert!(a.reshape([12, 2, 9]).is_owned()); // (4, 6, 9) -> (4 * [3, 2], 9)
/// ```
///
/// Please note that default order of device (row-major or column-major) matters. For the same
/// tensor slicing, if the device is column major, then behavior of merging contiguous dimensions
/// can be different:
///
/// ```rust
/// # use rstsr::prelude::*;
/// # let mut device = DeviceCpu::default();
/// # device.set_default_order(ColMajor);
/// // contiguous situation: ([4, 6], 9), or say the first two dimensions are contiguous
/// // this is different to (4, [6, 9]) in row major case
/// let a = rt::arange((288, &device)).into_shape([4, 8, 9]).into_slice((.., 0..6, ..));
/// println!("{:?}", a.layout());
/// // 3-Dim (dyn), contiguous: f
/// // shape: [4, 6, 9], stride: [1, 4, 32], offset: 0
///
/// // merge dimensions into a single dimension, col-major will be different to row-major case
/// assert!(a.reshape([4, 54]).is_owned()); // (4, 6, 9) -> (4, 6 * 9)
/// assert!(!a.reshape([24, 9]).is_owned()); // ([4, 6], 9) -> (4 * 6, 9)
/// ```
///
/// You can also use function [`reshape_with_args`]`(shape, copy)` to specify whether to copy data
/// when the new shape is not compatible with the original shape.
///
/// Also, you can use function [`reshapeable_without_copy`] to check whether the tensor can be
/// reshaped to the new shape without copying data.
///
/// # See also
///
/// ## Similar function from other crates/libraries
///
/// - Python Array API standard: [`reshape`](https://data-apis.org/array-api/2024.12/API_specification/generated/array_api.reshape.html)
/// - NumPy: [`reshape`](https://numpy.org/doc/stable/reference/generated/numpy.reshape.html)
/// - ndarray: [`to_shape`](https://docs.rs/ndarray/latest/ndarray/struct.ArrayBase.html#method.to_shape)
///
/// ## Related functions in RSTSR
///
/// - [`reshape_with_args`]: Reshape with advanced arguments for controlling the order for reading
/// the tensor, and whether to copy data.
/// - [`reshapeable_without_copy`]: Check whether the layout is compatible with the new shape.
/// - [`to_layout`]: Return a tensor with the specified layout.
/// - [`to_contig`]: Return an owned contiguous tensor.
///
/// ## Variants of this function
///
/// - [`reshape`] / [`reshape_f`]: Taking reference and returning Cow.
/// - [`into_shape`] / [`into_shape_f`]: Taking ownership and returning owned tensor.
/// - [`change_shape`] / [`change_shape_f`]: Taking ownership and returning Cow.
/// - [`to_shape`] / [`to_shape_f`]: Alias to [`reshape`] / [`reshape_f`].
/// - Associated methods on [`TensorAny`]:
///
/// - [`TensorAny::reshape`] / [`TensorAny::reshape_f`]
/// - [`TensorAny::into_shape`] / [`TensorAny::into_shape_f`]
/// - [`TensorAny::change_shape`] / [`TensorAny::change_shape_f`]
/// - [`TensorAny::to_shape`] / [`TensorAny::to_shape_f`]
pub use reshape as to_shape;
pub use reshape_f as to_shape_f;
/// Reshapes the given tensor to the specified shape.
///
/// # See also [`reshape`], [`into_shape`], [`change_shape`] and [`reshape_with_args`].
/* #endregion */