Series ====== .. cpp:class:: numpy::Series numpy C++ class. Example ------- .. code-block:: cpp #include using namespace numpy; // Use Series Series obj; // ... operations ... Constructors ------------ .. list-table:: :widths: 55 25 20 :header-rows: 1 * - Signature - Location - Example * - ``explicit Series(const numpy::NDArray& data, const std::optional& name = std::nullopt)`` - df_series.h:145 - * - ``Series(const std::vector& data, const std::optional& name = std::nullopt)`` - df_series.h:165 - * - ``Series(const numpy::NDArray& data, const Index& idx, const std::optional& name = std::nullopt)`` - df_series.h:197 - * - ``Series(const numpy::NDArray& data, const RangeIndex& idx, const std::optional& name = std::nullopt)`` - df_series.h:216 - * - ``Series(const std::vector& data, const Index& idx, const std::optional& name = std::nullopt)`` - df_series.h:233 - * - ``Series(const Series& other)`` - df_series.h:252 - * - ``Series(Series&& other) noexcept`` - df_series.h:266 - Construction ------------ .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``std::unique_ptr make_default_index(size_t sz) const`` - std::unique_ptr - df_series.h:5658 - Array Creation -------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``bool empty() const override`` - bool - df_series.h:339 - :ref:`View ` Indexing / Selection -------------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``T at(size_t idx) const`` - T - df_series.h:503 - :ref:`View ` * - ``Series at_time( const std::string& time, bool asof = false ) const`` - Series - df_series.h:5541 - * - ``T get(const std::string& key, const std::optional& default_value = std::nullopt) const`` - T - df_series.h:4693 - :ref:`View ` * - ``bool get_value_bool(size_t idx) const override`` - bool - df_series.h:885 - * - ``std::string get_value_str(size_t idx) const override`` - std::string - df_series.h:3561 - * - ``T item() const`` - T - df_series.h:4821 - :ref:`View ` * - ``std::vector> items() const`` - std::vector> - df_series.h:4835 - * - ``void items(Func&& func) const`` - void - df_series.h:4849 - * - ``size_t searchsorted(const T& value, const std::string& side = "left") const`` - size_t - df_series.h:5315 - :ref:`View ` * - ``Series take(const std::vector& indices) const`` - Series - df_series.h:670 - :ref:`View ` * - ``Series where(const numpy::NDArray& cond, const T& other) const`` - Series - df_series.h:614 - :ref:`View ` Shape Manipulation ------------------ .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``Series T\_() const`` - Series - df_series.h:5390 - * - ``numpy::NDArray ravel() const`` - numpy::NDArray - df_series.h:5119 - :ref:`View ` * - ``Series squeeze() const`` - Series - df_series.h:5338 - :ref:`View ` * - ``Series swapaxes(int /\*axis1\*/, int /\*axis2\*/) const`` - Series - df_series.h:5369 - :ref:`View ` * - ``Series transpose() const`` - Series - df_series.h:5383 - :ref:`View ` Statistics ---------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``std::optional cov( const Series& other, std::optional min_periods = std::nullopt, int ddof = 1) const`` - std::optional - df_series.h:4197 - :ref:`View ` * - ``std::optional max(bool skipna = true) const`` - std::optional - df_series.h:1111 - :ref:`View ` * - ``std::optional mean(bool skipna = true) const`` - std::optional - df_series.h:1011 - :ref:`View ` * - ``std::optional median(bool skipna = true) const`` - std::optional - df_series.h:1178 - :ref:`View ` * - ``std::optional min(bool skipna = true) const`` - std::optional - df_series.h:1075 - :ref:`View ` * - ``std::optional quantile(double q, const std::string& interpolation = "linear") const`` - std::optional - df_series.h:1371 - :ref:`View ` * - ``std::optional std(bool skipna = true, int ddof = 1) const`` - std::optional - df_series.h:5345 - :ref:`View ` * - ``std::optional std\_(bool skipna = true, int ddof = 1) const`` - std::optional - df_series.h:1031 - * - ``std::optional sum(bool skipna = true) const`` - std::optional - df_series.h:973 - :ref:`View ` * - ``std::optional var(bool skipna = true, int ddof = 1) const`` - std::optional - df_series.h:1040 - :ref:`View ` Sorting ------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``numpy::NDArray argsort(bool ascending = true) const`` - numpy::NDArray - df_series.h:2180 - :ref:`View ` * - ``Series sort_index(bool ascending = true) const`` - Series - df_series.h:2220 - * - ``Series sort_values(bool ascending = true, bool /\*na_position_last\*/ = true) const`` - Series - df_series.h:2205 - Math Operations --------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``Series abs() const`` - Series - df_series.h:2039 - :ref:`View ` * - ``Series add(const Series& other, T fill_value = T`` - Series - df_series.h:1637 - :ref:`View ` * - ``Series add(T scalar) const`` - Series - df_series.h:1657 - :ref:`View ` * - ``Series add_prefix(const std::string& prefix, int axis = 0) const`` - Series - df_series.h:3508 - * - ``Series add_suffix(const std::string& suffix, int axis = 0) const`` - Series - df_series.h:3537 - * - ``Series ceil() const`` - Series - df_series.h:1886 - :ref:`View ` * - ``Series divide(const Series& other, T fill_value = T`` - Series - df_series.h:1754 - :ref:`View ` * - ``Expanding expanding(size_t min_periods = 1) const`` - Expanding - df_series.h:2719 - * - ``Series explode(bool ignore_index = false) const`` - Series - df_series.h:3457 - * - ``Series floor() const`` - Series - df_series.h:1875 - :ref:`View ` * - ``Series floordiv(const Series& other) const`` - Series - df_series.h:1769 - * - ``Series floordiv(T scalar) const`` - Series - df_series.h:1786 - * - ``Series mod(const Series& other) const`` - Series - df_series.h:1802 - :ref:`View ` * - ``Series mod(T scalar) const`` - Series - df_series.h:1819 - :ref:`View ` * - ``Series mode(bool dropna = true) const`` - Series - df_series.h:1314 - :ref:`View ` * - ``Series multiply(const Series& other, T fill_value = T`` - Series - df_series.h:1719 - :ref:`View ` * - ``Series round(int decimals = 0) const`` - Series - df_series.h:1862 - :ref:`View ` * - ``Series subtract(const Series& other, T fill_value = T`` - Series - df_series.h:1688 - :ref:`View ` * - ``Series truncate(const std::optional& before = std::nullopt, const std::optional& after = std::nullopt) const`` - Series - df_series.h:2839 - :ref:`View ` Linear Algebra -------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``T dot(const Series& other) const`` - T - df_series.h:4295 - :ref:`View ` * - ``T dot(const numpy::NDArray& other) const`` - T - df_series.h:4307 - :ref:`View ` * - ``void invalidate_caches() const`` - void - df_series.h:5639 - Random ------ .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``Series sample( size_t n = 1, std::optional random_state = std::nullopt, bool replace = false) const`` - Series - df_series.h:5275 - :ref:`View ` Comparison ---------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``bool equals(const Series& other) const`` - bool - df_series.h:4440 - Set Operations -------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``Series unique() const`` - Series - df_series.h:2384 - :ref:`View ` I/O --- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``void to_clipboard(bool excel = true, const std::string& sep = "\\t") const`` - void - df_series.h:3188 - * - ``std::string to_csv(bool include_index = true, char sep = ',') const`` - std::string - df_series.h:2930 - * - ``std::map to_dict() const`` - std::map - df_series.h:2995 - * - ``void to_excel( const std::string& excel_writer, const std::string& sheet_name = "Sheet1", const std::string& na_rep = "", const std::string& float_format = "", bool header = true, bool index = true, const std::string& index_label = "", size_t startrow = 0, size_t startcol = 0, bool merge_cells = true, const std::string& inf_rep = "inf", std::optional> freeze_panes = std::nullopt) const`` - void - df_series.h:3324 - * - ``std::vector to_feather( const std::string& path = "", const std::string& compression = "uncompressed", int compression_level = -1, int64_t chunksize = -1, int version = 2) const`` - std::vector - df_series.h:3417 - * - ``DataFrame to_frame(const std::optional& name = std::nullopt) const`` - DataFrame - df_series.h:3014 - * - ``std::vector to_hdf( const std::string& path_or_buf = "", const std::string& key = "data", const std::string& mode = "a", std::optional complevel = std::nullopt, const std::string& complib = "zlib", bool append = false, const std::string& format = "fixed", bool index = true) const`` - std::vector - df_series.h:3253 - * - ``std::string to_json(const std::string& orient = "index") const`` - std::string - df_series.h:2957 - * - ``std::string to_latex(bool header = true, bool index = true) const`` - std::string - df_series.h:3024 - * - ``void to_latex(const std::string& path, bool header = true, bool index = true) const`` - void - df_series.h:3064 - * - ``file << to_latex(header, index)`` - file << - df_series.h:3069 - * - ``std::vector to_list() const`` - std::vector - df_series.h:2912 - * - ``std::string to_markdown(bool index = true) const`` - std::string - df_series.h:3080 - * - ``void to_markdown(const std::string& path, bool index = true) const`` - void - df_series.h:3118 - * - ``file << to_markdown(index)`` - file << - df_series.h:3123 - * - ``numpy::NDArray to_numpy() const`` - numpy::NDArray - df_series.h:2905 - :ref:`View ` * - ``std::vector to_orc( const std::string& path = "", const std::string& engine = "pyarrow", std::optional index = std::nullopt) const`` - std::vector - df_series.h:3442 - * - ``std::vector to_parquet( const std::string& path = "", const std::string& engine = "pyarrow", const std::string& compression = "snappy", std::optional index = std::nullopt) const`` - std::vector - df_series.h:3357 - * - ``void to_pickle(const std::string& path) const`` - void - df_series.h:3143 - * - ``std::optional to_sql( const std::string& name, const std::string& con_path, const std::string& schema = "", const std::string& if_exists = "fail", bool index = true, const std::string& index_label = "", std::optional chunksize = std::nullopt, const std::map& dtype =`` - std::optional - df_series.h:3287 - * - ``std::vector to_stata( const std::string& path = "", const std::map& convert_dates =`` - std::vector - df_series.h:3386 - * - ``std::string to_string() const override`` - std::string - df_series.h:3586 - :ref:`View ` * - ``std::vector to_string_vector() const override`` - std::vector - df_series.h:3573 - * - ``std::vector tolist() const`` - std::vector - df_series.h:5376 - :ref:`View ` Joining / Splitting ------------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``Series repeat(size_t repeats) const`` - Series - df_series.h:5212 - :ref:`View ` Type Handling ------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``Series astype() const`` - Series - df_series.h:2894 - :ref:`View ` * - ``Series copy(bool deep = true) const`` - Series - df_series.h:2875 - :ref:`View ` * - ``void copy_value_from(size_t src_idx, size_t dst_idx) override`` - void - df_series.h:950 - * - ``Series view() const`` - Series - df_series.h:5417 - :ref:`View ` Special Functions ----------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``Series combine(const Series& other, Func&& func) const`` - Series - df_series.h:4012 - :ref:`View ` * - ``Series combine_first(const Series& other) const`` - Series - df_series.h:4030 - Type Checking ------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``bool is_na_at(size_t idx) const override`` - bool - df_series.h:819 - Other Methods ------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``GlobalUnlock(hMem)`` - - df_series.h:3215 - * - ``SetClipboardData(CF_TEXT, hMem)`` - - df_series.h:3218 - * - ``auto agg(Func&& func) const -> decltype(func(std::declval>()))`` - auto - df_series.h:2618 - * - ``std::optional agg(const std::string& func) const`` - std::optional - df_series.h:2631 - * - ``DataFrame agg(const std::vector& funcs) const`` - DataFrame - df_series.h:2658 - * - ``auto aggregate(Func&& func) const -> decltype(agg(std::forward(func)))`` - auto - df_series.h:2664 - * - ``std::optional aggregate(const std::string& func) const`` - std::optional - df_series.h:2671 - * - ``DataFrame aggregate(const std::vector& funcs) const`` - DataFrame - df_series.h:2682 - * - ``std::pair, Series> align( const Series& other, const std::string& join = "outer", const std::optional& fill_value = std::nullopt) const`` - std::pair, Series> - df_series.h:3696 - * - ``auto apply(Func&& func) const -> Series()))>`` - auto - df_series.h:2544 - * - ``Series apply(const std::string& func) const`` - Series - df_series.h:2562 - * - ``size_t argmax() const`` - size_t - df_series.h:1487 - :ref:`View ` * - ``size_t argmin() const`` - size_t - df_series.h:1456 - :ref:`View ` * - ``Series asfreq(const std::string& freq, const std::string& method = "") const`` - Series - df_series.h:2787 - * - ``std::optional asof(const std::string& where) const`` - std::optional - df_series.h:3775 - * - ``T asof(size_t where) const`` - T - df_series.h:5472 - * - ``Series asof(const std::vector& where) const`` - Series - df_series.h:5519 - * - ``std::optional autocorr(int lag = 1) const`` - std::optional - df_series.h:3808 - * - ``std::vector axes() const override`` - std::vector - df_series.h:485 - :ref:`View ` * - ``Series backfill(std::optional limit = std::nullopt) const`` - Series - df_series.h:3900 - * - ``Series between(const T& left, const T& right, const std::string& inclusive = "both") const`` - Series - df_series.h:2006 - :ref:`View ` * - ``Series between_time( const std::string& start_time, const std::string& end_time, const std::string& inclusive = "both" ) const`` - Series - df_series.h:5565 - * - ``Series bfill(std::optional limit = std::nullopt) const`` - Series - df_series.h:3854 - * - ``bool bool\_() const`` - bool - df_series.h:3953 - :ref:`View ` * - ``size_t cache_memory_usage() const override`` - size_t - df_series.h:3675 - * - ``Series case_when( const std::vector, T>>& caselist, const std::optional& default_value = std::nullopt) const`` - Series - df_series.h:3976 - * - ``void clear_cache() const override`` - void - df_series.h:3660 - * - ``Series clip(const T& lower, const T& upper) const`` - Series - df_series.h:2057 - :ref:`View ` * - ``std::unique_ptr clone() const override`` - std::unique_ptr - df_series.h:3652 - :ref:`View ` * - ``numpy::NDArray codes_arr(`` - numpy::NDArray - df_series.h:4528 - * - ``DataFrame compare( const Series& other, int align_axis = 1, bool keep_shape = false, bool keep_equal = false ) const`` - DataFrame - df_series.h:4108 - * - ``std::optional corr( const Series& other, const std::string& method = "pearson", std::optional min_periods = std::nullopt) const`` - std::optional - df_series.h:4122 - * - ``size_t count() const override`` - size_t - df_series.h:702 - :ref:`View ` * - ``Series cummax(bool /\*skipna\*/ = true) const`` - Series - df_series.h:2120 - * - ``Series cummin(bool /\*skipna\*/ = true) const`` - Series - df_series.h:2101 - * - ``Series cumprod(bool /\*skipna\*/ = true) const`` - Series - df_series.h:2086 - :ref:`View ` * - ``Series cumsum(bool /\*skipna\*/ = true) const`` - Series - df_series.h:2071 - :ref:`View ` * - ``DataFrame describe( const std::vector& percentiles =`` - DataFrame - df_series.h:1416 - :ref:`View ` * - ``Series diff(int periods = 1) const`` - Series - df_series.h:2139 - :ref:`View ` * - ``Series div(const Series& other, T fill_value = T`` - Series - df_series.h:1726 - * - ``Series div(T scalar) const`` - Series - df_series.h:1746 - * - ``std::pair, Series> divmod(const T& other) const`` - std::pair, Series> - df_series.h:4251 - :ref:`View ` * - ``std::pair, Series> divmod(const Series& other) const`` - std::pair, Series> - df_series.h:4268 - :ref:`View ` * - ``Series drop(const std::vector& labels) const`` - Series - df_series.h:4324 - * - ``Series drop_duplicates(const std::string& keep = "first") const`` - Series - df_series.h:2466 - * - ``Series droplevel(int level) const`` - Series - df_series.h:4350 - * - ``Series dropna() const`` - Series - df_series.h:796 - * - ``std::string dtype_name() const override`` - std::string - df_series.h:371 - :ref:`View ` * - ``numpy::NDArray duplicated(const std::string& keep = "first") const`` - numpy::NDArray - df_series.h:2427 - * - ``Series eq(const Series& other) const`` - Series - df_series.h:4364 - * - ``Series eq(const T& scalar) const`` - Series - df_series.h:4368 - * - ``EWM ewm(double span, bool adjust = true, bool ignore_na = false) const`` - EWM - df_series.h:2732 - * - ``std::pair, Series> factorize(bool sort = false) const`` - std::pair, Series> - df_series.h:4471 - * - ``Series ffill(std::optional limit = std::nullopt) const`` - Series - df_series.h:3909 - * - ``std::ofstream file(path)`` - std::ofstream - df_series.h:3065 - :ref:`View ` * - ``std::ofstream file(path)`` - std::ofstream - df_series.h:3119 - :ref:`View ` * - ``std::ofstream file(path, std::ios::binary)`` - std::ofstream - df_series.h:3144 - :ref:`View ` * - ``Series fillna(const T& value) const`` - Series - df_series.h:770 - * - ``void fillna_double(double value) override`` - void - df_series.h:836 - * - ``Series filter( const std::optional>& items = std::nullopt, const std::optional& like = std::nullopt, const std::optional& regex = std::nullopt) const`` - Series - df_series.h:4622 - :ref:`View ` * - ``Series first(const std::string& offset) const`` - Series - df_series.h:4664 - :ref:`View ` * - ``std::optional first_valid_index() const`` - std::optional - df_series.h:2797 - * - ``func(index\_->get_value_str(i), data\_.getElementAt(`` - - df_series.h:4851 - * - ``Series ge(const Series& other) const`` - Series - df_series.h:4423 - * - ``Series ge(const T& scalar) const`` - Series - df_series.h:4427 - * - ``SeriesGroupBy groupby(const Series& by, bool sort = true) const`` - SeriesGroupBy - df_series.h:2760 - * - ``\* Series groups(`` - \* Series - df_series.h:2752 - :ref:`View ` * - ``Series gt(const Series& other) const`` - Series - df_series.h:4412 - * - ``Series gt(const T& scalar) const`` - Series - df_series.h:4416 - * - ``bool has_cached_values() const override`` - bool - df_series.h:3664 - * - ``bool has_multiindex() const`` - bool - df_series.h:467 - * - ``bool hasnans() const override`` - bool - df_series.h:681 - * - ``Series head(size_t n = 5) const`` - Series - df_series.h:654 - * - ``T iat(size_t idx) const`` - T - df_series.h:515 - * - ``std::string idxmax() const`` - std::string - df_series.h:1525 - * - ``std::string idxmin() const`` - std::string - df_series.h:1518 - * - ``Series iloc(size_t start, size_t stop, size_t step = 1) const`` - Series - df_series.h:525 - * - ``Series iloc(const std::vector& indices) const`` - Series - df_series.h:542 - * - ``const IndexBase& index() const override`` - const IndexBase& - df_series.h:403 - :ref:`View ` * - ``IndexBase& index_mut()`` - IndexBase& - df_series.h:410 - * - ``void info(std::ostream\* buf = nullptr) const`` - void - df_series.h:4711 - :ref:`View ` * - ``Series interpolate( const std::string& method = "linear", std::optional limit = std::nullopt) const`` - Series - df_series.h:4728 - * - ``numpy::NDArray isna() const`` - numpy::NDArray - df_series.h:730 - * - ``numpy::NDArray isnull() const`` - numpy::NDArray - df_series.h:4806 - * - ``std::vector keys() const`` - std::vector - df_series.h:4859 - :ref:`View ` * - ``std::optional kurt(bool skipna = true) const`` - std::optional - df_series.h:1271 - * - ``std::optional kurtosis(bool skipna = true) const`` - std::optional - df_series.h:1307 - :ref:`View ` * - ``\* For Series, the row labels (index) are prefixed.`` - \* For Series, the row - df_series.h:3499 - * - ``\* For Series, the row labels (index) are suffixed.`` - \* For Series, the row - df_series.h:3528 - * - ``Series last(const std::string& offset) const`` - Series - df_series.h:4679 - * - ``std::optional last_valid_index() const`` - std::optional - df_series.h:2817 - * - ``Series le(const Series& other) const`` - Series - df_series.h:4397 - * - ``Series le(const T& scalar) const`` - Series - df_series.h:4401 - * - ``T loc(const std::string& label) const`` - T - df_series.h:563 - * - ``Series loc(const std::vector& labels) const`` - Series - df_series.h:576 - * - ``Series lt(const Series& other) const`` - Series - df_series.h:4386 - * - ``Series lt(const T& scalar) const`` - Series - df_series.h:4390 - * - ``Series map(const std::unordered_map& mapping) const`` - Series - df_series.h:2572 - * - ``auto map(Func&& func) const -> Series()))>`` - auto - df_series.h:2593 - * - ``Series mask(const numpy::NDArray& cond, const T& other) const`` - Series - df_series.h:632 - :ref:`View ` * - ``memcpy(pMem, text.c_str(), text.size() + 1)`` - - df_series.h:3214 - :ref:`View ` * - ``size_t memory_usage(bool index = true, bool /\*deep\*/ = false) const`` - size_t - df_series.h:4873 - * - ``Series mul(const Series& other, T fill_value = T`` - Series - df_series.h:1695 - * - ``Series mul(T scalar) const`` - Series - df_series.h:1715 - * - ``const MultiIndex& multiindex() const`` - const MultiIndex& - df_series.h:474 - * - ``std::optional name() const override`` - std::optional - df_series.h:378 - :ref:`View ` * - ``size_t nbytes() const override`` - size_t - df_series.h:360 - :ref:`View ` * - ``size_t ndim() const override`` - size_t - df_series.h:353 - :ref:`View ` * - ``Series ne(const Series& other) const`` - Series - df_series.h:4375 - * - ``Series ne(const T& scalar) const`` - Series - df_series.h:4379 - * - ``numpy::NDArray new_mask(`` - numpy::NDArray - df_series.h:4582 - * - ``Series nlargest(size_t n = 5, const std::string& keep = "first") const`` - Series - df_series.h:4890 - * - ``numpy::NDArray notna() const`` - numpy::NDArray - df_series.h:750 - * - ``numpy::NDArray notnull() const`` - numpy::NDArray - df_series.h:4813 - * - ``Series nsmallest(size_t n = 5, const std::string& keep = "first") const`` - Series - df_series.h:4943 - * - ``size_t nunique(bool dropna = true) const`` - size_t - df_series.h:2402 - * - ``Series pad(std::optional limit = std::nullopt) const`` - Series - df_series.h:3945 - :ref:`View ` * - ``std::vector> pairs(counts.begin(), counts.end())`` - std::vector> - df_series.h:2505 - :ref:`View ` * - ``Series pct_change(int periods = 1) const`` - Series - df_series.h:1426 - * - ``auto pipe(Func&& func, Args&&... args) const`` - auto - df_series.h:2688 - * - ``T pop(size_t pos)`` - T - df_series.h:4544 - * - ``T pop(const std::string& label)`` - T - df_series.h:4605 - * - ``Series pow(const Series& other) const`` - Series - df_series.h:1835 - :ref:`View ` * - ``Series pow(double exponent) const`` - Series - df_series.h:1847 - :ref:`View ` * - ``std::optional prod(bool skipna = true) const`` - std::optional - df_series.h:1147 - :ref:`View ` * - ``std::optional product(bool skipna = true) const`` - std::optional - df_series.h:4993 - :ref:`View ` * - ``Series radd(const T& scalar) const`` - Series - df_series.h:5000 - * - ``Series radd(const Series& other) const`` - Series - df_series.h:5004 - * - ``Series rank(const std::string& method = "average", bool ascending = true, const std::string& na_option = "keep", bool pct = false) const`` - Series - df_series.h:2244 - * - ``static std::vector rank_values(const std::vector& values)`` - static std::vector - df_series.h:5620 - * - ``Series rdiv(const T& scalar) const`` - Series - df_series.h:5037 - * - ``std::pair, Series> rdivmod(const T& scalar) const`` - std::pair, Series> - df_series.h:5099 - * - ``Series reindex( const std::vector& labels, const std::string& method = "", const std::optional& fill_value = std::nullopt) const`` - Series - df_series.h:5130 - * - ``Series reindex_like( const Series& other, const std::string& method = "", const std::optional& fill_value = std::nullopt) const`` - Series - df_series.h:5179 - * - ``Series rename(const std::optional& new_name) const`` - Series - df_series.h:3490 - * - ``Series reorder_levels(const std::vector& order) const`` - Series - df_series.h:5196 - * - ``Series replace(const T& to_replace, const T& value) const`` - Series - df_series.h:5232 - :ref:`View ` * - ``Series replace(const std::map& replacements) const`` - Series - df_series.h:5252 - :ref:`View ` * - ``void replace_value(double to_replace, double value) override`` - void - df_series.h:860 - * - ``std::string repr() const override`` - std::string - df_series.h:3615 - * - ``SeriesResampler resample(const std::string& freq, const std::string& closed = "left", const std::string& label = "left") const`` - SeriesResampler - df_series.h:2777 - * - ``void reset_index(bool /\*drop\*/ = true) override`` - void - df_series.h:444 - * - ``Series rfloordiv(const T& scalar) const`` - Series - df_series.h:5056 - * - ``Series rmod(const T& scalar) const`` - Series - df_series.h:5072 - * - ``Series rmul(const T& scalar) const`` - Series - df_series.h:5026 - * - ``Series rmul(const Series& other) const`` - Series - df_series.h:5030 - * - ``Rolling rolling(size_t window, size_t min_periods = 1, bool center = false) const`` - Rolling - df_series.h:2708 - * - ``Series rpow(double base) const`` - Series - df_series.h:5088 - * - ``Series rsub(const T& scalar) const`` - Series - df_series.h:5011 - * - ``Series rsub(const Series& other) const`` - Series - df_series.h:5019 - * - ``Series rtruediv(const T& scalar) const`` - Series - df_series.h:5049 - * - ``\* Series s(`` - \* Series - df_series.h:2705 - * - ``\* Series s(`` - \* Series - df_series.h:2716 - * - ``\* Series s(`` - \* Series - df_series.h:2729 - * - ``std::optional sem(bool skipna = true, int ddof = 1) const`` - std::optional - df_series.h:1223 - * - ``void set_index(std::unique_ptr new_index) override`` - void - df_series.h:417 - * - ``void set_index(const Index& new_index)`` - void - df_series.h:431 - * - ``void set_multiindex(MultiIndex multi_idx)`` - void - df_series.h:454 - * - ``void set_name(const std::optional& name) override`` - void - df_series.h:385 - * - ``void set_value_double(size_t idx, double value) override`` - void - df_series.h:932 - * - ``void set_value_nan(size_t idx) override`` - void - df_series.h:909 - * - ``std::vector shape() const override`` - std::vector - df_series.h:346 - :ref:`View ` * - ``Series shift(int periods = 1, const std::optional& fill_value = std::nullopt) const`` - Series - df_series.h:2157 - :ref:`View ` * - ``size_t size() const override`` - size_t - df_series.h:332 - :ref:`View ` * - ``std::optional skew(bool skipna = true) const`` - std::optional - df_series.h:1236 - :ref:`View ` * - ``Series sub(const Series& other, T fill_value = T`` - Series - df_series.h:1664 - * - ``Series sub(T scalar) const`` - Series - df_series.h:1684 - * - ``Series swaplevel(int i = -2, int j = -1) const`` - Series - df_series.h:5355 - * - ``Series tail(size_t n = 5) const`` - Series - df_series.h:662 - * - ``Series transform(Func&& func) const`` - Series - df_series.h:2606 - * - ``Series truediv(const Series& other) const`` - Series - df_series.h:1758 - * - ``Series truediv(T scalar) const`` - Series - df_series.h:1762 - * - ``\* Returns true if value is truthy (non-zero for numeric, true for bool)`` - \* Returns true if value is - df_series.h:883 - * - ``\* For scalar types (non-list-like), this returns a copy of the Series.`` - \* For scalar - df_series.h:3452 - :ref:`View ` * - ``Series tz_convert(const std::string& tz) const`` - Series - df_series.h:5589 - :ref:`View ` * - ``Series tz_localize( const std::string& tz, const std::string& ambiguous = "raise" ) const`` - Series - df_series.h:5607 - :ref:`View ` * - ``DataFrame unstack( int level = -1, std::optional fill_value = std::nullopt, bool sort = true ) const`` - DataFrame - df_series.h:3481 - * - ``void update(const Series& other)`` - void - df_series.h:5398 - * - ``void validate_index_data_alignment() const`` - void - df_series.h:5650 - * - ``Series value_counts(bool normalize = false, bool sort = true, bool ascending = false, bool dropna = true) const`` - Series - df_series.h:2482 - * - ``const numpy::NDArray& values() const`` - const numpy::NDArray& - df_series.h:396 - :ref:`View ` * - ``\* Series values(`` - \* Series - df_series.h:2751 - :ref:`View ` * - ``Series xs(const std::string& key, int level = 0) const`` - Series - df_series.h:5427 - Code Examples ------------- The following examples are extracted from the test suite. .. _example-series-empty-0: .. dropdown:: empty (np_test_1_all.cpp:6316) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 6306 :emphasize-lines: 11 } void test_data_generator_emptyBenchmarkSorting() { std::cout << "========= test_data_generator_empty ======================="; DataGenerator gen(42); // Test empty data generation std::vector data = gen.generate(0, DataPattern::RANDOM); if (!(data.empty())) { std::string description = std::string("test_data_generator_emptyBenchmarkSorting():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(data.empty())"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "Empty data generation test passed" << std::endl; std::cout << " -> tests passed" << std::endl; } .. _example-series-at-1: .. dropdown:: at (np_test_1_all.cpp:144) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 134 :emphasize-lines: 11 array.setElementAt({0, 0}, 1); array.setElementAt({0, 1}, 2); array.setElementAt({0, 2}, 3); array.setElementAt({1, 1}, 5); array.setElementAt({2, 2}, 9); // std::cout << "Array after setting elements:" << std::endl; //array.printArray(); // std::cout << "Element at (1,1): " << array.getElementAt({1, 1}) << std::endl; // std::cout << "Element at (2,2): " << array.getElementAt({2, 2}); std::cout << " -> tests passed" << std::endl; } void testArithmetic() { std::cout << "========= testArithmeticOperations ======================="; auto array1 = createFloat32Array({2, 2}, 5.0f); auto array2 = createFloat32Array({2, 2}, 3.0f); .. _example-series-get-2: .. dropdown:: get (np_test_1_all.cpp:28526) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 28516 :emphasize-lines: 11 std::cout << " -> tests passed" << std::endl; } void np_test_indexing_mask_indices() { std::cout << "========= mask_indices: triangular mask indices ======================="; // Get upper triangular indices for 3x3 matrix auto triu_idx = numpy::mask_indices(3, "triu", 0); // Should return tuple of 2 arrays bool passed = (std::get<0>(triu_idx).getSize() > 0); passed = passed && (std::get<1>(triu_idx).getSize() > 0); passed = passed && (std::get<0>(triu_idx).getSize() == std::get<1>(triu_idx).getSize()); // Get lower triangular indices auto tril_idx = numpy::mask_indices(3, "tril", 0); passed = passed && (std::get<0>(tril_idx).getSize() > 0); passed = passed && (std::get<1>(tril_idx).getSize() > 0); if (!passed) { std::cout << " [FAIL] : in np_test_indexing_mask_indices() : Mask indices incorrect"; .. _example-series-item-3: .. dropdown:: item (np_test_4_all.cpp:20048) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 20038 :emphasize-lines: 11 /** * @file np_test_phase6.cpp * @brief Test suite for Phase 6A - HIGH PRIORITY NDArray methods and masked array utilities * * Tests: * - ndarray.nonzero() - Return indices of non-zero elements * - ndarray.tobytes() - Convert to bytes representation * - ndarray.tolist() - Convert to nested list string * - ndarray.fill() - Fill with scalar value (in-place) * - ndarray.item() - Get single element as scalar * - ndarray.itemset() - Set single element value * - ma.masked_all_like() - Create masked array with all elements masked * * Created: 2025-10-28 * Status: Phase 6A Implementation - HIGH PRIORITY functions */ #include "../numpy/np_ndarray.h" #include "../numpy/np_masked_array.h" #include .. _example-series-searchsorted-4: .. dropdown:: searchsorted (np_test_2_all.cpp:8204) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 8194 :emphasize-lines: 11 // Test missing NumPy functions void test_numpy_functions() { std::cout << "========= NumPy Functions Test =========================="; // Test searchsorted { std::vector sorted_arr = { 1, 3, 5, 7, 9 }; std::vector values = { 2, 6, 8 }; auto result = numpy::searchsorted(sorted_arr, values, "left"); std::vector expected = { 1, 3, 4 }; if (result != expected) { std::cout << " searchsorted (left): -> [FAIL]"; throw std::runtime_error("searchsorted (left): FAILED - incorrect result indices"); } // std::cout << "[OK] searchsorted (left): PASSED" << std::endl; auto result_right = numpy::searchsorted(sorted_arr, values, "right"); std::vector expected_right = { 1, 3, 4 }; .. _example-series-take-5: .. dropdown:: take (np_test_5_all.cpp:4313) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 4303 :emphasize-lines: 11 for (size_t i = 0; i < 6; ++i) { arr.setElementAt({ i }, static_cast(i * 10)); // [0, 10, 20, 30, 40, 50] } // Take specific indices numpy::NDArray indices({ 3 }); indices.setElementAt({ 0 }, 5); // 50 indices.setElementAt({ 1 }, 2); // 20 indices.setElementAt({ 2 }, 0); // 0 auto result = numpy::take(arr, indices); if (result.getSize() != 3) { std::cout << " [FAIL] : in np_test_take_basic() : Wrong result size"; throw std::runtime_error("Test failed"); } if (result.getElementAt({ 0 }) != 50 || result.getElementAt({ 1 }) != 20 || result.getElementAt({ 2 }) != 0) { std::cout << " [FAIL] : in np_test_take_basic() : Wrong values extracted"; throw std::runtime_error("Test failed"); } .. _example-series-where-6: .. dropdown:: where (np_test_3_all.cpp:15253) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 15243 :emphasize-lines: 11 auto y_data = createInt32Array({ 4 }, 0); y_data.setElementAt({ 0 }, 100); y_data.setElementAt({ 1 }, 200); y_data.setElementAt({ 2 }, 300); y_data.setElementAt({ 3 }, 400); auto y_mask = createBoolArray({ 4 }, false); MaskedArray y(y_data, y_mask, -999); // Test where() selection auto result = where(condition, x, y); if (!(result.getElementAt({ 0 }) == 10)) { std::string description = std::string("test_where_selection():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(result.getElementAt({ 0 }) == 10)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(result.getElementAt({ 1 }) == 200)) { std::string description = std::string("test_where_selection():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(result.getElementAt({ 1 }) == 200)"; std::cout << std::string("[FAIL] ") + description << std::endl; .. _example-series-ravel-7: .. dropdown:: ravel (np_test_1_all.cpp:4082) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 4072 :emphasize-lines: 11 std::cout << "Testing ravel function...\n"; // Test with 2-D array auto arr_2d = createFloat64Array({ 2, 3 }); for (size_t i = 0; i < 2; ++i) { for (size_t j = 0; j < 3; ++j) { arr_2d.setElementAt({ i, j }, static_cast(i * 3 + j)); } } auto raveled = ravel(arr_2d); if (!(raveled.getShape() == std::vector({ 6 }))) { std::string description = std::string("testRavelFunction():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(raveled.getShape() == std::vector({ 6 }))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } for (size_t i = 0; i < 6; ++i) { if (!(isApproxEqualExt(raveled.getElementAt({ i }), static_cast(i)))) { std::string description = std::string("testRavelFunction():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(isApproxEqualExt(raveled.getElementAt({ i }), static_cast(i)))"; std::cout << std::string("[FAIL] ") + description << std::endl; .. _example-series-squeeze-8: .. dropdown:: squeeze (np_test_1_all.cpp:18076) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 18066 :emphasize-lines: 11 using namespace numpy; void testSqueeze() { std::cout << "========= testSqueeze ======================="; // Create array with singleton dimensions auto array = createInt32Array({ 1, 4, 1, 3, 1 }, 5); // Test squeeze all singleton dimensions auto squeezed_all = squeeze(array); if (!(squeezed_all.getShape().size() == 2)) { std::string description = std::string("testSqueeze():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(squeezed_all.getShape().size() == 2)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(squeezed_all.getShape()[0] == 4)) { std::string description = std::string("testSqueeze():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(squeezed_all.getShape()[0] == 4)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } .. _example-series-swapaxes-9: .. dropdown:: swapaxes (np_test_2_all.cpp:3707) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 3697 :emphasize-lines: 11 std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(isApproxEqualMCO(rolled.getElementAt({ 0, 0 }), arr.getElementAt({ 0, 3 })))) { std::string description = std::string("testRotationFlipOperations():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(isApproxEqualMCO(rolled.getElementAt({ 0, 0 }), arr.getElementAt({ 0, 3 })))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // Test swapaxes auto swapped = swapaxes(arr, 0, 1); if (!(swapped.getShape() == std::vector({ 4, 3 }))) { std::string description = std::string("testRotationFlipOperations():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(swapped.getShape() == std::vector({ 4, 3 }))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(isApproxEqualMCO(swapped.getElementAt({ 0, 0 }), arr.getElementAt({ 0, 0 })))) { std::string description = std::string("testRotationFlipOperations():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(isApproxEqualMCO(swapped.getElementAt({ 0, 0 }), arr.getElementAt({ 0, 0 })))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } .. _example-series-transpose-10: .. dropdown:: transpose (np_test_2_all.cpp:4973) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 4963 :emphasize-lines: 11 } /** * Test matrix properties and methods */ void testMatrixProperties() { std::cout << "========= testMatrixProperties ======================="; // Test transpose numpy::Matrix m("1 2 3; 4 5 6"); auto mt = m.transpose(); assert_test(mt.rows() == 3, "Transpose rows"); assert_test(mt.cols() == 2, "Transpose cols"); assert_test(std::abs(mt(0, 1) - 4.0) < 1e-10, "Transpose element"); assert_test(std::abs(mt(2, 0) - 3.0) < 1e-10, "Transpose element"); // Test trace for square matrix numpy::Matrix square("1 2; 3 4"); double tr = square.trace(); assert_test(std::abs(tr - 5.0) < 1e-10, "Matrix trace"); .. _example-series-cov-11: .. dropdown:: cov (np_test_1_all.cpp:12038) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 12028 :emphasize-lines: 11 data.setElementAt({ 0, 0 }, 1.0); data.setElementAt({ 0, 1 }, 2.0); data.setElementAt({ 0, 2 }, 3.0); // Variable 2: [2, 4, 6] (perfectly correlated) data.setElementAt({ 1, 0 }, 2.0); data.setElementAt({ 1, 1 }, 4.0); data.setElementAt({ 1, 2 }, 6.0); // Test covariance matrix auto cov_matrix = cov(data); if (!(cov_matrix.getShape()[0] == 2)) { std::string description = std::string("testCovarianceAndCorrelation():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(cov_matrix.getShape()[0] == 2)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(cov_matrix.getShape()[1] == 2)) { std::string description = std::string("testCovarianceAndCorrelation():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(cov_matrix.getShape()[1] == 2)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } .. _example-series-max-12: .. dropdown:: max (np_test_1_all.cpp:7274) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 7264 :emphasize-lines: 11 if (sizeof(uintp) == sizeof(void*)) { // std::cout << " -> uintp size matches pointer size"; } else { // std::cout << " ✗ uintp size doesn't match pointer size" << std::endl; } // Test range limits // std::cout << "Range Information:" << std::endl; // std::cout << " intp min: " << std::numeric_limits::min() << std::endl; // std::cout << " intp max: " << std::numeric_limits::max() << std::endl; // std::cout << " uintp max: " << std::numeric_limits::max() << std::endl; // std::cout << " longdouble digits: " << std::numeric_limits::digits << std::endl; std::cout << " -> tests passed" << std::endl; } void testComplexArithmeticExtendedTypes() { std::cout << "========= testComplexArithmeticExtendedTypes ======================="; clongdouble c1(3.0L, 4.0L); // 3 + 4i .. _example-series-mean-13: .. dropdown:: mean (np_test_1_all.cpp:11714) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 11704 :emphasize-lines: 11 // Create test array auto array = createInt32Array({ 2, 3 }, 0); array.setElementAt({ 0, 0 }, 1); array.setElementAt({ 0, 1 }, 2); array.setElementAt({ 0, 2 }, 3); array.setElementAt({ 1, 0 }, 4); array.setElementAt({ 1, 1 }, 5); array.setElementAt({ 1, 2 }, 6); // Test mean without axis auto mean_all = mean(array); if (!(approx_equal(mean_all.getElementAt({ 0 }), 3.5, 1e-10))) { std::string description = std::string("testBasicStatistics():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(approx_equal(mean_all.getElementAt({ 0 }), 3.5, 1e-10))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] mean (all elements) works correctly\n"; // Test mean along axis 0 auto mean_axis0 = mean(array, 0); if (!(mean_axis0.getShape()[0] == 3)) { .. _example-series-median-14: .. dropdown:: median (np_test_1_all.cpp:11882) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 11872 :emphasize-lines: 11 std::cout << "========= testMedianAndPercentiles ======================="; // Test median with odd number of elements auto odd_array = createInt32Array({ 5 }, 0); odd_array.setElementAt({ 0 }, 1); odd_array.setElementAt({ 1 }, 3); odd_array.setElementAt({ 2 }, 5); odd_array.setElementAt({ 3 }, 7); odd_array.setElementAt({ 4 }, 9); auto median_odd = median(odd_array); if (!(approx_equal(median_odd.getElementAt({ 0 }), 5.0, 1e-10))) { std::string description = std::string("testMedianAndPercentiles():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(approx_equal(median_odd.getElementAt({ 0 }), 5.0, 1e-10))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] Median with odd count works correctly\n"; // Test median with even number of elements auto even_array = createInt32Array({ 4 }, 0); even_array.setElementAt({ 0 }, 1); .. _example-series-min-15: .. dropdown:: min (np_test_1_all.cpp:2350) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 2340 :emphasize-lines: 11 if (i % 3 == 0) { large_array.setElementAt({i}, object_(static_cast(i))); } else if (i % 3 == 1) { large_array.setElementAt({i}, object_(static_cast(i) * 0.5)); } else { large_array.setElementAt({i}, object_(std::string("str") + std::to_string(i))); } } // Verify pattern for (size_t i = 0; i < std::min(large_size, size_t(100)); ++i) { // Check first 100 object_ obj = large_array.getElementAt({i}); if (i % 3 == 0) { if (!(obj.is_type())) { std::string description = std::string("testArrayEdgeCases():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(obj.is_type())"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } } else if (i % 3 == 1) { if (!(obj.is_type())) { std::string description = std::string("unknown_function():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(obj.is_type())"; .. _example-series-quantile-16: .. dropdown:: quantile (np_test_1_all.cpp:11929) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 11919 :emphasize-lines: 11 // Test 25th percentile auto perc25 = percentile(perc_array, 25.0); if (!(approx_equal(perc25.getElementAt({ 0 }), 3.25, 1e-10))) { std::string description = std::string("testMedianAndPercentiles():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(approx_equal(perc25.getElementAt({ 0 }), 3.25, 1e-10))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] 25th percentile works correctly\n"; // Test quantile (equivalent to percentile/100) auto quant75 = quantile(perc_array, 0.75); auto perc75 = percentile(perc_array, 75.0); if (!(approx_equal(quant75.getElementAt({ 0 }), perc75.getElementAt({ 0 }), 1e-10))) { std::string description = std::string("testMedianAndPercentiles():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(approx_equal(quant75.getElementAt({ 0 }), perc75.getElementAt({ 0 }), 1e-10))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] Quantile function works correctly\n"; std::cout << " -> tests passed" << std::endl; } .. _example-series-std-17: .. dropdown:: std (np_test_1_all.cpp:11836) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 11826 :emphasize-lines: 11 auto var_sample = var(array, std::nullopt, 1); // ddof=1 for sample variance double expected_sample_var = 1.25 * 4.0 / 3.0; // Bessel's correction if (!(approx_equal(var_sample.getElementAt({ 0 }), expected_sample_var, 1e-10))) { std::string description = std::string("testVarianceAndStandardDeviation():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(approx_equal(var_sample.getElementAt({ 0 }), expected_sample_var, 1e-10))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] Sample variance works correctly\n"; // Test standard deviation auto std_result = numpy::std(array, std::nullopt, 0); if (!(approx_equal(std_result.getElementAt({ 0 }), std::sqrt(expected_var), 1e-10))) { std::string description = std::string("testVarianceAndStandardDeviation():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(approx_equal(std_result.getElementAt({ 0 }), std::sqrt(expected_var), 1e-10))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] Standard deviation works correctly\n"; // Test along axis auto array2d = createFloat64Array({ 2, 2 }, 0); array2d.setElementAt({ 0, 0 }, 1.0); .. _example-series-sum-18: .. dropdown:: sum (np_test_1_all.cpp:11766) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 11756 :emphasize-lines: 11 throw std::runtime_error(description); } if (!(approx_equal(mean_axis1.getElementAt({ 1 }), 5.0, 1e-10))) { std::string description = std::string("testBasicStatistics():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(approx_equal(mean_axis1.getElementAt({ 1 }), 5.0, 1e-10))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] mean along axis 1 works correctly\n"; // Test sum auto sum_all = sum(array); if (!(sum_all.getElementAt({ 0 }) == 21)) { std::string description = std::string("testBasicStatistics():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(sum_all.getElementAt({ 0 }) == 21)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] sum works correctly\n"; // Test min and max auto min_all = min(array); auto max_all = max(array); .. _example-series-var-19: .. dropdown:: var (np_test_1_all.cpp:11816) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 11806 :emphasize-lines: 11 std::cout << "========= testVarianceAndStandardDeviation ======================="; // Create test array with known variance auto array = createFloat64Array({ 4 }, 0); array.setElementAt({ 0 }, 1.0); array.setElementAt({ 1 }, 2.0); array.setElementAt({ 2 }, 3.0); array.setElementAt({ 3 }, 4.0); // Test variance (population) auto var_result = var(array, std::nullopt, 0); // ddof=0 for population variance double expected_var = 1.25; // Known variance for [1,2,3,4] if (!(approx_equal(var_result.getElementAt({ 0 }), expected_var, 1e-10))) { std::string description = std::string("testVarianceAndStandardDeviation():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(approx_equal(var_result.getElementAt({ 0 }), expected_var, 1e-10))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] Population variance works correctly\n"; // Test variance (sample) auto var_sample = var(array, std::nullopt, 1); // ddof=1 for sample variance .. _example-series-argsort-20: .. dropdown:: argsort (np_test_1_all.cpp:16841) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 16831 :emphasize-lines: 11 std::cout << "========= test_argsort ======================="; // Test 1D array argsort NDArray arr1d({ 5 }); arr1d.setElementAt({ 0 }, 30); // index 0 arr1d.setElementAt({ 1 }, 10); // index 1 arr1d.setElementAt({ 2 }, 40); // index 2 arr1d.setElementAt({ 3 }, 20); // index 3 arr1d.setElementAt({ 4 }, 50); // index 4 auto indices = argsort(arr1d); // Expected order: 10(idx1), 20(idx3), 30(idx0), 40(idx2), 50(idx4) if (!(indices.getElementAt({ 0 }) == 1)) { std::string description = std::string("test_argsort():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(indices.getElementAt({ 0 }) == 1)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(indices.getElementAt({ 1 }) == 3)) { std::string description = std::string("test_argsort():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(indices.getElementAt({ 1 }) == 3)"; std::cout << std::string("[FAIL] ") + description << std::endl; .. _example-series-abs-21: .. dropdown:: abs (np_test_1_all.cpp:101) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 91 :emphasize-lines: 11 if (arr.getShape().size() == 1 && arr.getShape()[0] <= 10) { for (size_t i = 0; i < arr.getShape()[0]; ++i) { // std::cout << static_cast(arr.getElementAt({i})) << " "; } } // std::cout << std::endl; } // Helper function for core array extensions tests bool isApproxEqualExt(double a, double b, double tolerance = 1e-10) { return std::abs(a - b) < tolerance; } } void f_nothing() { // This function does nothing and tests nothing // It's a placeholder test function } // ------ merging np_test_advanced_indexing.cpp -- number of functions merged=16 -------------------------------- .. _example-series-add-22: .. dropdown:: add (np_test_1_all.cpp:6410) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 6400 :emphasize-lines: 11 void testCharArrayStringOperationsCharArray() { std::cout << "========= testStringOperations ======================="; // Test string concatenation std::vector words1 = {"Hello", "Good", "Nice"}; std::vector words2 = {" World", " Day", " Work"}; auto arr1 = array<32>(words1); auto arr2 = array<32>(words2); auto result = add(arr1, arr2); // std::cout << "String concatenation (add):" << std::endl; for (size_t i = 0; i < result.size(); ++i) { // std::cout << "'" << arr1[i] << "' + '" << arr2[i] << "' = '" << result[i] << "'"; } // Test scalar addition auto scalar_result = add(arr1, "!"); // std::cout << "Scalar concatenation:" << std::endl; for (size_t i = 0; i < scalar_result.size(); ++i) { // std::cout << "'" << arr1[i] << "' + '!' = '" << scalar_result[i] << "'"; .. _example-series-add-23: .. dropdown:: add (np_test_1_all.cpp:6410) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 6400 :emphasize-lines: 11 void testCharArrayStringOperationsCharArray() { std::cout << "========= testStringOperations ======================="; // Test string concatenation std::vector words1 = {"Hello", "Good", "Nice"}; std::vector words2 = {" World", " Day", " Work"}; auto arr1 = array<32>(words1); auto arr2 = array<32>(words2); auto result = add(arr1, arr2); // std::cout << "String concatenation (add):" << std::endl; for (size_t i = 0; i < result.size(); ++i) { // std::cout << "'" << arr1[i] << "' + '" << arr2[i] << "' = '" << result[i] << "'"; } // Test scalar addition auto scalar_result = add(arr1, "!"); // std::cout << "Scalar concatenation:" << std::endl; for (size_t i = 0; i < scalar_result.size(); ++i) { // std::cout << "'" << arr1[i] << "' + '!' = '" << scalar_result[i] << "'"; .. _example-series-ceil-24: .. dropdown:: ceil (np_test_2_all.cpp:5735) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 5725 :emphasize-lines: 11 throw std::runtime_error(description); } if (!(approx_equal(floor_result.getElementAt({ 5 }), std::floor(2.7)))) { std::string description = std::string("testRoundingFunctions():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(approx_equal(floor_result.getElementAt({ 5 }), std::floor(2.7)))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] floor function works correctly\n"; // Test ceil auto ceil_result = ceil(values); if (!(approx_equal(ceil_result.getElementAt({ 0 }), std::ceil(-2.7)))) { std::string description = std::string("testRoundingFunctions():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(approx_equal(ceil_result.getElementAt({ 0 }), std::ceil(-2.7)))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(approx_equal(ceil_result.getElementAt({ 5 }), std::ceil(2.7)))) { std::string description = std::string("testRoundingFunctions():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(approx_equal(ceil_result.getElementAt({ 5 }), std::ceil(2.7)))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } .. _example-series-divide-25: .. dropdown:: divide (np_test_3_all.cpp:16880) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 16870 :emphasize-lines: 11 std::cout << " -> tests passed" << std::endl; } void np_test_missing_math_functions_divide_array() { std::cout << "========= divide: array-array division ======================="; // explicit namespace to avoid name clashes numpy::NDArray a = numpy::arange(10.0, 16.0, 1.0); numpy::NDArray b = numpy::arange(2.0, 8.0, 1.0); numpy::NDArray result = numpy::divide(a, b); // Verify values: [10,11,12,13,14,15] / [2,3,4,5,6,7] = [5,3.666...,3,2.6,2.333...,2.142...] auto pass = true; double expected[] = { 5.0, 11.0 / 3.0, 3.0, 2.6, 14.0 / 6.0, 15.0 / 7.0 }; for (size_t i = 0; i < 6 && pass; ++i) { double val = result.getElementAt({ i }); double exp = expected[i]; if (std::abs(val - exp) > 1e-10) { pass = false; } .. _example-series-floor-26: .. dropdown:: floor (np_test_2_all.cpp:5721) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 5711 :emphasize-lines: 11 throw std::runtime_error(description); } if (!(approx_equal(round_result.getElementAt({ 5 }), std::round(2.7)))) { std::string description = std::string("testRoundingFunctions():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(approx_equal(round_result.getElementAt({ 5 }), std::round(2.7)))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] round function works correctly\n"; // Test floor auto floor_result = floor(values); if (!(approx_equal(floor_result.getElementAt({ 0 }), std::floor(-2.7)))) { std::string description = std::string("testRoundingFunctions():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(approx_equal(floor_result.getElementAt({ 0 }), std::floor(-2.7)))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(approx_equal(floor_result.getElementAt({ 5 }), std::floor(2.7)))) { std::string description = std::string("testRoundingFunctions():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(approx_equal(floor_result.getElementAt({ 5 }), std::floor(2.7)))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } .. _example-series-mod-27: .. dropdown:: mod (np_test_1_all.cpp:21258) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21248 :emphasize-lines: 11 a.setElementAt({ 1 }, -7); a.setElementAt({ 2 }, 7); a.setElementAt({ 3 }, -7); auto b = NDArray({ 4 }); b.setElementAt({ 0 }, 3); b.setElementAt({ 1 }, 3); b.setElementAt({ 2 }, -3); b.setElementAt({ 3 }, -3); auto result = mod(a, b); if (!(result.getElementAt({ 0 }) == 1)) { std::string description = std::string("testModFunction():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(result.getElementAt({ 0 }) == 1)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(result.getElementAt({ 1 }) == 2)) { std::string description = std::string("testModFunction():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(result.getElementAt({ 1 }) == 2)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); .. _example-series-mod-28: .. dropdown:: mod (np_test_1_all.cpp:21258) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21248 :emphasize-lines: 11 a.setElementAt({ 1 }, -7); a.setElementAt({ 2 }, 7); a.setElementAt({ 3 }, -7); auto b = NDArray({ 4 }); b.setElementAt({ 0 }, 3); b.setElementAt({ 1 }, 3); b.setElementAt({ 2 }, -3); b.setElementAt({ 3 }, -3); auto result = mod(a, b); if (!(result.getElementAt({ 0 }) == 1)) { std::string description = std::string("testModFunction():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(result.getElementAt({ 0 }) == 1)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(result.getElementAt({ 1 }) == 2)) { std::string description = std::string("testModFunction():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(result.getElementAt({ 1 }) == 2)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); .. _example-series-mode-29: .. dropdown:: mode (np_test_4_all.cpp:20711) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 20701 :emphasize-lines: 11 #include using namespace numpy; namespace numpy_tests { namespace numpy_tests_phase6b { void np_test_phase6b_can_cast() { std::cout << "=== Test can_cast() ==="; // Test SAFE casting mode (default) { // Same type is always safe if (!(can_cast(DType::INT32, DType::INT32, CastingMode::SAFE) == true)) { std::string description = std::string("np_test_phase6b_can_cast():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(can_cast(DType::INT32, DType::INT32, CastingMode::SAFE) == true)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(can_cast(DType::FLOAT64, DType::FLOAT64, CastingMode::SAFE) == true)) { std::string description = std::string("np_test_phase6b_can_cast():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(can_cast(DType::FLOAT64, DType::FLOAT64, CastingMode::SAFE) == true)"; std::cout << std::string("[FAIL] ") + description << std::endl; .. _example-series-multiply-30: .. dropdown:: multiply (np_test_1_all.cpp:6426) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 6416 :emphasize-lines: 11 // Test scalar addition auto scalar_result = add(arr1, "!"); // std::cout << "Scalar concatenation:" << std::endl; for (size_t i = 0; i < scalar_result.size(); ++i) { // std::cout << "'" << arr1[i] << "' + '!' = '" << scalar_result[i] << "'"; } // Test string multiplication std::vector patterns = {"Ha", "Ho", "Hi"}; auto pattern_arr = array<32>(patterns); auto repeated = multiply(pattern_arr, 3); // std::cout << "String multiplication:" << std::endl; for (size_t i = 0; i < repeated.size(); ++i) { // std::cout << "'" << pattern_arr[i] << "' * 3 = '" << repeated[i] << "'"; } std::cout << " -> tests passed" << std::endl; } void testCaseConversionsCharArray() { std::cout << "========= testCaseConversions ======================="; .. _example-series-round-31: .. dropdown:: round (np_test_1_all.cpp:23769) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 23759 :emphasize-lines: 11 throw std::runtime_error(description); } if (!(power_scalar_result.getShape() == array.getShape())) { std::string description = std::string("testMathFunctionSignatures():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(power_scalar_result.getShape() == array.getShape())"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] Power functions have correct signatures\n"; // Test rounding functions with new decimals parameter auto round_result = round(array); // Default decimals=0 auto round_decimals_result = round(array, 2); // With decimals if (!(round_result.getShape() == array.getShape())) { std::string description = std::string("testMathFunctionSignatures():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(round_result.getShape() == array.getShape())"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(round_decimals_result.getShape() == array.getShape())) { std::string description = std::string("testMathFunctionSignatures():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(round_decimals_result.getShape() == array.getShape())"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); .. _example-series-subtract-32: .. dropdown:: subtract (np_test_3_all.cpp:16825) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 16815 :emphasize-lines: 11 std::cout << " -> tests passed" << std::endl; } void np_test_missing_math_functions_subtract_array() { std::cout << "========= subtract: array-array subtraction ======================="; // explicit namespace to avoid name clashes numpy::NDArray a = numpy::arange(10.0, 16.0, 1.0); numpy::NDArray b = numpy::arange(0.0, 6.0, 1.0); numpy::NDArray result = numpy::subtract(a, b); // Verify values: [10,11,12,13,14,15] - [0,1,2,3,4,5] = [10,10,10,10,10,10] auto pass = true; for (size_t i = 0; i < 6 && pass; ++i) { double val = result.getElementAt({ i }); double exp = 10.0; if (std::abs(val - exp) > 1e-10) { pass = false; } } .. _example-series-truncate-33: .. dropdown:: truncate (np_test_5_all.cpp:7536) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 7526 :emphasize-lines: 11 if (!passed) { std::cout << " [FAIL] : cutdeg failed"; throw std::runtime_error("np_test_cutdeg failed"); } std::cout << " -> tests passed" << std::endl; } void np_test_truncate() { std::cout << "========= truncate: truncate to size ======================="; numpy::Polynomial p({ 1.0, 2.0, 3.0, 4.0, 5.0 }); auto truncated = p.truncate(3); // Keep only first 3 coefficients auto coefs = truncated.coefficients(); bool passed = (coefs.size() == 3 && std::abs(coefs[0] - 1.0) < 1e-10 && std::abs(coefs[1] - 2.0) < 1e-10 && std::abs(coefs[2] - 3.0) < 1e-10); .. _example-series-dot-34: .. dropdown:: dot (np_test_2_all.cpp:11523) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 11513 :emphasize-lines: 11 numpy::NDArray v2({ 3 }); v1.setElementAt({ 0 }, 1.0); v1.setElementAt({ 1 }, 2.0); v1.setElementAt({ 2 }, 3.0); v2.setElementAt({ 0 }, 4.0); v2.setElementAt({ 1 }, 5.0); v2.setElementAt({ 2 }, 6.0); auto result = numpy::linalg::dot(v1, v2); double expected = 1.0 * 4.0 + 2.0 * 5.0 + 3.0 * 6.0; // = 32 // Extract scalar from 0-D array double result_value = result.getElementAt({}); if (std::abs(result_value - expected) > 1e-10) { std::cout << " [FAIL] : dot product incorrect, expected " << expected << ", got " << result_value; throw std::runtime_error("dot test failed"); } .. _example-series-dot-35: .. dropdown:: dot (np_test_2_all.cpp:11523) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 11513 :emphasize-lines: 11 numpy::NDArray v2({ 3 }); v1.setElementAt({ 0 }, 1.0); v1.setElementAt({ 1 }, 2.0); v1.setElementAt({ 2 }, 3.0); v2.setElementAt({ 0 }, 4.0); v2.setElementAt({ 1 }, 5.0); v2.setElementAt({ 2 }, 6.0); auto result = numpy::linalg::dot(v1, v2); double expected = 1.0 * 4.0 + 2.0 * 5.0 + 3.0 * 6.0; // = 32 // Extract scalar from 0-D array double result_value = result.getElementAt({}); if (std::abs(result_value - expected) > 1e-10) { std::cout << " [FAIL] : dot product incorrect, expected " << expected << ", got " << result_value; throw std::runtime_error("dot test failed"); } .. _example-series-sample-36: .. dropdown:: sample (np_test_1_all.cpp:22321) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 22311 :emphasize-lines: 11 throw std::runtime_error(description); } for (size_t i = 0; i < 3; ++i) { double val = random_samp.getElementAt({ i }); if (!(val >= 0.0 && val < 1.0)) { std::string description = std::string("testRandomUtilityFunctions():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(val >= 0.0 && val < 1.0)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } } // std::cout << "[OK] Random sample (alias)\n"; auto ranf_arr = ranf({ {3} }); if (!(ranf_arr.getShape()[0] == 3)) { std::string description = std::string("testRandomUtilityFunctions():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(ranf_arr.getShape()[0] == 3)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] ranf (alias)\n"; auto sample_arr = sample({ {3} }); .. _example-series-unique-37: .. dropdown:: unique (np_test_1_all.cpp:6259) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 6249 :emphasize-lines: 11 if (!(data.size() == 100)) { std::string description = std::string("test_data_generator_few_uniqueBenchmarkSorting():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(data.size() == 100)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // Count unique values std::vector sorted_copy = data; std::sort(sorted_copy.begin(), sorted_copy.end()); auto unique_end = std::unique(sorted_copy.begin(), sorted_copy.end()); size_t unique_count = std::distance(sorted_copy.begin(), unique_end); // Should have significantly fewer unique values than total elements if (!(unique_count < data.size() / 2)) { std::string description = std::string("test_data_generator_few_uniqueBenchmarkSorting():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(unique_count < data.size() / 2)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "Few unique data generation test passed. Unique values: " << unique_count << std::endl; .. _example-series-to_numpy-38: .. dropdown:: to_numpy (np_test_5_all.cpp:21373) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21363 :emphasize-lines: 11 if (errors == 0) { std::cout << "np_test_timedelta_components -> tests passed" << std::endl; } return errors; } // ============================================================================= // Test 4: Total Conversion Properties // ============================================================================= int np_test_timedelta_total_conversions() { int errors = 0; numpy::Timedelta td(1, 12, 0); // 1 day 12 hours = 1.5 days = 36 hours // total_seconds { double secs = td.total_seconds(); double expected = (24 + 12) * 3600.0; if (std::abs(secs - expected) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_total_conversions: total_seconds expected " << expected << ", got " << secs << std::endl; .. _example-series-to_string-39: .. dropdown:: to_string (np_test_1_all.cpp:454) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 444 :emphasize-lines: 11 // Modify through different views view1.setElementAt({0, 0}, 100); view2.setElementAt({2, 1}, 200); // This is (1, 2) in original view3.setElementAt({0, 0}, 300); // This is (1, 1) in original // std::cout << "After modifications through multiple views:" << std::endl; //original.printArray(); // Verify all changes are reflected if (!(original.getElementAt({0, 0}) == 100)) { std::string description = std::string("testAdvancedViewLifecycle():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(original.getElementAt({0, 0}) == 100)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(original.getElementAt({1, 2}) == 200)) { std::string description = std::string("testAdvancedViewLifecycle():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(original.getElementAt({1, 2}) == 200)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(original.getElementAt({1, 1}) == 300)) { std::string description = std::string("testAdvancedViewLifecycle():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(original.getElementAt({1, 1}) == 300)"; .. _example-series-tolist-40: .. dropdown:: tolist (np_test_4_all.cpp:20046) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 20036 :emphasize-lines: 11 } // namespace numpy_tests /** * @file np_test_phase6.cpp * @brief Test suite for Phase 6A - HIGH PRIORITY NDArray methods and masked array utilities * * Tests: * - ndarray.nonzero() - Return indices of non-zero elements * - ndarray.tobytes() - Convert to bytes representation * - ndarray.tolist() - Convert to nested list string * - ndarray.fill() - Fill with scalar value (in-place) * - ndarray.item() - Get single element as scalar * - ndarray.itemset() - Set single element value * - ma.masked_all_like() - Create masked array with all elements masked * * Created: 2025-10-28 * Status: Phase 6A Implementation - HIGH PRIORITY functions */ #include "../numpy/np_ndarray.h" .. _example-series-repeat-41: .. dropdown:: repeat (np_test_1_all.cpp:18268) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 18258 :emphasize-lines: 11 // Create test array auto array = createInt32Array({ 2, 3 }, 0); for (size_t i = 0; i < 2; ++i) { for (size_t j = 0; j < 3; ++j) { array.setElementAt({ i, j }, static_cast(i * 3 + j + 1)); } } // Test repeat without axis (flattened) auto repeated_flat = repeat(array, 2); if (!(repeated_flat.getShape()[0] == 12)) { std::string description = std::string("testRepeat():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(repeated_flat.getShape()[0] == 12)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(repeated_flat.getElementAt({ 0 }) == 1)) { std::string description = std::string("testRepeat():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(repeated_flat.getElementAt({ 0 }) == 1)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } .. _example-series-astype-42: .. dropdown:: astype (np_test_3_all.cpp:796) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 786 :emphasize-lines: 11 auto ufunc_square = numpy::frompyfunc(square, 1, 1); numpy::NDArray arr({ 3 }); arr.setElementAt({ 0 }, 2.0); arr.setElementAt({ 1 }, 3.0); arr.setElementAt({ 2 }, 4.0); auto result = ufunc_square(arr); // Convert back to double to check values auto typed_result = numpy::astype(result); if (std::abs(typed_result.getElementAt({ 0 }) - 4.0) > 1e-10 || std::abs(typed_result.getElementAt({ 1 }) - 9.0) > 1e-10 || std::abs(typed_result.getElementAt({ 2 }) - 16.0) > 1e-10) { std::cout << "[FAIL] Basic frompyfunc creation failed"; return 1; } // std::cout << "[OK] Basic frompyfunc creation works correctly" << std::endl; std::cout << " -> tests passed" << std::endl; return 0; .. _example-series-copy-43: .. dropdown:: copy (np_test_1_all.cpp:9812) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 9802 :emphasize-lines: 11 //original.printArray(); // The modification should be at position (1,1) in original if (!(original.getElementAt({1, 1}) == 9999)) { std::string description = std::string("testSliceCopyVsViewMemoryOwnership():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(original.getElementAt({1, 1}) == 9999)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] Slice view shares memory with original"; // Test slice copy (should be independent) auto slice_copy = original.sliceArray({{2, 4}, {2, 4}}); // std::cout << "Slice copy [2:4, 2:4]:"; //slice_copy.printArray(); slice_copy.setElementAt({0, 0}, 7777); // std::cout << "After modifying slice copy at (0,0):" << std::endl; // std::cout << "Original array:" << std::endl; //original.printArray(); // std::cout << "Slice copy:" << std::endl; .. _example-series-view-44: .. dropdown:: view (np_test_1_all.cpp:440) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 430 :emphasize-lines: 11 for (size_t i = 0; i < 3; ++i) { for (size_t j = 0; j < 3; ++j) { original.setElementAt({i, j}, static_cast(i * 3 + j)); } } // std::cout << "Original array:" << std::endl; //original.printArray(); // Create multiple views auto view1 = original.view(); auto view2 = original.transposeView(); auto view3 = original.sliceView({{1, 3}, {1, 3}}); // Modify through different views view1.setElementAt({0, 0}, 100); view2.setElementAt({2, 1}, 200); // This is (1, 2) in original view3.setElementAt({0, 0}, 300); // This is (1, 1) in original // std::cout << "After modifications through multiple views:" << std::endl; //original.printArray(); .. _example-series-combine-45: .. dropdown:: combine (np_test_5_all.cpp:22273) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 22263 :emphasize-lines: 11 auto pass = true; std::string fail_msg; // Default constructor (NaT) numpy::Timestamp nat; if (!nat.isNaT()) { pass = false; fail_msg = "Default constructor should create NaT"; } // Component constructor numpy::Timestamp ts1(2024, 6, 15, 14, 30, 45); if (ts1.year() != 2024 || ts1.month() != 6 || ts1.day() != 15 || ts1.hour() != 14 || ts1.minute() != 30 || ts1.second() != 45) { pass = false; fail_msg = "Component constructor values incorrect"; } // With microseconds and nanoseconds numpy::Timestamp ts2(2024, 1, 1, 12, 0, 0, 123456, 789); .. _example-series-argmax-46: .. dropdown:: argmax (np_test_3_all.cpp:20521) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 20511 :emphasize-lines: 11 auto result = numpy::argmin(arr); // Should return 1 (index of (1,5)) if (result.getElementAt({0}) != 1) { throw std::runtime_error("argmin() failed: expected index 1"); } std::cout << "PASSED\n"; } void test_argmax_complex128() { std::cout << " Testing argmax() with complex128... "; numpy::NDArray arr({3}); arr.setElementAt({0}, complex128(3.0, 1.0)); // index 0 - largest arr.setElementAt({1}, complex128(1.0, 5.0)); // index 1 arr.setElementAt({2}, complex128(2.0, 2.0)); // index 2 auto result = numpy::argmax(arr); // Should return 0 (index of (3,1)) if (result.getElementAt({0}) != 0) { throw std::runtime_error("argmax() failed: expected index 0"); } .. _example-series-argmin-47: .. dropdown:: argmin (np_test_3_all.cpp:20506) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 20496 :emphasize-lines: 11 if (min_result.getElementAt({0}).real() != 2.0 || min_result.getElementAt({0}).imag() != 1.0) { throw std::runtime_error("min() tie-breaking failed: expected (2,1)"); } if (max_result.getElementAt({0}).real() != 2.0 || max_result.getElementAt({0}).imag() != 5.0) { throw std::runtime_error("max() tie-breaking failed: expected (2,5)"); } std::cout << "PASSED\n"; } void test_argmin_complex128() { std::cout << " Testing argmin() with complex128... "; numpy::NDArray arr({3}); arr.setElementAt({0}, complex128(3.0, 1.0)); // index 0 arr.setElementAt({1}, complex128(1.0, 5.0)); // index 1 - smallest arr.setElementAt({2}, complex128(2.0, 2.0)); // index 2 auto result = numpy::argmin(arr); // Should return 1 (index of (1,5)) if (result.getElementAt({0}) != 1) { throw std::runtime_error("argmin() failed: expected index 1"); } .. _example-series-axes-48: .. dropdown:: axes (np_test_5_all.cpp:16631) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 16621 :emphasize-lines: 11 return 0; } else { std::cout << " [FAIL] reshape() failed" << std::endl; return 1; } } // Test 15: transpose() - Transpose array (SKIPPED - needs implementation) int test_transpose() { std::cout << "\n[TEST] ma.transpose() - SKIPPED (needs correct transpose API)" << std::endl; return 0; // Skip for now } // Test 16: swapaxes() - Swap two axes (SKIPPED - needs implementation) int test_swapaxes() { std::cout << "\n[TEST] ma.swapaxes() - SKIPPED (needs correct swapaxes API)" << std::endl; return 0; // Skip for now } // Test 17: repeat() - Repeat elements int test_repeat() { .. _example-series-between-49: .. dropdown:: between (np_test_4_all.cpp:19254) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 19244 :emphasize-lines: 11 } numpy::NDArray x({3}); double* x_data = x.data(); x_data[0] = 0.5; x_data[1] = 1.5; x_data[2] = 2.5; numpy::NDArray result = numpy::interp(x, xp, fp); const double* result_data = result.data(); // Linear interpolation results (not exact function values): // x=0.5: interpolate between (0,0) and (1,1) → 0.5 // x=1.5: interpolate between (1,1) and (2,4) → 2.5 // x=2.5: interpolate between (2,4) and (3,9) → 6.5 if (!(is_close(result_data[0], 0.5))) { std::string description = std::string("test_interp_array():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(is_close(result_data[0], 0.5))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(is_close(result_data[1], 2.5))) { std::string description = std::string("test_interp_array():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(is_close(result_data[1], 2.5))"; std::cout << std::string("[FAIL] ") + description << std::endl; .. _example-series-bool_-50: .. dropdown:: bool_ (np_test_3_all.cpp:15233) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 15223 :emphasize-lines: 11 std::cout << "========= test_where_selection ===="; // Create condition, x, and y arrays auto cond_data = createBoolArray({ 4 }, false); cond_data.setElementAt({ 0 }, true); cond_data.setElementAt({ 1 }, false); cond_data.setElementAt({ 2 }, true); cond_data.setElementAt({ 3 }, false); auto cond_mask = createBoolArray({ 4 }, false); MaskedArray condition(cond_data, cond_mask, bool_(false)); auto x_data = createInt32Array({ 4 }, 0); x_data.setElementAt({ 0 }, 10); x_data.setElementAt({ 1 }, 20); x_data.setElementAt({ 2 }, 30); x_data.setElementAt({ 3 }, 40); auto x_mask = createBoolArray({ 4 }, false); MaskedArray x(x_data, x_mask, -999); .. _example-series-clip-51: .. dropdown:: clip (np_test_1_all.cpp:15142) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 15132 :emphasize-lines: 11 numpy::NDArray values({ 5 }); values.setElementAt({ 0 }, -2.0); values.setElementAt({ 1 }, -1.0); values.setElementAt({ 2 }, 0.5); values.setElementAt({ 3 }, 2.0); values.setElementAt({ 4 }, 5.0); double min_val = -1.0; double max_val = 3.0; auto clip_result = numpy::clip(values, min_val, max_val); bool test8_pass = true; if (std::abs(clip_result.getElementAt({ 0 }) - (-1.0)) > 1e-10 || std::abs(clip_result.getElementAt({ 3 }) - 2.0) > 1e-10 || std::abs(clip_result.getElementAt({ 4 }) - 3.0) > 1e-10) { test8_pass = false; } if (test8_pass) { // std::cout << "[OK] Clip function works correctly"; .. _example-series-clone-52: .. dropdown:: clone (np_test_1_all.cpp:24942) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 24932 :emphasize-lines: 11 } // Test reproducibility numpy::random::PCG64DXSM rng2(11111); if (rng2.next_uint64() != val) { std::cout << " [FAIL] : in np_test_bitgen_pcg64dxsm() : not reproducible"; throw std::runtime_error("np_test_bitgen_pcg64dxsm failed"); } // Test clone auto cloned = rng.clone(); if (cloned->name() != "PCG64DXSM") { std::cout << " [FAIL] : in np_test_bitgen_pcg64dxsm() : clone name incorrect"; throw std::runtime_error("np_test_bitgen_pcg64dxsm failed"); } std::cout << " -> tests passed" << std::endl; } // ============================================================================ // PHILOX TESTS .. _example-series-count-53: .. dropdown:: count (np_test_1_all.cpp:3616) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 3606 :emphasize-lines: 11 // Create larger arrays for performance testing auto large_arr = NDArray::createOnes({100, 100}); auto broadcast_arr = NDArray::createOnes({1, 100}); // Time the operation (basic timing) auto start = std::chrono::high_resolution_clock::now(); auto result = large_arr.addArrays(broadcast_arr); auto end = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast(end - start); // std::cout << "Large array broadcasting took " << duration.count() << " microseconds" << std::endl; // Verify result shape if (!((result.getShape() == std::vector{100, 100}))) { std::string description = std::string("test_broadcasting_performance():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !((result.getShape() == std::vector{100, 100}))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(result.getElementAt({50, 50}) == 2.0)) { std::string description = std::string("test_broadcasting_performance():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(result.getElementAt({50, 50}) == 2.0)"; std::cout << std::string("[FAIL] ") + description << std::endl; .. _example-series-cumprod-54: .. dropdown:: cumprod (np_test_5_all.cpp:5107) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 5097 :emphasize-lines: 11 } void np_test_cumprod_1d() { std::cout << "========= cumprod 1D ======================="; // Test cumprod with 1D array numpy::NDArray arr({ 5 }); arr.setElementAt({ 0 }, 1); arr.setElementAt({ 1 }, 2); arr.setElementAt({ 2 }, 3); arr.setElementAt({ 3 }, 4); arr.setElementAt({ 4 }, 5); auto result = numpy::cumprod(arr); // Expected: [1, 2, 6, 24, 120] if (result.getElementAt({ 0 }) != 1 || result.getElementAt({ 1 }) != 2 || result.getElementAt({ 2 }) != 6 || result.getElementAt({ 3 }) != 24 || result.getElementAt({ 4 }) != 120) { std::cout << " [FAIL] : in np_test_cumprod_1d() : Incorrect cumprod result"; throw std::runtime_error("Test failed"); .. _example-series-cumsum-55: .. dropdown:: cumsum (np_test_5_all.cpp:5028) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 5018 :emphasize-lines: 11 namespace numpy_tests_cumulative_operations { void np_test_cumsum_1d() { std::cout << "========= cumsum 1D ======================="; // Test cumsum with 1D array numpy::NDArray arr({ 5 }); arr.setElementAt({ 0 }, 1); arr.setElementAt({ 1 }, 2); arr.setElementAt({ 2 }, 3); arr.setElementAt({ 3 }, 4); arr.setElementAt({ 4 }, 5); auto result = numpy::cumsum(arr); // Expected: [1, 3, 6, 10, 15] if (result.getElementAt({ 0 }) != 1 || result.getElementAt({ 1 }) != 3 || result.getElementAt({ 2 }) != 6 || result.getElementAt({ 3 }) != 10 || result.getElementAt({ 4 }) != 15) { std::cout << " [FAIL] : in np_test_cumsum_1d() : Incorrect cumsum result"; throw std::runtime_error("Test failed"); .. _example-series-describe-56: .. dropdown:: describe (np_test_1_all.cpp:11448) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 11438 :emphasize-lines: 11 auto moment2_result = moment(normal_data, 2); // std::cout << "2nd moment: " << moment2_result.getElementAt({ 0 }) << std::endl; if (!(moment2_result.getElementAt({ 0 }) > 0)) { std::string description = std::string("testDistributionShapeMeasures():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(moment2_result.getElementAt({ 0 }) > 0)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] Moment calculation\n"; // Test describe auto desc_result = describe(normal_data); // std::cout << "Describe result:" << std::endl; // std::cout << " nobs: " << desc_result.nobs << std::endl; // std::cout << " min: " << desc_result.minmax.first << ", max: " << desc_result.minmax.second << std::endl; // std::cout << " mean: " << desc_result.mean << std::endl; // std::cout << " variance: " << desc_result.variance << std::endl; if (!(desc_result.nobs == 5)) { std::string description = std::string("testDistributionShapeMeasures():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(desc_result.nobs == 5)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } .. _example-series-diff-57: .. dropdown:: diff (np_test_2_all.cpp:4947) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 4937 :emphasize-lines: 11 // Test matrix addition and subtraction numpy::Matrix a("1 2; 3 4"); numpy::Matrix b("5 6; 7 8"); auto sum = a + b; assert_test(std::abs(sum(0, 0) - 6.0) < 1e-10, "Matrix addition"); assert_test(std::abs(sum(1, 1) - 12.0) < 1e-10, "Matrix addition"); auto diff = b - a; assert_test(std::abs(diff(0, 0) - 4.0) < 1e-10, "Matrix subtraction"); assert_test(std::abs(diff(1, 1) - 4.0) < 1e-10, "Matrix subtraction"); // Test matrix multiplication (not element-wise!) auto product = a * b; assert_test(std::abs(product(0, 0) - 19.0) < 1e-10, "Matrix multiplication 0,0"); assert_test(std::abs(product(0, 1) - 22.0) < 1e-10, "Matrix multiplication 0,1"); assert_test(std::abs(product(1, 0) - 43.0) < 1e-10, "Matrix multiplication 1,0"); assert_test(std::abs(product(1, 1) - 50.0) < 1e-10, "Matrix multiplication 1,1"); // Test scalar multiplication .. _example-series-divmod-58: .. dropdown:: divmod (np_test_1_all.cpp:21140) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21130 :emphasize-lines: 11 auto a = NDArray({ 3 }); a.setElementAt({ 0 }, 7.0); a.setElementAt({ 1 }, -7.0); a.setElementAt({ 2 }, 7.5); auto b = NDArray({ 3 }); b.setElementAt({ 0 }, 3.0); b.setElementAt({ 1 }, 3.0); b.setElementAt({ 2 }, 2.0); auto [quotient, remainder] = divmod(a, b); if (!(quotient.getElementAt({ 0 }) == 2.0)) { std::string description = std::string("testDivmodFunction():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(quotient.getElementAt({ 0 }) == 2.0)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(std::abs(remainder.getElementAt({ 0 }) - 1.0) < 1e-10)) { std::string description = std::string("testDivmodFunction():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(std::abs(remainder.getElementAt({ 0 }) - 1.0) < 1e-10)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); .. _example-series-divmod-59: .. dropdown:: divmod (np_test_1_all.cpp:21140) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21130 :emphasize-lines: 11 auto a = NDArray({ 3 }); a.setElementAt({ 0 }, 7.0); a.setElementAt({ 1 }, -7.0); a.setElementAt({ 2 }, 7.5); auto b = NDArray({ 3 }); b.setElementAt({ 0 }, 3.0); b.setElementAt({ 1 }, 3.0); b.setElementAt({ 2 }, 2.0); auto [quotient, remainder] = divmod(a, b); if (!(quotient.getElementAt({ 0 }) == 2.0)) { std::string description = std::string("testDivmodFunction():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(quotient.getElementAt({ 0 }) == 2.0)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(std::abs(remainder.getElementAt({ 0 }) - 1.0) < 1e-10)) { std::string description = std::string("testDivmodFunction():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(std::abs(remainder.getElementAt({ 0 }) - 1.0) < 1e-10)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); .. _example-series-dtype_name-60: .. dropdown:: dtype_name (np_test_2_all.cpp:3567) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 3557 :emphasize-lines: 11 std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(flags_info.writeable == true)) { std::string description = std::string("testArrayInfo():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(flags_info.writeable == true)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // Test dtype functions if (!(dtype_name(arr) == "float64")) { std::string description = std::string("testArrayInfo():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(dtype_name(arr) == \"float64\")"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(dtype_itemsize(arr) == sizeof(double))) { std::string description = std::string("testArrayInfo():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(dtype_itemsize(arr) == sizeof(double))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } .. _example-series-file-61: .. dropdown:: file (np_test_1_all.cpp:27026) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 27016 :emphasize-lines: 11 } // Test with filename size_t size1 = io::get_remaining_size(test_filename); if (size1 != 100) { std::cout << " [FAIL] : in test_get_remaining_size() : expected 100 bytes, got " << size1; throw std::runtime_error("test_get_remaining_size failed: incorrect file size"); } // Test with file stream std::ifstream file(test_filename, std::ios::binary); file.seekg(30); // Move to position 30 size_t size2 = io::get_remaining_size(file); if (size2 != 70) { std::cout << " [FAIL] : in test_get_remaining_size() : expected 70 remaining bytes, got " << size2; throw std::runtime_error("test_get_remaining_size failed: incorrect remaining size"); } // Verify position preserved auto pos = file.tellg(); if (pos != 30) { .. _example-series-file-62: .. dropdown:: file (np_test_1_all.cpp:27026) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 27016 :emphasize-lines: 11 } // Test with filename size_t size1 = io::get_remaining_size(test_filename); if (size1 != 100) { std::cout << " [FAIL] : in test_get_remaining_size() : expected 100 bytes, got " << size1; throw std::runtime_error("test_get_remaining_size failed: incorrect file size"); } // Test with file stream std::ifstream file(test_filename, std::ios::binary); file.seekg(30); // Move to position 30 size_t size2 = io::get_remaining_size(file); if (size2 != 70) { std::cout << " [FAIL] : in test_get_remaining_size() : expected 70 remaining bytes, got " << size2; throw std::runtime_error("test_get_remaining_size failed: incorrect remaining size"); } // Verify position preserved auto pos = file.tellg(); if (pos != 30) { .. _example-series-file-63: .. dropdown:: file (np_test_1_all.cpp:27026) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 27016 :emphasize-lines: 11 } // Test with filename size_t size1 = io::get_remaining_size(test_filename); if (size1 != 100) { std::cout << " [FAIL] : in test_get_remaining_size() : expected 100 bytes, got " << size1; throw std::runtime_error("test_get_remaining_size failed: incorrect file size"); } // Test with file stream std::ifstream file(test_filename, std::ios::binary); file.seekg(30); // Move to position 30 size_t size2 = io::get_remaining_size(file); if (size2 != 70) { std::cout << " [FAIL] : in test_get_remaining_size() : expected 70 remaining bytes, got " << size2; throw std::runtime_error("test_get_remaining_size failed: incorrect remaining size"); } // Verify position preserved auto pos = file.tellg(); if (pos != 30) { .. _example-series-filter-64: .. dropdown:: filter (np_test_2_all.cpp:9555) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 9545 :emphasize-lines: 11 for (int i = 0; i < size; i++) { signal[i] = std::sin(2.0f * 3.14159f * i / 8.0f) + 0.1f * (i % 3 - 1); } // std::cout << "Original Signal: "; for (int i = 0; i < size; i++) { // std::cout << std::setw(8) << std::fixed << std::setprecision(3) << signal[i] << " "; } // std::cout << std::endl; // Apply a simple smoothing filter (moving average) const int kernel_size = 3; std::vector kernel = { 1.0f / 3.0f, 1.0f / 3.0f, 1.0f / 3.0f }; // For simplicity, we'll do a basic convolution manually for demonstration for (int i = 1; i < size - 1; i++) { filtered[i] = (signal[i - 1] + signal[i] + signal[i + 1]) / 3.0f; } filtered[0] = signal[0]; filtered[size - 1] = signal[size - 1]; .. _example-series-first-65: .. dropdown:: first (np_test_4_all.cpp:12410) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 12400 :emphasize-lines: 11 // std::cout << "[OK] NaN-ignoring behavior tests\n"; } // Test both NaN returns first NaN void test_fmax_both_nan() { std::cout << "========= test_fmax_both_nan ===="; double nan1 = std::numeric_limits::quiet_NaN(); double nan2 = std::numeric_limits::quiet_NaN(); // If both are NaN, return first (which is still NaN) double result = numpy::fmax(nan1, nan2); if (!std::isnan(result)) { std::cout << " [FAIL] : test_fmax_both_nan failed - fmax(NaN, NaN) should be NaN"; throw std::runtime_error("fmax(NaN, NaN) should return NaN"); } // std::cout << "[OK] Both NaN returns NaN test\n"; } // Test type preservation .. _example-series-groups-66: .. dropdown:: groups (np_test_3_all.cpp:12782) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 12772 :emphasize-lines: 11 } if (!(arr.getElementAt({ 1, 1 }) == 40)) { std::string description = std::string("np_test_io_fromregex_complex():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(arr.getElementAt({ 1, 1 }) == 40)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] Multiple capture groups" << std::endl; } // Test 2: Mixed capture groups (would need structured array for full support) { create_test_file(filename, "data: 100, 1.5\ndata: 200, 2.5\ndata: 300, 3.5\n"); auto arr = fromregex(filename, R"(data:\s+(\d+),\s+([\d.]+))"); if (!(arr.getShape()[0] == 3)) { std::string description = std::string("np_test_io_fromregex_complex():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(arr.getShape()[0] == 3)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } .. _example-series-index-67: .. dropdown:: index (np_test_5_all.cpp:1283) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 1273 :emphasize-lines: 11 // ============================================================================ // SEARCH OPERATION TESTS // ============================================================================ void np_test_string_index() { std::cout << "========= index search operation ======================="; std::vector strings = { "hello world", "tomorrow" }; auto arr = numpy::char_::array<32>(strings); auto indices = numpy::char_::index(arr, "o"); bool passed = (indices.getSize() == arr.size()); if (!passed) { std::cout << " [FAIL] : in np_test_string_index() : indices size mismatch"; throw std::runtime_error("np_test_string_index failed"); } std::cout << " -> tests passed" << std::endl; } .. _example-series-info-68: .. dropdown:: info (np_test_2_all.cpp:19772) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 19762 :emphasize-lines: 11 // ============================================================================ // INFO TESTS (using primitive types to avoid NDArray complexities) // ============================================================================ void np_test_introspection_info() { std::cout << "========= info: display object information ======================="; // Test info on primitive type int x = 42; // std::cout << "Primitive type info:" << std::endl; numpy::introspection::info(x); double y = 3.14; // std::cout << "Double type info:" << std::endl; numpy::introspection::info(y, true); bool passed = true; // Just verify no exceptions if (!passed) { std::cout << " [FAIL] : in np_test_introspection_info() : info test failed"; throw std::runtime_error("np_test_introspection_info failed"); .. _example-series-keys-69: .. dropdown:: keys (np_test_2_all.cpp:8614) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 8604 :emphasize-lines: 11 if (!indices.empty()) { std::cout << " IPP empty array test: -> [FAIL]"; throw std::runtime_error("IPP empty array test: FAILED - should return empty"); } // std::cout << "[OK] IPP empty array test: PASSED" << std::endl; } // Test 6: Large array performance { const size_t n = 10000; std::vector> keys(2); keys[0].resize(n); keys[1].resize(n); std::mt19937 gen(42); std::uniform_int_distribution dist(0, 1000); for (size_t i = 0; i < n; ++i) { keys[0][i] = dist(gen); keys[1][i] = dist(gen); } .. _example-series-kurtosis-70: .. dropdown:: kurtosis (np_test_1_all.cpp:11433) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 11423 :emphasize-lines: 11 // std::cout << "Skewness of [1,2,3,4,5]: " << skew_result.getElementAt({ 0 }) << std::endl; // Should be close to 0 for symmetric data if (!(std::abs(skew_result.getElementAt({ 0 })) < 0.1)) { std::string description = std::string("testDistributionShapeMeasures():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(std::abs(skew_result.getElementAt({ 0 })) < 0.1)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] Skewness calculation\n"; // Test kurtosis auto kurt_result = kurtosis(normal_data); // std::cout << "Kurtosis of [1,2,3,4,5]: " << kurt_result.getElementAt({ 0 }) << std::endl; // std::cout << "[OK] Kurtosis calculation\n"; // Test moment auto moment2_result = moment(normal_data, 2); // std::cout << "2nd moment: " << moment2_result.getElementAt({ 0 }) << std::endl; if (!(moment2_result.getElementAt({ 0 }) > 0)) { std::string description = std::string("testDistributionShapeMeasures():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(moment2_result.getElementAt({ 0 }) > 0)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); .. _example-series-mask-71: .. dropdown:: mask (np_test_1_all.cpp:27691) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 27681 :emphasize-lines: 11 void test_mask_rows_cols() { std::cout << "========= ma::mask_rows() and ma::mask_cols(): mask operations ==="; auto data = numpy::array({ {1.0, 2.0, 3.0}, {4.0, 5.0, 6.0} }); auto mask = numpy::array({ {false, true, false}, {false, false, false} }); auto ma = numpy::ma::masked_array(data, mask); auto result_rows = numpy::ma::mask_rows(ma); auto result_cols = numpy::ma::mask_cols(ma); // std::cout << " ma::mask_rows(): row 0 fully masked: " << (result_rows.mask().getElementAt({ 0, 0 }) ? "true" : "false") << std::endl; // std::cout << " ma::mask_cols(): column 1 fully masked: " << (result_cols.mask().getElementAt({ 1, 1 }) ? "true" : "false"); std::cout << " -> tests passed"; } void test_compress_rowcols() { std::cout << "========= ma::compress_rowcols(): remove masked rows/columns ==="; auto data = numpy::array({ {1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}, {7.0, 8.0, 9.0} }); auto mask = numpy::array({ {false, false, false}, {false, true, false}, {false, false, false} }); auto ma = numpy::ma::masked_array(data, mask); .. _example-series-memcpy-72: .. dropdown:: memcpy (np_test_4_all.cpp:22178) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 22168 :emphasize-lines: 11 // std::cout << "[INFO] Serialized size: " << bytes.size() << " bytes" << std::endl; // Check magic number if (bytes[0] != 'N' || bytes[1] != 'D' || bytes[2] != 'A' || bytes[3] != 'R') { std::cout << " [FAIL] : Invalid magic number"; throw std::runtime_error("dumps magic number test failed"); } // Check version (bytes 4-7, little-endian uint32) uint32_t version; std::memcpy(&version, &bytes[4], 4); if (version != 1) { std::cout << " [FAIL] : Invalid version: " << version; throw std::runtime_error("dumps version test failed"); } // Check dtype size (bytes 8-11) uint32_t dtype_size; std::memcpy(&dtype_size, &bytes[8], 4); if (dtype_size != sizeof(double)) { std::cout << " [FAIL] : Invalid dtype size: " << dtype_size; .. _example-series-name-73: .. dropdown:: name (np_test_1_all.cpp:24865) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 24855 :emphasize-lines: 11 uint64_t before_restore = rng.next_uint64(); rng.set_state(state); uint64_t after_restore = rng.next_uint64(); if (before_restore != after_restore) { std::cout << " [FAIL] : in np_test_bitgen_mt19937() : state restore failed"; throw std::runtime_error("np_test_bitgen_mt19937 failed: state"); } // Test name if (rng.name() != "MT19937") { std::cout << " [FAIL] : in np_test_bitgen_mt19937() : incorrect name"; throw std::runtime_error("np_test_bitgen_mt19937 failed: name"); } std::cout << " -> tests passed" << std::endl; } // ============================================================================ // PCG64 TESTS // ============================================================================ .. _example-series-nbytes-74: .. dropdown:: nbytes (np_test_2_all.cpp:3547) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 3537 :emphasize-lines: 11 } // Test itemsize if (!(itemsize(arr) == sizeof(double))) { std::string description = std::string("testArrayInfo():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(itemsize(arr) == sizeof(double))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // Test nbytes if (!(nbytes(arr) == 24 * sizeof(double))) { std::string description = std::string("testArrayInfo():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(nbytes(arr) == 24 * sizeof(double))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // Test flags auto flags_info = flags(arr); if (!(flags_info.owndata == true)) { std::string description = std::string("testArrayInfo():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(flags_info.owndata == true)"; std::cout << std::string("[FAIL] ") + description << std::endl; .. _example-series-ndim-75: .. dropdown:: ndim (np_test_2_all.cpp:3526) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 3516 :emphasize-lines: 11 void testArrayInfo() { std::cout << "Testing array information functions...\n"; // Test basic info functions auto arr = createFloat64Array({ 2, 3, 4 }); for (size_t i = 0; i < arr.getSize(); ++i) { arr.setElementAt({ i / 12, (i / 4) % 3, i % 4 }, static_cast(i)); } // Test ndim if (!(ndim(arr) == 3)) { std::string description = std::string("testArrayInfo():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(ndim(arr) == 3)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // Test size if (!(size(arr) == 24)) { std::string description = std::string("testArrayInfo():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(size(arr) == 24)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); .. _example-series-pad-76: .. dropdown:: pad (np_test_1_all.cpp:18733) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 18723 :emphasize-lines: 11 std::cout << "========= testPadding ======================="; // Create test array auto array = createInt32Array({ 2, 2 }, 0); array.setElementAt({ 0, 0 }, 1); array.setElementAt({ 0, 1 }, 2); array.setElementAt({ 1, 0 }, 3); array.setElementAt({ 1, 1 }, 4); // Test constant padding auto padded_const = pad(array, 1, "constant", 0); if (!(padded_const.getShape()[0] == 4)) { std::string description = std::string("testPadding():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(padded_const.getShape()[0] == 4)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(padded_const.getShape()[1] == 4)) { std::string description = std::string("testPadding():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(padded_const.getShape()[1] == 4)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } .. _example-series-pairs-77: .. dropdown:: pairs (np_test_2_all.cpp:8793) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 8783 :emphasize-lines: 11 if (result != expected) { std::cout << " IPP integer msort: -> [FAIL]"; throw std::runtime_error("IPP integer msort: FAILED - incorrect sorted order"); } // std::cout << "[OK] IPP integer msort: PASSED" << std::endl; } // Test 2: Float msort with stability test { // Test stability using pairs (value, original_index) struct TestPair { double value; int original_index; bool operator==(const TestPair& other) const { return value == other.value && original_index == other.original_index; } bool operator<(const TestPair& other) const { return value < other.value; } }; .. _example-series-pow-78: .. dropdown:: pow (np_test_1_all.cpp:15230) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 15220 :emphasize-lines: 11 std::cout << "[FAIL] Broadcasting validation failed" << std::endl; errors++; } // Test 11: Performance with caching std::cout << "========= test_caching_performance =======================" ; int call_count = 0; auto expensive_func = [&call_count](double x) { call_count++; return std::pow(x, 3) + std::sin(x); // Simulate expensive computation }; auto cached_vectorized = numpy::vectorize(expensive_func, true, 100); numpy::NDArray test_array({ 3 }); test_array.setElementAt({ 0 }, 1.0); test_array.setElementAt({ 1 }, 2.0); test_array.setElementAt({ 2 }, 3.0); // First call .. _example-series-pow-79: .. dropdown:: pow (np_test_1_all.cpp:15230) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 15220 :emphasize-lines: 11 std::cout << "[FAIL] Broadcasting validation failed" << std::endl; errors++; } // Test 11: Performance with caching std::cout << "========= test_caching_performance =======================" ; int call_count = 0; auto expensive_func = [&call_count](double x) { call_count++; return std::pow(x, 3) + std::sin(x); // Simulate expensive computation }; auto cached_vectorized = numpy::vectorize(expensive_func, true, 100); numpy::NDArray test_array({ 3 }); test_array.setElementAt({ 0 }, 1.0); test_array.setElementAt({ 1 }, 2.0); test_array.setElementAt({ 2 }, 3.0); // First call .. _example-series-prod-80: .. dropdown:: prod (np_test_1_all.cpp:11795) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 11785 :emphasize-lines: 11 throw std::runtime_error(description); } // std::cout << "[OK] min and max work correctly\n"; // Test product auto small_array = createInt32Array({ 3 }, 0); small_array.setElementAt({ 0 }, 2); small_array.setElementAt({ 1 }, 3); small_array.setElementAt({ 2 }, 4); auto prod_result = prod(small_array); if (!(prod_result.getElementAt({ 0 }) == 24)) { std::string description = std::string("testBasicStatistics():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(prod_result.getElementAt({ 0 }) == 24)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] prod works correctly\n"; std::cout << " -> tests passed" << std::endl; } void testVarianceAndStandardDeviation() { .. _example-series-product-81: .. dropdown:: product (np_test_1_all.cpp:5362) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 5352 :emphasize-lines: 11 try { auto result = array1.multiplyArrays(array2); std::cout << "[FAIL] Incompatible shape multiplication should have thrown" << std::endl; } catch (const std::invalid_argument& e) { // std::cout << "[OK] Incompatible multiplication properly throws: " << e.what(); } // Test incompatible dot product try { auto result = array1.dotProduct(array2); // 2x3 * 3x2 should actually work // std::cout << "[OK] Compatible dot product (2x3 * 3x2) works" << std::endl; } catch (const std::exception& e) { std::cout << " [FAIL] : in testIncompatibleShapesErrorExtended(): Unexpected dot product error: " << e.what(); throw std::runtime_error("testIncompatibleShapesErrorExtended(): Unexpected dot product error: " + std::string(e.what())); } // Test truly incompatible dot product auto array3 = createInt32Array({2, 2}, 1); try { auto result = array1.dotProduct(array3); // 2x3 * 2x2 should fail std::cout << "[FAIL] Incompatible dot product should have thrown" << std::endl; .. _example-series-replace-82: .. dropdown:: replace (np_test_1_all.cpp:6717) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 6707 :emphasize-lines: 11 std::vector text = {"Hello world", "The world is big", "world peace"}; auto arr = array<64>(text); // std::cout << "Original text:" << std::endl; for (size_t i = 0; i < arr.size(); ++i) { // std::cout << "'" << arr[i] << "'"; } // Test replace auto replaced = replace(arr, "world", "universe"); // std::cout << "After replacing 'world' with 'universe':" << std::endl; for (size_t i = 0; i < replaced.size(); ++i) { // std::cout << "'" << replaced[i] << "'"; } // Test replace with count limit std::vector repeated_text = {"test test test", "more test cases", "test everything"}; auto repeated_arr = array<64>(repeated_text); auto limited_replace = replace(repeated_arr, "test", "example", 1); .. _example-series-replace-83: .. dropdown:: replace (np_test_1_all.cpp:6717) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 6707 :emphasize-lines: 11 std::vector text = {"Hello world", "The world is big", "world peace"}; auto arr = array<64>(text); // std::cout << "Original text:" << std::endl; for (size_t i = 0; i < arr.size(); ++i) { // std::cout << "'" << arr[i] << "'"; } // Test replace auto replaced = replace(arr, "world", "universe"); // std::cout << "After replacing 'world' with 'universe':" << std::endl; for (size_t i = 0; i < replaced.size(); ++i) { // std::cout << "'" << replaced[i] << "'"; } // Test replace with count limit std::vector repeated_text = {"test test test", "more test cases", "test everything"}; auto repeated_arr = array<64>(repeated_text); auto limited_replace = replace(repeated_arr, "test", "example", 1); .. _example-series-shape-84: .. dropdown:: shape (np_test_1_all.cpp:3751) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 3741 :emphasize-lines: 11 } for (size_t j = 0; j < 3; ++j) { arr3.setElementAt({0, j}, static_cast((j + 1) * 100)); // [100, 200, 300] } // Broadcast all arrays together std::vector> arrays = {arr1, arr2, arr3}; auto broadcasted = broadcast_arrays(arrays); // All should have shape (2, 3) for (const auto& arr : broadcasted) { if (!((arr.getShape() == std::vector{2, 3}))) { std::string description = std::string("test_broadcast_arrays():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !((arr.getShape() == std::vector{2, 3}))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } } // Check values if (!(broadcasted[0].getElementAt({0, 1}) == 2.0)) { .. _example-series-shift-85: .. dropdown:: shift (np_test_1_all.cpp:2761) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 2751 :emphasize-lines: 11 throw std::runtime_error(description); } if (!(left_array.getElementAt({3}) == 16384)) { std::string description = std::string("testBitShifts():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(left_array.getElementAt({3}) == 16384)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] Left shift by array\n"; // Test excessive shift (should result in 0) auto excessive_left = left_shift(arr, 20); // More than 16 bits if (!(excessive_left.getElementAt({0}) == 0)) { std::string description = std::string("testBitShifts():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(excessive_left.getElementAt({0}) == 0)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(excessive_left.getElementAt({1}) == 0)) { std::string description = std::string("testBitShifts():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(excessive_left.getElementAt({1}) == 0)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); .. _example-series-size-86: .. dropdown:: size (np_test_1_all.cpp:47) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 37 :emphasize-lines: 11 using namespace numpy; using namespace numpy::benchmark; using namespace numpy::char_; // Helper functions for array comparison tests namespace { const double TOLERANCE = 1e-10; bool allTrue(const NDArray& arr) { std::vector indices(arr.getShape().size(), 0); do { if (!arr.getElementAt(indices)) { return false; } } while (incrementIndices(indices, arr.getShape())); return true; } bool allFalse(const NDArray& arr) { std::vector indices(arr.getShape().size(), 0); .. _example-series-skew-87: .. dropdown:: skew (np_test_1_all.cpp:11422) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 11412 :emphasize-lines: 11 std::cout << "========= testDistributionShapeMeasures ======================="; // Test skewness with known data auto normal_data = createFloat32Array({ 5 }, 0.0f); normal_data.setElementAt({ 0 }, 1.0f); normal_data.setElementAt({ 1 }, 2.0f); normal_data.setElementAt({ 2 }, 3.0f); normal_data.setElementAt({ 3 }, 4.0f); normal_data.setElementAt({ 4 }, 5.0f); auto skew_result = skew(normal_data); // std::cout << "Skewness of [1,2,3,4,5]: " << skew_result.getElementAt({ 0 }) << std::endl; // Should be close to 0 for symmetric data if (!(std::abs(skew_result.getElementAt({ 0 })) < 0.1)) { std::string description = std::string("testDistributionShapeMeasures():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(std::abs(skew_result.getElementAt({ 0 })) < 0.1)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] Skewness calculation\n"; // Test kurtosis .. _example-series-types-88: .. dropdown:: types (np_test_1_all.cpp:2261) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 2251 :emphasize-lines: 11 std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(*obj.get_as() == static_cast(i * 10))) { std::string description = std::string("testArrayEdgeCases():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(*obj.get_as() == static_cast(i * 10))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } } // Test 5: Arrays with all different types (heterogeneous) NDArray hetero_array = createMixedObjectArray({ object_(42), object_(3.14), object_(std::string("text")), object_(true), object_(NDArray({2}, 1.5)) }); if (!(hetero_array.getSize() == 5)) { std::string description = std::string("testArrayEdgeCases():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(hetero_array.getSize() == 5)"; .. _example-series-tz_convert-89: .. dropdown:: tz_convert (np_test_5_all.cpp:22899) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 22889 :emphasize-lines: 11 if (floored_h.hour() != 14 || floored_h.minute() != 0 || floored_h.second() != 0) { pass = false; fail_msg = "floor to hour failed"; } // ceil to hour numpy::Timestamp ceiled_h = ts.ceil("h"); if (ceiled_h.hour() != 15 || ceiled_h.minute() != 0) { pass = false; fail_msg = "ceil to hour failed"; } // round to hour (37 minutes -> round up) numpy::Timestamp rounded_h = ts.round("h"); if (rounded_h.hour() != 15) { pass = false; fail_msg = "round to hour should be 15 (37 > 30)"; } // normalize (floor to day) numpy::Timestamp normalized = ts.normalize(); .. _example-series-tz_localize-90: .. dropdown:: tz_localize (np_test_5_all.cpp:22892) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 22882 :emphasize-lines: 11 auto pass = true; std::string fail_msg; numpy::Timestamp ts(2024, 6, 15, 14, 37, 45, 123456); // floor to hour numpy::Timestamp floored_h = ts.floor("h"); if (floored_h.hour() != 14 || floored_h.minute() != 0 || floored_h.second() != 0) { pass = false; fail_msg = "floor to hour failed"; } // ceil to hour numpy::Timestamp ceiled_h = ts.ceil("h"); if (ceiled_h.hour() != 15 || ceiled_h.minute() != 0) { pass = false; fail_msg = "ceil to hour failed"; } // round to hour (37 minutes -> round up) numpy::Timestamp rounded_h = ts.round("h"); .. _example-series-values-91: .. dropdown:: values (np_test_1_all.cpp:15133) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 15123 :emphasize-lines: 11 std::cout << " -> tests passed" << std::endl; } else { std::cout << "[FAIL] Where function failed" << std::endl; errors++; } // Test 8: Clip function std::cout << "========= test_clip_function =======================" ; numpy::NDArray values({ 5 }); values.setElementAt({ 0 }, -2.0); values.setElementAt({ 1 }, -1.0); values.setElementAt({ 2 }, 0.5); values.setElementAt({ 3 }, 2.0); values.setElementAt({ 4 }, 5.0); double min_val = -1.0; double max_val = 3.0; auto clip_result = numpy::clip(values, min_val, max_val); .. _example-series-values-92: .. dropdown:: values (np_test_1_all.cpp:15133) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 15123 :emphasize-lines: 11 std::cout << " -> tests passed" << std::endl; } else { std::cout << "[FAIL] Where function failed" << std::endl; errors++; } // Test 8: Clip function std::cout << "========= test_clip_function =======================" ; numpy::NDArray values({ 5 }); values.setElementAt({ 0 }, -2.0); values.setElementAt({ 1 }, -1.0); values.setElementAt({ 2 }, 0.5); values.setElementAt({ 3 }, 2.0); values.setElementAt({ 4 }, 5.0); double min_val = -1.0; double max_val = 3.0; auto clip_result = numpy::clip(values, min_val, max_val);