This quick start guide is meant as a very brief overview of some of the things
that can be done with NumCpp. For a full breakdown of everything available
in the NumCpp library please visit the Full Documentation.
CONTAINERS
The main data structure in NumCpp is the NdArray. It is inherently a 2D array class, with 1D arrays being implemented as 1xN arrays. There is also a DataCube class that is provided as a convenience container for storing an array of 2D NdArrays, but it has limited usefulness past a simple container.
NumPy
NumCpp
a = np.array([[1, 2], [3, 4], [5, 6]])
nc::NdArray<int> a = { {1, 2}, {3, 4}, {5, 6} }
a.reshape([2, 3])
a.reshape(2, 3)
a.astype(np.double)
a.astype<double>()
INITIALIZERS
Many initializer functions are provided that return NdArrays for common needs.
NumPy
NumCpp
np.linspace(1, 10, 5)
nc::linspace<dtype>(1, 10, 5)
np.arange(3, 7)
nc::arange<dtype>(3, 7)
np.eye(4)
nc::eye<dtype>(4)
np.zeros([3, 4])
nc::zeros<dtype>(3, 4)
nc::NdArray<dtype>(3, 4) a = 0
np.ones([3, 4])
nc::ones<dtype>(3, 4)
nc::NdArray<dtype>(3, 4) a = 1
np.nans([3, 4])
nc::nans(3, 4)
nc::NdArray<double>(3, 4) a = nc::constants::nan
np.empty([3, 4])
nc::empty<dtype>(3, 4)
nc::NdArray<dtype>(3, 4) a
SLICING/BROADCASTING
NumCpp offers NumPy style slicing and broadcasting.
NumPy
NumCpp
a[2, 3]
a(2, 3)
a[2:5, 5:8]
a(nc::Slice(2, 5), nc::Slice(5, 8))
a({2, 5}, {5, 8})
a[:, 7]
a(a.rSlice(), 7)
a[a > 5]
a[a > 5]
a[a > 5] = 0
a.putMask(a > 5, 0)
RANDOM
The random module provides simple ways to create random arrays.
NumPy
NumCpp
np.random.seed(666)
nc::random::seed(666)
np.random.randn(3, 4)
nc::random::randN<double>(nc::Shape(3, 4))
nc::random::randN<double>({3, 4})
np.random.randint(0, 10, [3, 4])
nc::random::randInt<int>(nc::Shape(3, 4), 0, 10)
nc::random::randInt<int>({3, 4}, 0, 10)
np.random.rand(3, 4)
nc::random::rand<double>(nc::Shape(3,4))
nc::random::rand<double>({3, 4})
np.random.choice(a, 3)
nc::random::choice(a, 3)
CONCATENATION
Many ways to concatenate NdArray are available.
NumPy
NumCpp
np.stack([a, b, c], axis=0)
nc::stack({a, b, c}, nc::Axis::ROW)
np.vstack([a, b, c])
nc::vstack({a, b, c})
np.hstack([a, b, c])
nc::hstack({a, b, c})
np.append(a, b, axis=1)
nc::append(a, b, nc::Axis::COL)
DIAGONAL, TRIANGULAR, AND FLIP
The following return new NdArrays.
NumPy
NumCpp
np.diagonal(a)
nc::diagonal(a)
np.triu(a)
nc::triu(a)
np.tril(a)
nc::tril(a)
np.flip(a, axis=0)
nc::flip(a, nc::Axis::ROW)
np.flipud(a)
nc::flipud(a)
np.fliplr(a)
nc::fliplr(a)
ITERATION
NumCpp follows the idioms of the C++ STL providing iterator pairs to iterate on arrays in different fashions.
NumPy
NumCpp
for value in a
for(auto it = a.begin(); it < a.end(); ++it)
for(auto& value : a)
LOGICAL
Logical FUNCTIONS in NumCpp behave the same as NumPy.
NumPy
NumCpp
np.where(a > 5, a, b)
nc::where(a > 5, a, b)
np.any(a)
nc::any(a)
np.all(a)
nc::all(a)
np.logical_and(a, b)
nc::logical_and(a, b)
np.logical_or(a, b)
nc::logical_or(a, b)
np.isclose(a, b)
nc::isclose(a, b)
np.allclose(a, b)
nc::allclose(a, b)
COMPARISONS
NumPy
NumCpp
np.equal(a, b)
nc::equal(a, b)
a == b
np.not_equal(a, b)
nc::not_equal(a, b)
a != b
rows, cols = np.nonzero(a)
auto [rows, cols] = nc::nonzero(a)
MINIMUM, MAXIMUM, SORTING
NumPy
NumCpp
np.min(a)
nc::min(a)
np.max(a)
nc::max(a)
np.argmin(a)
nc::argmin(a)
np.argmax(a)
nc::argmax(a)
np.sort(a, axis=0)
nc::sort(a, nc::Axis::ROW)
np.argsort(a, axis=1)
nc::argsort(a, nc::Axis::COL)
np.unique(a)
nc::unique(a)
np.setdiff1d(a, b)
nc::setdiff1d(a, b)
np.diff(a)
nc::diff(a)
REDUCERS
Reducers accumulate values of NdArrays along specified axes. When no axis is specified, values are accumulated along all axes.
NumPy
NumCpp
np.sum(a)
nc::sum(a)
np.sum(a, axis=0)
nc::sum(a, nc::Axis::ROW)
np.prod(a)
nc::prod(a)
np.prod(a, axis=0)
nc::prod(a, nc::Axis::ROW)
np.mean(a)
nc::mean(a)
np.mean(a, axis=0)
nc::mean(a, nc::Axis::ROW)
np.count_nonzero(a)
nc::count_nonzero(a)
np.count_nonzero(a, axis=0)
nc::count_nonzero(a, nc::Axis::ROW)
I/O
Print and file output methods. All NumCpp classes support a print() method and << stream operators.
NumPy
NumCpp
print(a)
a.print()
std::cout << a
a.tofile(filename, sep=’\n’)
a.tofile(filename, '\n')
np.fromfile(filename, sep=’\n’)
nc::fromfile<dtype>(filename, '\n')
np.dump(a, filename)
nc::dump(a, filename)
np.load(filename)
nc::load<dtype>(filename)
MATHEMATICAL FUNCTIONS
NumCpp universal functions are provided for a large set number of mathematical functions.
I just installed Numcpp on a new machine and tried to compile a piece of code which was working on another machine.
However, on the new machine, I get compilation error: ambiguous overload for ‘operator+’ (operand types are ‘nc::NdArray<double>’ and ‘int’).
There are errors related to the ambiguity for nearly all the operators.
I was wondering if you could help me fix this issue.
I am using Boost 1.7, Clang 6.0, and tried different versions of gcc, including 7 , 8.3.0, 9.2.
Thanks in advance.
I was amazingto see the description about "median": Does NOT average if array has even number of elements!
// Method Description:
/// Return the median along a given axis. Does NOT average
/// if array has even number of elements!
///
/// @param
/// inAxis (Optional, default NONE)
/// @return
/// NdArray
///
NdArray<dtype> median(Axis inAxis = Axis::NONE) const noexcept
.\Numcpp_include/NumCpp/Vector/Vec3.hpp:271:38: error: no matching function for call to 'hypot(const double&, const double&, const double&)'
return std::hypot(x, y, z);
If you implement these methods it will be very useful.
for example in python suppose we have arrays of rectangle points (2 4) so we can find TopLeft and BottomRight like this :
in matlab using one int vector's data as selector of another vector or matirx is supported. For example,
a=[9 8 7 6 5];
b=[5 1 3];
a(b)
will give answer [5 9 7]
using pointer in c++ together with Numcpp could fullfill this problem but seemed cumbersome. so would you please add support for this functionality? like:
Ndarray a= {9,8,7,6,5};
Ndarray b={4,0,2,0};
a.select(b) represent {5,9,7,9}
by the way, it would be nice to add find, findfirst findall methods which would return an Ndarray and could be used as selector of another Ndarray if it is int type.
thanks.
i try to build Numcpp on ubuntu1604. there are some bugs . cake is 3.15.2 and boost is 1.68.
***there is the log
Scanning dependencies of target Example
[ 50%] Building CXX object CMakeFiles/Example.dir/ReadMe.cpp.o
In file included from /home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Functions.hpp:57:0,
from /home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp.hpp:37,
from /home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/ReadMe.cpp:1:
/home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Functions/asarray.hpp: In function 'nc::NdArray nc::asarray(const std::array<_Tp, _Nm>&)':
/home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Functions/asarray.hpp:55:23: error: missing template arguments before '(' token
return NdArray(inArray);
^
/home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Functions/asarray.hpp: In function 'nc::NdArray nc::asarray(const std::vector<_RealType>&)':
/home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Functions/asarray.hpp:72:23: error: missing template arguments before '(' token
return NdArray(inVector);
^
/home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Functions/asarray.hpp: In function 'nc::NdArray nc::asarray(const std::deque<_Tp>&)':
/home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Functions/asarray.hpp:89:23: error: missing template arguments before '(' token
return NdArray(inDeque);
^
/home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Functions/asarray.hpp: In function 'nc::NdArray nc::asarray(const std::set&)':
/home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Functions/asarray.hpp:106:23: error: missing template arguments before '(' token
return NdArray(inSet);
^
/home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Functions/asarray.hpp: In function 'nc::NdArray nc::asarray(std::initializer_list<Tp>&)':
/home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Functions/asarray.hpp:124:23: error: missing template arguments before '(' token
return NdArray(inList);
^
/home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Functions/asarray.hpp: In function 'nc::NdArray nc::asarray(std::initializer_list<std::initializer_list<Tp> >&)':
/home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Functions/asarray.hpp:142:23: error: missing template arguments before '(' token
return NdArray(inList);
^
In file included from /home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Rotations/DCM.hpp:35:0,
from /home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Rotations.hpp:31,
from /home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp.hpp:44,
from /home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/ReadMe.cpp:1:
/home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Rotations/Quaternion.hpp: At global scope:
/home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Rotations/Quaternion.hpp:61:70: error: array must be initialized with a brace-enclosed initializer
std::array<double, 4> components = { 0.0, 0.0, 0.0, 1.0 };
^
/home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Rotations/Quaternion.hpp:61:70: error: too many initializers for 'std::array<double, 4ul>'
In file included from /home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Rotations/DCM.hpp:35:0,
from /home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Rotations.hpp:31,
from /home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp.hpp:44,
from /home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/ReadMe.cpp:1:
/home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Rotations/Quaternion.hpp: In static member function 'static nc::rotations::Quaternion nc::rotations::Quaternion::identity()':
/home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Rotations/Quaternion.hpp:357:35: error: use of deleted function 'constexpr nc::rotations::Quaternion::Quaternion()'
return Quaternion();
^
In file included from /home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Rotations/DCM.hpp:35:0,
from /home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Rotations.hpp:31,
from /home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp.hpp:44,
from /home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/ReadMe.cpp:1:
/home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Rotations/Quaternion.hpp:179:13: note: 'constexpr nc::rotations::Quaternion::Quaternion() noexcept' is implicitly deleted because its exception-specification does not match the implicit exception-specification 'noexcept (false)'
Quaternion() noexcept = default;
^
In file included from /home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Rotations/DCM.hpp:35:0,
from /home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Rotations.hpp:31,
from /home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp.hpp:44,
from /home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/ReadMe.cpp:1:
/home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Rotations/Quaternion.hpp: In member function 'nc::NdArray nc::rotations::Quaternion::toNdArray() const':
/home/lisas/numcpp_new/numcpp_new/NumCpp/examples/ReadMe/../../include/NumCpp/Rotations/Quaternion.hpp:655:31: error: missing template arguments before '(' token
return NdArray(components);
^
CMakeFiles/Example.dir/build.make:62: recipe for target 'CMakeFiles/Example.dir/ReadMe.cpp.o' failed
make[2]: *** [CMakeFiles/Example.dir/ReadMe.cpp.o] Error 1
CMakeFiles/Makefile2:75: recipe for target 'CMakeFiles/Example.dir/all' failed
make[1]: *** [CMakeFiles/Example.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2
Hey,
I was wondering if you could let me know how I can get numpy.diag in Numcpp. I could not find anything regarding that method in the documentation. There is nc:diagonal, which is different with numpy.diag. Wondering if you have already implemented numpy.diag .
There's a compilation error with C++11. The error occurs in both basic programs as well as the examples.
In file included from ReadMe.cpp:1:
In file included from /usr/local/include/NumCpp.hpp:34:
In file included from /usr/local/include/NumCpp/Coordinates.hpp:31:
In file included from /usr/local/include/NumCpp/Coordinates/Coordinate.hpp:31:
In file included from /usr/local/include/NumCpp/Coordinates/Dec.hpp:33:
In file included from /usr/local/include/NumCpp/Functions/deg2rad.hpp:31:
In file included from /usr/local/include/NumCpp/NdArray.hpp:32:
/usr/local/include/NumCpp/NdArray/NdArrayOperators.hpp:805:47: error: 'dtype' does not refer to a value
returnArray.begin(), std::bit_not<dtype>());
^
/usr/local/include/NumCpp/NdArray/NdArrayOperators.hpp:797:23: note: declared here
template<typename dtype>
^
/usr/local/include/NumCpp/NdArray/NdArrayOperators.hpp:805:39: error: no member named 'bit_not' in namespace 'std'
returnArray.begin(), std::bit_not<dtype>());
~~~~~^
/usr/local/include/NumCpp/NdArray/NdArrayOperators.hpp:805:54: error: expected expression
returnArray.begin(), std::bit_not<dtype>());
^
ReadMe.cpp:89:10: warning: decomposition declarations are a C++17 extension [-Wc++17-extensions]
auto [rows, cols] = nc::nonzero(a);
^~~~~~~~~~~~
1 warning and 3 errors generated.
To Reproduce
cd examples/ReadMe
c++ -std=c++11 ReadMe.cpp -o test -lboost_filesystem
Expected behavior
The program compiles, as it does with C++14 and C++17.
Compiler Info
c++ --version
Apple LLVM version 10.0.1 (clang-1001.0.46.4)
Target: x86_64-apple-darwin18.7.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
I got a vs2017 C++ project,which contains two source files and one header file as below:
exutil.h #pragma once #ifndef EXUTIL_H #define EXUTIL_H #include "NumCpp.hpp" #endif // !EXUTIL_H
exutil.cpp #include "exutil.h"
ex1.cpp #include "exutil.h"
int main() { return 0; }
When building, vs prompted:
exutil.obj : error LNK2005: "class boost::random::mersenne_twister_engine<unsigned int,32,624,397,31,2567483615,11,4294967295,7,2636928640,15,4022730752,18,1812433253> nc::generator_" (?generator_@nc@@3v?$mersenne_twister_engine@I$0CA@$0CHA@$0BIN@$0BP@$0JJAILANP@$0L@$0PPPPPPPP@$06$0JNCMFGIA@$0P@$0OPMGAAAA@$0BC@$0GMAHIJGF@@random@boost@@A) already defined in ex1.obj
ex1.obj : error LNK2005: "class nc::NdArray __cdecl nc::imageProcessing::windowExceedances(class nc::NdArray const &,unsigned char)" (?windowExceedances@imageProcessing@nc@@ya?AV?$NdArray@_N@2@AEBV32@E@Z) already defined in ex1.obj
ex1.obj : error LNK2005: "class nc::NdArray __cdecl nc::find(class nc::NdArray const &,unsigned int)" (?find@nc@@ya?AV?$NdArray@I@1@AEBV?$NdArray@_N@1@I@Z) already defined in ex1.obj
\x64\Release\ex1.exe : fatal error LNK1169: one or more multiply defined symbols
This happens whether or not write functions or class in exutil.cpp.
Making related functions in .hpp files inline and variables extern could fixed linking error.But I am not sure the consequences.
What I use was the most recent version of NumCpp cloned from github.
Thanks.
Hey,
I've been trying to access the rows and columns of my 2D array using [i,j] and replace its values with some other values, however, it seems that Ndarray doesn't support neither X[i,j] (which works in python) nor X[i][j] ways of accessing elements. It seems that the array is considered 1D and if I want to reach the X[1][2] element in a 3*3 array for example, I should access it as X[5]. Am I wrong? I was wondering if you could tell me how I can access the rows and columns of an Ndarray like X[i][j].
you know ,in pytorch, use tensor.numpy() transform to tensor andtorch.Tensor(numpy)transform to numpy. Is there any method to transform torch::Tensor to nc::NdArray? or nc::NdArray to torch::Tensor
Hi, i'm beginner in C++, and search in the web about install and use library's C++, but i don't find a good tutorial.
can you help me how use your library ?
i'm try to use vstack to stack a series ndarray,but the size of series is uncertain and the initializer_list can't convert from vector or list.
so,can i change the implement of the stack function?
For all of my tests, I tested for several times and checked the output.
Can you please explain why there exists such a big performance gap? Especially the C++ one is much slower, it so counter-intuitive...
Thanks very much!
Hi,
I tried going through the function in (https://github.com/dpilger26/NumCpp/blob/master/src/NumCpp/Methods.hpp). To me, it seems that the methods like slicing are supported for 2d array but not for the nd-array. Is it true or can you please point me to an nd-array example.
Thanks
Thank you very much for the project.
However, here is one thing I cannot resolve so far...May be it is just my week python understanding (not familiar).
Python project, which I try to convert into C++ QT project has a line like img = numpy.array(img, dtype=numpy.uint8);
Which, in c++ should looks like nc::array(img, nc::uint8);
but it is not works..
Appreciate if you can show hot to solve.
Thanks
I have built a Dynamic-link library using NumCpp and then used Python to call this dll file, in my Python code, the array is in Numpy, so how can I pass Numpy array into the NumCpp API?
I dump the array in numpy use a.dump("test.bin"). Yet I can not recover the array in NumCpp with auto a = nc::load("test.bin") .
Is the file format of NumCpp differs from numpy in python?
Hi
I am not sure I understand the purpose of this project. As I understand it, it's a numpy-like tool for C++ that can be used from python. I can't find any reference (without reading the code) to what I am looking for. Is the memory-layout the same as in numpy? Can you wrap (without copying) between numpy and NumCpp? Can you use NumCpp as a drop-in replacement for numpy?
BTW, are you aware of pythran's numpy implementation?
Thanks!
When I'm using linspace with double, everything works fine, but if argument have to be 0, there is for example value like this -3.60684e-14. It's very small number, but have to be a zero value.