<commit_before>/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved.  Released under a BSD (revised)
license as described in the file LICENSE.
 */
#include <fstream>
#include <iostream>
using namespace std;

#ifndef _WIN32
#include <unistd.h>
#endif
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
#include <algorithm>

#include "rand48.h"
#include "global_data.h"

/* Define the last version where files are backward compatible. */
#define LAST_COMPATIBLE_VERSION "6.1.3"
#define VERSION_FILE_WITH_CUBIC "6.1.3"

void initialize_regressor(vw& all)
{
  // Regressor is already initialized.
  if (all.reg.weight_vector != NULL) {
    return;
  }

  size_t length = ((size_t)1) << all.num_bits;
  all.reg.weight_mask = (length << all.reg.stride_shift) - 1;
  all.reg.weight_vector = calloc_or_die<weight>(length << all.reg.stride_shift);
  if (all.reg.weight_vector == NULL)
    {
      cerr << all.program_name << ": Failed to allocate weight array with " << all.num_bits << " bits: try decreasing -b <bits>" << endl;
      throw exception();
    }
  if (all.random_weights)
    {
      for (size_t j = 0; j < length; j++)
	all.reg.weight_vector[j << all.reg.stride_shift] = (float)(frand48() - 0.5);
    }
  if (all.random_positive_weights)
    {
      for (size_t j = 0; j < length; j++)
	all.reg.weight_vector[j << all.reg.stride_shift] = (float)(0.1 * frand48());
    }
  if (all.initial_weight != 0.)
    for (size_t j = 0; j < length << all.reg.stride_shift; j+= ( ((size_t)1) << all.reg.stride_shift))
      all.reg.weight_vector[j] = all.initial_weight;
}

const size_t buf_size = 512;

void save_load_header(vw& all, io_buf& model_file, bool read, bool text)
{

  char buff[buf_size];
  char buff2[buf_size];
  uint32_t text_len;

  if (model_file.files.size() > 0)
    {
      uint32_t v_length = (uint32_t)version.to_string().length()+1;
      text_len = sprintf(buff, "Version %s\n", version.to_string().c_str());
      memcpy(buff2,version.to_string().c_str(),v_length);
      if (read)
	v_length = buf_size;
      bin_text_read_write(model_file, buff2, v_length,
			  "", read,
			  buff, text_len, text);
      version_struct v_tmp(buff2);
      if (v_tmp < LAST_COMPATIBLE_VERSION)
	{
	  cout << "Model has possibly incompatible version! " << v_tmp.to_string() << endl;
	  throw exception();
	}

      char model = 'm';
      bin_text_read_write_fixed(model_file,&model,1,
				"file is not a model file", read,
				"", 0, text);

      text_len = sprintf(buff, "Min label:%f\n", all.sd->min_label);
      bin_text_read_write_fixed(model_file,(char*)&all.sd->min_label, sizeof(all.sd->min_label),
				"", read,
				buff, text_len, text);

      text_len = sprintf(buff, "Max label:%f\n", all.sd->max_label);
      bin_text_read_write_fixed(model_file,(char*)&all.sd->max_label, sizeof(all.sd->max_label),
				"", read,
				buff, text_len, text);

      text_len = sprintf(buff, "bits:%d\n", (int)all.num_bits);
      uint32_t local_num_bits = all.num_bits;
      bin_text_read_write_fixed(model_file,(char *)&local_num_bits, sizeof(local_num_bits),
				"", read,
				buff, text_len, text);
      if (all.default_bits != true && all.num_bits != local_num_bits)
	{
	  cout << "vw: -b bits mismatch: command-line " << all.num_bits << " != " << local_num_bits << " stored in model" << endl;
	  throw exception();
	}
      all.default_bits = false;
      all.num_bits = local_num_bits;

      uint32_t pair_len = (uint32_t)all.pairs.size();
      text_len = sprintf(buff, "%d pairs: ", (int)pair_len);
      bin_text_read_write_fixed(model_file,(char *)&pair_len, sizeof(pair_len),
				"", read,
				buff, text_len, text);
      for (size_t i = 0; i < pair_len; i++)
	{
	  char pair[2];
	  if (!read)
	    {
	      memcpy(pair,all.pairs[i].c_str(),2);
	      text_len = sprintf(buff, "%s ", all.pairs[i].c_str());
	    }
	  bin_text_read_write_fixed(model_file, pair,2,
				    "", read,
				    buff, text_len, text);
	  if (read)
	    {
	      string temp(pair, 2);
	      if (count(all.pairs.begin(), all.pairs.end(), temp) == 0)
		all.pairs.push_back(temp);
	    }
	}
      bin_text_read_write_fixed(model_file,buff,0,
				"", read,
				"\n",1,text);

      uint32_t triple_len = (uint32_t)all.triples.size();
      text_len = sprintf(buff, "%d triples: ", (int)triple_len);
      bin_text_read_write_fixed(model_file,(char *)&triple_len, sizeof(triple_len),
				"", read,
			    buff,text_len, text);
      for (size_t i = 0; i < triple_len; i++)
	{
	  char triple[3];
	  if (!read)
	    {
	      text_len = sprintf(buff, "%s ", all.triples[i].c_str());
	      memcpy(triple, all.triples[i].c_str(), 3);
	    }
	  bin_text_read_write_fixed(model_file,triple,3,
				    "", read,
				    buff,text_len,text);
	  if (read)
	    {
	      string temp(triple,3);
	      if (count(all.triples.begin(), all.triples.end(), temp) == 0)
		all.triples.push_back(temp);
	    }
	}
      bin_text_read_write_fixed(model_file,buff,0,
				"", read,
				"\n",1, text);

      text_len = sprintf(buff, "lda:%d\n", (int)all.lda);
      bin_text_read_write_fixed(model_file,(char*)&all.lda, sizeof(all.lda),
				"", read,
				buff, text_len,text);

      uint32_t ngram_len = (uint32_t)all.ngram_strings.size();
      text_len = sprintf(buff, "%d ngram: ", (int)ngram_len);
      bin_text_read_write_fixed(model_file,(char *)&ngram_len, sizeof(ngram_len),
				"", read,
				buff,text_len, text);
      for (size_t i = 0; i < ngram_len; i++)
	{
	  char ngram[3] = {0,0,0};
	  if (!read) {
	    text_len = sprintf(buff, "%s ", all.ngram_strings[i].c_str());
	    memcpy(ngram, all.ngram_strings[i].c_str(), min(3, all.ngram_strings[i].size()));
	  }
	  bin_text_read_write_fixed(model_file,ngram,3,
				    "", read,
				    buff,text_len,text);
	  if (read)
	    {
	      string temp(ngram,3);
	      all.ngram_strings.push_back(temp);
	    }
	}
      if(read)
	compile_gram(all.ngram_strings, all.ngram, (char*)"grams", all.quiet);

      bin_text_read_write_fixed(model_file,buff,0,
				"", read,
				"\n",1, text);

      uint32_t skip_len = (uint32_t)all.skip_strings.size();
      text_len = sprintf(buff, "%d skip: ", (int)skip_len);
      bin_text_read_write_fixed(model_file,(char *)&skip_len, sizeof(skip_len),
				"", read,
				buff,text_len, text);
      for (size_t i = 0; i < skip_len; i++)
	{
	  char skip[3] = {0,0,0};
	  if (!read) {
	    text_len = sprintf(buff, "%s ", all.skip_strings[i].c_str());
	    memcpy(skip, all.skip_strings[i].c_str(), min(3, all.skip_strings[i].size()));
	  }
	  bin_text_read_write_fixed(model_file,skip,3,
				    "", read,
				    buff,text_len,text);
	  if (read)
	    {
	      string temp(skip,3);
	      all.skip_strings.push_back(temp);
	    }
	}
      if(read)
	compile_gram(all.skip_strings, all.skips, (char*)"skips", all.quiet);
      bin_text_read_write_fixed(model_file,buff,0,
				"", read,
				"\n",1, text);

      text_len = sprintf(buff, "options:%s\n", all.file_options->str().c_str());
      uint32_t len = (uint32_t)all.file_options->str().length()+1;
      memcpy(buff2, all.file_options->str().c_str(),len);
      if (read)
	len = buf_size;
      bin_text_read_write(model_file,buff2, len,
			  "", read,
			  buff, text_len, text);
      if (read)
	all.file_options->str(buff2);
    }

}

void dump_regressor(vw& all, string reg_name, bool as_text)
{
  if (reg_name == string(""))
    return;
  string start_name = reg_name+string(".writing");
  io_buf io_temp;

  io_temp.open_file(start_name.c_str(), all.stdin_off, io_buf::WRITE);

  save_load_header(all, io_temp, false, as_text);
  all.l->save_load(io_temp, false, as_text);

  io_temp.flush(); // close_file() should do this for me ...
  io_temp.close_file();
  remove(reg_name.c_str());
  rename(start_name.c_str(),reg_name.c_str());
}

void save_predictor(vw& all, string reg_name, size_t current_pass)
{
  stringstream filename;
  filename << reg_name;
  if (all.save_per_pass)
    filename << "." << current_pass;
  dump_regressor(all, filename.str(), false);
}

void finalize_regressor(vw& all, string reg_name)
{
  if (!all.early_terminate){
    if (all.per_feature_regularizer_output.length() > 0)
      dump_regressor(all, all.per_feature_regularizer_output, false);
    else
      dump_regressor(all, reg_name, false);
    if (all.per_feature_regularizer_text.length() > 0)
      dump_regressor(all, all.per_feature_regularizer_text, true);
    else{
      dump_regressor(all, all.text_regressor_name, true);
      all.print_invert = true;
      dump_regressor(all, all.inv_hash_regressor_name, true);
      all.print_invert = false;
    }
  }
}

void parse_regressor_args(vw& all, po::variables_map& vm, io_buf& io_temp)
{
  vector<string> regs;
  if (vm.count("initial_regressor") || vm.count("i"))
    regs = vm["initial_regressor"].as< vector<string> >();

  if (vm.count("input_feature_regularizer"))
    regs.push_back(vm["input_feature_regularizer"].as<string>());

  if (regs.size() > 0) {
    io_temp.open_file(regs[0].c_str(), all.stdin_off, io_buf::READ);
    if (!all.quiet) {
        //cerr << "initial_regressor = " << regs[0] << endl;
      if (regs.size() > 1) {
        cerr << "warning: ignoring remaining " << (regs.size() - 1) << " initial regressors" << endl;
      }
    }
  }

  save_load_header(all, io_temp, true, false);
}

void parse_mask_regressor_args(vw& all)
{
  po::variables_map& vm = all.vm;
  if (vm.count("feature_mask")) {
    size_t length = ((size_t)1) << all.num_bits;
    string mask_filename = vm["feature_mask"].as<string>();
    if (vm.count("initial_regressor")){
      vector<string> init_filename = vm["initial_regressor"].as< vector<string> >();
      if(mask_filename == init_filename[0]){//-i and -mask are from same file, just generate mask
        return;
      }
    }

    //all other cases, including from different file, or -i does not exist, need to read in the mask file
    io_buf io_temp_mask;
    io_temp_mask.open_file(mask_filename.c_str(), false, io_buf::READ);
    save_load_header(all, io_temp_mask, true, false);
    all.l->save_load(io_temp_mask, true, false);
    io_temp_mask.close_file();

    // Deal with the over-written header from initial regressor
    if (vm.count("initial_regressor")) {
      vector<string> init_filename = vm["initial_regressor"].as< vector<string> >();

      // Load original header again.
      io_buf io_temp;
      io_temp.open_file(init_filename[0].c_str(), false, io_buf::READ);
      save_load_header(all, io_temp, true, false);
      io_temp.close_file();

      // Re-zero the weights, in case weights of initial regressor use different indices
      for (size_t j = 0; j < length; j++){
        all.reg.weight_vector[j << all.reg.stride_shift] = 0.;
      }
    } else {
      // If no initial regressor, just clear out the options loaded from the header.
      all.file_options->str("");
    }
  }
}

<commit_msg>Multiple regressor initialisation fix (12)<commit_after>/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved.  Released under a BSD (revised)
license as described in the file LICENSE.
 */
#include <fstream>
#include <iostream>
using namespace std;

#ifndef _WIN32
#include <unistd.h>
#endif
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
#include <algorithm>

#include "rand48.h"
#include "global_data.h"

/* Define the last version where files are backward compatible. */
#define LAST_COMPATIBLE_VERSION "6.1.3"
#define VERSION_FILE_WITH_CUBIC "6.1.3"

void initialize_regressor(vw& all)
{
  // Regressor is already initialized.
  if (all.reg.weight_vector != NULL) {
    return;
  }

  size_t length = ((size_t)1) << all.num_bits;
  all.reg.weight_mask = (length << all.reg.stride_shift) - 1;
  all.reg.weight_vector = calloc_or_die<weight>(length << all.reg.stride_shift);
  if (all.reg.weight_vector == NULL)
    {
      cerr << all.program_name << ": Failed to allocate weight array with " << all.num_bits << " bits: try decreasing -b <bits>" << endl;
      throw exception();
    } else
  if (all.initial_weight != 0.)
    {
     for (size_t j = 0; j < length << all.reg.stride_shift; j+= ( ((size_t)1) << all.reg.stride_shift))
       all.reg.weight_vector[j] = all.initial_weight;
    } else
  if (all.random_positive_weights)
    {
      for (size_t j = 0; j < length; j++)
	all.reg.weight_vector[j << all.reg.stride_shift] = (float)(0.1 * frand48());
    } else
  if (all.random_weights)
    {
      for (size_t j = 0; j < length; j++)
	all.reg.weight_vector[j << all.reg.stride_shift] = (float)(frand48() - 0.5);
    }
}

const size_t buf_size = 512;

void save_load_header(vw& all, io_buf& model_file, bool read, bool text)
{

  char buff[buf_size];
  char buff2[buf_size];
  uint32_t text_len;

  if (model_file.files.size() > 0)
    {
      uint32_t v_length = (uint32_t)version.to_string().length()+1;
      text_len = sprintf(buff, "Version %s\n", version.to_string().c_str());
      memcpy(buff2,version.to_string().c_str(),v_length);
      if (read)
	v_length = buf_size;
      bin_text_read_write(model_file, buff2, v_length,
			  "", read,
			  buff, text_len, text);
      version_struct v_tmp(buff2);
      if (v_tmp < LAST_COMPATIBLE_VERSION)
	{
	  cout << "Model has possibly incompatible version! " << v_tmp.to_string() << endl;
	  throw exception();
	}

      char model = 'm';
      bin_text_read_write_fixed(model_file,&model,1,
				"file is not a model file", read,
				"", 0, text);

      text_len = sprintf(buff, "Min label:%f\n", all.sd->min_label);
      bin_text_read_write_fixed(model_file,(char*)&all.sd->min_label, sizeof(all.sd->min_label),
				"", read,
				buff, text_len, text);

      text_len = sprintf(buff, "Max label:%f\n", all.sd->max_label);
      bin_text_read_write_fixed(model_file,(char*)&all.sd->max_label, sizeof(all.sd->max_label),
				"", read,
				buff, text_len, text);

      text_len = sprintf(buff, "bits:%d\n", (int)all.num_bits);
      uint32_t local_num_bits = all.num_bits;
      bin_text_read_write_fixed(model_file,(char *)&local_num_bits, sizeof(local_num_bits),
				"", read,
				buff, text_len, text);
      if (all.default_bits != true && all.num_bits != local_num_bits)
	{
	  cout << "vw: -b bits mismatch: command-line " << all.num_bits << " != " << local_num_bits << " stored in model" << endl;
	  throw exception();
	}
      all.default_bits = false;
      all.num_bits = local_num_bits;

      uint32_t pair_len = (uint32_t)all.pairs.size();
      text_len = sprintf(buff, "%d pairs: ", (int)pair_len);
      bin_text_read_write_fixed(model_file,(char *)&pair_len, sizeof(pair_len),
				"", read,
				buff, text_len, text);
      for (size_t i = 0; i < pair_len; i++)
	{
	  char pair[2];
	  if (!read)
	    {
	      memcpy(pair,all.pairs[i].c_str(),2);
	      text_len = sprintf(buff, "%s ", all.pairs[i].c_str());
	    }
	  bin_text_read_write_fixed(model_file, pair,2,
				    "", read,
				    buff, text_len, text);
	  if (read)
	    {
	      string temp(pair, 2);
	      if (count(all.pairs.begin(), all.pairs.end(), temp) == 0)
		all.pairs.push_back(temp);
	    }
	}
      bin_text_read_write_fixed(model_file,buff,0,
				"", read,
				"\n",1,text);

      uint32_t triple_len = (uint32_t)all.triples.size();
      text_len = sprintf(buff, "%d triples: ", (int)triple_len);
      bin_text_read_write_fixed(model_file,(char *)&triple_len, sizeof(triple_len),
				"", read,
			    buff,text_len, text);
      for (size_t i = 0; i < triple_len; i++)
	{
	  char triple[3];
	  if (!read)
	    {
	      text_len = sprintf(buff, "%s ", all.triples[i].c_str());
	      memcpy(triple, all.triples[i].c_str(), 3);
	    }
	  bin_text_read_write_fixed(model_file,triple,3,
				    "", read,
				    buff,text_len,text);
	  if (read)
	    {
	      string temp(triple,3);
	      if (count(all.triples.begin(), all.triples.end(), temp) == 0)
		all.triples.push_back(temp);
	    }
	}
      bin_text_read_write_fixed(model_file,buff,0,
				"", read,
				"\n",1, text);

      text_len = sprintf(buff, "lda:%d\n", (int)all.lda);
      bin_text_read_write_fixed(model_file,(char*)&all.lda, sizeof(all.lda),
				"", read,
				buff, text_len,text);

      uint32_t ngram_len = (uint32_t)all.ngram_strings.size();
      text_len = sprintf(buff, "%d ngram: ", (int)ngram_len);
      bin_text_read_write_fixed(model_file,(char *)&ngram_len, sizeof(ngram_len),
				"", read,
				buff,text_len, text);
      for (size_t i = 0; i < ngram_len; i++)
	{
	  char ngram[3] = {0,0,0};
	  if (!read) {
	    text_len = sprintf(buff, "%s ", all.ngram_strings[i].c_str());
	    memcpy(ngram, all.ngram_strings[i].c_str(), min(3, all.ngram_strings[i].size()));
	  }
	  bin_text_read_write_fixed(model_file,ngram,3,
				    "", read,
				    buff,text_len,text);
	  if (read)
	    {
	      string temp(ngram,3);
	      all.ngram_strings.push_back(temp);
	    }
	}
      if(read)
	compile_gram(all.ngram_strings, all.ngram, (char*)"grams", all.quiet);

      bin_text_read_write_fixed(model_file,buff,0,
				"", read,
				"\n",1, text);

      uint32_t skip_len = (uint32_t)all.skip_strings.size();
      text_len = sprintf(buff, "%d skip: ", (int)skip_len);
      bin_text_read_write_fixed(model_file,(char *)&skip_len, sizeof(skip_len),
				"", read,
				buff,text_len, text);
      for (size_t i = 0; i < skip_len; i++)
	{
	  char skip[3] = {0,0,0};
	  if (!read) {
	    text_len = sprintf(buff, "%s ", all.skip_strings[i].c_str());
	    memcpy(skip, all.skip_strings[i].c_str(), min(3, all.skip_strings[i].size()));
	  }
	  bin_text_read_write_fixed(model_file,skip,3,
				    "", read,
				    buff,text_len,text);
	  if (read)
	    {
	      string temp(skip,3);
	      all.skip_strings.push_back(temp);
	    }
	}
      if(read)
	compile_gram(all.skip_strings, all.skips, (char*)"skips", all.quiet);
      bin_text_read_write_fixed(model_file,buff,0,
				"", read,
				"\n",1, text);

      text_len = sprintf(buff, "options:%s\n", all.file_options->str().c_str());
      uint32_t len = (uint32_t)all.file_options->str().length()+1;
      memcpy(buff2, all.file_options->str().c_str(),len);
      if (read)
	len = buf_size;
      bin_text_read_write(model_file,buff2, len,
			  "", read,
			  buff, text_len, text);
      if (read)
	all.file_options->str(buff2);
    }

}

void dump_regressor(vw& all, string reg_name, bool as_text)
{
  if (reg_name == string(""))
    return;
  string start_name = reg_name+string(".writing");
  io_buf io_temp;

  io_temp.open_file(start_name.c_str(), all.stdin_off, io_buf::WRITE);

  save_load_header(all, io_temp, false, as_text);
  all.l->save_load(io_temp, false, as_text);

  io_temp.flush(); // close_file() should do this for me ...
  io_temp.close_file();
  remove(reg_name.c_str());
  rename(start_name.c_str(),reg_name.c_str());
}

void save_predictor(vw& all, string reg_name, size_t current_pass)
{
  stringstream filename;
  filename << reg_name;
  if (all.save_per_pass)
    filename << "." << current_pass;
  dump_regressor(all, filename.str(), false);
}

void finalize_regressor(vw& all, string reg_name)
{
  if (!all.early_terminate){
    if (all.per_feature_regularizer_output.length() > 0)
      dump_regressor(all, all.per_feature_regularizer_output, false);
    else
      dump_regressor(all, reg_name, false);
    if (all.per_feature_regularizer_text.length() > 0)
      dump_regressor(all, all.per_feature_regularizer_text, true);
    else{
      dump_regressor(all, all.text_regressor_name, true);
      all.print_invert = true;
      dump_regressor(all, all.inv_hash_regressor_name, true);
      all.print_invert = false;
    }
  }
}

void parse_regressor_args(vw& all, po::variables_map& vm, io_buf& io_temp)
{
  vector<string> regs;
  if (vm.count("initial_regressor") || vm.count("i"))
    regs = vm["initial_regressor"].as< vector<string> >();

  if (vm.count("input_feature_regularizer"))
    regs.push_back(vm["input_feature_regularizer"].as<string>());

  if (regs.size() > 0) {
    io_temp.open_file(regs[0].c_str(), all.stdin_off, io_buf::READ);
    if (!all.quiet) {
        //cerr << "initial_regressor = " << regs[0] << endl;
      if (regs.size() > 1) {
        cerr << "warning: ignoring remaining " << (regs.size() - 1) << " initial regressors" << endl;
      }
    }
  }

  save_load_header(all, io_temp, true, false);
}

void parse_mask_regressor_args(vw& all)
{
  po::variables_map& vm = all.vm;
  if (vm.count("feature_mask")) {
    size_t length = ((size_t)1) << all.num_bits;
    string mask_filename = vm["feature_mask"].as<string>();
    if (vm.count("initial_regressor")){
      vector<string> init_filename = vm["initial_regressor"].as< vector<string> >();
      if(mask_filename == init_filename[0]){//-i and -mask are from same file, just generate mask
        return;
      }
    }

    //all other cases, including from different file, or -i does not exist, need to read in the mask file
    io_buf io_temp_mask;
    io_temp_mask.open_file(mask_filename.c_str(), false, io_buf::READ);
    save_load_header(all, io_temp_mask, true, false);
    all.l->save_load(io_temp_mask, true, false);
    io_temp_mask.close_file();

    // Deal with the over-written header from initial regressor
    if (vm.count("initial_regressor")) {
      vector<string> init_filename = vm["initial_regressor"].as< vector<string> >();

      // Load original header again.
      io_buf io_temp;
      io_temp.open_file(init_filename[0].c_str(), false, io_buf::READ);
      save_load_header(all, io_temp, true, false);
      io_temp.close_file();

      // Re-zero the weights, in case weights of initial regressor use different indices
      for (size_t j = 0; j < length; j++){
        all.reg.weight_vector[j << all.reg.stride_shift] = 0.;
      }
    } else {
      // If no initial regressor, just clear out the options loaded from the header.
      all.file_options->str("");
    }
  }
}

<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    $RCSfile: vtkDeformedVolume.cxx,v $
  Language:  C++
  Date:      $Date: 2007/05/04 14:34:34 $
  Version:   $Revision: 1.1 $

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkDeformedVolume.h"

//----------------------------------------------------------------------------
vtkDeformedVolume* vtkDeformedVolume::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkDeformedVolume");
  if(ret)
    {
    return (vtkDeformedVolume*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkDeformedVolume;
}

//----------------------------------------------------------------------------
vtkDeformedVolume::vtkDeformedVolume()
{
  for (int i = 0; i < 3; i++)
    {
      this->Translation[i] = 0.0;
      this->Location[i] = 0;
    }

  this->GridTransform = vtkGridTransformBSpline::New();
  this->GridTransform->SetInterpolationModeToLinear();

  this->Transform = vtkTransformPolyDataFilter::New();
  this->Transform->SetTransform(this->GridTransform);

  this->Volume = vtkMassProperties::New();
  this->Volume->SetInputConnection(this->Transform->GetOutputPort());
}

//----------------------------------------------------------------------------
vtkDeformedVolume::~vtkDeformedVolume()
{
  this->Transform->Delete();
  this->GridTransform->Delete();
  this->Volume->Delete();
}

//----------------------------------------------------------------------------
void vtkDeformedVolume::SetZeroGrid(vtkImageData *grid)
{
  this->Grid = grid;
  this->GridTransform->SetDisplacementGrid(grid);
  this->GridTransform->Inverse();
}

//----------------------------------------------------------------------------
void vtkDeformedVolume::SetDeformedSurface(vtkPolyData *surface)
{
  this->Surface = surface;
  this->Transform->SetInput(surface);
}

//----------------------------------------------------------------------------
double vtkDeformedVolume::GetDeformedVolume()
{
  double deformedvolume;

  this->Grid->SetScalarComponentFromFloat(this->Location[0],
            this->Location[1],
            this->Location[2],
            0, this->Translation[0]);
  this->Grid->SetScalarComponentFromFloat(this->Location[0],
            this->Location[1],
            this->Location[2],
            1, this->Translation[1]);
  this->Grid->SetScalarComponentFromFloat(this->Location[0],
            this->Location[1],
            this->Location[2],
            2, this->Translation[2]);
  this->Grid->Modified();

  this->GridTransform->Update();
  this->Transform->Update();

  deformedvolume = this->Volume->GetVolume();

  this->Grid->SetScalarComponentFromFloat(this->Location[0],
            this->Location[1],
            this->Location[2],
            0, 0);
  this->Grid->SetScalarComponentFromFloat(this->Location[0],
            this->Location[1],
            this->Location[2],
            1, 0);
  this->Grid->SetScalarComponentFromFloat(this->Location[0],
            this->Location[1],
            this->Location[2],
            2, 0);
  this->Grid->Modified();

  return deformedvolume;

}

//----------------------------------------------------------------------------
void vtkDeformedVolume::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
}

<commit_msg>Fixes in Mwierz<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    $RCSfile: vtkDeformedVolume.cxx,v $
  Language:  C++
  Date:      $Date: 2007/05/04 14:34:34 $
  Version:   $Revision: 1.1 $

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkDeformedVolume.h"

//----------------------------------------------------------------------------
vtkDeformedVolume* vtkDeformedVolume::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkDeformedVolume");
  if(ret)
    {
    return (vtkDeformedVolume*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkDeformedVolume;
}

//----------------------------------------------------------------------------
vtkDeformedVolume::vtkDeformedVolume()
{
  for (int i = 0; i < 3; i++)
    {
      this->Translation[i] = 0.0;
      this->Location[i] = 0;
    }

  this->GridTransform = vtkGridTransformBSpline::New();
  this->GridTransform->SetInterpolationModeToLinear();

  this->Transform = vtkTransformPolyDataFilter::New();
  this->Transform->SetTransform(this->GridTransform);

  this->Volume = vtkMassProperties::New();
  this->Volume->SetInputConnection(this->Transform->GetOutputPort());
}

//----------------------------------------------------------------------------
vtkDeformedVolume::~vtkDeformedVolume()
{
  this->Transform->Delete();
  this->GridTransform->Delete();
  this->Volume->Delete();
}

//----------------------------------------------------------------------------
void vtkDeformedVolume::SetZeroGrid(vtkImageData *grid)
{
  this->Grid = grid;
  this->GridTransform->SetDisplacementGrid(grid);
  this->GridTransform->Inverse();
}

//----------------------------------------------------------------------------
void vtkDeformedVolume::SetDeformedSurface(vtkPolyData *surface)
{
  this->Surface = surface;
#if (VTK_MAJOR_VERSION <= 5)
  this->Transform->SetInput(surface);
#else
  this->Transform->SetInputData(surface);
#endif
}

//----------------------------------------------------------------------------
double vtkDeformedVolume::GetDeformedVolume()
{
  double deformedvolume;

  this->Grid->SetScalarComponentFromFloat(this->Location[0],
            this->Location[1],
            this->Location[2],
            0, this->Translation[0]);
  this->Grid->SetScalarComponentFromFloat(this->Location[0],
            this->Location[1],
            this->Location[2],
            1, this->Translation[1]);
  this->Grid->SetScalarComponentFromFloat(this->Location[0],
            this->Location[1],
            this->Location[2],
            2, this->Translation[2]);
  this->Grid->Modified();

  this->GridTransform->Update();
  this->Transform->Update();

  deformedvolume = this->Volume->GetVolume();

  this->Grid->SetScalarComponentFromFloat(this->Location[0],
            this->Location[1],
            this->Location[2],
            0, 0);
  this->Grid->SetScalarComponentFromFloat(this->Location[0],
            this->Location[1],
            this->Location[2],
            1, 0);
  this->Grid->SetScalarComponentFromFloat(this->Location[0],
            this->Location[1],
            this->Location[2],
            2, 0);
  this->Grid->Modified();

  return deformedvolume;

}

//----------------------------------------------------------------------------
void vtkDeformedVolume::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
}

<|endoftext|>


<commit_before>#include <cmath>
#include <string>

#include <ros/ros.h>
#include <tf2_ros/transform_listener.h>
#include <geometry_msgs/TransformStamped.h>

#include "servo_msgs/KrsServoDegree.h"

class TargetPlanner {
public:
  static const unsigned int SERVO_ID_MAX = 3;
  static const double FRAME_LENGTH = 1.0;

  TargetPlanner()
    : transform_buffer(),
      transform_listener(transform_buffer)
  {
    for (int i=0; i<SERVO_ID_MAX; i++) servo[i].id = i;
    frame_length = FRAME_LENGTH;
  }

  explicit TargetPlanner(double desired_length)
    : transform_buffer(),
      transform_listener(transform_buffer)
  {
    for (int i=0; i<SERVO_ID_MAX; i++) servo[i].id = i;
    frame_length = desired_length;
  }

  ~TargetPlanner()
  {}

  bool plan(void) {
    try {
      transform_stamped
        = transform_buffer.lookupTransform("/tomato", "/arm_base", ros::Time(0));
    } catch (tf2::TransformException& exception) {
      ROS_ERROR("%s", exception.what());
      return false;
    }

    std_msgs::float64 sqrt
      = std::sqrt(std::pow(transform_stamped.transform.translation.x)
        + std::sqrt(std::pow(transform_stamped.transform.translation.y);

    servo[0].angle
      = std::atan(transform_stamped.transfrom.translation.y
                  / transform_stamped.transfrom.translation.x)
        + std::acos(sqrt / (2 * frame_length));

    servo[1].angle = 2 * servo[0].angle;
    servo[2].angle = -servo[0].angle;

    return true;
  }

private:
  tf2_ros::Buffer transform_buffer;
  tf2_ros::TransformListener transform_listener;

  geometry_msgs::TransformStamped transform_stamped;
  std::vector<servo_msgs::KrsServoDegree> servo[SERVO_ID_MAX];
  double frame_length;
};

int main(int argc, char** argv) {
  ros::init(argc, argv, "trajectory_planner");
  ros::NodeHandle node_handle;
  ros::Publisher publisher = node_handle.advertise<servo_msgs::KrsServoDegree>("krs_servo", 16);

  ros::Rate rate(10.0);

  TargetPlanner planner;

  while (node_handle.ok()) {
    if (planner.plan())
      for (int id = 0; id < planner.SERVO_ID_MAX; id++)
        publisher.publish(planner.servo[id]);

    rate.sleep();
  }

  return 0;
}
<commit_msg>Update simple_trajectory_planner node<commit_after>#include <cmath>
#include <string>

#include "ros/ros.h"
#include "tf2_ros/transform_listener.h"
#include "geometry_msgs/TransformStamped.h"

#include "servo_msgs/KrsServoDegree.h"

class TargetPlanner {
public:
  static const unsigned int SERVO_ID_MAX = 3;
  static const double FRAME_LENGTH = 1.0;

  TargetPlanner()
    : transform_buffer(),
      transform_listener(transform_buffer)
  {
    for (int i=0; i<SERVO_ID_MAX; i++) servo[i].id = i;
    frame_length = FRAME_LENGTH;
  }

  explicit TargetPlanner(double desired_length)
    : transform_buffer(),
      transform_listener(transform_buffer)
  {
    for (int i=0; i<SERVO_ID_MAX; i++) servo[i].id = i;
    frame_length = desired_length;
  }

  ~TargetPlanner()
  {}

  bool plan(void) {
    try {
      transform_stamped
        = transform_buffer.lookupTransform("/tomato", "/arm_base", ros::Time(0));
    } catch (tf2::TransformException& exception) {
      ROS_ERROR("%s", exception.what());
      return false;
    }

    std_msgs::float64 sqrt
      = std::sqrt(std::pow(transform_stamped.transform.translation.x)
        + std::sqrt(std::pow(transform_stamped.transform.translation.y);

    servo[0].angle
      = std::atan(transform_stamped.transfrom.translation.y
                  / transform_stamped.transfrom.translation.x)
        + std::acos(sqrt / (2 * frame_length));

    servo[1].angle = 2 * servo[0].angle;
    servo[2].angle = -servo[0].angle;

    return true;
  }

private:
  tf2_ros::Buffer transform_buffer;
  tf2_ros::TransformListener transform_listener;

  geometry_msgs::TransformStamped transform_stamped;
  std::vector<servo_msgs::KrsServoDegree> servo[SERVO_ID_MAX];
  double frame_length;
};

int main(int argc, char** argv) {
  ros::init(argc, argv, "trajectory_planner");
  ros::NodeHandle node_handle;
  ros::Publisher publisher = node_handle.advertise<servo_msgs::KrsServoDegree>("krs_servo", 16);

  ros::Rate rate(10.0);

  TargetPlanner planner;

  while (node_handle.ok()) {
    if (planner.plan())
      for (int id = 0; id < planner.SERVO_ID_MAX; id++)
        publisher.publish(planner.servo[id]);

    rate.sleep();
  }

  return 0;
}
<|endoftext|>


<commit_before>// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.

// Copyright (c) 2019 Romain Janvier and Pierre Moulon

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef OPENMVG_MATCHING_MATCHER_HNSW_HPP
#define OPENMVG_MATCHING_MATCHER_HNSW_HPP

#include <memory>
#ifdef OPENMVG_USE_OPENMP
#include <omp.h>
#endif
#include <typeindex>
#include <vector>

#include "openMVG/matching/matching_interface.hpp"
#include "openMVG/matching/metric.hpp"
#include "openMVG/matching/metric_hnsw.hpp"

#include "third_party/hnswlib/hnswlib.h"

using namespace hnswlib;

namespace openMVG {
namespace matching {

enum HNSWMETRIC {
  L2_HNSW,
  L1_HNSW,
  HAMMING_HNSW
};

// By default compute square(L2 distance).
template <typename Scalar = float, typename Metric = L2<Scalar>, HNSWMETRIC MetricType = HNSWMETRIC::L2_HNSW>
class HNSWMatcher: public ArrayMatcher<Scalar, Metric>
{
public:
  using DistanceType = typename Metric::ResultType;

  HNSWMatcher() = default;
  virtual ~HNSWMatcher()= default;

  /**
   * Build the matching structure
   *
   * \param[in] dataset   Input data.
   * \param[in] nbRows    The number of component.
   * \param[in] dimension Length of the data contained in the dataset.
   *
   * \return True if success.
   */
  bool Build
  (
    const Scalar * dataset,
    int nbRows,
    int dimension
  ) override
  {
    HNSW_metric_.reset();
    HNSW_matcher_.reset();

    if (nbRows < 1)
    {
      return false;
    }

    dimension_ = dimension;

    const std::type_index distance_type(typeid(DistanceType));
    // Here this is tricky since there is no specialization
    switch (MetricType)
    {
    case  HNSWMETRIC::L1_HNSW:
      if (distance_type == typeid(int)) {
        HNSW_metric_.reset(dynamic_cast<SpaceInterface<DistanceType> *>(new custom_hnsw::L1SpaceInteger(dimension)));
      }
      break;
    case  HNSWMETRIC::L2_HNSW:
      if (distance_type == typeid(int)) {
        HNSW_metric_.reset(dynamic_cast<SpaceInterface<DistanceType> *>(new L2SpaceI(dimension)));
      } else
      if (distance_type == typeid(float)) {
        HNSW_metric_.reset(dynamic_cast<SpaceInterface<DistanceType> *>(new L2Space(dimension)));
      }
      break;
    case  HNSWMETRIC::HAMMING_HNSW:
      if (distance_type == typeid(unsigned int)) {
        HNSW_metric_.reset(dynamic_cast<SpaceInterface<DistanceType> *>(new custom_hnsw::HammingSpace<uint8_t>(dimension)));
      }
      break;
    }

    if (!HNSW_metric_) {
      OPENMVG_LOG_ERROR << "HNSW matcher: this type of distance is not handled yet";
      return false;
    }

    HNSW_matcher_.reset(new HierarchicalNSW<DistanceType>(HNSW_metric_.get(), nbRows, 16, 100));

    // add a first point...
    HNSW_matcher_->addPoint(static_cast<const void *>(dataset), static_cast<size_t>(0));
    //...and the others in parallel
    #ifdef OPENMVG_USE_OPENMP
    #pragma omp parallel for
    #endif
    for (int vector_id = 1; vector_id < nbRows; ++vector_id) {
        HNSW_matcher_->addPoint(static_cast<const void *>(dataset + dimension * vector_id), static_cast<size_t>(vector_id));
    }

    return true;
  };

  /**
   * Search the nearest Neighbor of the scalar array query.
   *
   * \param[in]   query     The query array.
   * \param[out]  indice    The indice of array in the dataset that.
   *  have been computed as the nearest array.
   * \param[out]  distance  The distance between the two arrays.
   *
   * \return True if success.
   */
  bool SearchNeighbour
  (
    const Scalar * query,
    int * indice,
    DistanceType * distance
  ) override
  {
    if (!HNSW_matcher_)
      return false;
    HNSW_matcher_->setEf(16); //here we stay conservative but it could probably be lowered in this case (first NN)
    const auto result = HNSW_matcher_->searchKnn(query, 1).top();
    *indice = result.second;
    *distance =  result.first;
    return true;
  }

  /**
   * Search the N nearest Neighbor of the scalar array query.
   *
   * \param[in]   query     The query array.
   * \param[in]   nbQuery   The number of query rows.
   * \param[out]  indices   The corresponding (query, neighbor) indices.
   * \param[out]  distances The distances between the matched arrays.
   * \param[in]  NN        The number of maximal neighbor that will be searched.
   *
   * \return True if success.
   */
  bool SearchNeighbours
  (
    const Scalar * query, int nbQuery,
    IndMatches * pvec_indices,
    std::vector<DistanceType> * pvec_distances,
    size_t NN
  ) override
  {
    if (!HNSW_matcher_)
      return false;
    // EfSearch parameter could not be < NN.
    // -
    // For vectors with dimensionality of approx. 64-128 and for 2 NNs,
    // EfSearch = 16 produces good results in conjonction with other parameters fixed in this file (EfConstruct = 16, M = 100).
    // But nothing has been evaluated on our side for lower / higher dimensionality and for a higher number of NNs.
    // So for now and for NN > 2, EfSearch is fixed to 2 * NNs without a good a priori knowledge.
    // A good value for EfSearch could really depends on the two other parameters (EfConstruct / M).
    if (NN <= 2) {
      HNSW_matcher_->setEf(16);
    } else {
      HNSW_matcher_->setEf(std::max(NN*2, static_cast<size_t>(nbQuery)));
    }
    pvec_indices->resize(nbQuery * NN);
    pvec_distances->resize(nbQuery * NN);
    #ifdef OPENMVG_USE_OPENMP
    #pragma omp parallel for
    #endif
    for (int query_id = 0; query_id < nbQuery; query_id++) {
      auto result = HNSW_matcher_->searchKnn(static_cast<const void *>(query + dimension_ * query_id), NN);
      size_t result_id = NN - 1;
      while(!result.empty())
      {
        const auto & res = result.top();
        const size_t match_id = query_id * NN + result_id;
        pvec_indices->operator[](match_id) = {static_cast<IndexT>(query_id), static_cast<IndexT>(res.second)};
        pvec_distances->operator[](match_id) = res.first;
        result.pop();
        result_id--;
      }
    }
    return true;
  };

private:
  int dimension_;
  std::unique_ptr<SpaceInterface<DistanceType>> HNSW_metric_;
  std::unique_ptr<HierarchicalNSW<DistanceType>> HNSW_matcher_;
};

}  // namespace matching
}  // namespace openMVG

#endif  // OPENMVG_MATCHING_MATCHER_HNSW_HPP
<commit_msg>Typo fix<commit_after>// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.

// Copyright (c) 2019 Romain Janvier and Pierre Moulon

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef OPENMVG_MATCHING_MATCHER_HNSW_HPP
#define OPENMVG_MATCHING_MATCHER_HNSW_HPP

#include <memory>
#ifdef OPENMVG_USE_OPENMP
#include <omp.h>
#endif
#include <typeindex>
#include <vector>

#include "openMVG/matching/matching_interface.hpp"
#include "openMVG/matching/metric.hpp"
#include "openMVG/matching/metric_hnsw.hpp"

#include "third_party/hnswlib/hnswlib.h"

using namespace hnswlib;

namespace openMVG {
namespace matching {

enum HNSWMETRIC {
  L2_HNSW,
  L1_HNSW,
  HAMMING_HNSW
};

// By default compute square(L2 distance).
template <typename Scalar = float, typename Metric = L2<Scalar>, HNSWMETRIC MetricType = HNSWMETRIC::L2_HNSW>
class HNSWMatcher: public ArrayMatcher<Scalar, Metric>
{
public:
  using DistanceType = typename Metric::ResultType;

  HNSWMatcher() = default;
  virtual ~HNSWMatcher()= default;

  /**
   * Build the matching structure
   *
   * \param[in] dataset   Input data.
   * \param[in] nbRows    The number of component.
   * \param[in] dimension Length of the data contained in the dataset.
   *
   * \return True if success.
   */
  bool Build
  (
    const Scalar * dataset,
    int nbRows,
    int dimension
  ) override
  {
    HNSW_metric_.reset();
    HNSW_matcher_.reset();

    if (nbRows < 1)
    {
      return false;
    }

    dimension_ = dimension;

    const std::type_index distance_type(typeid(DistanceType));
    // Here this is tricky since there is no specialization
    switch (MetricType)
    {
    case  HNSWMETRIC::L1_HNSW:
      if (distance_type == typeid(int)) {
        HNSW_metric_.reset(dynamic_cast<SpaceInterface<DistanceType> *>(new custom_hnsw::L1SpaceInteger(dimension)));
      }
      break;
    case  HNSWMETRIC::L2_HNSW:
      if (distance_type == typeid(int)) {
        HNSW_metric_.reset(dynamic_cast<SpaceInterface<DistanceType> *>(new L2SpaceI(dimension)));
      } else
      if (distance_type == typeid(float)) {
        HNSW_metric_.reset(dynamic_cast<SpaceInterface<DistanceType> *>(new L2Space(dimension)));
      }
      break;
    case  HNSWMETRIC::HAMMING_HNSW:
      if (distance_type == typeid(unsigned int)) {
        HNSW_metric_.reset(dynamic_cast<SpaceInterface<DistanceType> *>(new custom_hnsw::HammingSpace<uint8_t>(dimension)));
      }
      break;
    }

    if (!HNSW_metric_) {
      OPENMVG_LOG_ERROR << "HNSW matcher: this type of distance is not handled yet";
      return false;
    }

    HNSW_matcher_.reset(new HierarchicalNSW<DistanceType>(HNSW_metric_.get(), nbRows, 16, 100));

    // add a first point...
    HNSW_matcher_->addPoint(static_cast<const void *>(dataset), static_cast<size_t>(0));
    //...and the others in parallel
    #ifdef OPENMVG_USE_OPENMP
    #pragma omp parallel for
    #endif
    for (int vector_id = 1; vector_id < nbRows; ++vector_id) {
        HNSW_matcher_->addPoint(static_cast<const void *>(dataset + dimension * vector_id), static_cast<size_t>(vector_id));
    }

    return true;
  };

  /**
   * Search the nearest Neighbor of the scalar array query.
   *
   * \param[in]   query     The query array.
   * \param[out]  indice    The indice of array in the dataset that.
   *  have been computed as the nearest array.
   * \param[out]  distance  The distance between the two arrays.
   *
   * \return True if success.
   */
  bool SearchNeighbour
  (
    const Scalar * query,
    int * indice,
    DistanceType * distance
  ) override
  {
    if (!HNSW_matcher_)
      return false;
    HNSW_matcher_->setEf(16); //here we stay conservative but it could probably be lowered in this case (first NN)
    const auto result = HNSW_matcher_->searchKnn(query, 1).top();
    *indice = result.second;
    *distance =  result.first;
    return true;
  }

  /**
   * Search the N nearest Neighbor of the scalar array query.
   *
   * \param[in]   query     The query array.
   * \param[in]   nbQuery   The number of query rows.
   * \param[out]  indices   The corresponding (query, neighbor) indices.
   * \param[out]  distances The distances between the matched arrays.
   * \param[in]  NN        The number of maximal neighbor that will be searched.
   *
   * \return True if success.
   */
  bool SearchNeighbours
  (
    const Scalar * query, int nbQuery,
    IndMatches * pvec_indices,
    std::vector<DistanceType> * pvec_distances,
    size_t NN
  ) override
  {
    if (!HNSW_matcher_)
      return false;
    // EfSearch parameter could not be < NN.
    // -
    // For vectors with dimensionality of approx. 64-128 and for 2 NNs,
    // EfSearch = 16 produces good results in conjunction with other parameters fixed in this file (EfConstruct = 16, M = 100).
    // But nothing has been evaluated on our side for lower / higher dimensionality and for a higher number of NNs.
    // So for now and for NN > 2, EfSearch is fixed to 2 * NNs without a good a priori knowledge.
    // A good value for EfSearch could really depends on the two other parameters (EfConstruct / M).
    if (NN <= 2) {
      HNSW_matcher_->setEf(16);
    } else {
      HNSW_matcher_->setEf(std::max(NN*2, static_cast<size_t>(nbQuery)));
    }
    pvec_indices->resize(nbQuery * NN);
    pvec_distances->resize(nbQuery * NN);
    #ifdef OPENMVG_USE_OPENMP
    #pragma omp parallel for
    #endif
    for (int query_id = 0; query_id < nbQuery; query_id++) {
      auto result = HNSW_matcher_->searchKnn(static_cast<const void *>(query + dimension_ * query_id), NN);
      size_t result_id = NN - 1;
      while(!result.empty())
      {
        const auto & res = result.top();
        const size_t match_id = query_id * NN + result_id;
        pvec_indices->operator[](match_id) = {static_cast<IndexT>(query_id), static_cast<IndexT>(res.second)};
        pvec_distances->operator[](match_id) = res.first;
        result.pop();
        result_id--;
      }
    }
    return true;
  };

private:
  int dimension_;
  std::unique_ptr<SpaceInterface<DistanceType>> HNSW_metric_;
  std::unique_ptr<HierarchicalNSW<DistanceType>> HNSW_matcher_;
};

}  // namespace matching
}  // namespace openMVG

#endif  // OPENMVG_MATCHING_MATCHER_HNSW_HPP
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2017 deipi.com LLC and contributors. All rights reserved.
 *
 * 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 "test_geospatial_query.h"

#include "utils.h"

const std::string path_test_geo = std::string(PATH_TESTS) + "/examples/json/";

const test_geo_t geo_range_tests[] {
	// The range search always is sort by centroids' search.
	{
		// Search: The polygon's search  describes North Dakota.
		"location:..\"POLYGON((-104.026930 48.998427, -104.039833 45.931363, -96.569131 45.946643, -97.228311 48.990383))\"",
		{ "North Dakota", "Bismarck", "Minot", "North Dakota and South Dakota" }
	},
	{
		// Search: The Multipolygon's search  describes North Dakota and South Dakota.
		"location:..\"MULTIPOLYGON(((-104.026930 48.998427, -104.039833 45.931363, -96.569131 45.946643, -97.228311 48.990383)), ((-104.039833 45.931363, -104.050903 43.005315, -96.514283 42.513275, -96.569131 45.946643)))\"",
		{ "North Dakota", "Bismarck", "Minot", "Rapid City", "Wyoming", "North Dakota and South Dakota" }
	},
	{
		// Search: The polygon's search  describes Wyoming.
		"location:..\"POLYGON((-111.038993 44.991571, -111.039795 41.002575, -104.044008 41.000901, -104.055265 44.988552))\"",
		{ "Utah", "Wyoming", "Mountain View, Wyoming", "North Dakota and South Dakota" }
	},
	// Empty regions inside.
	{
		"location:..\"CIRCLE(-100 40, 1000)\"", { }
	}
};

const test_geo_t geo_terms_tests[] {
	// Test for search by terms.
	{
		"location:\"POLYGON((-104.026930 48.998427, -104.039833 45.931363, -96.569131 45.946643, -97.228311 48.990383))\"",
		{ "North Dakota" }
	},
	{
		"location:\"POINT(-100.783990 46.808598)\"",
		{ "Bismarck" }
	},
	{
		"location:\"POINT(-101.293014 48.233434)\"",
		{ "Minot" }
	},
	{
		"location:\"POINT(-103.237178 44.079583)\"",
		{ "Rapid City" }
	},
	{
		"location:\"MULTIPOLYGON(((-114.0475 41, -114.0475 42, -111.01 42, -111.01 41, -114.0475 41)), ((-114.0475 37, -114.0475 41, -109.0475 41, -109.0475 37, -114.0475 37)))\"",
		{ "Utah" }
	},
	{
		"location:\"POLYGON((-111.038993 44.991571, -111.039795 41.002575, -104.044008 41.000901, -104.055265 44.988552))\"",
		{ "Wyoming" }
	},
	{
		"location:\"POINT(-110.34118652 41.2695495)\"",
		{ "Mountain View, Wyoming" }
	},
	{
		"location:\"MULTIPOLYGON(((-104.026930 48.998427, -104.039833 45.931363, -96.569131 45.946643, -97.228311 48.990383)), ((-104.039833 45.931363, -104.050903 43.005315, -96.514283 42.513275, -96.569131 45.946643)))\"",
		{ "North Dakota and South Dakota" }
	},
	{
		"attraction_location:\"POINT(-110.58837891 44.42789588)\"",
		{ "Wyoming" }
	},
	// There are not terms.
	{
		"location:\"POINT(-100 40)\"", { }
	}
};

static DB_Test db_geo(".db_geo.db", std::vector<std::string>({
		path_test_geo + "geo_1.txt",
		path_test_geo + "geo_2.txt",
		path_test_geo + "geo_3.txt",
		path_test_geo + "geo_4.txt",
		path_test_geo + "geo_5.txt",
		path_test_geo + "geo_6.txt",
		path_test_geo + "geo_7.txt",
		path_test_geo + "geo_8.txt"
	}), DB_WRITABLE | DB_SPAWN | DB_NOWAL);

static int make_search(const test_geo_t _tests[], int len) {
	int cont = 0;
	query_field_t query;
	query.offset = 0;
	query.limit = 10;
	query.check_at_least = 0;
	query.spelling = false;
	query.synonyms = false;
	query.is_fuzzy = false;
	query.is_nearest = false;

	for (int i = 0; i < len; ++i) {
		test_geo_t p = _tests[i];
		query.query.clear();
		query.sort.clear();
		query.query.push_back(p.query);
		query.sort.push_back("_id");

		try {
			std::vector<std::string> suggestions;
			auto mset = db_geo.db_handler.get_mset(query, nullptr, nullptr, suggestions);
			if (mset.size() != p.expect_datas.size()) {
				++cont;
				L_ERR(nullptr, "ERROR: Different number of documents. Obtained %d. Expected: %zu.", mset.size(), p.expect_datas.size());
			} else {
				auto it = p.expect_datas.begin();
				for (auto m = mset.begin(); m != mset.end(); ++it, ++m) {
					auto document = db_geo.db_handler.get_document(*m);
					auto region = document.get_obj().at("region").as_string();
					if (region != *it) {
						++cont;
						L_ERR(nullptr, "Different regions. Result: %s Expected: %s", region.c_str(), it->c_str());
					}
				}
			}
		} catch (const std::exception& exc) {
			++cont;
			L_EXC(nullptr, "ERROR: %s\n", exc.what());
		}
	}

	return cont;
}

int geo_range_test() {
	INIT_LOG
	try {
		int cont = make_search(geo_range_tests, arraySize(geo_range_tests));
		if (cont == 0) {
			L_DEBUG(nullptr, "Testing search range geospatials is correct!");
		} else {
			L_ERR(nullptr, "ERROR: Testing search range geospatials has mistakes.");
		}
		RETURN(cont);
	} catch (const Xapian::Error& exc) {
		L_EXC(nullptr, "ERROR: %s", exc.get_msg().c_str());
		RETURN(1);
	} catch (const std::exception& exc) {
		L_EXC(nullptr, "ERROR: %s", exc.what());
		RETURN(1);
	}
}

int geo_terms_test() {
	INIT_LOG
	try {
		int cont = make_search(geo_terms_tests, arraySize(geo_terms_tests));
		if (cont == 0) {
			L_DEBUG(nullptr, "Testing search by geospatial terms is correct!");
		} else {
			L_ERR(nullptr, "ERROR: Testing search by geospatial terms has mistakes.");
		}
		RETURN(cont);
	} catch (const Xapian::Error& exc) {
		L_EXC(nullptr, "ERROR: %s", exc.get_msg().c_str());
		RETURN(1);
	} catch (const std::exception& exc) {
		L_EXC(nullptr, "ERROR: %s", exc.what());
		RETURN(1);
	}
}
<commit_msg>Update tests/test_geospatial_query<commit_after>/*
 * Copyright (C) 2017 deipi.com LLC and contributors. All rights reserved.
 *
 * 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 "test_geospatial_query.h"

#include "utils.h"

const std::string path_test_geo = std::string(PATH_TESTS) + "/examples/json/";

const std::vector<test_geo_t> geo_range_tests({
	// The range search always is sort by centroids' search.
	{
		// Search: The polygon's search  describes North Dakota.
		"location:..\"POLYGON((-104.026930 48.998427, -104.039833 45.931363, -96.569131 45.946643, -97.228311 48.990383))\"",
		{ "North Dakota", "Bismarck", "Minot", "North Dakota and South Dakota" }
	},
	{
		// Search: The Multipolygon's search  describes North Dakota and South Dakota.
		"location:..\"MULTIPOLYGON(((-104.026930 48.998427, -104.039833 45.931363, -96.569131 45.946643, -97.228311 48.990383)), ((-104.039833 45.931363, -104.050903 43.005315, -96.514283 42.513275, -96.569131 45.946643)))\"",
		{ "North Dakota", "Bismarck", "Minot", "Rapid City", "Wyoming", "North Dakota and South Dakota" }
	},
	{
		// Search: The polygon's search  describes Wyoming.
		"location:..\"POLYGON((-111.038993 44.991571, -111.039795 41.002575, -104.044008 41.000901, -104.055265 44.988552))\"",
		{ "Utah", "Wyoming", "Mountain View, Wyoming", "North Dakota and South Dakota" }
	},
	// Empty regions inside.
	{
		"location:..\"CIRCLE(-100 40, 1000)\"", { }
	}
});

const std::vector<test_geo_t> geo_terms_tests({
	// Test for search by terms.
	{
		"location:\"POLYGON((-104.026930 48.998427, -104.039833 45.931363, -96.569131 45.946643, -97.228311 48.990383))\"",
		{ "North Dakota" }
	},
	{
		"location:\"POINT(-100.783990 46.808598)\"",
		{ "Bismarck" }
	},
	{
		"location:\"POINT(-101.293014 48.233434)\"",
		{ "Minot" }
	},
	{
		"location:\"POINT(-103.237178 44.079583)\"",
		{ "Rapid City" }
	},
	{
		"location:\"MULTIPOLYGON(((-114.0475 41, -114.0475 42, -111.01 42, -111.01 41, -114.0475 41)), ((-114.0475 37, -114.0475 41, -109.0475 41, -109.0475 37, -114.0475 37)))\"",
		{ "Utah" }
	},
	{
		"location:\"POLYGON((-111.038993 44.991571, -111.039795 41.002575, -104.044008 41.000901, -104.055265 44.988552))\"",
		{ "Wyoming" }
	},
	{
		"location:\"POINT(-110.34118652 41.2695495)\"",
		{ "Mountain View, Wyoming" }
	},
	{
		"location:\"MULTIPOLYGON(((-104.026930 48.998427, -104.039833 45.931363, -96.569131 45.946643, -97.228311 48.990383)), ((-104.039833 45.931363, -104.050903 43.005315, -96.514283 42.513275, -96.569131 45.946643)))\"",
		{ "North Dakota and South Dakota" }
	},
	{
		"attraction_location:\"POINT(-110.58837891 44.42789588)\"",
		{ "Wyoming" }
	},
	// There are not terms.
	{
		"location:\"POINT(-100 40)\"", { }
	}
});

static DB_Test db_geo(".db_geo.db", std::vector<std::string>({
		path_test_geo + "geo_1.txt",
		path_test_geo + "geo_2.txt",
		path_test_geo + "geo_3.txt",
		path_test_geo + "geo_4.txt",
		path_test_geo + "geo_5.txt",
		path_test_geo + "geo_6.txt",
		path_test_geo + "geo_7.txt",
		path_test_geo + "geo_8.txt"
	}), DB_WRITABLE | DB_SPAWN | DB_NOWAL);

static int make_search(const std::vector<test_geo_t> _tests) {
	int cont = 0;
	query_field_t query;

	for (const auto& test : _tests) {
		query.query.clear();
		query.sort.clear();
		query.query.push_back(test.query);
		query.sort.push_back("_id");

		try {
			std::vector<std::string> suggestions;
			auto mset = db_geo.db_handler.get_mset(query, nullptr, nullptr, suggestions);
			if (mset.size() != test.expect_datas.size()) {
				++cont;
				L_ERR(nullptr, "ERROR: Different number of documents. Obtained %d. Expected: %zu.", mset.size(), test.expect_datas.size());
			} else {
				auto it = test.expect_datas.begin();
				for (auto m = mset.begin(); m != mset.end(); ++it, ++m) {
					auto document = db_geo.db_handler.get_document(*m);
					auto region = document.get_obj().at("region").as_string();
					if (region != *it) {
						++cont;
						L_ERR(nullptr, "Different regions. Result: %s Expected: %s", region.c_str(), it->c_str());
					}
				}
			}
		} catch (const std::exception& exc) {
			++cont;
			L_EXC(nullptr, "ERROR: %s\n", exc.what());
		}
	}

	return cont;
}

int geo_range_test() {
	INIT_LOG
	try {
		int cont = make_search(geo_range_tests);
		if (cont == 0) {
			L_DEBUG(nullptr, "Testing search range geospatials is correct!");
		} else {
			L_ERR(nullptr, "ERROR: Testing search range geospatials has mistakes.");
		}
		RETURN(cont);
	} catch (const Xapian::Error& exc) {
		L_EXC(nullptr, "ERROR: %s", exc.get_msg().c_str());
		RETURN(1);
	} catch (const std::exception& exc) {
		L_EXC(nullptr, "ERROR: %s", exc.what());
		RETURN(1);
	}
}

int geo_terms_test() {
	INIT_LOG
	try {
		int cont = make_search(geo_terms_tests);
		if (cont == 0) {
			L_DEBUG(nullptr, "Testing search by geospatial terms is correct!");
		} else {
			L_ERR(nullptr, "ERROR: Testing search by geospatial terms has mistakes.");
		}
		RETURN(cont);
	} catch (const Xapian::Error& exc) {
		L_EXC(nullptr, "ERROR: %s", exc.get_msg().c_str());
		RETURN(1);
	} catch (const std::exception& exc) {
		L_EXC(nullptr, "ERROR: %s", exc.what());
		RETURN(1);
	}
}
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "invalidargumentexception.h"
#include <QString>

/*!
\class QmlDesigner::InvalidArgumentException
\ingroup CoreExceptions
\brief Exception for a invalid argument

*/
namespace QmlDesigner {

/*!
\brief Constructor

\param line use the __LINE__ macro
\param function use the __FUNCTION__ or the Q_FUNC_INFO macro
\param file use the __FILE__ macro
*/
InvalidArgumentException::InvalidArgumentException(int line,
                                                   const QString &function,
                                                   const QString &file,
                                                   const QString &argument)
 : Exception(line, function, file), m_argument(argument)
{

}

QString InvalidArgumentException::description() const
{
    if (function() == "createNode")
        return QString(QObject::tr("Failed to create item of type %1")).arg(m_argument);

    return Exception::description();
}

/*!
\brief Returns the type of this exception

\returns the type as a string
*/
QString InvalidArgumentException::type() const
{
    return "InvalidArgumentException";
}

/*!
\brief Returns the argument of this exception

\returns the argument as a string
*/
QString InvalidArgumentException::argument() const
{
    return m_argument;
}

}
<commit_msg>tr()-glitch.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "invalidargumentexception.h"
#include <QString>
#include <QCoreApplication>
/*!
\class QmlDesigner::InvalidArgumentException
\ingroup CoreExceptions
\brief Exception for a invalid argument

*/
namespace QmlDesigner {

/*!
\brief Constructor

\param line use the __LINE__ macro
\param function use the __FUNCTION__ or the Q_FUNC_INFO macro
\param file use the __FILE__ macro
*/
InvalidArgumentException::InvalidArgumentException(int line,
                                                   const QString &function,
                                                   const QString &file,
                                                   const QString &argument)
 : Exception(line, function, file), m_argument(argument)
{

}

QString InvalidArgumentException::description() const
{
    if (function() == "createNode")
        return QCoreApplication::translate("QmlDesigner::InvalidArgumentException", "Failed to create item of type %1").arg(m_argument);

    return Exception::description();
}

/*!
\brief Returns the type of this exception

\returns the type as a string
*/
QString InvalidArgumentException::type() const
{
    return "InvalidArgumentException";
}

/*!
\brief Returns the argument of this exception

\returns the argument as a string
*/
QString InvalidArgumentException::argument() const
{
    return m_argument;
}

}
<|endoftext|>


<commit_before>#include "Character.h"
#include "Packet.h"
#include "NNNetworkSystem.h"

CCharacter::CCharacter(void):m_CharacterSprite(NULL)
{
	AnimationImageInfo idleAnimationImageInfo = {2, L"idle",{10.f,10.f}};
	m_AnimationImageInfo.insert( std::map< CharacterState, AnimationImageInfo >::value_type(IDLE,idleAnimationImageInfo));

	AnimationImageInfo walkAnimationImageInfo = {2, L"walk",{20.f,10.f}};
	m_AnimationImageInfo.insert( std::map< CharacterState, AnimationImageInfo >::value_type(WALK,walkAnimationImageInfo));

	AnimationImageInfo attackAnimationImageInfo = {2, L"attack",{10.f,10.f}};
	m_AnimationImageInfo.insert( std::map< CharacterState, AnimationImageInfo >::value_type(ATTACK,attackAnimationImageInfo));

	AnimationImageInfo dieAnimationImageInfo = {2, L"die",{10.f,10.f}};
	m_AnimationImageInfo.insert( std::map< CharacterState, AnimationImageInfo >::value_type(DIE,dieAnimationImageInfo));

	m_AnimationFrameTime = 0.f;

	TransState(IDLE);

	//NNAudioSystem::GetInstance()->AddEffectSound( "Effect", L"Sound/effect.wav" );
	//NNAudioSystem::GetInstance()->AddEffectSound( "Effect1", L"Sound/effect1.mp3" );

}

CCharacter::~CCharacter(void)
{
}

void CCharacter::TransState(CharacterState state)
{
	m_CharacterState = state;
	m_AnimationFrameTime = 0;
	m_NowFrame = 0;
	AnimationImageInfo nowAnimationImageInfo = m_AnimationImageInfo.find(m_CharacterState)->second;
	if( m_CharacterSprite != NULL)
	{
		RemoveChild(m_CharacterSprite);
	}
	WCHAR buff[1024];
	swprintf_s(buff,L"Sprite/%s_%d.png",nowAnimationImageInfo.imagePrefix.c_str(),m_NowFrame);
	std::wstring framePath = buff;//L"Sprite/" + nowAnimationImageInfo.imagePrefix + "_";
	m_CharacterSprite = NNSprite::Create(framePath);
	SetCenter(m_CharacterSprite->GetImageWidth()/2.f, m_CharacterSprite->GetImageHeight()/2.f);
	AddChild(m_CharacterSprite);
}

void CCharacter::Update( float dTime)
{

	//Animation With m_State
	AnimationImageInfo nowAnimationImageInfo = m_AnimationImageInfo.find(m_CharacterState)->second;

	//Calculate 'Now Frame' With integration dtime
	m_AnimationFrameTime += dTime;
	bool isFrameChange = false;
	while(nowAnimationImageInfo.frameDelay[m_NowFrame] < m_AnimationFrameTime)
	{
		m_AnimationFrameTime -= nowAnimationImageInfo.frameDelay[m_NowFrame];
		m_NowFrame = (m_NowFrame+1)%nowAnimationImageInfo.totalFrameCount;
		isFrameChange = true;
	}
	if(isFrameChange= true)
	{
		RemoveChild(m_CharacterSprite);
		WCHAR buff[1024];
		swprintf_s(buff,L"Sprite/%s_%d.png",nowAnimationImageInfo.imagePrefix.c_str(),m_NowFrame);
		std::wstring framePath = buff;
		m_CharacterSprite = NNSprite::Create(framePath);
		SetCenter(m_CharacterSprite->GetImageWidth()/2.f, m_CharacterSprite->GetImageHeight()/2.f);
		AddChild(m_CharacterSprite);
	}

	//Check Moving Input, and set Position to d
	if ( NNInputSystem::GetInstance()->GetKeyState( 'A' ) == KEY_DOWN  ||
		NNInputSystem::GetInstance()->GetKeyState( 'A' ) == KEY_PRESSED)
	{
		//Left
		SetPosition( GetPosition() + NNPoint( cos((GetRotation() + -90.f)/180.f*3.14f), sin((GetRotation() -90.f)/180.f*3.14f)) * dTime * 100.f );
	}
	if ( NNInputSystem::GetInstance()->GetKeyState( 'D' ) == KEY_DOWN  ||
		NNInputSystem::GetInstance()->GetKeyState( 'D' ) == KEY_PRESSED)
	{
		//Right
		SetPosition( GetPosition() + NNPoint( cos((GetRotation() + +90.f)/180.f*3.14f), sin((GetRotation() +90.f)/180.f*3.14f)) * dTime * 100.f );
	}
	if ( NNInputSystem::GetInstance()->GetKeyState( 'W' ) == KEY_DOWN  ||
		NNInputSystem::GetInstance()->GetKeyState( 'W' ) == KEY_PRESSED)
	{
		//UP
		SetPosition( GetPosition() + NNPoint( cos((GetRotation())/180.f*3.14f), sin((GetRotation())/180.f*3.14f)) * dTime * 100.f );
	}
	if ( NNInputSystem::GetInstance()->GetKeyState( 'S' ) == KEY_DOWN  ||
		NNInputSystem::GetInstance()->GetKeyState( 'S' ) == KEY_PRESSED)
	{
		//Down
		SetPosition( GetPosition() + NNPoint( cos((GetRotation() + 180.f)/180.f*3.14f), sin((GetRotation() + 180.f)/180.f*3.14f)) * dTime * 100.f );
	}

	if ( NNInputSystem::GetInstance()->GetKeyState( '1' ) == KEY_DOWN )
	{
		TransState(WALK);
	}
	if ( NNInputSystem::GetInstance()->GetKeyState( '2' ) == KEY_DOWN )
	{
		TransState(IDLE);
	}
	if ( NNInputSystem::GetInstance()->GetKeyState( '3' ) == KEY_DOWN )
	{
		TransState(ATTACK);
	}
	if ( NNInputSystem::GetInstance()->GetKeyState( '4' ) == KEY_DOWN )
	{
		TransState(DIE);
	}
	if ( NNInputSystem::GetInstance()->GetKeyState( '5' ) == KEY_DOWN )
	{
//		NNAudioSystem::GetInstance()->PlayEffectSound( "Effect" );
	}
	if ( NNInputSystem::GetInstance()->GetKeyState( '6' ) == KEY_DOWN )
{
	//	NNAudioSystem::GetInstance()->PlayEffectSound( "Effect1" );
	}
	if ( NNInputSystem::GetInstance()->GetKeyState( '7' ) == KEY_DOWN )
	{
		ChatBroadcastRequest CBR = ChatBroadcastRequest();
		strcpy_s(CBR.m_Chat,"hihi");
	//	NNNetworkSystem::GetInstance()->Send(&CBR);
	}
	//Change Image By now Frame.
	NNPoint mousePoint = NNInputSystem::GetInstance()->GetMousePosition();
	WCHAR buff[1024];
	swprintf_s(buff,L"%f / %f",mousePoint.GetX(),m_CharacterSprite->GetRotation());//mousePoint.GetY());
	SetCenter(m_CharacterSprite->GetImageWidth()/2.f,m_CharacterSprite->GetImageHeight()/2.f);
	SetRotation(atan2f(mousePoint.GetY() - 300.f, mousePoint.GetX() - 400.f) * 180.0f / 3.14f);
}
void CCharacter::Render()
{
	NNObject::Render();
}<commit_msg>움직임을 GameScene에서 하도록<commit_after>#include "Character.h"
#include "Packet.h"
#include "NNNetworkSystem.h"

CCharacter::CCharacter(void):m_CharacterSprite(NULL)
{
	AnimationImageInfo idleAnimationImageInfo = {2, L"idle",{10.f,10.f}};
	m_AnimationImageInfo.insert( std::map< CharacterState, AnimationImageInfo >::value_type(IDLE,idleAnimationImageInfo));

	AnimationImageInfo walkAnimationImageInfo = {2, L"walk",{20.f,10.f}};
	m_AnimationImageInfo.insert( std::map< CharacterState, AnimationImageInfo >::value_type(WALK,walkAnimationImageInfo));

	AnimationImageInfo attackAnimationImageInfo = {2, L"attack",{10.f,10.f}};
	m_AnimationImageInfo.insert( std::map< CharacterState, AnimationImageInfo >::value_type(ATTACK,attackAnimationImageInfo));

	AnimationImageInfo dieAnimationImageInfo = {2, L"die",{10.f,10.f}};
	m_AnimationImageInfo.insert( std::map< CharacterState, AnimationImageInfo >::value_type(DIE,dieAnimationImageInfo));

	m_AnimationFrameTime = 0.f;

	TransState(IDLE);

	//NNAudioSystem::GetInstance()->AddEffectSound( "Effect", L"Sound/effect.wav" );
	//NNAudioSystem::GetInstance()->AddEffectSound( "Effect1", L"Sound/effect1.mp3" );

}

CCharacter::~CCharacter(void)
{
}

void CCharacter::TransState(CharacterState state)
{
	m_CharacterState = state;
	m_AnimationFrameTime = 0;
	m_NowFrame = 0;
	AnimationImageInfo nowAnimationImageInfo = m_AnimationImageInfo.find(m_CharacterState)->second;
	if( m_CharacterSprite != NULL)
	{
		RemoveChild(m_CharacterSprite);
	}
	WCHAR buff[1024];
	swprintf_s(buff,L"Sprite/%s_%d.png",nowAnimationImageInfo.imagePrefix.c_str(),m_NowFrame);
	std::wstring framePath = buff;//L"Sprite/" + nowAnimationImageInfo.imagePrefix + "_";
	m_CharacterSprite = NNSprite::Create(framePath);
	SetCenter(m_CharacterSprite->GetImageWidth()/2.f, m_CharacterSprite->GetImageHeight()/2.f);
	AddChild(m_CharacterSprite);
}

void CCharacter::Update( float dTime)
{

	//Animation With m_State
	AnimationImageInfo nowAnimationImageInfo = m_AnimationImageInfo.find(m_CharacterState)->second;

	//Calculate 'Now Frame' With integration dtime
	m_AnimationFrameTime += dTime;
	bool isFrameChange = false;
	while(nowAnimationImageInfo.frameDelay[m_NowFrame] < m_AnimationFrameTime)
	{
		m_AnimationFrameTime -= nowAnimationImageInfo.frameDelay[m_NowFrame];
		m_NowFrame = (m_NowFrame+1)%nowAnimationImageInfo.totalFrameCount;
		isFrameChange = true;
	}
	if(isFrameChange= true)
	{
		RemoveChild(m_CharacterSprite);
		WCHAR buff[1024];
		swprintf_s(buff,L"Sprite/%s_%d.png",nowAnimationImageInfo.imagePrefix.c_str(),m_NowFrame);
		std::wstring framePath = buff;
		m_CharacterSprite = NNSprite::Create(framePath);
		SetCenter(m_CharacterSprite->GetImageWidth()/2.f, m_CharacterSprite->GetImageHeight()/2.f);
		AddChild(m_CharacterSprite);
	}

	//Change Image By now Frame.
	NNPoint mousePoint = NNInputSystem::GetInstance()->GetMousePosition();
	WCHAR buff[1024];
	swprintf_s(buff,L"%f / %f",mousePoint.GetX(),m_CharacterSprite->GetRotation());//mousePoint.GetY());
	SetCenter(m_CharacterSprite->GetImageWidth()/2.f,m_CharacterSprite->GetImageHeight()/2.f);
	SetRotation(atan2f(mousePoint.GetY() - 300.f, mousePoint.GetX() - 400.f) * 180.0f / 3.14f);
}
void CCharacter::Render()
{
	NNObject::Render();
}<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_PLAYGROUND_OPERATORS_RECONSTRUCTIONS_HH
#define DUNE_GDT_PLAYGROUND_OPERATORS_RECONSTRUCTIONS_HH

#include <dune/gdt/playground/localevaluation/swipdg.hh>
#include <dune/gdt/operators/fluxreconstruction.hh>

namespace Dune {
namespace GDT {
namespace Operators {

template <class GridViewType, class DiffusionFactorType, class DiffusionTensorType>
class DiffusiveFluxReconstruction
{
  static_assert(GridViewType::dimension == 2, "Only implemented for dimDomain 2 at the moment!");
  static_assert(std::is_base_of<Stuff::IsLocalizableFunction, DiffusionFactorType>::value,
                "DiffusionFactorType has to be tagged as Stuff::IsLocalizableFunction!");
  static_assert(std::is_base_of<Stuff::IsLocalizableFunction, DiffusionTensorType>::value,
                "DiffusionTensorType has to be tagged as Stuff::IsLocalizableFunction!");

public:
  typedef typename GridViewType::template Codim<0>::Entity EntityType;
  typedef typename GridViewType::ctype DomainFieldType;
  static const unsigned int dimDomain = GridViewType::dimension;
  typedef typename DiffusionFactorType::RangeFieldType FieldType;
  typedef typename DiffusionFactorType::DomainType DomainType;

private:
  static_assert(dimDomain == 2, "Not implemented!");

public:
  DiffusiveFluxReconstruction(const GridViewType& grid_view, const DiffusionFactorType& diffusion_factor,
                              const DiffusionTensorType& diffusion_tensor)
    : grid_view_(grid_view)
    , diffusion_factor_(diffusion_factor)
    , diffusion_tensor_(diffusion_tensor)
  {
  }

  template <class GV, class V>
  void apply(const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, FieldType, 1>& source,
             DiscreteFunction<Spaces::RaviartThomas::PdelabBased<GV, 0, FieldType, dimDomain>, V>& range) const
  {
    const auto& rtn0_space   = range.space();
    auto& range_vector       = range.vector();
    const FieldType infinity = std::numeric_limits<FieldType>::infinity();
    for (size_t ii = 0; ii < range_vector.size(); ++ii)
      range_vector[ii] = infinity;
    const LocalEvaluation::SWIPDG::Inner<DiffusionFactorType, DiffusionTensorType> inner_evaluation(diffusion_factor_,
                                                                                diffusion_tensor_);
    const LocalEvaluation::SWIPDG::BoundaryLHS<DiffusionFactorType, DiffusionTensorType> boundary_evaluation(
        diffusion_factor_, diffusion_tensor_);
    const Stuff::Functions::Constant<EntityType, DomainFieldType, dimDomain, FieldType, 1> constant_one(1);
    DomainType normal(0);
    DomainType xx_entity(0);
    DynamicMatrix<FieldType> tmp_matrix(1, 1, 0);
    DynamicMatrix<FieldType> tmp_matrix_en_en(1, 1, 0);
    DynamicMatrix<FieldType> tmp_matrix_en_ne(1, 1, 0);
    std::vector<
        typename Spaces::RaviartThomas::PdelabBased<GV, 0, FieldType, dimDomain>::BaseFunctionSetType::RangeType>
        basis_values(
            rtn0_space.mapper().maxNumDofs(),
            typename Spaces::RaviartThomas::PdelabBased<GV, 0, FieldType, dimDomain>::BaseFunctionSetType::RangeType(
                0));
    // walk the grid
    const auto entity_it_end = grid_view_.template end<0>();
    for (auto entity_it = grid_view_.template begin<0>(); entity_it != entity_it_end; ++entity_it) {
      const auto& entity            = *entity_it;
      const auto local_DoF_indices  = rtn0_space.local_DoF_indices(entity);
      const auto global_DoF_indices = rtn0_space.mapper().globalIndices(entity);
      assert(global_DoF_indices.size() == local_DoF_indices.size());
      const auto local_diffusion_factor = diffusion_factor_.local_function(entity);
      const auto local_diffusion_tensor = diffusion_tensor_.local_function(entity);
      const auto local_source           = source.local_function(entity);
      const auto local_basis            = rtn0_space.base_function_set(entity);
      const auto local_constant_one     = constant_one.local_function(entity);
      // walk the intersections
      const auto intersection_it_end = grid_view_.iend(entity);
      for (auto intersection_it = grid_view_.ibegin(entity); intersection_it != intersection_it_end;
           ++intersection_it) {
        const auto& intersection = *intersection_it;
        if (intersection.neighbor() && !intersection.boundary()) {
          const auto neighbor_ptr = intersection.outside();
          const auto& neighbor = *neighbor_ptr;
          if (grid_view_.indexSet().index(entity) < grid_view_.indexSet().index(neighbor)) {
            const auto local_diffusion_factor_neighbor = diffusion_factor_.local_function(neighbor);
            const auto local_diffusion_tensor_neighbor = diffusion_tensor_.local_function(neighbor);
            const auto local_source_neighbor           = source.local_function(neighbor);
            const auto local_constant_one_neighbor     = constant_one.local_function(neighbor);
            const size_t local_intersection_index      = intersection.indexInInside();
            const size_t local_DoF_index               = local_DoF_indices[local_intersection_index];
            // do a face quadrature
            FieldType lhs                = 0;
            FieldType rhs                = 0;
            const size_t integrand_order = inner_evaluation.order(*local_diffusion_factor,
                                                                  *local_diffusion_tensor,
                                                                  *local_diffusion_factor_neighbor,
                                                                  *local_diffusion_tensor_neighbor,
                                                                  *local_constant_one,
                                                                  *local_source,
                                                                  *local_constant_one_neighbor,
                                                                  *local_source_neighbor);
            assert(integrand_order < std::numeric_limits<int>::max());
            const auto& quadrature =
                QuadratureRules<DomainFieldType, dimDomain - 1>::rule(intersection.type(), int(integrand_order));
            const auto quadrature_it_end = quadrature.end();
            for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) {
              const auto& xx_intersection        = quadrature_it->position();
              xx_entity                          = intersection.geometryInInside().global(xx_intersection);
              normal                             = intersection.unitOuterNormal(xx_intersection);
              const FieldType integration_factor = intersection.geometry().integrationElement(xx_intersection);
              const FieldType weigth             = quadrature_it->weight();
              // evalaute
              local_basis.evaluate(xx_entity, basis_values);
              const auto& basis_value = basis_values[local_DoF_index];
              tmp_matrix *= 0.0;
              tmp_matrix_en_en *= 0.0;
              tmp_matrix_en_ne *= 0.0;
              inner_evaluation.evaluate(*local_diffusion_factor,
                                        *local_diffusion_tensor,
                                        *local_diffusion_factor_neighbor,
                                        *local_diffusion_tensor_neighbor,
                                        *local_constant_one,
                                        *local_source,
                                        *local_constant_one_neighbor,
                                        *local_source_neighbor,
                                        intersection,
                                        xx_intersection,
                                        tmp_matrix_en_en, // <- we are interested in this one
                                        tmp_matrix,
                                        tmp_matrix_en_ne, // <- and this one
                                        tmp_matrix);
              // compute integrals
              assert(tmp_matrix_en_en.rows() >= 1);
              assert(tmp_matrix_en_en.cols() >= 1);
              assert(tmp_matrix_en_ne.rows() >= 1);
              assert(tmp_matrix_en_ne.cols() >= 1);
              lhs += integration_factor * weigth * (basis_value * normal);
              rhs += integration_factor * weigth * (tmp_matrix_en_en[0][0] + tmp_matrix_en_ne[0][0]);
            } // do a face quadrature
            // set DoF
            const size_t global_DoF_index = global_DoF_indices[local_DoF_index];
            // and make sure we are the first to do so
            assert(!(range_vector[global_DoF_index] < infinity));
            range_vector[global_DoF_index] = rhs / lhs;
          }
        } else if (intersection.boundary() && !intersection.neighbor()) {
          const size_t local_intersection_index = intersection.indexInInside();
          const size_t local_DoF_index          = local_DoF_indices[local_intersection_index];
          // do a face quadrature
          FieldType lhs                = 0;
          FieldType rhs                = 0;
          const size_t integrand_order = boundary_evaluation.order(
              *local_diffusion_factor, *local_diffusion_tensor, *local_source, *local_constant_one);
          assert(integrand_order < std::numeric_limits<int>::max());
          const auto& quadrature =
              QuadratureRules<DomainFieldType, dimDomain - 1>::rule(intersection.type(), int(integrand_order));
          const auto quadrature_it_end = quadrature.end();
          for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) {
            const auto xx_intersection         = quadrature_it->position();
            normal                             = intersection.unitOuterNormal(xx_intersection);
            const FieldType integration_factor = intersection.geometry().integrationElement(xx_intersection);
            const FieldType weigth             = quadrature_it->weight();
            xx_entity                          = intersection.geometryInInside().global(xx_intersection);
            // evalaute
            local_basis.evaluate(xx_entity, basis_values);
            const auto& basis_value = basis_values[local_DoF_index];
            tmp_matrix *= 0.0;
            boundary_evaluation.evaluate(*local_diffusion_factor,
                                         *local_diffusion_tensor,
                                         *local_constant_one,
                                         *local_source,
                                         intersection,
                                         xx_intersection,
                                         tmp_matrix);
            // compute integrals
            assert(tmp_matrix.rows() >= 1);
            assert(tmp_matrix.cols() >= 1);
            lhs += integration_factor * weigth * (basis_value * normal);
            rhs += integration_factor * weigth * tmp_matrix[0][0];
          } // do a face quadrature
          // set DoF
          const size_t global_DoF_index = global_DoF_indices[local_DoF_index];
          assert(!(range_vector[global_DoF_index] < infinity));
          // and make sure we are the first to do so
          range_vector[global_DoF_index] = rhs / lhs;
        } else
          DUNE_THROW(Stuff::Exceptions::internal_error, "Unknown intersection type!");
      } // walk the intersections
    } // walk the grid
  } // ... apply(...)

private:
  const GridViewType& grid_view_;
  const DiffusionFactorType& diffusion_factor_;
  const DiffusionTensorType& diffusion_tensor_;
}; // class DiffusiveFluxReconstruction

} // namespace Operators
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_PLAYGROUND_OPERATORS_RECONSTRUCTIONS_HH
<commit_msg>[operators.fluxreconstruction] add over_integrate<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_PLAYGROUND_OPERATORS_RECONSTRUCTIONS_HH
#define DUNE_GDT_PLAYGROUND_OPERATORS_RECONSTRUCTIONS_HH

#include <boost/numeric/conversion/cast.hpp>

#include <dune/gdt/playground/localevaluation/swipdg.hh>
#include <dune/gdt/operators/fluxreconstruction.hh>

namespace Dune {
namespace GDT {
namespace Operators {

template <class GridViewType, class DiffusionFactorType, class DiffusionTensorType>
class DiffusiveFluxReconstruction
{
  static_assert(GridViewType::dimension == 2, "Only implemented for dimDomain 2 at the moment!");
  static_assert(std::is_base_of<Stuff::IsLocalizableFunction, DiffusionFactorType>::value,
                "DiffusionFactorType has to be tagged as Stuff::IsLocalizableFunction!");
  static_assert(std::is_base_of<Stuff::IsLocalizableFunction, DiffusionTensorType>::value,
                "DiffusionTensorType has to be tagged as Stuff::IsLocalizableFunction!");

public:
  typedef typename GridViewType::template Codim<0>::Entity EntityType;
  typedef typename GridViewType::ctype DomainFieldType;
  static const unsigned int dimDomain = GridViewType::dimension;
  typedef typename DiffusionFactorType::RangeFieldType FieldType;
  typedef typename DiffusionFactorType::DomainType DomainType;

private:
  static_assert(dimDomain == 2, "Not implemented!");

public:
  DiffusiveFluxReconstruction(const GridViewType& grid_view, const DiffusionFactorType& diffusion_factor,
                              const DiffusionTensorType& diffusion_tensor, const size_t over_integrate = 0)
    : grid_view_(grid_view)
    , diffusion_factor_(diffusion_factor)
    , diffusion_tensor_(diffusion_tensor)
    , over_integrate_(over_integrate)
  {
  }

  template <class GV, class V>
  void apply(const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, FieldType, 1>& source,
             DiscreteFunction<Spaces::RaviartThomas::PdelabBased<GV, 0, FieldType, dimDomain>, V>& range) const
  {
    const auto& rtn0_space   = range.space();
    auto& range_vector       = range.vector();
    const FieldType infinity = std::numeric_limits<FieldType>::infinity();
    for (size_t ii = 0; ii < range_vector.size(); ++ii)
      range_vector[ii] = infinity;
    const LocalEvaluation::SWIPDG::Inner<DiffusionFactorType, DiffusionTensorType> inner_evaluation(diffusion_factor_,
                                                                                diffusion_tensor_);
    const LocalEvaluation::SWIPDG::BoundaryLHS<DiffusionFactorType, DiffusionTensorType> boundary_evaluation(
        diffusion_factor_, diffusion_tensor_);
    const Stuff::Functions::Constant<EntityType, DomainFieldType, dimDomain, FieldType, 1> constant_one(1);
    DomainType normal(0);
    DomainType xx_entity(0);
    DynamicMatrix<FieldType> tmp_matrix(1, 1, 0);
    DynamicMatrix<FieldType> tmp_matrix_en_en(1, 1, 0);
    DynamicMatrix<FieldType> tmp_matrix_en_ne(1, 1, 0);
    std::vector<
        typename Spaces::RaviartThomas::PdelabBased<GV, 0, FieldType, dimDomain>::BaseFunctionSetType::RangeType>
        basis_values(
            rtn0_space.mapper().maxNumDofs(),
            typename Spaces::RaviartThomas::PdelabBased<GV, 0, FieldType, dimDomain>::BaseFunctionSetType::RangeType(
                0));
    // walk the grid
    const auto entity_it_end = grid_view_.template end<0>();
    for (auto entity_it = grid_view_.template begin<0>(); entity_it != entity_it_end; ++entity_it) {
      const auto& entity            = *entity_it;
      const auto local_DoF_indices  = rtn0_space.local_DoF_indices(entity);
      const auto global_DoF_indices = rtn0_space.mapper().globalIndices(entity);
      assert(global_DoF_indices.size() == local_DoF_indices.size());
      const auto local_diffusion_factor = diffusion_factor_.local_function(entity);
      const auto local_diffusion_tensor = diffusion_tensor_.local_function(entity);
      const auto local_source           = source.local_function(entity);
      const auto local_basis            = rtn0_space.base_function_set(entity);
      const auto local_constant_one     = constant_one.local_function(entity);
      // walk the intersections
      const auto intersection_it_end = grid_view_.iend(entity);
      for (auto intersection_it = grid_view_.ibegin(entity); intersection_it != intersection_it_end;
           ++intersection_it) {
        const auto& intersection = *intersection_it;
        if (intersection.neighbor() && !intersection.boundary()) {
          const auto neighbor_ptr = intersection.outside();
          const auto& neighbor = *neighbor_ptr;
          if (grid_view_.indexSet().index(entity) < grid_view_.indexSet().index(neighbor)) {
            const auto local_diffusion_factor_neighbor = diffusion_factor_.local_function(neighbor);
            const auto local_diffusion_tensor_neighbor = diffusion_tensor_.local_function(neighbor);
            const auto local_source_neighbor           = source.local_function(neighbor);
            const auto local_constant_one_neighbor     = constant_one.local_function(neighbor);
            const size_t local_intersection_index      = intersection.indexInInside();
            const size_t local_DoF_index               = local_DoF_indices[local_intersection_index];
            // do a face quadrature
            FieldType lhs                = 0;
            FieldType rhs                = 0;
            const size_t integrand_order = inner_evaluation.order(*local_diffusion_factor,
                                                                  *local_diffusion_tensor,
                                                                  *local_diffusion_factor_neighbor,
                                                                  *local_diffusion_tensor_neighbor,
                                                                  *local_constant_one,
                                                                  *local_source,
                                                                  *local_constant_one_neighbor,
                                                                  *local_source_neighbor);
            const auto& quadrature = QuadratureRules<DomainFieldType, dimDomain - 1>::rule(
                intersection.type(), boost::numeric_cast<int>(integrand_order + over_integrate_));
            const auto quadrature_it_end = quadrature.end();
            for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) {
              const auto& xx_intersection        = quadrature_it->position();
              xx_entity                          = intersection.geometryInInside().global(xx_intersection);
              normal                             = intersection.unitOuterNormal(xx_intersection);
              const FieldType integration_factor = intersection.geometry().integrationElement(xx_intersection);
              const FieldType weigth             = quadrature_it->weight();
              // evalaute
              local_basis.evaluate(xx_entity, basis_values);
              const auto& basis_value = basis_values[local_DoF_index];
              tmp_matrix *= 0.0;
              tmp_matrix_en_en *= 0.0;
              tmp_matrix_en_ne *= 0.0;
              inner_evaluation.evaluate(*local_diffusion_factor,
                                        *local_diffusion_tensor,
                                        *local_diffusion_factor_neighbor,
                                        *local_diffusion_tensor_neighbor,
                                        *local_constant_one,
                                        *local_source,
                                        *local_constant_one_neighbor,
                                        *local_source_neighbor,
                                        intersection,
                                        xx_intersection,
                                        tmp_matrix_en_en, // <- we are interested in this one
                                        tmp_matrix,
                                        tmp_matrix_en_ne, // <- and this one
                                        tmp_matrix);
              // compute integrals
              assert(tmp_matrix_en_en.rows() >= 1);
              assert(tmp_matrix_en_en.cols() >= 1);
              assert(tmp_matrix_en_ne.rows() >= 1);
              assert(tmp_matrix_en_ne.cols() >= 1);
              lhs += integration_factor * weigth * (basis_value * normal);
              rhs += integration_factor * weigth * (tmp_matrix_en_en[0][0] + tmp_matrix_en_ne[0][0]);
            } // do a face quadrature
            // set DoF
            const size_t global_DoF_index = global_DoF_indices[local_DoF_index];
            // and make sure we are the first to do so
            assert(!(range_vector[global_DoF_index] < infinity));
            range_vector[global_DoF_index] = rhs / lhs;
          }
        } else if (intersection.boundary() && !intersection.neighbor()) {
          const size_t local_intersection_index = intersection.indexInInside();
          const size_t local_DoF_index          = local_DoF_indices[local_intersection_index];
          // do a face quadrature
          FieldType lhs                = 0;
          FieldType rhs                = 0;
          const size_t integrand_order = boundary_evaluation.order(
              *local_diffusion_factor, *local_diffusion_tensor, *local_source, *local_constant_one);
          const auto& quadrature = QuadratureRules<DomainFieldType, dimDomain - 1>::rule(
              intersection.type(), boost::numeric_cast<int>(integrand_order + over_integrate_));
          const auto quadrature_it_end = quadrature.end();
          for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) {
            const auto xx_intersection         = quadrature_it->position();
            normal                             = intersection.unitOuterNormal(xx_intersection);
            const FieldType integration_factor = intersection.geometry().integrationElement(xx_intersection);
            const FieldType weigth             = quadrature_it->weight();
            xx_entity                          = intersection.geometryInInside().global(xx_intersection);
            // evalaute
            local_basis.evaluate(xx_entity, basis_values);
            const auto& basis_value = basis_values[local_DoF_index];
            tmp_matrix *= 0.0;
            boundary_evaluation.evaluate(*local_diffusion_factor,
                                         *local_diffusion_tensor,
                                         *local_constant_one,
                                         *local_source,
                                         intersection,
                                         xx_intersection,
                                         tmp_matrix);
            // compute integrals
            assert(tmp_matrix.rows() >= 1);
            assert(tmp_matrix.cols() >= 1);
            lhs += integration_factor * weigth * (basis_value * normal);
            rhs += integration_factor * weigth * tmp_matrix[0][0];
          } // do a face quadrature
          // set DoF
          const size_t global_DoF_index = global_DoF_indices[local_DoF_index];
          assert(!(range_vector[global_DoF_index] < infinity));
          // and make sure we are the first to do so
          range_vector[global_DoF_index] = rhs / lhs;
        } else
          DUNE_THROW(Stuff::Exceptions::internal_error, "Unknown intersection type!");
      } // walk the intersections
    } // walk the grid
  } // ... apply(...)

private:
  const GridViewType& grid_view_;
  const DiffusionFactorType& diffusion_factor_;
  const DiffusionTensorType& diffusion_tensor_;
  const size_t over_integrate_;
}; // class DiffusiveFluxReconstruction

} // namespace Operators
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_PLAYGROUND_OPERATORS_RECONSTRUCTIONS_HH
<|endoftext|>