#include <algorithm>
#include <cfloat>
#include <vector>

#include "caffe/layer.hpp"
#include "caffe/util/math_functions.hpp"
#include "caffe/vision_layers.hpp"

namespace caffe {

template <typename Dtype>
void SoftmaxPairLossLayer<Dtype>::LayerSetUp(
    const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) {
  LossLayer<Dtype>::LayerSetUp(bottom, top);
  softmax_bottom_vec_1.clear();
  softmax_bottom_vec_2.clear();
  softmax_bottom_vec_1.push_back(bottom[0]);
  softmax_bottom_vec_2.push_back(bottom[1]);
  softmax_top_vec_1.clear();
  softmax_top_vec_2.clear();
  softmax_top_vec_1.push_back(&prob_1);
  softmax_top_vec_2.push_back(&prob_2);
  softmax_layer_1->SetUp(softmax_bottom_vec_1, &softmax_top_vec_1);
  softmax_layer_2->SetUp(softmax_bottom_vec_2, &softmax_top_vec_2);
  coef1=1;
}

template <typename Dtype>
void SoftmaxPairLossLayer<Dtype>::Reshape(
    const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) {
  LossLayer<Dtype>::Reshape(bottom, top);
  softmax_layer_1->Reshape(softmax_bottom_vec_1, &softmax_top_vec_1);
  softmax_layer_2->Reshape(softmax_bottom_vec_2, &softmax_top_vec_2);
  //if (top->size() >= 2) {
    // softmax output
    //(*top)[1]->ReshapeLike(*bottom[0]);
  //}
}

template <typename Dtype>
void SoftmaxPairLossLayer<Dtype>::Forward_cpu(
    const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) {
  // The forward pass computes the softmax prob values.
  softmax_layer_1->Forward(softmax_bottom_vec_1, &softmax_top_vec_1);
  softmax_layer_2->Forward(softmax_bottom_vec_2, &softmax_top_vec_2);
  const Dtype* prob_data1 = prob_1.cpu_data();
  const Dtype* prob_data2 = prob_2.cpu_data();
  //const Dtype* dist_data = bottom[2]->cpu_data();
  const Dtype* label = bottom[2]->cpu_data();//const Dtype* label = bottom[3]->cpu_data();
  //const Dtype* pairlabel = bottom[4]->cpu_data();
  int num = prob_1.num();
  int dim = prob_1.count() / num;
  int spatial_dim = prob_1.height() * prob_1.width();
  Dtype loss1 = 0;
  Dtype loss2 = 0;
  Dtype loss3 = 0;
  //LOG(INFO) << "dim: "<< dim << ", spatial_dim:" << spatial_dim;
  for (int i = 0; i < num; ++i) {
    for (int j = 0; j < spatial_dim; j++) {
      loss1 -= log(std::max(prob_data1[i * dim +
          static_cast<int>(label[i * spatial_dim + j]) * spatial_dim + j],
                           Dtype(FLT_MIN)));
      loss2 -= log(std::max(prob_data2[i * dim +
                static_cast<int>(label[i * spatial_dim + j]) * spatial_dim + j],
                                 Dtype(FLT_MIN)));
    }
  }
    /*for (int i=0;i<bottom[2]->num();i++){
  	  Dtype dloss=0;
  	  if (dist_data[i]*pairlabel[i]>20)
  	  {
  		  dloss=dist_data[i]*pairlabel[i];
  	  }else{
  		  dloss=log(1+exp(dist_data[i]*pairlabel[i]));
  	  }
  	  loss3=loss3+dloss;
    }*/
  (*top)[0]->mutable_cpu_data()[0] = (loss1+loss2) / num / spatial_dim+coef1*loss3;
  //if (top->size() == 2) {
    //(*top)[1]->ShareData(prob_);
  //}
}

template <typename Dtype>
void SoftmaxPairLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
    const vector<bool>& propagate_down,
    vector<Blob<Dtype>*>* bottom) {
  /*if (propagate_down[3]||propagate_down[4]) {
    LOG(FATAL) << this->type_name()
               << " Layer cannot backpropagate to label inputs.";
  }*/
  //if (propagate_down[0]) {
    Dtype* bottom_diff1 = (*bottom)[0]->mutable_cpu_diff();
    Dtype* bottom_diff2 = (*bottom)[1]->mutable_cpu_diff();
    //Dtype* bottom_diff3 = (*bottom)[2]->mutable_cpu_diff();
    const Dtype* prob_data1 = prob_1.cpu_data();
    const Dtype* prob_data2 = prob_2.cpu_data();
    //const Dtype* dist_data = (*bottom)[2]->cpu_data();
    //const Dtype* pairlabel = (*bottom)[4]->cpu_data();
    caffe_copy(prob_1.count(), prob_data1, bottom_diff1);
    caffe_copy(prob_2.count(), prob_data2, bottom_diff2);
    const Dtype* label = (*bottom)[2]->cpu_data();//const Dtype* label = (*bottom)[3]->cpu_data();
    int num = prob_1.num();
    int dim = prob_1.count() / num;
    int spatial_dim = prob_1.height() * prob_1.width();
    for (int i = 0; i < num; ++i) {
      for (int j = 0; j < spatial_dim; ++j) {
        bottom_diff1[i * dim + static_cast<int>(label[i * spatial_dim + j])
            * spatial_dim + j] -= 1;
        bottom_diff2[i * dim + static_cast<int>(label[i * spatial_dim + j])
                    * spatial_dim + j] -= 1;
      }
    }
    /*for (int i=0;i < (*bottom)[2]->num();i++){
    		Dtype scales=1-1/(1+exp(pairlabel[i]*dist_data[i]));
    		scales=scales*label[i];
    		bottom_diff3[i]=scales*coef1;
    }*/
    // Scale gradient
    const Dtype loss_weight = top[0]->cpu_diff()[0];
    caffe_scal(prob_1.count(), loss_weight / num / spatial_dim, bottom_diff1);
    caffe_scal(prob_2.count(), loss_weight / num / spatial_dim, bottom_diff2);
  //}
}


#ifdef CPU_ONLY
STUB_GPU(SoftmaxPairLossLayer);
#endif

INSTANTIATE_CLASS(SoftmaxPairLossLayer);


}  // namespace caffe
