/* NiuTrans.Tensor - an open-source tensor library
* Copyright (C) 2017, Natural Language Processing Lab, Northestern University.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/*
* $Created by: XIAO Tong (email: xiaotong@mail.neu.edu.cn) 2018-04-24
*/

#include <math.h>
#include "../XTensor.h"
#include "Power.h"
#include "Power.cuh"

namespace nts { // namespace nts(NiuTrans.Tensor)
/*
get the power(a, p)
>> a - the tensor
>> power - as it is
*/
void Power(XTensor * a, DTYPE p)
{
#ifdef USE_CUDA
    /* run it on GPUs */
    if (a->devID >= 0) {
        CudaPower(a, p);
        return;
    }
#endif

    CheckNTErrors((a->dataType == DEFAULT_DTYPE), "TODO!");

    DTYPE * d = (DTYPE*)a->data;
    if (p == 0) {
        for (int i = 0; i < a->unitNum; i++)
            d[i] = (DTYPE)1.0;
    }
    else if (p == (DTYPE)0.5) {
        for (int i = 0; i < a->unitNum; i++)
            d[i] = (DTYPE)sqrt(d[i]);
    }
    else if (p == (DTYPE)2.0) {
        for (int i = 0; i < a->unitNum; i++)
            d[i] = d[i] * d[i];
    }
    else {
        for (int i = 0; i < a->unitNum; i++)
            d[i] = (DTYPE)pow(d[i], p);
    }
}

} // namespace nts(NiuTrans.Tensor)