github.com/matrixorigin/matrixone@v1.2.0/pkg/vectorize/moarray/gonums_utils.go (about)

     1  // Copyright 2023 Matrix Origin
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package moarray
    16  
    17  import (
    18  	"github.com/matrixorigin/matrixone/pkg/common/moerr"
    19  	"github.com/matrixorigin/matrixone/pkg/container/types"
    20  	"gonum.org/v1/gonum/mat"
    21  	"math"
    22  )
    23  
    24  func ToGonumVector[T types.RealNumbers](arr1 []T) *mat.VecDense {
    25  
    26  	n := len(arr1)
    27  	_arr1 := make([]float64, n)
    28  
    29  	//TODO: @arjun optimize this cast to retain float32 precision in float64 array
    30  	// if float64, just copy
    31  	// if float32, convert to float64 without losing precision
    32  	for i := 0; i < n; i++ {
    33  		_arr1[i] = float64(arr1[i])
    34  	}
    35  
    36  	return mat.NewVecDense(n, _arr1)
    37  }
    38  
    39  func ToGonumVectors[T types.RealNumbers](arrays ...[]T) (res []*mat.VecDense, err error) {
    40  
    41  	n := len(arrays)
    42  	if n == 0 {
    43  		return res, nil
    44  	}
    45  
    46  	array0Dim := len(arrays[0])
    47  	for i := 1; i < n; i++ {
    48  		if len(arrays[i]) != array0Dim {
    49  			return nil, moerr.NewArrayInvalidOpNoCtx(array0Dim, len(arrays[i]))
    50  		}
    51  	}
    52  
    53  	res = make([]*mat.VecDense, n)
    54  
    55  	for i, arr := range arrays {
    56  		res[i] = ToGonumVector[T](arr)
    57  	}
    58  	return res, nil
    59  }
    60  
    61  func ToMoArray[T types.RealNumbers](vec *mat.VecDense) (arr []T, err error) {
    62  	n := vec.Len()
    63  	arr = make([]T, n)
    64  	for i := 0; i < n; i++ {
    65  		//TODO: @arjun optimize this cast
    66  		arr[i] = T(vec.AtVec(i))
    67  	}
    68  	for i := 0; i < n; i++ {
    69  		if math.IsInf(float64(arr[i]), 0) {
    70  			return nil, moerr.NewInternalErrorNoCtx("vector contains infinity values")
    71  		}
    72  	}
    73  	return arr, nil
    74  }
    75  
    76  func ToMoArrays[T types.RealNumbers](vecs []*mat.VecDense) ([][]T, error) {
    77  	moVectors := make([][]T, len(vecs))
    78  	var err error
    79  	for i, vec := range vecs {
    80  		moVectors[i], err = ToMoArray[T](vec)
    81  		if err != nil {
    82  			return nil, err
    83  		}
    84  	}
    85  	return moVectors, nil
    86  }