NumCpp  2.18.0
A Templatized Header Only C++ Implementation of the Python NumPy Library
Loading...
Searching...
No Matches
insert.hpp
Go to the documentation of this file.
1
28#pragma once
29
30#include <utility>
31#include <vector>
32
35#include "NumCpp/Core/Slice.hpp"
36#include "NumCpp/Core/Types.hpp"
38#include "NumCpp/NdArray.hpp"
39
40namespace nc
41{
42 //============================================================================
43 // Method Description:
53 template<typename dtype>
54 NdArray<dtype> insert(const NdArray<dtype>& arr, int32 index, const dtype& value)
55 {
56 const NdArray<dtype> values = { value };
57 return insert(arr, index, values);
58 }
59
60 //============================================================================
61 // Method Description:
71 template<typename dtype>
72 NdArray<dtype> insert(const NdArray<dtype>& arr, int32 index, const NdArray<dtype>& values)
73 {
74 if (index < 0)
75 {
76 index += arr.size();
77 // still
78 if (index < 0)
79 {
80 THROW_INVALID_ARGUMENT_ERROR("index out of range");
81 }
82 }
83 else if (index > static_cast<int32>(arr.size()))
84 {
85 THROW_INVALID_ARGUMENT_ERROR("index out of range");
86 }
87
88 const auto valuesSlice = Slice(index, index + values.size());
89 auto result = NdArray<dtype>(1, arr.size() + values.size());
90 result.put(valuesSlice, values);
91
92 NdArray<bool> mask(result.shape());
93 mask.fill(true);
94 mask.put(valuesSlice, false);
95 result.putMask(mask, arr.flatten());
96
97 return result;
98 }
99
100 //============================================================================
101 // Method Description:
112 template<typename dtype>
113 NdArray<dtype> insert(const NdArray<dtype>& arr, int32 index, const dtype& value, Axis axis)
114 {
115 const NdArray<dtype> values = { value };
116 return insert(arr, index, values, axis);
117 }
118
119 //============================================================================
120 // Method Description:
131 template<typename dtype>
132 NdArray<dtype> insert(const NdArray<dtype>& arr, int32 index, const NdArray<dtype>& values, Axis axis)
133 {
134 switch (axis)
135 {
136 case Axis::NONE:
137 {
138 return insert(arr, index, values);
139 }
140 case Axis::ROW:
141 {
142 if (!(values.size() == arr.numCols() || values.isscalar() || values.numCols() == arr.numCols()))
143 {
144 THROW_INVALID_ARGUMENT_ERROR("input values shape cannot be broadcast to input array dimensions");
145 }
146
147 if (index < 0)
148 {
149 index += arr.numRows();
150 // still
151 if (index < 0)
152 {
153 THROW_INVALID_ARGUMENT_ERROR("index out of range");
154 }
155 }
156 else if (index > static_cast<int32>(arr.numRows()))
157 {
158 THROW_INVALID_ARGUMENT_ERROR("index out of range");
159 }
160
161 auto result = NdArray<dtype>();
162 int32 valuesSize{};
163 if (values.size() == arr.numCols() || values.isscalar())
164 {
165 result.resizeFast(arr.numRows() + 1, arr.numCols());
166 valuesSize = 1;
167 }
168 else if (values.numCols() == arr.numCols())
169 {
170 result.resizeFast(arr.numRows() + values.numRows(), arr.numCols());
171 valuesSize = values.numRows();
172 }
173
174 auto mask = ones_like<bool>(result);
175 mask.put(Slice(index, index + valuesSize), mask.cSlice(), false);
176
177 result.putMask(mask, arr);
178 result.putMask(!mask, values);
179
180 return result;
181 }
182 case Axis::COL:
183 {
184 if (!(values.size() == arr.numRows() || values.isscalar() || values.numRows() == arr.numRows()))
185 {
186 THROW_INVALID_ARGUMENT_ERROR("input values shape cannot be broadcast to input array dimensions");
187 }
188
189 if (index < 0)
190 {
191 index += arr.numCols();
192 // still
193 if (index < 0)
194 {
195 THROW_INVALID_ARGUMENT_ERROR("index out of range");
196 }
197 }
198 else if (index > static_cast<int32>(arr.numCols()))
199 {
200 THROW_INVALID_ARGUMENT_ERROR("index out of range");
201 }
202
203 auto result = NdArray<dtype>();
204 int32 valuesSize{};
205 if (values.size() == arr.numRows() || values.isscalar())
206 {
207 result.resizeFast(arr.numRows(), arr.numCols() + 1);
208 valuesSize = 1;
209 }
210 else if (values.numRows() == arr.numRows())
211 {
212 result.resizeFast(arr.numRows(), arr.numCols() + values.numCols());
213 valuesSize = values.numCols();
214 }
215
216 auto mask = ones_like<bool>(result);
217 mask.put(mask.rSlice(), Slice(index, index + valuesSize), false);
218
219 result.putMask(mask, arr);
220 result.putMask(!mask, values);
221
222 return result;
223 }
224 default:
225 {
226 // get rid of compiler warning
227 return {};
228 }
229 }
230 }
231
232 //============================================================================
233 // Method Description:
244 template<typename dtype, typename Indices, type_traits::ndarray_int_concept<Indices> = 0>
245 NdArray<dtype> insert(const NdArray<dtype>& arr, const Indices& indices, const dtype& value, Axis axis = Axis::NONE)
246 {
247 const NdArray<dtype> values = { value };
248 return insert(arr, indices, values, axis);
249 }
250
251 //============================================================================
252 // Method Description:
263 template<typename dtype>
264 NdArray<dtype> insert(const NdArray<dtype>& arr, Slice slice, const dtype& value, Axis axis = Axis::NONE)
265 {
266 auto sliceIndices = slice.toIndices(arr.dimSize(axis));
267 return insert(arr,
268 NdArray<uint32>(sliceIndices.data(), sliceIndices.size(), PointerPolicy::SHELL),
269 value,
270 axis);
271 }
272
273 //============================================================================
274 // Method Description:
285 template<typename dtype, typename Indices, type_traits::ndarray_int_concept<Indices> = 0>
286 NdArray<dtype>
287 insert(const NdArray<dtype>& arr, const Indices& indices, const NdArray<dtype>& values, Axis axis = Axis::NONE)
288 {
289 const auto isScalarValue = values.isscalar();
290
291 switch (axis)
292 {
293 case Axis::NONE:
294 {
295 if (!isScalarValue && indices.size() != values.size())
296 {
297 THROW_INVALID_ARGUMENT_ERROR("could not broadcast values into indices");
298 }
299
300 const auto arrSize = static_cast<int32>(arr.size());
301
302 std::vector<std::pair<int32, dtype>> indexValues(indices.size());
303 if (isScalarValue)
304 {
305 const auto value = values.front();
306 stl_algorithms::transform(indices.begin(),
307 indices.end(),
308 indexValues.begin(),
309 [arrSize, value](auto index) -> std::pair<int32, dtype>
310 {
311 if constexpr (type_traits::is_ndarray_signed_int_v<Indices>)
312 {
313 if (index < 0)
314 {
315 index += arrSize;
316 }
317 // still
318 if (index < 0)
319 {
320 THROW_INVALID_ARGUMENT_ERROR("index out of range");
321 }
322 }
323 if (static_cast<int32>(index) > arrSize)
324 {
325 THROW_INVALID_ARGUMENT_ERROR("index out of range");
326 }
327
328 return std::make_pair(static_cast<int32>(index), value);
329 });
330 }
331 else
332 {
333 stl_algorithms::transform(indices.begin(),
334 indices.end(),
335 values.begin(),
336 indexValues.begin(),
337 [arrSize](auto index, const auto& value) -> std::pair<int32, dtype>
338 {
339 if constexpr (type_traits::is_ndarray_signed_int_v<Indices>)
340 {
341 if (index < 0)
342 {
343 index += arrSize;
344 }
345 // still
346 if (index < 0)
347 {
348 THROW_INVALID_ARGUMENT_ERROR("index out of range");
349 }
350 }
351 if (static_cast<int32>(index) > arrSize)
352 {
353 THROW_INVALID_ARGUMENT_ERROR("index out of range");
354 }
355
356 return std::make_pair(static_cast<int32>(index), value);
357 });
358 }
359
360 stl_algorithms::sort(indexValues.begin(),
361 indexValues.end(),
362 [](const auto& indexValue1, const auto& indexValue2) noexcept -> bool
363 { return indexValue1.first < indexValue2.first; });
364 auto indexValuesUnique = std::vector<typename decltype(indexValues)::value_type>{};
365 std::unique_copy(indexValues.begin(),
366 indexValues.end(),
367 std::back_inserter(indexValuesUnique),
368 [](const auto& indexValue1, const auto& indexValue2) noexcept -> bool
369 { return indexValue1.first == indexValue2.first; });
370
371 auto result = NdArray<dtype>(1, arr.size() + indexValuesUnique.size());
372
373 auto mask = ones_like<bool>(result);
374 int32 counter = 0;
375 std::for_each(indexValuesUnique.begin(),
376 indexValuesUnique.end(),
377 [&counter, &mask](auto& indexValue) noexcept -> void
378 { mask[indexValue.first + counter++] = false; });
379
380 result.putMask(mask, arr);
381
382 auto valuesSorted = [&indexValuesUnique]
383 {
384 std::vector<dtype> values_;
385 values_.reserve(indexValuesUnique.size());
386 std::transform(indexValuesUnique.begin(),
387 indexValuesUnique.end(),
388 std::back_inserter(values_),
389 [](const auto& indexValue) { return indexValue.second; });
390 return values_;
391 }();
392
393 result.putMask(!mask, NdArray<dtype>(valuesSorted.data(), valuesSorted.size(), PointerPolicy::SHELL));
394
395 return result;
396 }
397 case Axis::ROW:
398 {
399 const auto arrNumRows = static_cast<int32>(arr.numRows());
400
401 std::vector<std::pair<int32, NdArray<dtype>>> indexValues(indices.size());
402 if (values.isscalar())
403 {
404 const auto value = values.front();
405 auto valueRow = NdArray<dtype>(1, arr.numCols());
406 valueRow.fill(value);
407 stl_algorithms::transform(indices.begin(),
408 indices.end(),
409 indexValues.begin(),
410 [arrNumRows, &valueRow](auto index) -> std::pair<int32, NdArray<dtype>>
411 {
412 if constexpr (type_traits::is_ndarray_signed_int_v<Indices>)
413 {
414 if (index < 0)
415 {
416 index += arrNumRows;
417 }
418 // still
419 if (index < 0)
420 {
421 THROW_INVALID_ARGUMENT_ERROR("index out of range");
422 }
423 }
424 if (static_cast<int32>(index) > arrNumRows)
425 {
426 THROW_INVALID_ARGUMENT_ERROR("index out of range");
427 }
428
429 return std::make_pair(static_cast<int32>(index), valueRow);
430 });
431 }
432 else if (values.size() == arr.numCols())
433 {
434 stl_algorithms::transform(indices.begin(),
435 indices.end(),
436 indexValues.begin(),
437 [arrNumRows, &values](auto index) -> std::pair<int32, NdArray<dtype>>
438 {
439 if constexpr (type_traits::is_ndarray_signed_int_v<Indices>)
440 {
441 if (index < 0)
442 {
443 index += arrNumRows;
444 }
445 // still
446 if (index < 0)
447 {
448 THROW_INVALID_ARGUMENT_ERROR("index out of range");
449 }
450 }
451 if (static_cast<int32>(index) > arrNumRows)
452 {
453 THROW_INVALID_ARGUMENT_ERROR("index out of range");
454 }
455
456 return std::make_pair(static_cast<int32>(index), values);
457 });
458 }
459 else if (values.numCols() == arr.numCols() && values.numRows() == indices.size())
460 {
461 int32 counter = 0;
462 std::transform(indices.begin(),
463 indices.end(),
464 indexValues.begin(),
465 [arrNumRows, &values, &counter](auto index) -> std::pair<int32, NdArray<dtype>>
466 {
467 if constexpr (type_traits::is_ndarray_signed_int_v<Indices>)
468 {
469 if (index < 0)
470 {
471 index += arrNumRows;
472 }
473 // still
474 if (index < 0)
475 {
476 THROW_INVALID_ARGUMENT_ERROR("index out of range");
477 }
478 }
479 if (static_cast<int32>(index) > arrNumRows)
480 {
481 THROW_INVALID_ARGUMENT_ERROR("index out of range");
482 }
483
484 return std::make_pair(static_cast<int32>(index),
485 values(counter++, values.cSlice()));
486 });
487 }
488 else
489 {
490 THROW_INVALID_ARGUMENT_ERROR("input values shape cannot be broadcast to input array dimensions");
491 }
492
493 stl_algorithms::sort(indexValues.begin(),
494 indexValues.end(),
495 [](const auto& indexValue1, const auto& indexValue2) noexcept -> bool
496 { return indexValue1.first < indexValue2.first; });
497 auto indexValuesUnique = std::vector<typename decltype(indexValues)::value_type>{};
498 std::unique_copy(indexValues.begin(),
499 indexValues.end(),
500 std::back_inserter(indexValuesUnique),
501 [](const auto& indexValue1, const auto& indexValue2) noexcept -> bool
502 { return indexValue1.first == indexValue2.first; });
503
504 auto result = NdArray<dtype>(arrNumRows + indexValuesUnique.size(), arr.numCols());
505
506 auto mask = ones_like<bool>(result);
507 int32 counter = 0;
508 std::for_each(indexValuesUnique.begin(),
509 indexValuesUnique.end(),
510 [&counter, &mask](auto& indexValue) noexcept -> void
511 { mask.put(indexValue.first + counter++, mask.cSlice(), false); });
512
513 result.putMask(mask, arr);
514
515 counter = 0;
516 for (const auto& [index, values_] : indexValuesUnique)
517 {
518 result.put(index + counter++, result.cSlice(), values_);
519 }
520
521 return result;
522 }
523 case Axis::COL:
524 {
525 return insert(arr.transpose(), indices, values.transpose(), Axis::ROW).transpose();
526 }
527 default:
528 {
529 // get rid of compiler warning
530 return {};
531 }
532 }
533 }
534
535 //============================================================================
536 // Method Description:
547 template<typename dtype>
548 NdArray<dtype> insert(const NdArray<dtype>& arr, Slice slice, const NdArray<dtype>& values, Axis axis = Axis::NONE)
549 {
550 auto sliceIndices = slice.toIndices(arr.dimSize(axis));
551 return insert(arr,
552 NdArray<uint32>(sliceIndices.data(), sliceIndices.size(), PointerPolicy::SHELL),
553 values,
554 axis);
555 }
556} // namespace nc
#define THROW_INVALID_ARGUMENT_ERROR(msg)
Definition Error.hpp:37
Holds 1D and 2D arrays, the main work horse of the NumCpp library.
Definition NdArrayCore.hpp:135
size_type dimSize(Axis inAxis) const noexcept
Definition NdArrayCore.hpp:2756
size_type size() const noexcept
Definition NdArrayCore.hpp:4600
size_type numCols() const noexcept
Definition NdArrayCore.hpp:3541
self_type flatten() const
Definition NdArrayCore.hpp:2923
self_type & fill(value_type inFillValue) noexcept
Definition NdArrayCore.hpp:2884
const_reference front() const noexcept
Definition NdArrayCore.hpp:2936
self_type & putMask(const NdArray< bool > &inMask, const value_type &inValue)
Definition NdArrayCore.hpp:4211
size_type numRows() const noexcept
Definition NdArrayCore.hpp:3553
iterator begin() noexcept
Definition NdArrayCore.hpp:1311
bool isscalar() const noexcept
Definition NdArrayCore.hpp:3032
self_type & put(index_type inIndex, const value_type &inValue)
Definition NdArrayCore.hpp:3769
A Class for slicing into NdArrays.
Definition Slice.hpp:45
std::vector< uint32 > toIndices(uint32 inArrayDimSize)
Definition Slice.hpp:214
void sort(RandomIt first, RandomIt last) noexcept
Definition StlAlgorithms.hpp:697
OutputIt transform(InputIt first, InputIt last, OutputIt destination, UnaryOperation unaryFunction)
Definition StlAlgorithms.hpp:776
Definition Cartesian.hpp:39
NdArray< dtype > insert(const NdArray< dtype > &arr, int32 index, const dtype &value)
Definition insert.hpp:54
Axis
Enum To describe an axis.
Definition Enums.hpp:36
@ ROW
Definition Enums.hpp:38
@ COL
Definition Enums.hpp:39
@ NONE
Definition Enums.hpp:37
std::int32_t int32
Definition Types.hpp:36
NdArray< dtypeOut > ones_like(const NdArray< dtype > &inArray)
Definition ones_like.hpp:45
@ SHELL
Definition Enums.hpp:58