<commit_before>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2017 Advanced Micro Devices, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *******************************************************************************/

#include <../driver/activ_driver.hpp>
#include <miopen/activ.hpp>
#include <miopen/rnn.hpp>
#include <miopen/env.hpp>
#include <miopen/util.hpp>
#include <miopen/float_equal.hpp>
#include <vector>
#include <numeric>

#include <miopengemm/gemm.hpp>

namespace miopen {

MIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_CONV_DIRECT)

struct AutoEnableProfiling
{
    AutoEnableProfiling(Handle& x) : h(x)
    {
        prev_state = h.IsProfilingEnabled();
        h.EnableProfiling();
    }

    ~AutoEnableProfiling()
    {
        h.EnableProfiling(prev_state);
        h.ResetKernelTime();
    }

    private:
    Handle& h;
    bool prev_state;
};

void RNNDescriptor::RNNForwardTraining(Handle& handle,
	const int seqLen,
//	const TensorDescriptor& xDesc,
	ConstData_t x,
//	const TensorDescriptor& hxDesc,
	ConstData_t hx,
//	const TensorDescriptor& cxDesc,
	ConstData_t cx,
//	const TensorDescriptor& wDesc,
	ConstData_t w,
//	const TensorDescriptor& yDesc,
	Data_t y,
//	const TensorDescriptor& hyDesc,
	Data_t hy,
//	const TensorDescriptor& cyDesc,
	Data_t cy,
	Data_t workSpace,
	size_t workSpaceSize,
	Data_t reserveSpace,
	size_t reserveSpaceSize,
	const std::vector<int> &in_n,
	const int in_h,
	const int hy_d,
	const int hy_n,
	const int hy_h,
	const int out_h) const
{/*
	if (x == nullptr || w == nullptr || y == nullptr)
	{
		MIOPEN_THROW(miopenStatusBadParm);
	}
	if (xDesc.GetSize() != yDesc.GetSize() || xDesc.GetSize() != wDesc.GetSize())
	{
		MIOPEN_THROW(miopenStatusBadParm);
	}
	if (xDesc.GetType() != yDesc.GetType() || xDesc.GetType() != wDesc.GetType())
	{
		MIOPEN_THROW(miopenStatusBadParm);
	}
*/
//	int in_n, in_c, in_h, in_w;
	//		std::tie(in_n, in_c, in_h, in_w) = tie4(xDesc.GetLengths());

//	int out_h, out_w;
	//		std::tie(std::ignore, std::ignore, out_h, out_w) = tie4(yDesc.GetLengths());
/*
	if (workSpace == nullptr ||
		workSpaceSize < ForwardGetWorkSpaceSize(handle, wDesc, xDesc, yDesc) || reserveSpaceSize < ForwardGetReserveSpaceSize(handle, wDesc, xDesc, yDesc))
	{
		MIOPEN_THROW("Workspace is required");
	}
	*/

//	miopenRNNMode_t mode;
//	int seqLength;
//	int layer;
//	int bidir;
//	int bias;

	int batch_n = std::accumulate(in_n.begin(), in_n.end(), 0);

	bool bidirection = (bidir != 0);
	bool biased = (bias != 0);
	int numlayer = layer;
	int bacc, baccbi;
	int bi = bidirection ? 2 : 1;

	int wei_len = (bi * (in_h + hy_h + out_h) + (numlayer - 1) * bi * (bi + 1) * hy_h) * hy_h;
	if (biased)
	{
		wei_len += (bi * 2 + (numlayer - 1) * bi * (bi + 1)) * hy_h + bi * out_h;
	}

	int wei_shift_bias =
		((in_h + hy_h + out_h) * bi + (bi * hy_h + hy_h) * bi * (numlayer - 1)) * hy_h;
	int in_stride = in_h;
	int hy_stride = hy_h * bi;
	int h_stride = hy_h * bi;
	int out_stride = out_h;
	int wei_stride = hy_h * bi;

	if (mode == miopenRNNRELU || mode == miopenRNNTANH)
	{
#if MIOPEN_USE_MIOPENGEMM

		printf("rnn gpu \n");
		cl_command_queue Q = (cl_command_queue)handle.GetStream();

		for (int li = 0; li < numlayer; li++)
		{
			int hid_shift = li * batch_n * hy_h * bi;
			int hx_shift = li * bi * in_n[0] * hy_h;

			// from input
			if (li == 0)
			{
				MIOpenGEMM::gemm0<float>(false,
					false,
					false,
					batch_n,
					hy_h * bi,
					in_h,
					1,
					x,
					0,
					in_stride,
					w,
					0,
					wei_stride,
					1,
					reserveSpace,
					hid_shift,
					hy_stride,
					&Q,
					0,
					nullptr,
					nullptr);
			}
			else
			{
				int wei_shift = bi * (in_h + hy_h) * hy_h + (li - 1) * bi * (bi * hy_h + hy_h) * hy_h;
				int prelayer_shift = (li - 1) * batch_n * hy_h * bi;

				MIOpenGEMM::gemm0<float>(false,
					false,
					false,
					batch_n,
					hy_h * bi,
					hy_h * bi,
					1,
					workSpace,
					prelayer_shift,
					hy_stride,
					w,
					wei_shift,
					wei_stride,
					1,
					reserveSpace,
					hid_shift,
					hy_stride,
					&Q,
					0,
					nullptr,
					nullptr);
			}

			// from hidden state
			bacc = 0;
			baccbi = batch_n;
			for (int ti = 0; ti < seqLen; ti++)
			{
				baccbi -= in_n[seqLen - 1 - ti];

				int wei_shift =
					li == 0 ? (in_h * hy_h * bi)
					: (bi * (in_h + hy_h) * hy_h + (li - 1) * bi * (bi * hy_h + hy_h) * hy_h +
						bi * hy_h * hy_stride);

				if (ti == 0)
				{
					MIOpenGEMM::gemm0<float>(false,
						false,
						false,
						in_n[ti],
						hy_h,
						hy_h,
						1,
						hx,
						hx_shift,
						h_stride,
						w,
						wei_shift,
						wei_stride,
						1,
						reserveSpace,
						hid_shift + bacc * hy_stride,
						hy_stride,
						&Q,
						0,
						nullptr,
						nullptr);

					if (bidirection)
					{
						MIOpenGEMM::gemm0<float>(false,
							false,
							false,
							in_n[seqLen - 1 - ti],
							hy_h,
							hy_h,
							1,
							hx,
							hx_shift + hy_h,
							h_stride,
							w,
							wei_shift + hy_h,
							wei_stride,
							1,
							reserveSpace,
							hid_shift + baccbi * hy_stride + hy_h,
							hy_stride,
							&Q,
							0,
							nullptr,
							nullptr);
					}
				}
				else
				{
					MIOpenGEMM::gemm0<float>(false,
						false,
						false,
						in_n[ti],
						hy_h,
						hy_h,
						1,
						hy,
						hx_shift,
						h_stride,
						w,
						wei_shift,
						wei_stride,
						1,
						reserveSpace,
						hid_shift + bacc * hy_stride,
						hy_stride,
						&Q,
						0,
						nullptr,
						nullptr);

					if (bidirection)
					{
						MIOpenGEMM::gemm0<float>(false,
							false,
							false,
							in_n[seqLen - 1 - ti],
							hy_h,
							hy_h,
							1,
							hy,
							hx_shift + hy_h,
							h_stride,
							w,
							wei_shift + hy_h,
							wei_stride,
							1,
							reserveSpace,
							hid_shift + baccbi * hy_stride + hy_h,
							hy_stride,
							&Q,
							0,
							nullptr,
							nullptr);
					}
				}

				int rsv_sz = batch_n * hy_d * hy_h;
				std::vector<int> rsv_size(3, 1);
				rsv_size.push_back(rsv_sz);

				miopenTensorDescriptor_t rsvTensor;
				miopenCreateTensorDescriptor(&rsvTensor);
				SetTensor4d(rsvTensor, rsv_size);

				miopenActivationMode_t amode;
				amode = (mode == miopenRNNRELU) ? miopenActivationRELU : miopenActivationTANH;

				ActivationDescriptor activDesc = {amode, 1, 0, 1};

				float alpha = 1, beta = 0;

				activDesc.Forward(handle,
					&alpha,
					miopen::deref(rsvTensor),
					reserveSpace,
					&beta,
					miopen::deref(rsvTensor),
					workSpace);

				bacc += in_n[ti];
			}

		}

		int prelayer_shift = (numlayer - 1) * batch_n * hy_h * bi;
		int wei_shift = bi * (in_h + hy_h) * hy_h + (numlayer - 1) * bi * (bi * hy_h + hy_h) * hy_h;

		MIOpenGEMM::gemm0<float>(false,
			false,
			true,
			batch_n,
			out_h,
			hy_h * bi,
			1,
			workSpace,
			prelayer_shift,
			hy_stride,
			w,
			wei_shift,
			wei_stride,
			1,
			y,
			0,
			out_stride,
			&Q,
			0,
			nullptr,
			nullptr);

		clFinish(Q);
#else
		MIOPEN_THROW("GEMM is not supported");
#endif
	}
	else if (mode == miopenLSTM)
	{
		printf("lstm gpu \n");
	}
	else if (mode == miopenGRU)
	{
		printf("gru gpu \n");
	}

};

void RNNDescriptor::RNNBackwardData(Handle& handle,
	const int seqLen,
	const TensorDescriptor& yDesc,
	ConstData_t y,
	const TensorDescriptor& dyDesc,
	ConstData_t dy,
	const TensorDescriptor& dhyDesc,
	ConstData_t dhy,
	const TensorDescriptor& dcyDesc,
	ConstData_t dcy,
	const TensorDescriptor& wDesc,
	ConstData_t w,
	const TensorDescriptor& hxDesc,
	ConstData_t hx,
	const TensorDescriptor& cxDesc,
	ConstData_t cx,
	const TensorDescriptor& dxDesc,
	Data_t dx,
	const TensorDescriptor& dhxDesc,
	Data_t dhx,
	const TensorDescriptor& dcxDesc,
	Data_t dcx,
	Data_t workSpace,
	size_t workSpaceSize,
	ConstData_t reserveSpace,
	size_t reserveSpaceSize) const
{
	/*
	if (dx == nullptr || w == nullptr || dy == nullptr)
	{
		MIOPEN_THROW(miopenStatusBadParm);
	}
	if (dyDesc.GetSize() != dxDesc.GetSize() || dyDesc.GetSize() != wDesc.GetSize())
	{
		MIOPEN_THROW(miopenStatusBadParm);
	}
	if (dyDesc.GetType() != dxDesc.GetType() || dyDesc.GetType() != wDesc.GetType())
	{
		MIOPEN_THROW(miopenStatusBadParm);
	}

	*/

        int in_n, in_c, in_h, in_w;
	//		std::tie(in_n, in_c, in_h, in_w) = tie4(xDesc.GetLengths());

	int wei_n, wei_h, wei_w;
	//		std::tie(wei_n, std::ignore, wei_h, wei_w) = tie4(wDesc.GetLengths());

	int out_h, out_w;
	//		std::tie(std::ignore, std::ignore, out_h, out_w) = tie4(yDesc.GetLengths());
};

void RNNDescriptor::RNNBackwardWeights(Handle& handle,
	const int seqLen,
	const TensorDescriptor& xDesc,
	ConstData_t x,
	const TensorDescriptor& hxDesc,
	ConstData_t hx,
	const TensorDescriptor& dyDesc,
	ConstData_t dy,
	ConstData_t workSpace,
	size_t workSpaceSize,
	const TensorDescriptor& dwDesc,
	Data_t dw,
	ConstData_t reserveSpace,
	size_t reserveSpaceSize) const
{

        int in_n, in_c, in_h, in_w;
	//		std::tie(in_n, in_c, in_h, in_w) = tie4(xDesc.GetLengths());

	int wei_n, wei_h, wei_w;
	//		std::tie(wei_n, std::ignore, wei_h, wei_w) = tie4(wDesc.GetLengths());

	int out_h, out_w;
	//		std::tie(std::ignore, std::ignore, out_h, out_w) = tie4(yDesc.GetLengths());
};

} // namespace miopen
<commit_msg>activ************<commit_after>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2017 Advanced Micro Devices, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *******************************************************************************/

#include <../driver/activ_driver.hpp>
#include <miopen/activ.hpp>
#include <miopen/rnn.hpp>
#include <miopen/env.hpp>
#include <miopen/util.hpp>
#include <miopen/float_equal.hpp>
#include <vector>
#include <numeric>

#include <miopengemm/gemm.hpp>

namespace miopen {

MIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_CONV_DIRECT)

struct AutoEnableProfiling
{
    AutoEnableProfiling(Handle& x) : h(x)
    {
        prev_state = h.IsProfilingEnabled();
        h.EnableProfiling();
    }

    ~AutoEnableProfiling()
    {
        h.EnableProfiling(prev_state);
        h.ResetKernelTime();
    }

    private:
    Handle& h;
    bool prev_state;
};

void RNNDescriptor::RNNForwardTraining(Handle& handle,
	const int seqLen,
//	const TensorDescriptor& xDesc,
	ConstData_t x,
//	const TensorDescriptor& hxDesc,
	ConstData_t hx,
//	const TensorDescriptor& cxDesc,
	ConstData_t cx,
//	const TensorDescriptor& wDesc,
	ConstData_t w,
//	const TensorDescriptor& yDesc,
	Data_t y,
//	const TensorDescriptor& hyDesc,
	Data_t hy,
//	const TensorDescriptor& cyDesc,
	Data_t cy,
	Data_t workSpace,
	size_t workSpaceSize,
	Data_t reserveSpace,
	size_t reserveSpaceSize,
	const std::vector<int> &in_n,
	const int in_h,
	const int hy_d,
	const int hy_n,
	const int hy_h,
	const int out_h) const
{/*
	if (x == nullptr || w == nullptr || y == nullptr)
	{
		MIOPEN_THROW(miopenStatusBadParm);
	}
	if (xDesc.GetSize() != yDesc.GetSize() || xDesc.GetSize() != wDesc.GetSize())
	{
		MIOPEN_THROW(miopenStatusBadParm);
	}
	if (xDesc.GetType() != yDesc.GetType() || xDesc.GetType() != wDesc.GetType())
	{
		MIOPEN_THROW(miopenStatusBadParm);
	}
*/
//	int in_n, in_c, in_h, in_w;
	//		std::tie(in_n, in_c, in_h, in_w) = tie4(xDesc.GetLengths());

//	int out_h, out_w;
	//		std::tie(std::ignore, std::ignore, out_h, out_w) = tie4(yDesc.GetLengths());
/*
	if (workSpace == nullptr ||
		workSpaceSize < ForwardGetWorkSpaceSize(handle, wDesc, xDesc, yDesc) || reserveSpaceSize < ForwardGetReserveSpaceSize(handle, wDesc, xDesc, yDesc))
	{
		MIOPEN_THROW("Workspace is required");
	}
	*/

//	miopenRNNMode_t mode;
//	int seqLength;
//	int layer;
//	int bidir;
//	int bias;

	int batch_n = std::accumulate(in_n.begin(), in_n.end(), 0);

	bool bidirection = (bidir != 0);
	bool biased = (bias != 0);
	int numlayer = layer;
	int bacc, baccbi;
	int bi = bidirection ? 2 : 1;

	int wei_len = (bi * (in_h + hy_h + out_h) + (numlayer - 1) * bi * (bi + 1) * hy_h) * hy_h;
	if (biased)
	{
		wei_len += (bi * 2 + (numlayer - 1) * bi * (bi + 1)) * hy_h + bi * out_h;
	}

	int wei_shift_bias =
		((in_h + hy_h + out_h) * bi + (bi * hy_h + hy_h) * bi * (numlayer - 1)) * hy_h;
	int in_stride = in_h;
	int hy_stride = hy_h * bi;
	int h_stride = hy_h * bi;
	int out_stride = out_h;
	int wei_stride = hy_h * bi;

	if (mode == miopenRNNRELU || mode == miopenRNNTANH)
	{
#if MIOPEN_USE_MIOPENGEMM

		printf("rnn gpu \n");
		cl_command_queue Q = (cl_command_queue)handle.GetStream();

		for (int li = 0; li < numlayer; li++)
		{
			int hid_shift = li * batch_n * hy_h * bi;
			int hx_shift = li * bi * in_n[0] * hy_h;

			// from input
			if (li == 0)
			{
				MIOpenGEMM::gemm0<float>(false,
					false,
					false,
					batch_n,
					hy_h * bi,
					in_h,
					1,
					x,
					0,
					in_stride,
					w,
					0,
					wei_stride,
					1,
					reserveSpace,
					hid_shift,
					hy_stride,
					&Q,
					0,
					nullptr,
					nullptr);
			}
			else
			{
				int wei_shift = bi * (in_h + hy_h) * hy_h + (li - 1) * bi * (bi * hy_h + hy_h) * hy_h;
				int prelayer_shift = (li - 1) * batch_n * hy_h * bi;

				MIOpenGEMM::gemm0<float>(false,
					false,
					false,
					batch_n,
					hy_h * bi,
					hy_h * bi,
					1,
					workSpace,
					prelayer_shift,
					hy_stride,
					w,
					wei_shift,
					wei_stride,
					1,
					reserveSpace,
					hid_shift,
					hy_stride,
					&Q,
					0,
					nullptr,
					nullptr);
			}

			// from hidden state
			bacc = 0;
			baccbi = batch_n;
			for (int ti = 0; ti < seqLen; ti++)
			{
				baccbi -= in_n[seqLen - 1 - ti];

				int wei_shift =
					li == 0 ? (in_h * hy_h * bi)
					: (bi * (in_h + hy_h) * hy_h + (li - 1) * bi * (bi * hy_h + hy_h) * hy_h +
						bi * hy_h * hy_stride);

				if (ti == 0)
				{
					MIOpenGEMM::gemm0<float>(false,
						false,
						false,
						in_n[ti],
						hy_h,
						hy_h,
						1,
						hx,
						hx_shift,
						h_stride,
						w,
						wei_shift,
						wei_stride,
						1,
						reserveSpace,
						hid_shift + bacc * hy_stride,
						hy_stride,
						&Q,
						0,
						nullptr,
						nullptr);

					if (bidirection)
					{
						MIOpenGEMM::gemm0<float>(false,
							false,
							false,
							in_n[seqLen - 1 - ti],
							hy_h,
							hy_h,
							1,
							hx,
							hx_shift + hy_h,
							h_stride,
							w,
							wei_shift + hy_h,
							wei_stride,
							1,
							reserveSpace,
							hid_shift + baccbi * hy_stride + hy_h,
							hy_stride,
							&Q,
							0,
							nullptr,
							nullptr);
					}
				}
				else
				{
					MIOpenGEMM::gemm0<float>(false,
						false,
						false,
						in_n[ti],
						hy_h,
						hy_h,
						1,
						hy,
						hx_shift,
						h_stride,
						w,
						wei_shift,
						wei_stride,
						1,
						reserveSpace,
						hid_shift + bacc * hy_stride,
						hy_stride,
						&Q,
						0,
						nullptr,
						nullptr);

					if (bidirection)
					{
						MIOpenGEMM::gemm0<float>(false,
							false,
							false,
							in_n[seqLen - 1 - ti],
							hy_h,
							hy_h,
							1,
							hy,
							hx_shift + hy_h,
							h_stride,
							w,
							wei_shift + hy_h,
							wei_stride,
							1,
							reserveSpace,
							hid_shift + baccbi * hy_stride + hy_h,
							hy_stride,
							&Q,
							0,
							nullptr,
							nullptr);
					}
				}

				int rsv_sz = batch_n * hy_d * hy_h;
				std::vector<int> rsv_size(3, 1);
				rsv_size.push_back(rsv_sz);

				miopenTensorDescriptor_t rsvTensor;
				miopenCreateTensorDescriptor(&rsvTensor);
				SetTensor4d(rsvTensor, rsv_size);

				float alpha = 1, beta = 0;
				ActivationDescriptor activDesc;

				if (mode == miopenRNNRELU)
				{
					activDesc = { miopenActivationRELU, 1, 0, 1 };
				}
				else if (mode == miopenRNNTANH)
				{
					activDesc = { miopenActivationTANH, 1, 1, 1 };
				}

				activDesc.Forward(handle,
					&alpha,
					miopen::deref(rsvTensor),
					reserveSpace,
					&beta,
					miopen::deref(rsvTensor),
					workSpace);

				bacc += in_n[ti];
			}

		}

		int prelayer_shift = (numlayer - 1) * batch_n * hy_h * bi;
		int wei_shift = bi * (in_h + hy_h) * hy_h + (numlayer - 1) * bi * (bi * hy_h + hy_h) * hy_h;

		MIOpenGEMM::gemm0<float>(false,
			false,
			true,
			batch_n,
			out_h,
			hy_h * bi,
			1,
			workSpace,
			prelayer_shift,
			hy_stride,
			w,
			wei_shift,
			wei_stride,
			1,
			y,
			0,
			out_stride,
			&Q,
			0,
			nullptr,
			nullptr);

		clFinish(Q);
#else
		MIOPEN_THROW("GEMM is not supported");
#endif
	}
	else if (mode == miopenLSTM)
	{
		printf("lstm gpu \n");
	}
	else if (mode == miopenGRU)
	{
		printf("gru gpu \n");
	}

};

void RNNDescriptor::RNNBackwardData(Handle& handle,
	const int seqLen,
	const TensorDescriptor& yDesc,
	ConstData_t y,
	const TensorDescriptor& dyDesc,
	ConstData_t dy,
	const TensorDescriptor& dhyDesc,
	ConstData_t dhy,
	const TensorDescriptor& dcyDesc,
	ConstData_t dcy,
	const TensorDescriptor& wDesc,
	ConstData_t w,
	const TensorDescriptor& hxDesc,
	ConstData_t hx,
	const TensorDescriptor& cxDesc,
	ConstData_t cx,
	const TensorDescriptor& dxDesc,
	Data_t dx,
	const TensorDescriptor& dhxDesc,
	Data_t dhx,
	const TensorDescriptor& dcxDesc,
	Data_t dcx,
	Data_t workSpace,
	size_t workSpaceSize,
	ConstData_t reserveSpace,
	size_t reserveSpaceSize) const
{
	/*
	if (dx == nullptr || w == nullptr || dy == nullptr)
	{
		MIOPEN_THROW(miopenStatusBadParm);
	}
	if (dyDesc.GetSize() != dxDesc.GetSize() || dyDesc.GetSize() != wDesc.GetSize())
	{
		MIOPEN_THROW(miopenStatusBadParm);
	}
	if (dyDesc.GetType() != dxDesc.GetType() || dyDesc.GetType() != wDesc.GetType())
	{
		MIOPEN_THROW(miopenStatusBadParm);
	}

	*/

        int in_n, in_c, in_h, in_w;
	//		std::tie(in_n, in_c, in_h, in_w) = tie4(xDesc.GetLengths());

	int wei_n, wei_h, wei_w;
	//		std::tie(wei_n, std::ignore, wei_h, wei_w) = tie4(wDesc.GetLengths());

	int out_h, out_w;
	//		std::tie(std::ignore, std::ignore, out_h, out_w) = tie4(yDesc.GetLengths());
};

void RNNDescriptor::RNNBackwardWeights(Handle& handle,
	const int seqLen,
	const TensorDescriptor& xDesc,
	ConstData_t x,
	const TensorDescriptor& hxDesc,
	ConstData_t hx,
	const TensorDescriptor& dyDesc,
	ConstData_t dy,
	ConstData_t workSpace,
	size_t workSpaceSize,
	const TensorDescriptor& dwDesc,
	Data_t dw,
	ConstData_t reserveSpace,
	size_t reserveSpaceSize) const
{

        int in_n, in_c, in_h, in_w;
	//		std::tie(in_n, in_c, in_h, in_w) = tie4(xDesc.GetLengths());

	int wei_n, wei_h, wei_w;
	//		std::tie(wei_n, std::ignore, wei_h, wei_w) = tie4(wDesc.GetLengths());

	int out_h, out_w;
	//		std::tie(std::ignore, std::ignore, out_h, out_w) = tie4(yDesc.GetLengths());
};

} // namespace miopen
<|endoftext|>


<commit_before>/*
 * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)
 *
 * 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.
 *
 */

#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include <votca/tools/getline.h>
#include "grotopologyreader.h"

namespace votca { namespace csg {

bool GROTopologyReader::ReadTopology(string file, Topology &top)
{
    // cleanup topology to store new data
    ifstream fl;
    string tmp;
    top.Cleanup();

    fl.open(file.c_str());
    if(!fl.is_open())
      throw std::runtime_error("Could not open file: " + file);

    string title;
    getline(fl, title);

    getline(fl, tmp);
    int natoms = atoi(tmp.c_str());
    for(;natoms>0; natoms--) {
        char c[6];
        fl.read(c, 5);
        c[5] = 0;

        string resname;
        fl >> resname;
        int resnr = atoi(c);
        if(resnr >= top.ResidueCount()) {
            if (top.ResidueCount()==0) //gro resnr start with 1 but VOTCA starts with 0
	      top.CreateResidue("ZERO"); // create 0 res, to allow to keep gro numbering
            top.CreateResidue(resname);
            //cout << " created residue " << c << " " << resnr << " " << resname<<"-\n";
        }
        string atomname;
        string x, y, z;
        fl >> atomname;
        fl >> tmp;
        fl >> x; fl >> y; fl >> z;
	//BeadType=atomname is not correct, but still better than no type at all!
        top.CreateBead(1, atomname, top.GetOrCreateBeadType(atomname), resnr, 1., 0.);
        getline(fl, tmp);
    }

    getline(fl, tmp); //read box line
    if(fl.eof())
      throw std::runtime_error("unexpected end of file in poly file, when boxline");
    Tokenizer tok(tmp, " ");
    vector<double> fields;
    tok.ConvertToVector<double>(fields);
    matrix box;
    if ( fields.size() == 3 ) {
      box.ZeroMatrix();
      for (int i=0;i<3;i++) box[i][i] = fields[i];
    } else if ( fields.size() == 9 ) {
      box[0][0]=  fields[0];
      box[1][1]=  fields[1];
      box[2][2]=  fields[2];
      box[0][1]=  fields[3];
      box[0][2]=  fields[4];
      box[1][1]=  fields[5];
      box[1][2]=  fields[6];
      box[2][1]=  fields[7];
      box[2][2]=  fields[8];
    } else {
      throw std::runtime_error("Error while reading box (last) line of"+ file);
    }
    top.setBox(box);

    fl.close();

    cout << "WARNING: topology created from .gro file, masses and charges are wrong!\n";

    return true;
}

}}
<commit_msg>fixed grotopologyreader: use fixed format instead of whitespace separator<commit_after>/*
 * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)
 *
 * 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.
 *
 */

#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include <votca/tools/getline.h>
#include <boost/algorithm/string.hpp>
#include "grotopologyreader.h"

namespace votca { namespace csg {

bool GROTopologyReader::ReadTopology(string file, Topology &top)
{
    // cleanup topology to store new data
    ifstream fl;
    string tmp;
    top.Cleanup();

    fl.open(file.c_str());
    if(!fl.is_open())
      throw std::runtime_error("Could not open file: " + file);

    string title;
    getline(fl, title);

    getline(fl, tmp);
    int natoms = atoi(tmp.c_str());
    for(;natoms>0; natoms--) {
        char c[6];
        fl.read(c, 5);
        c[5] = 0; //fix trailing char

        int resnr = atoi(c);
        //residue name
        fl.read(c, 5);
        if(resnr >= top.ResidueCount()) {
            if (top.ResidueCount()==0) //gro resnr start with 1 but VOTCA starts with 0
              top.CreateResidue("ZERO"); // create 0 res, to allow to keep gro numbering
            string withoutWhitespace;
            withoutWhitespace  = string(c);
            boost::algorithm::trim(withoutWhitespace);
            top.CreateResidue(withoutWhitespace);
        }
        //atom name
        char atomname[6];
        fl.read(atomname, 5);
        atomname[5]=0; //fix trailing character
        string atomnameWoWs;
        atomnameWoWs  = string(atomname);
        boost::algorithm::trim(atomnameWoWs);
        //atom number, not needed
        char buf[5];
        fl.read(buf, 5);
        //position
        char x[8], y[8], z[8];
        fl.read(x,8);
        fl.read(y,8);
        fl.read(z,8);
        top.CreateBead(1, atomnameWoWs, top.GetOrCreateBeadType(atomnameWoWs), resnr, 1., 0.);
        getline(fl, tmp);
    }

    getline(fl, tmp); //read box line
    if(fl.eof())
      throw std::runtime_error("unexpected end of file in poly file, when boxline");
    Tokenizer tok(tmp, " ");
    vector<double> fields;
    tok.ConvertToVector<double>(fields);
    matrix box;
    if ( fields.size() == 3 ) {
      box.ZeroMatrix();
      for (int i=0;i<3;i++) box[i][i] = fields[i];
    } else if ( fields.size() == 9 ) {
      box[0][0]=  fields[0];
      box[1][1]=  fields[1];
      box[2][2]=  fields[2];
      box[0][1]=  fields[3];
      box[0][2]=  fields[4];
      box[1][1]=  fields[5];
      box[1][2]=  fields[6];
      box[2][1]=  fields[7];
      box[2][2]=  fields[8];
    } else {
      throw std::runtime_error("Error while reading box (last) line of"+ file);
    }
    top.setBox(box);

    fl.close();

    cout << "WARNING: topology created from .gro file, masses and charges are wrong!\n";

    return true;
}

}}
<|endoftext|>


<commit_before><commit_msg>OR-1127<commit_after><|endoftext|>


<commit_before>#include "sampler/Sampler.h"
#include "Test.h"

using namespace PR;

PR_BEGIN_TESTCASE(Sampler)
PR_TEST("Align 1");
{
	auto N = PM::pm_Set(0, 0, 1);
	auto V = PM::pm_Set(0, 1, 0);

	auto R = Sampler::align(N, V);

	PR_CHECK_NEARLY_EQ_3(R, V);
}

PR_TEST("Align 2");
{
	auto N = PM::pm_Set(0, 1, 0);
	auto V = PM::pm_Set(0, 1, 0);

	auto R = Sampler::align(N, V);

	PR_CHECK_NEARLY_EQ_3(R, PM::pm_Set(0, 0, -1));
}

PR_TEST("Align 3");
{
	auto N = PM::pm_Normalize3D(PM::pm_Set(0, 0.5f, 0.5f));
	auto V = PM::pm_Set(0, 1, 0);

	auto R = Sampler::align(N, V);

	PR_CHECK_NEARLY_EQ_3(R, PM::pm_Normalize3D(PM::pm_Set(0, 0.5f, -0.5f)));
}

PR_TEST("Align 4");
{
	auto N = PM::pm_Set(1, 0, 0);
	auto V = PM::pm_Set(0, 1, 0);

	auto R = Sampler::align(N, V);

	PR_CHECK_NEARLY_EQ_3(R, PM::pm_Set(0, 1, 0));
}

PR_END_TESTCASE()

// MAIN
PRT_BEGIN_MAIN
PRT_TESTCASE(Sampler);
PRT_END_MAIN<commit_msg>Fixed a tiny error.<commit_after>#include "sampler/Projection.h"
#include "Test.h"

using namespace PR;

PR_BEGIN_TESTCASE(Sampler)
PR_TEST("Align 1");
{
	auto N = PM::pm_Set(0, 0, 1);
	auto V = PM::pm_Set(0, 1, 0);

	auto R = Projection::align(N, V);

	PR_CHECK_NEARLY_EQ_3(R, V);
}

PR_TEST("Align 2");
{
	auto N = PM::pm_Set(0, 1, 0);
	auto V = PM::pm_Set(0, 1, 0);

	auto R = Projection::align(N, V);

	PR_CHECK_NEARLY_EQ_3(R, PM::pm_Set(0, 0, -1));
}

PR_TEST("Align 3");
{
	auto N = PM::pm_Normalize3D(PM::pm_Set(0, 0.5f, 0.5f));
	auto V = PM::pm_Set(0, 1, 0);

	auto R = Projection::align(N, V);

	PR_CHECK_NEARLY_EQ_3(R, PM::pm_Normalize3D(PM::pm_Set(0, 0.5f, -0.5f)));
}

PR_TEST("Align 4");
{
	auto N = PM::pm_Set(1, 0, 0);
	auto V = PM::pm_Set(0, 1, 0);

	auto R = Projection::align(N, V);

	PR_CHECK_NEARLY_EQ_3(R, PM::pm_Set(0, 1, 0));
}

PR_END_TESTCASE()

// MAIN
PRT_BEGIN_MAIN
PRT_TESTCASE(Sampler);
PRT_END_MAIN<|endoftext|>


<commit_before>#include <El.hpp>
#include "kmeans.hpp"

/*******************************************/
namespace skyml = skylark::ml;
/*******************************************/

int main(int argc, char* argv[]) {
    El::Environment env(argc, argv);

    try {
        const std::string data_fn =
            El::Input<std::string>("-f","datafile (TSV)","");
        const El::Unsigned k = El::Input("-k","number of clusters",2);
        const size_t nsamples =
            El::Input("-n","number of samples in data",10);
        const size_t dim =
            El::Input("-d","Dimensionality of data",4);
        std::string init = El::Input<std::string>("-I",
                "initialization method [forgy | random | plusplus]","forgy");
        const El::Unsigned max_iters =
            El::Input("-i","number of iterations",10);
        const El::Int seed = El::Input("-s","seeding for random init",2);
        const double tol = El::Input("-T","Convergence tolerance",1E-6);
        const std::string centroid_fn =
            El::Input<std::string>("-c","Pre-initialized centroids","");
        El::ProcessInput();

        El::mpi::Comm comm = El::mpi::COMM_WORLD;
        El::Grid grid(comm);
        El::Unsigned rank = El::mpi::Rank(comm);

        El::DistMatrix<double, El::STAR, El::VC> data(dim, nsamples);
        El::Matrix<double> centroids;

        if (!data_fn.empty()) {
            //El::Read(data, data_fn, El::ASCII);
            El::Read(data, data_fn, El::BINARY_FLAT);
            if (rank == root) {
                El::Output("Read complete for proc: ", rank);
                El::Output("Dim: (", data.Height(), ", ", data.Width() ,")");
            }
#if KM_DEBUG
            El::Print(data, "Data:");
#endif
        } else {
            El::Output("Creating random data:");
            El::Uniform(data, dim, nsamples);
        }

        if (!centroid_fn.empty()) {
            init = "none";
            El::Read(centroids, centroid_fn, El::ASCII);
        } else {
            El::Zeros(centroids, data.Height(), k);
        }

        // Do some checking
        assert(data.Height() == centroids.Height());
        assert(k == centroids.Width());

        if (rank == root) El::Output("Starting k-means ...");
        skyml::run_kmeans<double>(data, centroids, k,
                tol, init, seed, max_iters);
    }
    catch(std::exception& e) { El::ReportException(e); }

    return EXIT_SUCCESS;
}
<commit_msg>exec: adding prune flag<commit_after>#include <El.hpp>
#include "kmeans.hpp"

/*******************************************/
namespace skyml = skylark::ml;
/*******************************************/

int main(int argc, char* argv[]) {
    El::Environment env(argc, argv);

    try {
        const std::string data_fn =
            El::Input<std::string>("-f","datafile (TSV)","");
        const El::Unsigned k = El::Input("-k","number of clusters",2);
        const size_t nsamples =
            El::Input("-n","number of samples in data",10);
        const size_t dim =
            El::Input("-d","Dimensionality of data",4);
        std::string init = El::Input<std::string>("-I",
                "initialization method [forgy | random | plusplus]","forgy");
        const El::Unsigned max_iters =
            El::Input("-i","number of iterations",10);
        const El::Int seed = El::Input("-s","seeding for random init",2);
        const double tol = El::Input("-T","Convergence tolerance",1E-6);
        const std::string centroid_fn =
            El::Input<std::string>("-c","Pre-initialized centroids","");
        const bool prune = El::Input("-p","Use triangle inequality", false);
        El::ProcessInput();

        El::mpi::Comm comm = El::mpi::COMM_WORLD;
        El::Grid grid(comm);
        El::Unsigned rank = El::mpi::Rank(comm);

        El::DistMatrix<double, El::STAR, El::VC> data(dim, nsamples);
        El::Matrix<double> centroids;

        if (!data_fn.empty()) {
            //El::Read(data, data_fn, El::ASCII);
            El::Read(data, data_fn, El::BINARY_FLAT);
            if (rank == root) {
                El::Output("Read complete for proc: ", rank);
                El::Output("Dim: (", data.Height(), ", ", data.Width() ,")");
            }
#if KM_DEBUG
            El::Print(data, "Data:");
#endif
        } else {
            El::Output("Creating random data:");
            El::Uniform(data, dim, nsamples);
        }

        if (!centroid_fn.empty()) {
            init = "none";
            El::Read(centroids, centroid_fn, El::ASCII);
        } else {
            El::Zeros(centroids, data.Height(), k);
        }

        // Do some checking
        assert(data.Height() == centroids.Height());
        assert(k == centroids.Width());

        if (rank == root) El::Output("Starting k-means ...");

        if (prune)
            skyml::run_tri_kmeans<double>(data, centroids, k,
                    tol, init, seed, max_iters);

        else
            skyml::run_kmeans<double>(data, centroids, k,
                    tol, init, seed, max_iters);
    }
    catch(std::exception& e) { El::ReportException(e); }

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>//
// File:   template.cc
// Author: ruehle
//
// Created on June 8, 2008, 10:41 PM
//

#include <math.h>
#include <boost/tokenizer.hpp>
#include <iostream>
#include <fstream>
#include <boost/program_options.hpp>
#include <cgengine.h>
#include <libversion.h>

using namespace std;

class CGAnalyzer
    : public CGObserver
{
public:
    void BeginCG(Topology *top, Topology *top_atom) {
    };
    void EndCG() {
    };

    void EvalConfiguration(Configuration *conf, Configuration *conf_atom = 0) {
    }

protected:
};

int main(int argc, char** argv)
{
    // we have one observer
    CGAnalyzer no;
    // The CGEngine does the work
    CGEngine cg_engine;

    // add our observer that it gets called to analyze frames
    cg_engine.AddObserver((CGObserver*)&no);

    // initialize the readers/writers,
    // this will be combined in an initialize function later
    TrajectoryWriter::RegisterPlugins();
    TrajectoryReader::RegisterPlugins();
    TopologyReader::RegisterPlugins();

    // lets read in some program options
    namespace po = boost::program_options;

    // Declare the supported options.
    po::options_description desc("Allowed options");

    // let cg_engine add some program options
    cg_engine.AddProgramOptions(desc);

    // now read in the command line
    po::variables_map vm;
    try {
        po::store(po::parse_command_line(argc, argv, desc), vm);
        po::notify(vm);
    }
    catch(po::error err) {
        cout << "error parsing command line: " << err.what() << endl;
        return -1;
    }
    // does the user want help?
    if (vm.count("help")) {
        cout << "csg_nemat, lib version " << LIB_VERSION_STR << "\n\n";
        cout << desc << endl;
        return 0;
    }
    // or asks for the program version?
    if (vm.count("version")) {
        cout << "csg_nemat, lib version " << LIB_VERSION_STR  << "\n";
        return 0;
    }

    // try to run the cg process, go through the frames, etc...
    try {
        cg_engine.Run(desc, vm);
    }
    // did an error occour?
    catch(string error) {
        cerr << "An error occoured!" << endl << error << endl;
    }
    return 0;
}

<commit_msg>changed template to no configuration<commit_after>//
// File:   template.cc
// Author: ruehle
//
// Created on June 8, 2008, 10:41 PM
//

#include <math.h>
#include <boost/tokenizer.hpp>
#include <iostream>
#include <fstream>
#include <boost/program_options.hpp>
#include <cgengine.h>
#include <libversion.h>

using namespace std;

class CGAnalyzer
    : public CGObserver
{
public:
    void BeginCG(Topology *top, Topology *top_atom) {
    };
    void EndCG() {
    };

    void EvalConfiguration(Topology *top, Topology *top_atom = 0) {
    }

protected:
};

int main(int argc, char** argv)
{
    // we have one observer
    CGAnalyzer no;
    // The CGEngine does the work
    CGEngine cg_engine;

    // add our observer that it gets called to analyze frames
    cg_engine.AddObserver((CGObserver*)&no);

    // initialize the readers/writers,
    // this will be combined in an initialize function later
    TrajectoryWriter::RegisterPlugins();
    TrajectoryReader::RegisterPlugins();
    TopologyReader::RegisterPlugins();

    // lets read in some program options
    namespace po = boost::program_options;

    // Declare the supported options.
    po::options_description desc("Allowed options");

    // let cg_engine add some program options
    cg_engine.AddProgramOptions(desc);

    // now read in the command line
    po::variables_map vm;
    try {
        po::store(po::parse_command_line(argc, argv, desc), vm);
        po::notify(vm);
    }
    catch(po::error err) {
        cout << "error parsing command line: " << err.what() << endl;
        return -1;
    }
    // does the user want help?
    if (vm.count("help")) {
        cout << "csg_nemat, lib version " << LIB_VERSION_STR << "\n\n";
        cout << desc << endl;
        return 0;
    }
    // or asks for the program version?
    if (vm.count("version")) {
        cout << "csg_nemat, lib version " << LIB_VERSION_STR  << "\n";
        return 0;
    }

    // try to run the cg process, go through the frames, etc...
    try {
        cg_engine.Run(desc, vm);
    }
    // did an error occour?
    catch(string error) {
        cerr << "An error occoured!" << endl << error << endl;
    }
    return 0;
}

<|endoftext|>


<commit_before>/*
   Clique: a scalable implementation of the multifrontal algorithm

   Copyright (C) 2010-2011 Jack Poulson <jack.poulson@gmail.com>
   Copyright (C) 2011 Jack Poulson, Lexing Ying, and
   The University of Texas at Austin

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

template<typename F>
void
clique::DistDenseSymmMatrix<F>::LocalLDL
( bool conjugate, int n, F* A, int lda )
{
#ifndef RELEASE
    PushCallStack("DistDenseSymmMatrix::LocalLDL");
    if( lda < n )
        throw std::logic_error
        ("Leading dimension cannot be smaller than height");
#endif
    if( n <= 1 )
    {
#ifndef RELEASE
        PopCallStack();
#endif
        return;
    }

    std::vector<F> s21(n-1);
    for( int j=0; j<n; ++j )
    {
        const int a21Height = n - (j+1);

        // Extract the diagonal entry
        const F alpha11 = A[j+j*lda];

        // Make a copy of a21 in s21 before scaling
        std::memcpy( &s21[0], &A[(j+1)+j*lda], a21Height*sizeof(F) );

        // a21 := a21 / alpha11
        const F alpha11Inv = static_cast<F>(1)/alpha11;
        {
            F* RESTRICT a21 = &A[(j+1)+j*lda];
            for( int i=0; i<a21Height; ++i )
                a21[i] *= alpha11Inv;
        }

        // A22 := A22 - s21 a21^[T/H]
        if( conjugate )
        {
            const F* RESTRICT a21 = &A[(j+1)+j*lda];
            for( int k=0; k<a21Height; ++k )
            {
                const F conjAlpha = Conj(a21[k]);
                F* RESTRICT A22Col = &A[(j+1)+(j+1+k)*lda];
                for( int i=k; i<a21Height; ++i )
                    A22Col[i] -= s21[i]*conjAlpha;
            }
        }
        else
        {
            const F* RESTRICT a21 = &A[(j+1)+j*lda];
            for( int k=0; k<a21Height; ++k )
            {
                const F alpha = a21[k];
                F* RESTRICT A22Col = &A[(j+1)+(j+1+k)*lda];
                for( int i=k; i<a21Height; ++i )
                    A22Col[i] -= s21[i]*alpha;
            }
        }
    }
#ifndef RELEASE
    PopCallStack();
#endif
}

template<typename F>
void
clique::DistDenseSymmMatrix<F>::LDL( bool conjugate )
{
#ifndef RELEASE
    PushCallStack("DistDenseSymmMatrix::LDL");
#endif
    const int remainder = height_ % blockSize_;
    const int numBlockCols =
        ( remainder==0 ? height_/blockSize_ : height_/blockSize_+1 );

    const int maxA11Size = blockSize_*blockSize_;
    const int maxPackedA11Size = (blockSize_*blockSize_+blockSize_)/2;
    std::vector<F> A11(maxA11Size), packedA11(maxPackedA11Size);

    const int maxA21LocalHeight = height_/(gridHeight_*blockSize_) + blockSize_;
    std::vector<F> diagAndA21( (maxA21LocalHeight+1)*blockSize_ );

    int jLocalBlock = 0;
    for( int jBlock=0; jBlock<numBlockCols; ++jBlock )
    {
        const int j = jBlock*blockSize_;
        const int b = std::min(blockSize_,height_-j);
        const int ownerRow = jBlock % gridHeight_;
        const int ownerCol = jBlock % gridWidth_;

        // Compute the local height of the owning process column's data
        // TODO
        // const int blockColHeight = ?
        // const int A21LocalHeight = ?
        //
        // For now, just make it compile
        const int iLocalBlock = (jBlock-gridRow_+gridHeight_-1)/gridHeight_;
        const int iBlock = gridRow_ + iLocalBlock*gridHeight_;
        const int blockColHeight = localHeight_ - iLocalBlock*blockSize_;
        const int A21LocalHeight =
            ( ownerRow==gridRow_ ? blockColHeight-b : blockColHeight );

        if( ownerCol == gridCol_ )
        {
            F* blockCol = blockColBuffers_[jLocalBlock];
            F* A21 = ( ownerRow==gridRow_ ? &blockCol[b] : blockCol );
            const int blockColLDim = blockColHeight;

            if( ownerRow == gridRow_ )
            {
                // Perform the in-place LDL^[T/H] factorization
                LocalLDL( conjugate, b, blockCol, blockColLDim );

                // Pack the lower-triangle
                for( int k=0,offset=0; k<b; offset+=b-k,++k )
                    std::memcpy
                    ( &packedA11[offset], &blockCol[k+k*blockColLDim],
                      (b-k)*sizeof(F) );
            }

            // Broadcast A11[MC,MR] from the owning row to form A11[* ,MR]
            const int packedSize = (b*b+b)/2;
            mpi::Broadcast( &packedA11[0], packedSize, ownerRow, colComm_ );

            // Unpack A11
            for( int k=0,offset=0; k<b; offset+=b-k,++k )
                std::memcpy( &A11[k+k*b], &packedA11[offset], (b-k)*sizeof(F) );

            // A21 := A21 trilu(A11)^-[T/H]
            const char option = ( conjugate ? 'C' : 'T' );
            blas::Trsm
            ( 'R', 'L', option, 'U', A21LocalHeight, b,
              (F)1, &A11[0], b, A21, blockColLDim );

            // Copy D11[* ,MR] and A21[MC,MR] into a buffer
            for( int j=0; j<b; ++j )
                diagAndA21[j] = A11[j+j*b];
            for( int j=0; j<b; ++j )
                std::memcpy
                ( &diagAndA21[b+j*A21LocalHeight], &A21[j*blockColLDim],
                  A21LocalHeight*sizeof(F) );
        }

        // Broadcast D11[* ,MR] and A21[MC,MR] within rows to form
        // D11[* ,* ] and A21[MC,* ]
        mpi::Broadcast
        ( &diagAndA21[0], (A21LocalHeight+1)*b, ownerCol, rowComm_ );

        if( gridHeight_ == gridWidth_ )
        {
            if( gridCol_ == gridRow_ )
            {
                // Just perform a memcpy
                // TODO
            }
            else
            {
                // Pairwise Send/Recv to form S21[MR,* ] from A21[MC,* ]
                // TODO
            }
        }
        else
        {
            // Locally copy A21[VC,* ] out of A21[MC,* ]
            // TODO

            // SendRecv permutation to form A21[VR,* ] from A21[VC,* ]
            // TODO

            // Gather A21[VR,* ] within rows to form S21[MR,* ]
            // TODO
        }

        // S21[MC,* ] := A21[MC,* ] D11^-1
        // TODO

        // A22[MC,MR] -= S21[MC,* ] A21[MR,* ]^[T/H]
        // TODO

        if( ownerCol == gridCol_ )
            ++jLocalBlock;
    }
#ifndef RELEASE
    PopCallStack();
#endif
}

template<typename F>
void
clique::DistDenseSymmMatrix<F>::LDLT()
{
#ifndef RELEASE
    PushCallStack("DistDenseSymmMatrix::LDLT");
#endif
    LDL( false );
#ifndef RELEASE
    PopCallStack();
#endif
}

template<typename F>
void
clique::DistDenseSymmMatrix<F>::LDLH()
{
#ifndef RELEASE
    PushCallStack("DistDenseSymmMatrix::LDLH");
#endif
    LDL( true );
#ifndef RELEASE
    PopCallStack();
#endif
}

<commit_msg>Minor commit.<commit_after>/*
   Clique: a scalable implementation of the multifrontal algorithm

   Copyright (C) 2010-2011 Jack Poulson <jack.poulson@gmail.com>
   Copyright (C) 2011 Jack Poulson, Lexing Ying, and
   The University of Texas at Austin

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

template<typename F>
void
clique::DistDenseSymmMatrix<F>::LocalLDL
( bool conjugate, int n, F* A, int lda )
{
#ifndef RELEASE
    PushCallStack("DistDenseSymmMatrix::LocalLDL");
    if( lda < n )
        throw std::logic_error
        ("Leading dimension cannot be smaller than height");
#endif
    if( n <= 1 )
    {
#ifndef RELEASE
        PopCallStack();
#endif
        return;
    }

    std::vector<F> s21(n-1);
    for( int j=0; j<n; ++j )
    {
        const int a21Height = n - (j+1);

        // Extract the diagonal entry
        const F alpha11 = A[j+j*lda];

        // Make a copy of a21 in s21 before scaling
        std::memcpy( &s21[0], &A[(j+1)+j*lda], a21Height*sizeof(F) );

        // a21 := a21 / alpha11
        const F alpha11Inv = static_cast<F>(1)/alpha11;
        {
            F* RESTRICT a21 = &A[(j+1)+j*lda];
            for( int i=0; i<a21Height; ++i )
                a21[i] *= alpha11Inv;
        }

        // A22 := A22 - s21 a21^[T/H]
        if( conjugate )
        {
            const F* RESTRICT a21 = &A[(j+1)+j*lda];
            for( int k=0; k<a21Height; ++k )
            {
                const F conjAlpha = Conj(a21[k]);
                F* RESTRICT A22Col = &A[(j+1)+(j+1+k)*lda];
                for( int i=k; i<a21Height; ++i )
                    A22Col[i] -= s21[i]*conjAlpha;
            }
        }
        else
        {
            const F* RESTRICT a21 = &A[(j+1)+j*lda];
            for( int k=0; k<a21Height; ++k )
            {
                const F alpha = a21[k];
                F* RESTRICT A22Col = &A[(j+1)+(j+1+k)*lda];
                for( int i=k; i<a21Height; ++i )
                    A22Col[i] -= s21[i]*alpha;
            }
        }
    }
#ifndef RELEASE
    PopCallStack();
#endif
}

template<typename F>
void
clique::DistDenseSymmMatrix<F>::LDL( bool conjugate )
{
#ifndef RELEASE
    PushCallStack("DistDenseSymmMatrix::LDL");
#endif
    // We will frequently use these parameters, so let's use shorter names
    const int r = gridHeight_;
    const int c = gridWidth_;
    const int p = r*c;
    const int n = height_;
    const int nb = blockSize_;

    const int remainder = n % nb;
    const int numBlockCols = ( remainder==0 ? n/nb : n/nb+1 );

    const int maxA11Size = nb*nb;
    const int maxPackedA11Size = (nb*nb+nb)/2;
    std::vector<F> A11(maxA11Size), packedA11(maxPackedA11Size);

    const int maxA21LocalHeight = n/(r*nb) + nb;
    std::vector<F> diagAndA21( (maxA21LocalHeight+1)*nb );

    const int maxA21_VC_STAR_LocalHeight = n/(p*nb) + nb;
    std::vector<F> A21_VC_STAR( maxA21_VC_STAR_LocalHeight*nb );

    int jLocalBlock = 0;
    for( int jBlock=0; jBlock<numBlockCols; ++jBlock )
    {
        const int j = jBlock*nb;
        const int b = std::min(nb,n-j);
        const int ownerRow = jBlock % r;
        const int ownerCol = jBlock % c;
        const bool myRow = (ownerRow == gridRow_);
        const bool myCol = (ownerCol == gridCol_);

        const int iLocalBlock = (jBlock-gridRow_+r-1)/r;
        const int blockColHeight = localHeight_ - iLocalBlock*nb;
        const int A21LocalHeight =
            ( myRow ? blockColHeight-b : blockColHeight );

        if( myCol )
        {
            F* blockCol = blockColBuffers_[jLocalBlock];
            F* A21 = ( myRow ? &blockCol[b] : blockCol );
            const int blockColLDim = blockColHeight;

            if( myRow )
            {
                // Perform the in-place LDL^[T/H] factorization
                LocalLDL( conjugate, b, blockCol, blockColLDim );

                // Pack the lower-triangle
                for( int k=0,offset=0; k<b; offset+=b-k,++k )
                    std::memcpy
                    ( &packedA11[offset], &blockCol[k+k*blockColLDim],
                      (b-k)*sizeof(F) );
            }

            // Broadcast A11[MC,MR] from the owning row to form A11[* ,MR]
            const int packedSize = (b*b+b)/2;
            mpi::Broadcast( &packedA11[0], packedSize, ownerRow, colComm_ );

            // Unpack A11
            for( int k=0,offset=0; k<b; offset+=b-k,++k )
                std::memcpy( &A11[k+k*b], &packedA11[offset], (b-k)*sizeof(F) );

            // A21 := A21 trilu(A11)^-[T/H]
            const char option = ( conjugate ? 'C' : 'T' );
            blas::Trsm
            ( 'R', 'L', option, 'U', A21LocalHeight, b,
              (F)1, &A11[0], b, A21, blockColLDim );

            // Copy D11[* ,MR] and A21[MC,MR] into a buffer
            for( int j=0; j<b; ++j )
                diagAndA21[j] = A11[j+j*b];
            for( int j=0; j<b; ++j )
                std::memcpy
                ( &diagAndA21[b+j*A21LocalHeight], &A21[j*blockColLDim],
                  A21LocalHeight*sizeof(F) );
        }

        // Broadcast D11[* ,MR] and A21[MC,MR] within rows to form
        // D11[* ,* ] and A21[MC,* ]
        mpi::Broadcast
        ( &diagAndA21[0], (A21LocalHeight+1)*b, ownerCol, rowComm_ );

        if( gridHeight_ == gridWidth_ )
        {
            if( gridCol_ == gridRow_ )
            {
                // Just perform a memcpy
                // TODO
            }
            else
            {
                // Pairwise Send/Recv to form S21[MR,* ] from A21[MC,* ]
                // TODO
            }
        }
        else
        {
            // Locally copy A21[VC,* ] out of A21[MC,* ]
            const int A21_VC_STAR_Align = (jBlock+1) % p;
            //const int myFirstA21Block = ?

            // TODO

            // SendRecv permutation to form A21[VR,* ] from A21[VC,* ]
            // TODO

            // Gather A21[VR,* ] within rows to form S21[MR,* ]
            // TODO
        }

        // S21[MC,* ] := A21[MC,* ] D11^-1
        // TODO

        // A22[MC,MR] -= S21[MC,* ] A21[MR,* ]^[T/H]
        // TODO

        if( myCol )
            ++jLocalBlock;
    }
#ifndef RELEASE
    PopCallStack();
#endif
}

template<typename F>
void
clique::DistDenseSymmMatrix<F>::LDLT()
{
#ifndef RELEASE
    PushCallStack("DistDenseSymmMatrix::LDLT");
#endif
    LDL( false );
#ifndef RELEASE
    PopCallStack();
#endif
}

template<typename F>
void
clique::DistDenseSymmMatrix<F>::LDLH()
{
#ifndef RELEASE
    PushCallStack("DistDenseSymmMatrix::LDLH");
#endif
    LDL( true );
#ifndef RELEASE
    PopCallStack();
#endif
}

<|endoftext|>


<commit_before>
// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.

// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.

#include "config_dap.h"

#include "AISConnect.h"

/** Build an AISConnect. This calls Connect's constructor with \c name and
    accepts its default values for the other parameters. The AIS database to
    use is read from the configuration file ~/.dodsrc.

    @param name Create a virtual, AIS-enhanced, connection for this OPeNDAP
    data source.
    @exception AISDatabaseReadFailed Thrown if the AIS database listed in the
    ~/.dodsrc file could not be opened. */
AISConnect::AISConnect(const string &name) throw(AISDatabaseReadFailed)
    : Connect(name), d_ais_merge(0)
{
    const string &ais_db = RCReader::instance()->get_ais_database();
    if (ais_db != "")
	d_ais_merge = new AISMerge(ais_db);
}

/** Build an AISConnect. This calls Connect's constructor with \c name and
    accepts its default values for the other parameters. The AIS is
    initialized to use the database named by \c ais.

    @param name Create a virtual, AIS-enhanced, connection for this OPeNDAP
    data source.
    @param ais Read the AIS information from this XML file.
    @exception AISDatabaseReadFailed Thrown if the AIS database listed in the
    ~/.dodsrc file could not be opened. */
AISConnect::AISConnect(const string &name, const string &ais)
    throw(AISDatabaseReadFailed)
    : Connect(name), d_ais_merge(0)
{
    d_ais_merge = new AISMerge(ais);
}

/** Destroy an AISConnect. */
AISConnect::~AISConnect()
{
    delete d_ais_merge; d_ais_merge = 0;
}

/** Request an AIS-enhanced DAS object. Read the DAS object for this virtual
    connection's data source. Then check the AIS database and merge in any
    ancillary resources listed for it.

    @param das Deposit information to this object.
    @exception Error Thrown if the DAS request fails due to user error.
    @exception InternalErr Thrown if either the DAS request or the AIS merge
    request fails. */
void
AISConnect::request_das(DAS &das) throw(Error, InternalErr)
{
    Connect::request_das(das);

    if (d_ais_merge)
	d_ais_merge->merge(URL(false), das); // URL(false) --> URL w/o CE
}

// $Log: AISConnect.cc,v $
// Revision 1.5  2004/02/19 19:42:51  jimg
// Merged with release-3-4-2FCS and resolved conflicts.
//
// Revision 1.3.2.2  2004/02/11 22:26:45  jimg
// Changed all calls to delete so that whenever we use 'delete x' or
// 'delete[] x' the code also sets 'x' to null. This ensures that if a
// pointer is deleted more than once (e.g., when an exception is thrown,
// the method that throws may clean up and then the catching method may
// also clean up) the second, ..., call to delete gets a null pointer
// instead of one that points to already deleted memory.
//
// Revision 1.4  2003/12/08 18:02:29  edavis
// Merge release-3-4 into trunk
//
// Revision 1.3.2.1  2003/09/06 22:16:26  jimg
// Updated the documentation.
//
// Revision 1.3  2003/03/12 01:07:34  jimg
// Added regular expressions to the AIS subsystem. In an AIS database (XML)
// it is now possible to list a regular expression in place of an explicit
// URL. The AIS will try to match this Regexp against candidate URLs and
// return the ancillary resources for all those that succeed.
//
// Revision 1.2  2003/03/11 10:16:19  jimg
// if there's no AIS database, the field d_ais_merge is null. Make sure not to
// dereference that pointer in that case!
//
// Revision 1.1  2003/02/27 23:17:00  jimg
// Added.
//
<commit_msg>Formatting...<commit_after>
// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.

// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.

#include "config_dap.h"

#include "AISConnect.h"

/** Build an AISConnect. This calls Connect's constructor with \c name and
    accepts its default values for the other parameters. The AIS database to
    use is read from the configuration file ~/.dodsrc.

    @param name Create a virtual, AIS-enhanced, connection for this OPeNDAP
    data source.
    @exception AISDatabaseReadFailed Thrown if the AIS database listed in the
    ~/.dodsrc file could not be opened. */
AISConnect::AISConnect(const string &name) throw(AISDatabaseReadFailed)
    : Connect(name), d_ais_merge(0)
{
    const string &ais_db = RCReader::instance()->get_ais_database();
    if (ais_db != "")
	d_ais_merge = new AISMerge(ais_db);
}

/** Build an AISConnect. This calls Connect's constructor with \c name and
    accepts its default values for the other parameters. The AIS is
    initialized to use the database named by \c ais.

    @param name Create a virtual, AIS-enhanced, connection for this OPeNDAP
    data source.
    @param ais Read the AIS information from this XML file.
    @exception AISDatabaseReadFailed Thrown if the AIS database listed in the
    ~/.dodsrc file could not be opened. */
AISConnect::AISConnect(const string &name, const string &ais)
    throw(AISDatabaseReadFailed)
    : Connect(name), d_ais_merge(0)
{
    d_ais_merge = new AISMerge(ais);
}

/** Destroy an AISConnect. */
AISConnect::~AISConnect()
{
    delete d_ais_merge; d_ais_merge = 0;
}

/** Request an AIS-enhanced DAS object. Read the DAS object for this virtual
    connection's data source. Then check the AIS database and merge in any
    ancillary resources listed for it.

    @param das Deposit information to this object.
    @exception Error Thrown if the DAS request fails due to user error.
    @exception InternalErr Thrown if either the DAS request or the AIS merge
    request fails. */
void
AISConnect::request_das(DAS &das) throw(Error, InternalErr)
{
    Connect::request_das(das);

    if (d_ais_merge)
	    d_ais_merge->merge(URL(false), das); // URL(false) --> URL w/o CE
}

// $Log: AISConnect.cc,v $
// Revision 1.6  2004/10/22 21:48:20  jimg
// Formatting...
//
// Revision 1.5  2004/02/19 19:42:51  jimg
// Merged with release-3-4-2FCS and resolved conflicts.
//
// Revision 1.3.2.2  2004/02/11 22:26:45  jimg
// Changed all calls to delete so that whenever we use 'delete x' or
// 'delete[] x' the code also sets 'x' to null. This ensures that if a
// pointer is deleted more than once (e.g., when an exception is thrown,
// the method that throws may clean up and then the catching method may
// also clean up) the second, ..., call to delete gets a null pointer
// instead of one that points to already deleted memory.
//
// Revision 1.4  2003/12/08 18:02:29  edavis
// Merge release-3-4 into trunk
//
// Revision 1.3.2.1  2003/09/06 22:16:26  jimg
// Updated the documentation.
//
// Revision 1.3  2003/03/12 01:07:34  jimg
// Added regular expressions to the AIS subsystem. In an AIS database (XML)
// it is now possible to list a regular expression in place of an explicit
// URL. The AIS will try to match this Regexp against candidate URLs and
// return the ancillary resources for all those that succeed.
//
// Revision 1.2  2003/03/11 10:16:19  jimg
// if there's no AIS database, the field d_ais_merge is null. Make sure not to
// dereference that pointer in that case!
//
// Revision 1.1  2003/02/27 23:17:00  jimg
// Added.
//
<|endoftext|>


<commit_before>/*
 *
 * Copyright 2015, Google Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <string>

#include <grpc/grpc_security.h>
#include <grpc/support/log.h>

#include <grpc++/channel_arguments.h>
#include <grpc++/config.h>
#include <grpc++/credentials.h>
#include "src/cpp/client/channel.h"

namespace grpc {

class SecureCredentials GRPC_FINAL : public Credentials {
 public:
  explicit SecureCredentials(grpc_credentials* c_creds) : c_creds_(c_creds) {}
  ~SecureCredentials() GRPC_OVERRIDE { grpc_credentials_release(c_creds_); }
  grpc_credentials* GetRawCreds() { return c_creds_; }

  std::shared_ptr<grpc::ChannelInterface> CreateChannel(
      const string& target, const grpc::ChannelArguments& args) GRPC_OVERRIDE {
    grpc_channel_args channel_args;
    args.SetChannelArgs(&channel_args);
    return std::shared_ptr<ChannelInterface>(new Channel(
        args.GetSslTargetNameOverride().empty()
            ? target : args.GetSslTargetNameOverride(),
        grpc_secure_channel_create(c_creds_, target.c_str(), &channel_args)));
  }

  SecureCredentials* AsSecureCredentials() { return this; }

 private:
  grpc_credentials* const c_creds_;
};

namespace {
std::unique_ptr<Credentials> WrapCredentials(grpc_credentials* creds) {
  return creds == nullptr
             ? nullptr
             : std::unique_ptr<Credentials>(new SecureCredentials(creds));
}
}  // namespace

std::unique_ptr<Credentials> GoogleDefaultCredentials() {
  return WrapCredentials(grpc_google_default_credentials_create());
}

// Builds SSL Credentials given SSL specific options
std::unique_ptr<Credentials> SslCredentials(
    const SslCredentialsOptions& options) {
  grpc_ssl_pem_key_cert_pair pem_key_cert_pair = {
      options.pem_private_key.c_str(), options.pem_cert_chain.c_str()};

  grpc_credentials* c_creds = grpc_ssl_credentials_create(
      options.pem_root_certs.empty() ? nullptr : options.pem_root_certs.c_str(),
      options.pem_private_key.empty() ? nullptr : &pem_key_cert_pair);
  return WrapCredentials(c_creds);
}

// Builds credentials for use when running in GCE
std::unique_ptr<Credentials> ComputeEngineCredentials() {
  return WrapCredentials(grpc_compute_engine_credentials_create());
}

// Builds service account credentials.
std::unique_ptr<Credentials> ServiceAccountCredentials(
    const grpc::string& json_key, const grpc::string& scope,
    std::chrono::seconds token_lifetime) {
  if (token_lifetime.count() <= 0) {
    gpr_log(GPR_ERROR,
            "Trying to create JWTCredentials with non-positive lifetime");
    return WrapCredentials(nullptr);
  }
  gpr_timespec lifetime = gpr_time_from_seconds(token_lifetime.count());
  return WrapCredentials(grpc_service_account_credentials_create(
      json_key.c_str(), scope.c_str(), lifetime));
}

// Builds JWT credentials.
std::unique_ptr<Credentials> JWTCredentials(
    const grpc::string &json_key, std::chrono::seconds token_lifetime) {
  if (token_lifetime.count() <= 0) {
    gpr_log(GPR_ERROR,
            "Trying to create JWTCredentials with non-positive lifetime");
    return WrapCredentials(nullptr);
  }
  gpr_timespec lifetime = gpr_time_from_seconds(token_lifetime.count());
  return WrapCredentials(
      grpc_jwt_credentials_create(json_key.c_str(), lifetime));
}

// Builds IAM credentials.
std::unique_ptr<Credentials> IAMCredentials(
    const grpc::string& authorization_token,
    const grpc::string& authority_selector) {
  return WrapCredentials(grpc_iam_credentials_create(
      authorization_token.c_str(), authority_selector.c_str()));
}

// Combines two credentials objects into a composite credentials.
std::unique_ptr<Credentials> CompositeCredentials(
    const std::unique_ptr<Credentials>& creds1,
    const std::unique_ptr<Credentials>& creds2) {
  // Note that we are not saving unique_ptrs to the two credentials
  // passed in here. This is OK because the underlying C objects (i.e.,
  // creds1 and creds2) into grpc_composite_credentials_create will see their
  // refcounts incremented.
  SecureCredentials* s1 = creds1->AsSecureCredentials();
  SecureCredentials* s2 = creds2->AsSecureCredentials();
  if (s1 && s2) {
    return WrapCredentials(grpc_composite_credentials_create(
        s1->GetRawCreds(), s2->GetRawCreds()));
  }
  return nullptr;
}

}  // namespace grpc
<commit_msg>copy and paste does not work<commit_after>/*
 *
 * Copyright 2015, Google Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <string>

#include <grpc/grpc_security.h>
#include <grpc/support/log.h>

#include <grpc++/channel_arguments.h>
#include <grpc++/config.h>
#include <grpc++/credentials.h>
#include "src/cpp/client/channel.h"

namespace grpc {

class SecureCredentials GRPC_FINAL : public Credentials {
 public:
  explicit SecureCredentials(grpc_credentials* c_creds) : c_creds_(c_creds) {}
  ~SecureCredentials() GRPC_OVERRIDE { grpc_credentials_release(c_creds_); }
  grpc_credentials* GetRawCreds() { return c_creds_; }

  std::shared_ptr<grpc::ChannelInterface> CreateChannel(
      const string& target, const grpc::ChannelArguments& args) GRPC_OVERRIDE {
    grpc_channel_args channel_args;
    args.SetChannelArgs(&channel_args);
    return std::shared_ptr<ChannelInterface>(new Channel(
        args.GetSslTargetNameOverride().empty()
            ? target : args.GetSslTargetNameOverride(),
        grpc_secure_channel_create(c_creds_, target.c_str(), &channel_args)));
  }

  SecureCredentials* AsSecureCredentials() { return this; }

 private:
  grpc_credentials* const c_creds_;
};

namespace {
std::unique_ptr<Credentials> WrapCredentials(grpc_credentials* creds) {
  return creds == nullptr
             ? nullptr
             : std::unique_ptr<Credentials>(new SecureCredentials(creds));
}
}  // namespace

std::unique_ptr<Credentials> GoogleDefaultCredentials() {
  return WrapCredentials(grpc_google_default_credentials_create());
}

// Builds SSL Credentials given SSL specific options
std::unique_ptr<Credentials> SslCredentials(
    const SslCredentialsOptions& options) {
  grpc_ssl_pem_key_cert_pair pem_key_cert_pair = {
      options.pem_private_key.c_str(), options.pem_cert_chain.c_str()};

  grpc_credentials* c_creds = grpc_ssl_credentials_create(
      options.pem_root_certs.empty() ? nullptr : options.pem_root_certs.c_str(),
      options.pem_private_key.empty() ? nullptr : &pem_key_cert_pair);
  return WrapCredentials(c_creds);
}

// Builds credentials for use when running in GCE
std::unique_ptr<Credentials> ComputeEngineCredentials() {
  return WrapCredentials(grpc_compute_engine_credentials_create());
}

// Builds service account credentials.
std::unique_ptr<Credentials> ServiceAccountCredentials(
    const grpc::string& json_key, const grpc::string& scope,
    std::chrono::seconds token_lifetime) {
  if (token_lifetime.count() <= 0) {
    gpr_log(GPR_ERROR,
            "Trying to create ServiceAccountCredentials "
            "with non-positive lifetime");
    return WrapCredentials(nullptr);
  }
  gpr_timespec lifetime = gpr_time_from_seconds(token_lifetime.count());
  return WrapCredentials(grpc_service_account_credentials_create(
      json_key.c_str(), scope.c_str(), lifetime));
}

// Builds JWT credentials.
std::unique_ptr<Credentials> JWTCredentials(
    const grpc::string &json_key, std::chrono::seconds token_lifetime) {
  if (token_lifetime.count() <= 0) {
    gpr_log(GPR_ERROR,
            "Trying to create JWTCredentials with non-positive lifetime");
    return WrapCredentials(nullptr);
  }
  gpr_timespec lifetime = gpr_time_from_seconds(token_lifetime.count());
  return WrapCredentials(
      grpc_jwt_credentials_create(json_key.c_str(), lifetime));
}

// Builds IAM credentials.
std::unique_ptr<Credentials> IAMCredentials(
    const grpc::string& authorization_token,
    const grpc::string& authority_selector) {
  return WrapCredentials(grpc_iam_credentials_create(
      authorization_token.c_str(), authority_selector.c_str()));
}

// Combines two credentials objects into a composite credentials.
std::unique_ptr<Credentials> CompositeCredentials(
    const std::unique_ptr<Credentials>& creds1,
    const std::unique_ptr<Credentials>& creds2) {
  // Note that we are not saving unique_ptrs to the two credentials
  // passed in here. This is OK because the underlying C objects (i.e.,
  // creds1 and creds2) into grpc_composite_credentials_create will see their
  // refcounts incremented.
  SecureCredentials* s1 = creds1->AsSecureCredentials();
  SecureCredentials* s2 = creds2->AsSecureCredentials();
  if (s1 && s2) {
    return WrapCredentials(grpc_composite_credentials_create(
        s1->GetRawCreds(), s2->GetRawCreds()));
  }
  return nullptr;
}

}  // namespace grpc
<|endoftext|>


<commit_before>#include <core/video/window.h>
#include <core/video/context.h>
#include <core/log/log.h>
#include <core/event/eventdispatcher.h>

namespace fd {
namespace core {
namespace video {

using namespace log;
using namespace event;
using namespace math;

std::unordered_map<HWND, WINWindow*> WINWindow::windowHandles;

LRESULT WINWindow::WndProc(HWND hwnd, UINT msg, WPARAM w, LPARAM l) {
	WINWindow* window = windowHandles[hwnd];

	if (!window) goto end;

	switch (msg) {
		case WM_CLOSE:
			window->open = false;
			break;
		case WM_MOVE: {
			WindowEvent e(EventAction::Move, vec2i(window->GetWidth(), window->GetHeight()), vec2i(LOWORD(l), HIWORD(l)), false, false);
			EventDispatcher::DispatchEvent(&e);
			}
			break;
		case WM_SIZE: {
			WindowEvent e(EventAction::Resize, vec2i(LOWORD(l), HIWORD(l)), vec2i(), false, false);
			window->info.width = e.size.x;
			window->info.height = e.size.y;
			EventDispatcher::DispatchEvent(&e);
			}
			break;
	}

	end:

	return DefWindowProc(hwnd, msg, w, l);
}

WINWindow::WINWindow(WindowCreateInfo* info) : Window(info) {

	WNDCLASSEX wnd = { 0 };

	wnd.cbSize = sizeof(WNDCLASSEX);
	wnd.hCursor = LoadCursor(0, IDC_ARROW);
	wnd.hIcon = LoadIcon(0, IDI_WINLOGO);
	wnd.lpfnWndProc = (WNDPROC)WndProc;
	wnd.lpszClassName = L"DANK";
	wnd.style = CS_VREDRAW | CS_HREDRAW;

	if (!RegisterClassEx(&wnd)) {
		Log::Fatal("[WINWindow] Failed to register class");
		return;
	}

	if (Factory::GetAdapters().Find(info->graphicsAdapter) == ~0) {
		FD_WARN("[WINWindow] Invalid adapter specified!");
		info->graphicsAdapter = Factory::GetAdapters()[0];
	}

	if (Factory::GetOutputs().Find(info->outputWindow) == ~0) {
		FD_WARN("[WINWindow] Invalid output specified!");
		info->outputWindow = Factory::GetOutputs()[0];
	}

	RECT coord = { 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN) };

#ifdef FD_DX
	DXGI_MODE_DESC mode = info->outputWindow->FindBestMatchingMode(info->width, info->height, info->refreshRate);
	info->outputWindow->SetMode(mode);

	info->width = mode.Width;
	info->height = mode.Height;
	info->refreshRate = (uint32)((float32)mode.RefreshRate.Numerator / mode.RefreshRate.Denominator);

	coord = info->outputWindow->GetDesktopCoordinates();
#endif

	uint32 monitorWidth = coord.right - coord.left;
	uint32 monitorHeight = coord.bottom - coord.top;

	uint32 xPos = coord.left + (monitorWidth >> 1) - (info->width >> 1);
	uint32 yPos = coord.top + (monitorHeight>> 1) - (info->height>> 1);

	RECT r = { 0, 0, (LONG)info->width, (LONG)info->height };

	AdjustWindowRect(&r, WS_OVERLAPPEDWINDOW, FALSE);

	hwnd = CreateWindow(L"DANK", info->title.GetWCHAR(), WS_OVERLAPPEDWINDOW, xPos, yPos, r.right - r.left, r.bottom - r.top, 0, 0, 0, 0);
	Log::Debug("%u %u", r.right - r.left, r.bottom - r.top);
	if (!hwnd) {
		FD_FATAL("[WINWindow] Failed to create window! %u", GetLastError());
		return;
	}

	if (!Context::Init(this)) {
		DestroyWindow(hwnd);
		exit(1);
	}

	SetVisible(true);

	open = true;

	windowHandles[hwnd] = this;
}

WINWindow::~WINWindow() {
	Context::Dispose();

	DestroyWindow(hwnd);
}

void WINWindow::Update() const {

	MSG msg;

	if (PeekMessage(&msg, hwnd, 0, 0, PM_REMOVE)) {
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

}

void WINWindow::SetVisible(bool state) {
	ShowWindow(hwnd, state ? SW_SHOW : SW_HIDE);
}

void WINWindow::Resize(const WindowCreateInfo* const newInfo) {
	info = *newInfo;
	RECT r = { 0, 0, (LONG)info.width, (LONG)info.height };

	AdjustWindowRect(&r, WS_OVERLAPPEDWINDOW, FALSE);

	SetWindowPos(hwnd, HWND_TOP, 0, 0, r.right - r.left, r.bottom - r.top, SWP_NOMOVE | SWP_SHOWWINDOW);
}

}
}
}<commit_msg>Tomporary mouse input<commit_after>#include <core/video/window.h>
#include <core/video/context.h>
#include <core/log/log.h>
#include <core/event/eventdispatcher.h>

namespace fd {
namespace core {
namespace video {

using namespace log;
using namespace event;
using namespace math;

std::unordered_map<HWND, WINWindow*> WINWindow::windowHandles;

LRESULT WINWindow::WndProc(HWND hwnd, UINT msg, WPARAM w, LPARAM l) {
	WINWindow* window = windowHandles[hwnd];

	if (!window) goto end;

	switch (msg) {
		case WM_CLOSE:
			window->open = false;
			break;
		case WM_MOVE: {
			WindowEvent e(EventAction::Move, vec2i(window->GetWidth(), window->GetHeight()), vec2i(LOWORD(l), HIWORD(l)), false, false);
			EventDispatcher::DispatchEvent(&e);
			}
			break;
		case WM_SIZE: {
			WindowEvent e(EventAction::Resize, vec2i(LOWORD(l), HIWORD(l)), vec2i(), false, false);
			window->info.width = e.size.x;
			window->info.height = e.size.y;
			EventDispatcher::DispatchEvent(&e);
			}
			break;
		case WM_MOUSEMOVE: {
			MouseEvent e(EventAction::Move, vec2i(LOWORD(l), HIWORD(l)), vec2i(), 0);
			EventDispatcher::DispatchEvent(&e);
		}

	}

	end:

	return DefWindowProc(hwnd, msg, w, l);
}

WINWindow::WINWindow(WindowCreateInfo* info) : Window(info) {

	WNDCLASSEX wnd = { 0 };

	wnd.cbSize = sizeof(WNDCLASSEX);
	wnd.hCursor = LoadCursor(0, IDC_ARROW);
	wnd.hIcon = LoadIcon(0, IDI_WINLOGO);
	wnd.lpfnWndProc = (WNDPROC)WndProc;
	wnd.lpszClassName = L"DANK";
	wnd.style = CS_VREDRAW | CS_HREDRAW;

	if (!RegisterClassEx(&wnd)) {
		Log::Fatal("[WINWindow] Failed to register class");
		return;
	}

	if (Factory::GetAdapters().Find(info->graphicsAdapter) == ~0) {
		FD_WARN("[WINWindow] Invalid adapter specified!");
		info->graphicsAdapter = Factory::GetAdapters()[0];
	}

	if (Factory::GetOutputs().Find(info->outputWindow) == ~0) {
		FD_WARN("[WINWindow] Invalid output specified!");
		info->outputWindow = Factory::GetOutputs()[0];
	}

	RECT coord = { 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN) };

#ifdef FD_DX
	DXGI_MODE_DESC mode = info->outputWindow->FindBestMatchingMode(info->width, info->height, info->refreshRate);
	info->outputWindow->SetMode(mode);

	info->width = mode.Width;
	info->height = mode.Height;
	info->refreshRate = (uint32)((float32)mode.RefreshRate.Numerator / mode.RefreshRate.Denominator);

	coord = info->outputWindow->GetDesktopCoordinates();
#endif

	uint32 monitorWidth = coord.right - coord.left;
	uint32 monitorHeight = coord.bottom - coord.top;

	uint32 xPos = coord.left + (monitorWidth >> 1) - (info->width >> 1);
	uint32 yPos = coord.top + (monitorHeight>> 1) - (info->height>> 1);

	RECT r = { 0, 0, (LONG)info->width, (LONG)info->height };

	AdjustWindowRect(&r, WS_OVERLAPPEDWINDOW, FALSE);

	hwnd = CreateWindow(L"DANK", info->title.GetWCHAR(), WS_OVERLAPPEDWINDOW, xPos, yPos, r.right - r.left, r.bottom - r.top, 0, 0, 0, 0);
	Log::Debug("%u %u", r.right - r.left, r.bottom - r.top);
	if (!hwnd) {
		FD_FATAL("[WINWindow] Failed to create window! %u", GetLastError());
		return;
	}

	if (!Context::Init(this)) {
		DestroyWindow(hwnd);
		exit(1);
	}

	SetVisible(true);

	open = true;

	windowHandles[hwnd] = this;
}

WINWindow::~WINWindow() {
	Context::Dispose();

	DestroyWindow(hwnd);
}

void WINWindow::Update() const {

	MSG msg;

	if (PeekMessage(&msg, hwnd, 0, 0, PM_REMOVE)) {
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

}

void WINWindow::SetVisible(bool state) {
	ShowWindow(hwnd, state ? SW_SHOW : SW_HIDE);
}

void WINWindow::Resize(const WindowCreateInfo* const newInfo) {
	info = *newInfo;
	RECT r = { 0, 0, (LONG)info.width, (LONG)info.height };

	AdjustWindowRect(&r, WS_OVERLAPPEDWINDOW, FALSE);

	SetWindowPos(hwnd, HWND_TOP, 0, 0, r.right - r.left, r.bottom - r.top, SWP_NOMOVE | SWP_SHOWWINDOW);
}

}
}
}<|endoftext|>