<commit_before>//---------------------------------------------------------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2005, 2006, 2009 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//---------------------------------------------------------------------------

#include <base/timer.h>
#include <base/exceptions.h>
#include <iostream>
#include <algorithm>

// these includes should probably be properly
// ./configure'd using the AC_HEADER_TIME macro:
#include <sys/time.h>
#include <sys/resource.h>

#ifdef DEAL_II_COMPILER_SUPPORTS_MPI
#include <mpi.h>
#endif

// on SunOS 4.x, getrusage is stated in the man pages and exists, but
// is not declared in resource.h. declare it ourselves
#ifdef NO_HAVE_GETRUSAGE
extern "C" {
  int getrusage(int who, struct rusage* ru);
}
#endif

DEAL_II_NAMESPACE_OPEN

Timer::Timer()
                :
                cumulative_time (0.),
		cumulative_wall_time (0.)
{
  start();
}

void Timer::start ()
{
  running    = true;

  struct timeval wall_timer;
  gettimeofday(&wall_timer, NULL);
  start_wall_time = wall_timer.tv_sec + 1.e-6 * wall_timer.tv_usec;

  rusage usage;
  getrusage (RUSAGE_SELF, &usage);
  start_time = usage.ru_utime.tv_sec + 1.e-6 * usage.ru_utime.tv_usec;

  rusage usage_children;
  getrusage (RUSAGE_CHILDREN, &usage_children);
  start_time_children = usage_children.ru_utime.tv_sec + 1.e-6 * usage_children.ru_utime.tv_usec;
}

double Timer::stop ()
{
  if (running)
    {
      running = false;
      rusage usage;
      getrusage (RUSAGE_SELF, &usage);
      const double dtime = usage.ru_utime.tv_sec + 1.e-6 * usage.ru_utime.tv_usec;
      cumulative_time += dtime - start_time;

      rusage usage_children;
      getrusage (RUSAGE_CHILDREN, &usage_children);
      const double dtime_children =
	usage_children.ru_utime.tv_sec + 1.e-6 * usage_children.ru_utime.tv_usec;
      cumulative_time += dtime_children - start_time_children;

      struct timeval wall_timer;
      gettimeofday(&wall_timer, NULL);
      cumulative_wall_time += wall_timer.tv_sec + 1.e-6 * wall_timer.tv_usec
	- start_wall_time;
    }
  return cumulative_time;
}

double Timer::operator() () const
{
  if (running)
    {
      rusage usage;
      getrusage (RUSAGE_SELF, &usage);
      const double dtime =  usage.ru_utime.tv_sec + 1.e-6 * usage.ru_utime.tv_usec;

      rusage usage_children;
      getrusage (RUSAGE_CHILDREN, &usage_children);
      const double dtime_children =
	usage_children.ru_utime.tv_sec + 1.e-6 * usage_children.ru_utime.tv_usec;

      return dtime - start_time + dtime_children - start_time_children + cumulative_time;
    }
  else
    return cumulative_time;
}

double Timer::wall_time () const
{
  if (running)
    {
      struct timeval wall_timer;
      gettimeofday(&wall_timer, NULL);
      return wall_timer.tv_sec + 1.e-6 * wall_timer.tv_usec - start_wall_time +
	cumulative_wall_time;
    }
  else
    return cumulative_wall_time;
}

void Timer::reset ()
{
  cumulative_time = 0.;
  cumulative_wall_time = 0.;
  running         = false;
}

/* ---------------------------- TimerOutput -------------------------- */

TimerOutput::TimerOutput (std::ostream &stream,
			  const enum OutputFrequency output_frequency,
			  const enum OutputType output_type)
                          :
                          output_frequency (output_frequency),
			  output_type (output_type),
                          out_stream (stream, true)
{}

TimerOutput::TimerOutput (ConditionalOStream &stream,
			  const enum OutputFrequency output_frequency,
			  const enum OutputType output_type)
                          :
                          output_frequency (output_frequency),
			  output_type (output_type),
                          out_stream (stream)
{}

TimerOutput::~TimerOutput()
{
  while (active_sections.size() > 0)
    exit_section();

  if (output_frequency != every_call)
    print_summary();
}

void
TimerOutput::enter_section (const std::string &section_name)
{
  Assert (section_name.empty() == false,
	  ExcMessage ("Section string is empty."));

  Assert (std::find (active_sections.begin(), active_sections.end(),
		     section_name) == active_sections.end(),
	  ExcMessage ("Cannot enter the already active section."));

  if (sections.find (section_name) == sections.end())
    {
      sections[section_name].total_cpu_time = 0;
      sections[section_name].total_wall_time = 0;
      sections[section_name].n_calls = 0;
    }

  sections[section_name].timer.reset();
  sections[section_name].timer.start();
  sections[section_name].n_calls++;

  active_sections.push_back (section_name);
}

void
TimerOutput::exit_section (const std::string &section_name)
{
  Assert (sections.find (section_name) != sections.end(),
	  ExcMessage ("Cannot delete a section that was never created."));
  Assert (std::find (active_sections.begin(), active_sections.end(),
		     section_name) == active_sections.end(),
	  ExcMessage ("Cannot delete a section that has not been entered."));

				   // if no string is given, exit the last
				   // active section.
  const std::string actual_section_name = (section_name == "" ?
					   active_sections.back () :
					   section_name);

  sections[actual_section_name].timer.stop();
  sections[actual_section_name].total_wall_time += sections[section_name].timer.wall_time();

				       // get cpu time. on MPI
				       // systems, add the local
				       // contributions.
				       //
				       // TODO: this should rather be
				       // in the Timer class itself,
				       // shouldn't it?
  double cpu_time = sections[section_name].timer();
  {

				// On MPI, sum up all the local CPU
				// times.
#ifdef DEAL_II_COMPILER_SUPPORTS_MPI
    double total_cpu_time = 0.;
    int mpiInitialized;
    MPI_Initialized(&mpiInitialized);

    if( mpiInitialized )
      {
	MPI_Allreduce (&cpu_time, &total_cpu_time, 1, MPI_DOUBLE, MPI_SUM,
		       MPI_COMM_WORLD);
	cpu_time = total_cpu_time;
      }
#endif
    sections[actual_section_name].total_cpu_time += cpu_time;
  }

				   // in case we have to print out
				   // something, do that here...
  if (output_frequency != summary)
    {
      std::string output_time;
      std::ostringstream cpu;
      cpu << cpu_time << "s";
      std::ostringstream wall;
      wall << sections[actual_section_name].timer.wall_time() << "s";
      if (output_type == cpu_times)
	output_time = " CPU time: " + cpu.str();
      else if (output_type == wall_times)
	output_time = " wall time: " + wall.str() + ".";
      else
	output_time = ", CPU/wall time: " + cpu.str() + " / " + wall.str() + ".";

      out_stream << actual_section_name << output_time
		 << std::endl;
    }

				   // delete the index from the list of
				   // active ones
  active_sections.erase (std::find (active_sections.begin(), active_sections.end(),
				    section_name));
}

void
TimerOutput::print_summary ()
{
				// in case we want to write CPU times
  if (output_type != wall_times)
    {
      double total_cpu_time;

#ifdef DEAL_II_COMPILER_SUPPORTS_MPI
      {
	double my_cpu_time = timer_all();
	int mpiInitialized;
	MPI_Initialized(&mpiInitialized);

	if( mpiInitialized )
	  {
	    MPI_Allreduce (&my_cpu_time, &total_cpu_time, 1, MPI_DOUBLE, MPI_SUM,
			   MPI_COMM_WORLD);
	  }
	else
	  total_cpu_time = my_cpu_time;
      }
#else
      total_cpu_time = timer_all();
#endif

				   // check that the sum of all times is
				   // less or equal than the total
				   // time. otherwise, we might have
				   // generated a lot of overhead in this
				   // function.
      double check_time = 0.;
      for (std::map<std::string, Section>::const_iterator
	     i = sections.begin(); i!=sections.end(); ++i)
	check_time += i->second.total_cpu_time;

      if (check_time > total_cpu_time)
	{
	  total_cpu_time = check_time;
	  out_stream << std::endl << "Sum of counted times is larger than total time. "
		     << "Timer function may have introduced too much overhead." << std::endl;
	}

				   // now generate a nice table
      out_stream << "\n\n"
		 << "+---------------------------------------------+------------"
		 << "+------------+\n"
		 << "| Total CPU time elapsed since start          |";
      std::cout.width(10);
      std::cout.precision(3);
      out_stream << total_cpu_time << "s |            |\n";
      out_stream << "|                                             |            "
		 << "|            |\n";
      out_stream << "| Section                         | no. calls |";
      std::cout.width(10);
      std::cout.precision(3);
      out_stream << "  CPU time "  << " | % of total |\n";
      out_stream << "+---------------------------------------------+------------"
		 << "+------------+";
      for (std::map<std::string, Section>::const_iterator
	     i = sections.begin(); i!=sections.end(); ++i)
	{
	  std::string name_out = i->first;

				// resize the array so that it is always
				// of the same size
	  unsigned int pos_non_space = name_out.find_first_not_of (" ");
	  name_out.erase(0, pos_non_space);
	  name_out.resize (32, ' ');
	  out_stream << std::endl;
	  out_stream << "| " << name_out;
	  out_stream << "| ";
	  std::cout.width(9);
	  out_stream << i->second.n_calls << " |";
	  std::cout.width(10);
	  std::cout.precision(3);
	  out_stream << i->second.total_cpu_time << "s |";
	  std::cout.width(10);
	  std::cout.precision(2);
	  out_stream << i->second.total_cpu_time/total_cpu_time * 100 << "% |";
	}
      out_stream << std::endl
		 << "+---------------------------------------------+"
		 << "------------+------------+\n"
		 << std::endl;
    }

				// in case we want to write out wallclock times
  if (output_type != cpu_times)
    {
      double total_wall_time = timer_all.wall_time();

 				   // check that the sum of all times is
				   // less or equal than the total
				   // time. otherwise, we might have
				   // generated a lot of overhead in this
				   // function.
      double check_time = 0.;
      for (std::map<std::string, Section>::const_iterator
	     i = sections.begin(); i!=sections.end(); ++i)
	check_time += i->second.total_wall_time;

      if (check_time > total_wall_time)
	{
	  total_wall_time = check_time;
	  out_stream << std::endl
		     << "Sum of counted times is larger than total time. "
		     << "Timer function may have introduced too much overhead."
		     << std::endl;
	}

				   // now generate a nice table
     out_stream << "\n\n"
		 << "+---------------------------------------------+------------"
		 << "+------------+\n"
		 << "| Total wallclock time elapsed from start     |";
      std::cout.width(10);
      std::cout.precision(3);
      out_stream << total_wall_time << "s |            |\n";
      out_stream << "|                                             |            "
		 << "|            |\n";
      out_stream << "| Section                         | no. calls |";
      std::cout.width(10);
      std::cout.precision(3);
      out_stream << "  CPU time "  << " | % of total |\n";
      out_stream << "+---------------------------------------------+------------"
		 << "+------------+";
      for (std::map<std::string, Section>::const_iterator
	     i = sections.begin(); i!=sections.end(); ++i)
	{
	  std::string name_out = i->first;

				// resize the array so that it is always
				// of the same size
	  unsigned int pos_non_space = name_out.find_first_not_of (" ");
	  name_out.erase(0, pos_non_space);
	  name_out.resize (32, ' ');
	  out_stream << std::endl;
	  out_stream << "| " << name_out;
	  out_stream << "| ";
	  std::cout.width(9);
	  out_stream << i->second.n_calls << " |";
	  std::cout.width(10);
	  std::cout.precision(3);
	  out_stream << i->second.total_wall_time << "s |";
	  std::cout.width(10);
	  std::cout.precision(2);
	  out_stream << i->second.total_wall_time/total_wall_time * 100 << "% |";
	}
      out_stream << std::endl
		 << "+---------------------------------------------+"
		 << "------------+------------+\n"
		 << std::endl;
    }

}

DEAL_II_NAMESPACE_CLOSE
<commit_msg>Fixed a few functions so that TimerOutput actually works.<commit_after>//---------------------------------------------------------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2005, 2006, 2009 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//---------------------------------------------------------------------------

#include <base/timer.h>
#include <base/exceptions.h>
#include <iostream>
#include <algorithm>

// these includes should probably be properly
// ./configure'd using the AC_HEADER_TIME macro:
#include <sys/time.h>
#include <sys/resource.h>

#ifdef DEAL_II_COMPILER_SUPPORTS_MPI
#include <mpi.h>
#endif

// on SunOS 4.x, getrusage is stated in the man pages and exists, but
// is not declared in resource.h. declare it ourselves
#ifdef NO_HAVE_GETRUSAGE
extern "C" {
  int getrusage(int who, struct rusage* ru);
}
#endif

DEAL_II_NAMESPACE_OPEN

Timer::Timer()
                :
                cumulative_time (0.),
		cumulative_wall_time (0.)
{
  start();
}

void Timer::start ()
{
  running    = true;

  struct timeval wall_timer;
  gettimeofday(&wall_timer, NULL);
  start_wall_time = wall_timer.tv_sec + 1.e-6 * wall_timer.tv_usec;

  rusage usage;
  getrusage (RUSAGE_SELF, &usage);
  start_time = usage.ru_utime.tv_sec + 1.e-6 * usage.ru_utime.tv_usec;

  rusage usage_children;
  getrusage (RUSAGE_CHILDREN, &usage_children);
  start_time_children = usage_children.ru_utime.tv_sec + 1.e-6 * usage_children.ru_utime.tv_usec;
}

double Timer::stop ()
{
  if (running)
    {
      running = false;
      rusage usage;
      getrusage (RUSAGE_SELF, &usage);
      const double dtime = usage.ru_utime.tv_sec + 1.e-6 * usage.ru_utime.tv_usec;
      cumulative_time += dtime - start_time;

      rusage usage_children;
      getrusage (RUSAGE_CHILDREN, &usage_children);
      const double dtime_children =
	usage_children.ru_utime.tv_sec + 1.e-6 * usage_children.ru_utime.tv_usec;
      cumulative_time += dtime_children - start_time_children;

      struct timeval wall_timer;
      gettimeofday(&wall_timer, NULL);
      cumulative_wall_time += wall_timer.tv_sec + 1.e-6 * wall_timer.tv_usec
	- start_wall_time;
    }
  return cumulative_time;
}

double Timer::operator() () const
{
  if (running)
    {
      rusage usage;
      getrusage (RUSAGE_SELF, &usage);
      const double dtime =  usage.ru_utime.tv_sec + 1.e-6 * usage.ru_utime.tv_usec;

      rusage usage_children;
      getrusage (RUSAGE_CHILDREN, &usage_children);
      const double dtime_children =
	usage_children.ru_utime.tv_sec + 1.e-6 * usage_children.ru_utime.tv_usec;

      return dtime - start_time + dtime_children - start_time_children + cumulative_time;
    }
  else
    return cumulative_time;
}

double Timer::wall_time () const
{
  if (running)
    {
      struct timeval wall_timer;
      gettimeofday(&wall_timer, NULL);
      return wall_timer.tv_sec + 1.e-6 * wall_timer.tv_usec - start_wall_time +
	cumulative_wall_time;
    }
  else
    return cumulative_wall_time;
}

void Timer::reset ()
{
  cumulative_time = 0.;
  cumulative_wall_time = 0.;
  running         = false;
}

/* ---------------------------- TimerOutput -------------------------- */

TimerOutput::TimerOutput (std::ostream &stream,
			  const enum OutputFrequency output_frequency,
			  const enum OutputType output_type)
                          :
                          output_frequency (output_frequency),
			  output_type (output_type),
                          out_stream (stream, true)
{}

TimerOutput::TimerOutput (ConditionalOStream &stream,
			  const enum OutputFrequency output_frequency,
			  const enum OutputType output_type)
                          :
                          output_frequency (output_frequency),
			  output_type (output_type),
                          out_stream (stream)
{}

TimerOutput::~TimerOutput()
{
  while (active_sections.size() > 0)
    exit_section();

  if (output_frequency != every_call)
    print_summary();
}

void
TimerOutput::enter_section (const std::string &section_name)
{
  Assert (section_name.empty() == false,
	  ExcMessage ("Section string is empty."));

  Assert (std::find (active_sections.begin(), active_sections.end(),
		     section_name) == active_sections.end(),
	  ExcMessage ("Cannot enter the already active section."));

  if (sections.find (section_name) == sections.end())
    {
      sections[section_name].total_cpu_time = 0;
      sections[section_name].total_wall_time = 0;
      sections[section_name].n_calls = 0;
    }

  sections[section_name].timer.reset();
  sections[section_name].timer.start();
  sections[section_name].n_calls++;

  active_sections.push_back (section_name);
}

void
TimerOutput::exit_section (const std::string &section_name)
{
  if (section_name != "")
    {
      Assert (sections.find (section_name) != sections.end(),
	      ExcMessage ("Cannot delete a section that was never created."));
      Assert (std::find (active_sections.begin(), active_sections.end(),
			 section_name) != active_sections.end(),
	      ExcMessage ("Cannot delete a section that has not been entered."));
    }

				   // if no string is given, exit the last
				   // active section.
  const std::string actual_section_name = (section_name == "" ?
					   active_sections.back () :
					   section_name);

  sections[actual_section_name].timer.stop();
  sections[actual_section_name].total_wall_time
    += sections[actual_section_name].timer.wall_time();

				       // get cpu time. on MPI
				       // systems, add the local
				       // contributions.
				       //
				       // TODO: this should rather be
				       // in the Timer class itself,
				       // shouldn't it?
  double cpu_time = sections[actual_section_name].timer();
  {

				// On MPI, sum up all the local CPU
				// times.
#ifdef DEAL_II_COMPILER_SUPPORTS_MPI
    double total_cpu_time = 0.;
    int mpiInitialized;
    MPI_Initialized(&mpiInitialized);

    if( mpiInitialized )
      {
	MPI_Allreduce (&cpu_time, &total_cpu_time, 1, MPI_DOUBLE, MPI_SUM,
		       MPI_COMM_WORLD);
	cpu_time = total_cpu_time;
      }
#endif
    sections[actual_section_name].total_cpu_time += cpu_time;
  }

				   // in case we have to print out
				   // something, do that here...
  if (output_frequency != summary)
    {
      std::string output_time;
      std::ostringstream cpu;
      cpu << cpu_time << "s";
      std::ostringstream wall;
      wall << sections[actual_section_name].timer.wall_time() << "s";
      if (output_type == cpu_times)
	output_time = ", CPU time: " + cpu.str();
      else if (output_type == wall_times)
	output_time = ", wall time: " + wall.str() + ".";
      else
	output_time = ", CPU/wall time: " + cpu.str() + " / " + wall.str() + ".";

      out_stream << actual_section_name << output_time
		 << std::endl;
    }

				   // delete the index from the list of
				   // active ones
  active_sections.erase (std::find (active_sections.begin(), active_sections.end(),
				    actual_section_name));
}

void
TimerOutput::print_summary ()
{
				// in case we want to write CPU times
  if (output_type != wall_times)
    {
      double total_cpu_time;

#ifdef DEAL_II_COMPILER_SUPPORTS_MPI
      {
	double my_cpu_time = timer_all();
	int mpiInitialized;
	MPI_Initialized(&mpiInitialized);

	if( mpiInitialized )
	  {
	    MPI_Allreduce (&my_cpu_time, &total_cpu_time, 1, MPI_DOUBLE, MPI_SUM,
			   MPI_COMM_WORLD);
	  }
	else
	  total_cpu_time = my_cpu_time;
      }
#else
      total_cpu_time = timer_all();
#endif

				   // check that the sum of all times is
				   // less or equal than the total
				   // time. otherwise, we might have
				   // generated a lot of overhead in this
				   // function.
      double check_time = 0.;
      for (std::map<std::string, Section>::const_iterator
	     i = sections.begin(); i!=sections.end(); ++i)
	check_time += i->second.total_cpu_time;

      if (check_time > total_cpu_time)
	{
	  total_cpu_time = check_time;
	  out_stream << std::endl << "Sum of counted times is larger than total time. "
		     << "Timer function may have introduced too much overhead." << std::endl;
	}

				   // now generate a nice table
      out_stream << "\n\n"
		 << "+---------------------------------------------+------------"
		 << "+------------+\n"
		 << "| Total CPU time elapsed since start          |";
      std::cout.width(10);
      std::cout.precision(3);
      out_stream << total_cpu_time << "s |            |\n";
      out_stream << "|                                             |            "
		 << "|            |\n";
      out_stream << "| Section                         | no. calls |";
      std::cout.width(10);
      std::cout.precision(3);
      out_stream << "  CPU time "  << " | % of total |\n";
      out_stream << "+---------------------------------------------+------------"
		 << "+------------+";
      for (std::map<std::string, Section>::const_iterator
	     i = sections.begin(); i!=sections.end(); ++i)
	{
	  std::string name_out = i->first;

				// resize the array so that it is always
				// of the same size
	  unsigned int pos_non_space = name_out.find_first_not_of (" ");
	  name_out.erase(0, pos_non_space);
	  name_out.resize (32, ' ');
	  out_stream << std::endl;
	  out_stream << "| " << name_out;
	  out_stream << "| ";
	  std::cout.width(9);
	  out_stream << i->second.n_calls << " |";
	  std::cout.width(10);
	  std::cout.precision(3);
	  out_stream << i->second.total_cpu_time << "s |";
	  std::cout.width(10);
	  std::cout.precision(2);
	  out_stream << i->second.total_cpu_time/total_cpu_time * 100 << "% |";
	}
      out_stream << std::endl
		 << "+---------------------------------------------+"
		 << "------------+------------+\n"
		 << std::endl;
    }

				// in case we want to write out wallclock times
  if (output_type != cpu_times)
    {
      double total_wall_time = timer_all.wall_time();

 				   // check that the sum of all times is
				   // less or equal than the total
				   // time. otherwise, we might have
				   // generated a lot of overhead in this
				   // function.
      double check_time = 0.;
      for (std::map<std::string, Section>::const_iterator
	     i = sections.begin(); i!=sections.end(); ++i)
	check_time += i->second.total_wall_time;

      if (check_time > total_wall_time)
	{
	  total_wall_time = check_time;
	  out_stream << std::endl
		     << "Sum of counted times is larger than total time. "
		     << "Timer function may have introduced too much overhead."
		     << std::endl;
	}

				   // now generate a nice table
     out_stream << "\n\n"
		 << "+---------------------------------------------+------------"
		 << "+------------+\n"
		 << "| Total wallclock time elapsed from start     |";
      std::cout.width(10);
      std::cout.precision(3);
      out_stream << total_wall_time << "s |            |\n";
      out_stream << "|                                             |            "
		 << "|            |\n";
      out_stream << "| Section                         | no. calls |";
      std::cout.width(10);
      std::cout.precision(3);
      out_stream << "  wall time | % of total |\n";
      out_stream << "+---------------------------------------------+------------"
		 << "+------------+";
      for (std::map<std::string, Section>::const_iterator
	     i = sections.begin(); i!=sections.end(); ++i)
	{
	  std::string name_out = i->first;

				// resize the array so that it is always
				// of the same size
	  unsigned int pos_non_space = name_out.find_first_not_of (" ");
	  name_out.erase(0, pos_non_space);
	  name_out.resize (32, ' ');
	  out_stream << std::endl;
	  out_stream << "| " << name_out;
	  out_stream << "| ";
	  std::cout.width(9);
	  out_stream << i->second.n_calls << " |";
	  std::cout.width(10);
	  std::cout.precision(3);
	  out_stream << i->second.total_wall_time << "s |";
	  std::cout.width(10);
	  std::cout.precision(2);
	  out_stream << i->second.total_wall_time/total_wall_time * 100 << "% |";
	}
      out_stream << std::endl
		 << "+---------------------------------------------+"
		 << "------------+------------+\n"
		 << std::endl;
    }

}

DEAL_II_NAMESPACE_CLOSE
<|endoftext|>


<commit_before>// SuspTest.cpp
//
#include "Susp.h"

#include <iostream>

int main()
{
    int n = 10;
    Susp<int> susp([&n]() {
        std::cout << "function evaluated" << std::endl;
        return n++;
    });
    int i = susp.get();
    int j = susp.get();
    std::cout << i << ' ' << j << std::endl;
}
<commit_msg>Trivial update of SuspTest<commit_after>// SuspTest.cpp
//
#include "Susp.h"

#include <iostream>

int main()
{
    int n = 10;
    Susp<int> susp([&n]() {
        std::cout << "function evaluated" << std::endl;
        return n++;
    });
    int i = susp.get();
    int j = susp.get();
    std::cout << i << ' ' << j << ' ' << n << std::endl;
}
<|endoftext|>


<commit_before>#include "database.h"

bool Database::Insert(const Student & s)
{
    if(isFull()) return false;
    (*this) << s;
    return true;
}

const Database Database::Select(std::string name) const
{
    Database tmp;
    for(int i=0;i<num_record_;++i)
    {
        if(record_[i] == name)
        {
            tmp.Insert(record_[i]);
        }
    }

    return tmp;
}

void Database::Export(std::string filename) const
{
    std::ofstream fout(filename);
    if(fout)
    {
        fout << (*this);
    }
    fout.close();
}

bool Database::Import(std::string filename)
{
    std::ifstream fin(filename);
    if(fin)
    {
        Reset_();
        while(!fin.eof())
        {
            Student s;
            fin >> s;
            if(!(fin.eof()||isFull()))
                (*this) << s;
        }
        fin.close();
        return true;
    }
    else return false;

}

Database & Database::operator << (const Student & s)
{
    if(!isFull())
    {
        record_[num_record_++]=s;
        std::sort(record_, record_+num_record_);
    }
    return (*this);
}

std::ostream & operator << (std::ostream & os, const Database & db)
{
    for(int i=0;i<db.num_record_;++i)
    {
        os << db.record_[i] << std::endl;
    }

    return os;
}
<commit_msg>modify a variable name<commit_after>#include "database.h"

bool Database::Insert(const Student & s)
{
    if(isFull()) return false;
    (*this) << s;
    return true;
}

const Database Database::Select(std::string name) const
{
    Database result;
    for(int i=0;i<num_record_;++i)
    {
        if(record_[i] == name)
        {
            result << record_[i];
        }
    }

    return result;
}

void Database::Export(std::string filename) const
{
    std::ofstream fout(filename);
    if(fout)
    {
        fout << (*this);
    }
    fout.close();
}

bool Database::Import(std::string filename)
{
    std::ifstream fin(filename);
    if(fin)
    {
        Reset_();
        while(!fin.eof())
        {
            Student s;
            fin >> s;
            if(!(fin.eof()||isFull()))
                (*this) << s;
        }
        fin.close();
        return true;
    }
    else return false;

}

Database & Database::operator << (const Student & s)
{
    if(!isFull())
    {
        record_[num_record_++]=s;
        std::sort(record_, record_+num_record_);
    }
    return (*this);
}

std::ostream & operator << (std::ostream & os, const Database & db)
{
    for(int i=0;i<db.num_record_;++i)
    {
        os << db.record_[i] << std::endl;
    }

    return os;
}
<|endoftext|>


<commit_before>// Copyright 2015-2018 Elviss Strazdins. All rights reserved.

#ifndef OUZEL_AUDIO_VOICE_HPP
#define OUZEL_AUDIO_VOICE_HPP

#include <memory>
#include "math/Vector3.hpp"

namespace ouzel
{
    namespace audio
    {
        class Audio;
        class Mix;
        class Sound;

        class Voice final
        {
            friend Mix;
        public:
            Voice(Audio& initAudio, const std::shared_ptr<Sound>& initSound);
            ~Voice();

            Voice(const Voice&) = delete;
            Voice& operator=(const Voice&) = delete;
            Voice(Voice&&) = delete;
            Voice& operator=(Voice&&) = delete;

            inline const std::shared_ptr<Sound>& getSound() const { return sound; }

            void play(bool repeat = false);
            void pause();
            void stop();

            bool isPlaying() const { return playing; }
            bool isRepeating() const { return repeating; }

            void setOutput(Mix* newOutput);

        private:
            Audio& audio;
            uintptr_t streamId;

            std::shared_ptr<Sound> sound;

            bool playing = false;
            bool repeating = false;

            Mix* output = nullptr;
        };
    } // namespace audio
} // namespace ouzel

#endif // OUZEL_AUDIO_VOICE_HPP
<commit_msg>Add position to Voice<commit_after>// Copyright 2015-2018 Elviss Strazdins. All rights reserved.

#ifndef OUZEL_AUDIO_VOICE_HPP
#define OUZEL_AUDIO_VOICE_HPP

#include <memory>
#include "math/Vector3.hpp"

namespace ouzel
{
    namespace audio
    {
        class Audio;
        class Mix;
        class Sound;

        class Voice final
        {
            friend Mix;
        public:
            Voice(Audio& initAudio, const std::shared_ptr<Sound>& initSound);
            ~Voice();

            Voice(const Voice&) = delete;
            Voice& operator=(const Voice&) = delete;
            Voice(Voice&&) = delete;
            Voice& operator=(Voice&&) = delete;

            inline const std::shared_ptr<Sound>& getSound() const { return sound; }

            const Vector3<float>& getPosition() const { return position; }
            void setPosition(const Vector3<float>& newPosition) const { position = newPosition; }

            void play(bool repeat = false);
            void pause();
            void stop();

            bool isPlaying() const { return playing; }
            bool isRepeating() const { return repeating; }

            void setOutput(Mix* newOutput);

        private:
            Audio& audio;
            uintptr_t streamId;

            std::shared_ptr<Sound> sound;
            Vector3<float> position;

            bool playing = false;
            bool repeating = false;

            Mix* output = nullptr;
        };
    } // namespace audio
} // namespace ouzel

#endif // OUZEL_AUDIO_VOICE_HPP
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <vector>
#include <happly.h>

#include "filenames.h"
#include "points.h"
#include "cmd_flags.h"

using namespace std;
using cflags::Require;

DEFINE_string(filenames, kRequired, "", "The input filenames");
DEFINE_string(output_path, kOptional, ".", "The output path");
DEFINE_bool(const_normal, kOptional, "1", "Set constant normal if there is normal");
DEFINE_bool(verbose, kOptional, true, "Output logs");

bool read_ply(vector<float>& pts, vector<float>& normals, const string filename) {
  ifstream infile(filename, ios::binary);
  if (infile.fail()) {
    cout << "Can not open " << filename << endl;
    return false;
  }

  happly::PLYData plyIn(infile);

  pts = plyIn.getVertices();
  bool has_normal = plyIn.getElement("vertex").hasProperty("nx");
  if (has_normal) {
    normals = plyIn.getNormals();
  } else {
    normals.clear();
  }

  return true;
}

int main(int argc, char* argv[]) {
  bool succ = cflags::ParseCmd(argc, argv);
  if (!succ) {
    cflags::PrintHelpInfo("\nUsage: ply2points");
    return 0;
  }

  // file path
  string file_path = FLAGS_filenames;
  string output_path = FLAGS_output_path;
  if (output_path != ".") mkdir(output_path);
  else output_path = extract_path(file_path);
  output_path += "/";

  vector<string> all_files;
  get_all_filenames(all_files, file_path);

  for (int i = 0; i < all_files.size(); i++) {
    vector<float> vtx, normal;
    read_ply(vtx, normal, all_files[i]);

    string filename = extract_filename(all_files[i]);
    if (FLAGS_verbose) cout << "Processing: " << filename << std::endl;
    filename = output_path + filename + ".points";

    Points pts;
    bool succ = false;
    if (normal.empty()) {
      if (FLAGS_const_normal) {
        normal.assign(vtx.size(), sqrtf(3.0f) / 3.0f);
        succ = pts.set_points(vtx, normal);
      } else {
        vector<float> feature(vtx.size() / 3, 1.0f);
        succ = pts.set_points(vtx, normal, feature);
      }
    } else {
      succ = pts.set_points(vtx, normal);
    }

    if (!succ) {
      if (FLAGS_verbose) cout << "Failed: " << filename << std::endl;
      continue;
    }
    pts.write_points(filename);
  }

  return 0;
}
<commit_msg>Fix build error on Ubuntu 18.04<commit_after>#include <iostream>
#include <string>
#include <vector>
#include <happly.h>
#include <cmath>

#include "filenames.h"
#include "points.h"
#include "cmd_flags.h"

using namespace std;
using cflags::Require;

DEFINE_string(filenames, kRequired, "", "The input filenames");
DEFINE_string(output_path, kOptional, ".", "The output path");
DEFINE_bool(const_normal, kOptional, "1", "Set constant normal if there is normal");
DEFINE_bool(verbose, kOptional, true, "Output logs");

bool read_ply(vector<float>& pts, vector<float>& normals, const string filename) {
  ifstream infile(filename, ios::binary);
  if (infile.fail()) {
    cout << "Can not open " << filename << endl;
    return false;
  }

  happly::PLYData plyIn(infile);

  pts = plyIn.getVertices();
  bool has_normal = plyIn.getElement("vertex").hasProperty("nx");
  if (has_normal) {
    normals = plyIn.getNormals();
  } else {
    normals.clear();
  }

  return true;
}

int main(int argc, char* argv[]) {
  bool succ = cflags::ParseCmd(argc, argv);
  if (!succ) {
    cflags::PrintHelpInfo("\nUsage: ply2points");
    return 0;
  }

  // file path
  string file_path = FLAGS_filenames;
  string output_path = FLAGS_output_path;
  if (output_path != ".") mkdir(output_path);
  else output_path = extract_path(file_path);
  output_path += "/";

  vector<string> all_files;
  get_all_filenames(all_files, file_path);

  for (int i = 0; i < all_files.size(); i++) {
    vector<float> vtx, normal;
    read_ply(vtx, normal, all_files[i]);

    string filename = extract_filename(all_files[i]);
    if (FLAGS_verbose) cout << "Processing: " << filename << std::endl;
    filename = output_path + filename + ".points";

    Points pts;
    bool succ = false;
    if (normal.empty()) {
      if (FLAGS_const_normal) {
        normal.assign(vtx.size(), 0.57735f);
        succ = pts.set_points(vtx, normal);
      } else {
        vector<float> feature(vtx.size() / 3, 1.0f);
        succ = pts.set_points(vtx, normal, feature);
      }
    } else {
      succ = pts.set_points(vtx, normal);
    }

    if (!succ) {
      if (FLAGS_verbose) cout << "Failed: " << filename << std::endl;
      continue;
    }
    pts.write_points(filename);
  }

  return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>

auto square(int x) -> int
{
    return x * x;
}

int main() {

    /*
     * comment
     */
    std::cout << "Hello, World!" << std::endl; // comment
    const int              a = square(3);
    const std::string      s = "abc";
    const std::vector<int> v = {1, 2, 3};
    std::cout << a << std::endl;
    return 0;
}<commit_msg>Add other style function<commit_after>#include <iostream>
#include <vector>

// other function style
int square1(int x)
{
    return x * x;
}

auto square(int x) -> int
{
    return x * x;
}

int main() {

    /*
     * comment
     */
    std::cout << "Hello, World!" << std::endl; // comment
    const int              a = square(3);
    const std::string      s = "abc";
    const std::vector<int> v = {1, 2, 3};
    std::cout << a << std::endl;
    return 0;
}<|endoftext|>


<commit_before>
// Qt includes
#include <QDebug>
#include <QLayout>
#include <QTableView>
#include <QStandardItemModel>

// Visomics includes
#include "voExtendedTableView.h"
#include "voDataObject.h"
#include "vtkExtendedTable.h"

// VTK includes
#include <vtkDoubleArray.h>
#include <vtkStringArray.h>
#include <vtkTable.h>

// --------------------------------------------------------------------------
class voExtendedTableViewPrivate
{
public:
  voExtendedTableViewPrivate();

  QTableView*        TableView;
  QStandardItemModel Model;
};

// --------------------------------------------------------------------------
// voExtendedTableViewPrivate methods

// --------------------------------------------------------------------------
voExtendedTableViewPrivate::voExtendedTableViewPrivate()
{
  this->TableView = 0;
}

// --------------------------------------------------------------------------
// voExtendedTableView methods

// --------------------------------------------------------------------------
voExtendedTableView::voExtendedTableView(QWidget* newParent):
    Superclass(newParent), d_ptr(new voExtendedTableViewPrivate)
{
}

// --------------------------------------------------------------------------
voExtendedTableView::~voExtendedTableView()
{
}

// --------------------------------------------------------------------------
void voExtendedTableView::setupUi(QLayout *layout)
{
  Q_D(voExtendedTableView);

  d->TableView = new QTableView();
  d->TableView->setModel(&d->Model);

  layout->addWidget(d->TableView);
}

// --------------------------------------------------------------------------
void voExtendedTableView::setDataObject(voDataObject *dataObject)
{
  Q_D(voExtendedTableView);

  if (!dataObject)
    {
    qCritical() << "voExtendedTableView - Failed to setDataObject - dataObject is NULL";
    return;
    }

  vtkExtendedTable * extendedTable = vtkExtendedTable::SafeDownCast(dataObject->data());
  if (!extendedTable)
    {
    qCritical() << "voExtendedTableView - Failed to setDataObject - vtkExtendedTable data is expected !";
    return;
    }

  int modelRowCount = extendedTable->GetTotalNumberOfRows();
  if (extendedTable->HasColumnMetaData())
    {
    modelRowCount--;
    }
  d->Model.setRowCount(modelRowCount);

  int modelColumnCount = extendedTable->GetTotalNumberOfColumns();
  if (extendedTable->HasRowMetaData())
    {
    modelColumnCount--;
    }
  d->Model.setColumnCount(modelColumnCount);

  QColor headerBackgroundColor = QPalette().color(QPalette::Window);

  // Set column meta data
  if(extendedTable->HasColumnMetaData())
    {
      {
      vtkStringArray * metadata = extendedTable->GetColumnMetaDataOfInterestAsString();
      Q_ASSERT(metadata);
      for(int i = 0; i < metadata->GetNumberOfValues(); ++i)
        {
        int headerId = i;
        if (extendedTable->HasRowMetaData())
          {
          headerId += extendedTable->GetNumberOfRowMetaDataTypes() - 1;
          }
        QString value = QString(metadata->GetValue(i));
        d->Model.setHeaderData(headerId, Qt::Horizontal, value);
        }
      }
    // TODO Consider ColumnMetaDataTypeOfInterest
    for (int metadataType = 1; metadataType < extendedTable->GetNumberOfColumnMetaDataTypes(); ++metadataType)
      {
      vtkStringArray * metadata = extendedTable->GetColumnMetaDataAsString(metadataType);
      Q_ASSERT(metadata);
      for(int i = 0; i < metadata->GetNumberOfValues(); ++i)
        {
        int modelColumnId = i;
        if (extendedTable->HasRowMetaData())
          {
          modelColumnId += extendedTable->GetNumberOfRowMetaDataTypes() - 1;
          }
        int modelRowId = metadataType;
        if (extendedTable->HasColumnMetaData())
          {
          modelRowId--;
          }
        QString value = QString(metadata->GetValue(i));
        QStandardItem * currentItem = new QStandardItem(value);
        d->Model.setItem(modelRowId, modelColumnId, currentItem);
        currentItem->setData(headerBackgroundColor, Qt::BackgroundColorRole);
        currentItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
        }
      }
    }

  // Set row meta data
  if(extendedTable->HasRowMetaData())
    {
      {
      vtkStringArray * metadata = extendedTable->GetRowMetaDataOfInterestAsString();
      Q_ASSERT(metadata);
      for(int i = 0; i < metadata->GetNumberOfValues(); ++i)
        {
        int headerId = i;
        if (extendedTable->HasColumnMetaData())
          {
          headerId += extendedTable->GetNumberOfColumnMetaDataTypes() - 1;
          }
        QString value = QString(metadata->GetValue(i));
        d->Model.setHeaderData(headerId, Qt::Vertical, value);
        }
      }
    // TODO Consider RowMetaDataTypeOfInterest
    for (int metadataType = 1; metadataType < extendedTable->GetNumberOfRowMetaDataTypes(); ++metadataType)
      {
      vtkStringArray * metadata = extendedTable->GetRowMetaDataAsString(metadataType);
      Q_ASSERT(metadata);
      for(int i = 0; i < metadata->GetNumberOfValues(); ++i)
        {
        int modelColumnId = metadataType;
        if (extendedTable->HasRowMetaData())
          {
          modelColumnId--;
          }
        int modelRowId = i;
        if (extendedTable->HasColumnMetaData())
          {
          modelRowId += extendedTable->GetNumberOfColumnMetaDataTypes() - 1;
          }
        QString value = QString(metadata->GetValue(i));
        QStandardItem * currentItem = new QStandardItem(value);
        d->Model.setItem(modelRowId, modelColumnId, currentItem);
        currentItem->setData(headerBackgroundColor, Qt::BackgroundColorRole);
        currentItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
        }
      }
    }

  // Set Data
  vtkTable * data = extendedTable->GetData();
  if (data)
    {
    for (int cid = 0; cid < data->GetNumberOfColumns(); ++cid)
      {
      vtkDoubleArray * dataColumn = vtkDoubleArray::SafeDownCast(data->GetColumn(cid));
      Q_ASSERT(dataColumn);
      for (int rid = 0; rid < dataColumn->GetNumberOfTuples(); ++rid)
        {
        int modelColumnId = cid;
        if (extendedTable->HasRowMetaData())
          {
          modelColumnId += extendedTable->GetNumberOfRowMetaDataTypes() - 1;
          }
        int modelRowId = rid;
        if (extendedTable->HasColumnMetaData())
          {
          modelRowId += extendedTable->GetNumberOfColumnMetaDataTypes() - 1;
          }
        double value = dataColumn->GetValue(rid);
        QStandardItem * currentItem = new QStandardItem(QString::number(value));
        d->Model.setItem(modelRowId, modelColumnId, currentItem);
        currentItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
        }
      }
    }

}

<commit_msg>Fix voExtendedTableView to work with row/column of interest.<commit_after>
// Qt includes
#include <QDebug>
#include <QLayout>
#include <QTableView>
#include <QStandardItemModel>

// Visomics includes
#include "voExtendedTableView.h"
#include "voDataObject.h"
#include "vtkExtendedTable.h"

// VTK includes
#include <vtkDoubleArray.h>
#include <vtkStringArray.h>
#include <vtkTable.h>

// --------------------------------------------------------------------------
class voExtendedTableViewPrivate
{
public:
  voExtendedTableViewPrivate();

  QTableView*        TableView;
  QStandardItemModel Model;
};

// --------------------------------------------------------------------------
// voExtendedTableViewPrivate methods

// --------------------------------------------------------------------------
voExtendedTableViewPrivate::voExtendedTableViewPrivate()
{
  this->TableView = 0;
}

// --------------------------------------------------------------------------
// voExtendedTableView methods

// --------------------------------------------------------------------------
voExtendedTableView::voExtendedTableView(QWidget* newParent):
    Superclass(newParent), d_ptr(new voExtendedTableViewPrivate)
{
}

// --------------------------------------------------------------------------
voExtendedTableView::~voExtendedTableView()
{
}

// --------------------------------------------------------------------------
void voExtendedTableView::setupUi(QLayout *layout)
{
  Q_D(voExtendedTableView);

  d->TableView = new QTableView();
  d->TableView->setModel(&d->Model);

  layout->addWidget(d->TableView);
}

// --------------------------------------------------------------------------
void voExtendedTableView::setDataObject(voDataObject *dataObject)
{
  Q_D(voExtendedTableView);

  if (!dataObject)
    {
    qCritical() << "voExtendedTableView - Failed to setDataObject - dataObject is NULL";
    return;
    }

  vtkExtendedTable * extendedTable = vtkExtendedTable::SafeDownCast(dataObject->data());
  if (!extendedTable)
    {
    qCritical() << "voExtendedTableView - Failed to setDataObject - vtkExtendedTable data is expected !";
    return;
    }

  int modelRowCount = extendedTable->GetTotalNumberOfRows();
  if (extendedTable->HasColumnMetaData())
    {
    modelRowCount--;
    }
  d->Model.setRowCount(modelRowCount);

  int modelColumnCount = extendedTable->GetTotalNumberOfColumns();
  if (extendedTable->HasRowMetaData())
    {
    modelColumnCount--;
    }
  d->Model.setColumnCount(modelColumnCount);

  QColor headerBackgroundColor = QPalette().color(QPalette::Window);

  // Set column meta data
  for (vtkIdType tableRowItr = 0; tableRowItr < extendedTable->GetNumberOfColumnMetaDataTypes(); ++tableRowItr)
    {
    vtkStringArray * metadata = extendedTable->GetColumnMetaDataAsString(tableRowItr);
    Q_ASSERT(metadata);
    for(vtkIdType tableColItr = 0; tableColItr < metadata->GetNumberOfValues(); ++tableColItr)
      {
      int modelRowItr = tableRowItr;
      if (tableRowItr > extendedTable->GetColumnMetaDataTypeOfInterest())
        {
        modelRowItr--;
        }
      int modelColItr = tableColItr;
      if (extendedTable->HasRowMetaData())
        {
        modelColItr += extendedTable->GetNumberOfRowMetaDataTypes() - 1;
        }
      QString value = QString(metadata->GetValue(tableColItr));
      if(tableRowItr == extendedTable->GetColumnMetaDataTypeOfInterest())
        {
        d->Model.setHeaderData(modelColItr, Qt::Horizontal, value);
        }
      else
        {
        QStandardItem * currentItem = new QStandardItem(value);
        d->Model.setItem(modelRowItr, modelColItr, currentItem);
        currentItem->setData(headerBackgroundColor, Qt::BackgroundColorRole);
        currentItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
        }
      }
    }

  // Set row meta data
  for(vtkIdType tableColItr = 0; tableColItr < extendedTable->GetNumberOfRowMetaDataTypes(); ++tableColItr)
    {
    vtkStringArray * metadata = extendedTable->GetRowMetaDataAsString(tableColItr);
    Q_ASSERT(metadata);
    for (vtkIdType tableRowItr = 0; tableRowItr <  metadata->GetNumberOfValues(); ++tableRowItr)
      {
      int modelColItr = tableColItr;
      if (tableColItr > extendedTable->GetRowMetaDataTypeOfInterest())
        {
        modelColItr--;
        }
      int modelRowItr = tableRowItr;
      if (extendedTable->HasColumnMetaData())
        {
        modelRowItr += extendedTable->GetNumberOfColumnMetaDataTypes() - 1;
        }
      QString value = QString(metadata->GetValue(tableRowItr));
      if(tableColItr == extendedTable->GetRowMetaDataTypeOfInterest())
        {
        d->Model.setHeaderData(modelRowItr, Qt::Vertical, value);
        }
      else
        {
        QStandardItem * currentItem = new QStandardItem(value);
        d->Model.setItem(modelRowItr, modelColItr, currentItem);
        currentItem->setData(headerBackgroundColor, Qt::BackgroundColorRole);
        currentItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
        }
      }
    }

  // Set Data
  vtkTable * data = extendedTable->GetData();
  if (data)
    {
    for (int cid = 0; cid < data->GetNumberOfColumns(); ++cid)
      {
      vtkDoubleArray * dataColumn = vtkDoubleArray::SafeDownCast(data->GetColumn(cid));
      Q_ASSERT(dataColumn);
      for (int rid = 0; rid < dataColumn->GetNumberOfTuples(); ++rid)
        {
        int modelColumnId = cid;
        if (extendedTable->HasRowMetaData())
          {
          modelColumnId += extendedTable->GetNumberOfRowMetaDataTypes() - 1;
          }
        int modelRowId = rid;
        if (extendedTable->HasColumnMetaData())
          {
          modelRowId += extendedTable->GetNumberOfColumnMetaDataTypes() - 1;
          }
        double value = dataColumn->GetValue(rid);
        QStandardItem * currentItem = new QStandardItem(QString::number(value));
        d->Model.setItem(modelRowId, modelColumnId, currentItem);
        currentItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
        }
      }
    }
}
<|endoftext|>


<commit_before>/* ---------------------------------------------------------------------------
** This software is implemented as part of the course Dynamic Algorithms
** (Q4 2015) at Aarhus Univerity Denmark.
**
** TD_EAGER.cpp
** Implementation of a truly dynamic algorithm for dynamic transitive closure
** based on Shankowsis randomized reduction of dynamic transitive closure to dynamic matrix adjoint.
**
** Author: Martin Storgaard and Konstantinos Mampentzidis
** -------------------------------------------------------------------------*/

#include "TD_EAGER.h"

using namespace std;
void TD_EAGER::init(int n) {
	//initialize the adjacency matrix where we will store all the edges that are part of the graph
	//we need it in case our randomized algorithm fails (division by zero) to be able to reconstruct
	//the
	if(adjacency_matrix != NULL) delete[] adjacency_matrix;
	if(inverse_matrix != NULL) delete[] inverse_matrix;
	if(xs != NULL) delete[] xs;

	this->n = (uint32_t) n;

    // Allocate and initialize the adjacency matrix
	adjacency_matrix = new uint32_t[n*n];
	memset(adjacency_matrix, 0, n*n*sizeof(uint32_t));

    // Allocate and initialize the adjacency matrix
	inverse_matrix = new uint32_t[n*n];
	memset(inverse_matrix, 0, n*n*sizeof(uint32_t));

	// Compute I-A and (I-A)^(-1), i.e. I
	for(int i=0;i<n;i++) {
        inverse_matrix[i*n + i] = 1;
        adjacency_matrix[i*n + i] = 1;
    }
	//initialize the counter to be n since all vertices can reach it self
	count = (uint32_t) n;

	// Pre-compute random values
	xs = new uint32_t[n*n];
	for(int i = 0; i < n*n; i++) {
		xs[i] = next();
	}
}

inline void TD_EAGER::sherman_morrison(int i, int j, uint32_t u) {
	// Indicate that n does not change at this point.
	const uint32_t n = this->n;
	// Define loop invariants
	uint32_t k, m;

	// We do not need v, since it is only a multiplication by 1
	//uint32_t v = 1;

	//find (A^(-1)*u) => pick i-th column of A^(-1) and multiply every value by u
	uint32_t *a = new uint32_t[n];
	for(k=0;k<n;k++) {
		a[k] = mod_mul(inverse_matrix[k*n+i],u);
	}
	// v^T * A^(-1), i.e. multiply row j by 1
	uint32_t *b = &inverse_matrix[j*n];

	// find the value of the denominator 1 + v^T*A^(-1)*u
	uint32_t c = mod_add(1, mod_mul(u,b[i]));

	// Check that we do not divide by 0
	if(c == 0){
		// TODO: Use a better solutuon than simply exit!
		std::cout << "Division by zero!!!!!!!!" << std::endl;
		exit(1);
	}
	// Find the multiplicative inverse of c, and (maybe) multiply the nominator by this value
	c = mod_inv(c);
	// Reset the number of reachable nodes, we recount below
	count = 0;

	// Be smart, do not multiply by 1
	if(c != 1) {
		//find the nominator of sherman morisson formula and divide with the denominator at the same time.
		uint32_t *e = new uint32_t[n*n];
		for(k = 0; k < n; ++k) {
            // Point to the k'th row
            uint32_t *t1 = &e[k*n];
			for (m = 0; m < n; ++m) {
				t1[m] = mod_mul(c, mod_mul(a[k], b[m]));
			}
		}
		//update the inverse matrix and counter
		for(k = 0; k < n; ++k){
            const uint32_t kn = k*n;
            // Point to the k'th row
            uint32_t *t1 = &inverse_matrix[kn];
            const uint32_t *t2 = &e[kn];
			for(m = 0; m < n; ++m){
				t1[m] = mod_sub(t1[m], t2[m]);
				// Increment number of reachable nodes if k can reach m
				count += t1[m] != 0; // [conv.integral] ensures that this is 1 if true, 0 otherwise
			}
		}
		delete[] e;
	} else {
		// We do not need to multiply by 1
		// Calculate A^-1 - (fraction)
		for(k = 0; k < n; ++k){
            // Point to the k'th row
            uint32_t *t1 = &inverse_matrix[k*n];
			for(m = 0 ; m < n; ++m) {
				t1[m] = mod_sub(t1[m], mod_mul(a[k],b[m]));
				// Increment number of reachable nodes if k can reach m
				count += t1[m] != 0;  // [conv.integral] ensures that this is 1 if true, 0 otherwise
			}
		}
	}

	delete[] a;
}

void TD_EAGER::ins(int i, int j) {
	const uint32_t u = xs[i*n + j];
	adjacency_matrix[i*n + j] = u;

	//update the inverse matrix
	sherman_morrison(i, j, u);

}

void TD_EAGER::del(int i, int j) {
	// This is the same as inserting -u = P - u in the Z_P field
	sherman_morrison(i, j, (uint32_t) (P-adjacency_matrix[i*n + j]));
    // P - u + u (mod P) = 0
	adjacency_matrix[i*n + j] = 0;
}

unsigned int TD_EAGER::query() {
	// Oh, we were eager, wasn't we?
	return count;
}
<commit_msg>Removed a unnecessary cast<commit_after>/* ---------------------------------------------------------------------------
** This software is implemented as part of the course Dynamic Algorithms
** (Q4 2015) at Aarhus Univerity Denmark.
**
** TD_EAGER.cpp
** Implementation of a truly dynamic algorithm for dynamic transitive closure
** based on Shankowsis randomized reduction of dynamic transitive closure to dynamic matrix adjoint.
**
** Author: Martin Storgaard and Konstantinos Mampentzidis
** -------------------------------------------------------------------------*/

#include "TD_EAGER.h"

using namespace std;
void TD_EAGER::init(int n) {
	//initialize the adjacency matrix where we will store all the edges that are part of the graph
	//we need it in case our randomized algorithm fails (division by zero) to be able to reconstruct
	//the
	if(adjacency_matrix != NULL) delete[] adjacency_matrix;
	if(inverse_matrix != NULL) delete[] inverse_matrix;
	if(xs != NULL) delete[] xs;

	this->n = (uint32_t) n;

    // Allocate and initialize the adjacency matrix
	adjacency_matrix = new uint32_t[n*n];
	memset(adjacency_matrix, 0, n*n*sizeof(uint32_t));

    // Allocate and initialize the adjacency matrix
	inverse_matrix = new uint32_t[n*n];
	memset(inverse_matrix, 0, n*n*sizeof(uint32_t));

	// Compute I-A and (I-A)^(-1), i.e. I
	for(int i=0;i<n;i++) {
        inverse_matrix[i*n + i] = 1;
        adjacency_matrix[i*n + i] = 1;
    }
	//initialize the counter to be n since all vertices can reach it self
	count = (uint32_t) n;

	// Pre-compute random values
	xs = new uint32_t[n*n];
	for(int i = 0; i < n*n; i++) {
		xs[i] = next();
	}
}

inline void TD_EAGER::sherman_morrison(int i, int j, uint32_t u) {
	// Indicate that n does not change at this point.
	const uint32_t n = this->n;
	// Define loop invariants
	uint32_t k, m;

	// We do not need v, since it is only a multiplication by 1
	//uint32_t v = 1;

	//find (A^(-1)*u) => pick i-th column of A^(-1) and multiply every value by u
	uint32_t *a = new uint32_t[n];
	for(k=0;k<n;k++) {
		a[k] = mod_mul(inverse_matrix[k*n+i],u);
	}
	// v^T * A^(-1), i.e. multiply row j by 1
	uint32_t *b = &inverse_matrix[j*n];

	// find the value of the denominator 1 + v^T*A^(-1)*u
	uint32_t c = mod_add(1, mod_mul(u,b[i]));

	// Check that we do not divide by 0
	if(c == 0){
		// TODO: Use a better solutuon than simply exit!
		std::cout << "Division by zero!!!!!!!!" << std::endl;
		exit(1);
	}
	// Find the multiplicative inverse of c, and (maybe) multiply the nominator by this value
	c = mod_inv(c);
	// Reset the number of reachable nodes, we recount below
	count = 0;

	// Be smart, do not multiply by 1
	if(c != 1) {
		//find the nominator of sherman morisson formula and divide with the denominator at the same time.
		uint32_t *e = new uint32_t[n*n];
		for(k = 0; k < n; ++k) {
            // Point to the k'th row
            uint32_t *t1 = &e[k*n];
			for (m = 0; m < n; ++m) {
				t1[m] = mod_mul(c, mod_mul(a[k], b[m]));
			}
		}
		//update the inverse matrix and counter
		for(k = 0; k < n; ++k){
            const uint32_t kn = k*n;
            // Point to the k'th row
            uint32_t *t1 = &inverse_matrix[kn];
            const uint32_t *t2 = &e[kn];
			for(m = 0; m < n; ++m){
				t1[m] = mod_sub(t1[m], t2[m]);
				// Increment number of reachable nodes if k can reach m
				count += t1[m] != 0; // [conv.integral] ensures that this is 1 if true, 0 otherwise
			}
		}
		delete[] e;
	} else {
		// We do not need to multiply by 1
		// Calculate A^-1 - (fraction)
		for(k = 0; k < n; ++k){
            // Point to the k'th row
            uint32_t *t1 = &inverse_matrix[k*n];
			for(m = 0 ; m < n; ++m) {
				t1[m] = mod_sub(t1[m], mod_mul(a[k],b[m]));
				// Increment number of reachable nodes if k can reach m
				count += t1[m] != 0;  // [conv.integral] ensures that this is 1 if true, 0 otherwise
			}
		}
	}

	delete[] a;
}

void TD_EAGER::ins(int i, int j) {
	const uint32_t u = xs[i*n + j];
	adjacency_matrix[i*n + j] = u;

	//update the inverse matrix
	sherman_morrison(i, j, u);

}

void TD_EAGER::del(int i, int j) {
	// This is the same as inserting -u = P - u in the Z_P field
	sherman_morrison(i, j, P - adjacency_matrix[i*n + j]);
    // P - u + u (mod P) = 0
	adjacency_matrix[i*n + j] = 0;
}

unsigned int TD_EAGER::query() {
	// Oh, we were eager, wasn't we?
	return count;
}
<|endoftext|>


<commit_before>/**
 *  @copyright Copyright 2018 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  @file JPetUserTask.cpp
 */

#include "./JPetData/JPetData.h"
#include "./JPetUserTask.h"

JPetUserTask::JPetUserTask(const char* name): JPetTask(name) {}

bool JPetUserTask::init(const JPetParamsInterface& inOptions)
{
  fParams = dynamic_cast<const JPetParams&>(inOptions);
  return init();
}

bool JPetUserTask::run(const JPetDataInterface& inData)
{
  clearOutputEvents();
  auto event = dynamic_cast<const JPetData&>(inData);
  setEvent(&(event.getEvent()));
  return exec();
}

bool JPetUserTask::terminate(JPetParamsInterface& outOptions)
{
  bool result = terminate();
  outOptions = fParams;
  return result;
}

const JPetParamBank& JPetUserTask::getParamBank()
{
  DEBUG("JPetUserTask");
  auto paramManager = fParams.getParamManager();
  assert(paramManager);
  return paramManager->getParamBank();
}

void JPetUserTask::setStatistics(JPetStatistics* statistics)
{
  fStatistics = statistics;
}

JPetStatistics& JPetUserTask::getStatistics()
{
  assert(fStatistics);
  return *fStatistics;
}

void JPetUserTask::setEvent(TObject* ev)
{
  fEvent = ev;
}

jpet_options_tools::OptsStrAny JPetUserTask::getOptions() const
{
  return fParams.getOptions();
}

JPetTimeWindow* JPetUserTask::getOutputEvents()
{
  return fOutputEvents;
}

void JPetUserTask::clearOutputEvents()
{
  if (fOutputEvents) {
    fOutputEvents->Clear();
  }
}
<commit_msg>Add catching errors in JPetUserTask in case of bad Data type passed<commit_after>/**
 *  @copyright Copyright 2018 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  @file JPetUserTask.cpp
 */

#include "./JPetData/JPetData.h"
#include "./JPetUserTask.h"

JPetUserTask::JPetUserTask(const char* name): JPetTask(name) {}

bool JPetUserTask::init(const JPetParamsInterface& inOptions)
{
  fParams = dynamic_cast<const JPetParams&>(inOptions);
  return init();
}

bool JPetUserTask::run(const JPetDataInterface& inData)
{
  clearOutputEvents();
  try {
    auto event = dynamic_cast<const JPetData&>(inData);
    setEvent(&(event.getEvent()));
  } catch (const std::bad_cast& ex) {
    ERROR("Input data type is not the expected one in User Task");
    return false;
  }
  return exec();
}

bool JPetUserTask::terminate(JPetParamsInterface& outOptions)
{
  bool result = terminate();
  outOptions = fParams;
  return result;
}

const JPetParamBank& JPetUserTask::getParamBank()
{
  DEBUG("JPetUserTask");
  auto paramManager = fParams.getParamManager();
  assert(paramManager);
  return paramManager->getParamBank();
}

void JPetUserTask::setStatistics(JPetStatistics* statistics)
{
  fStatistics = statistics;
}

JPetStatistics& JPetUserTask::getStatistics()
{
  assert(fStatistics);
  return *fStatistics;
}

void JPetUserTask::setEvent(TObject* ev)
{
  fEvent = ev;
}

jpet_options_tools::OptsStrAny JPetUserTask::getOptions() const
{
  return fParams.getOptions();
}

JPetTimeWindow* JPetUserTask::getOutputEvents()
{
  return fOutputEvents;
}

void JPetUserTask::clearOutputEvents()
{
  if (fOutputEvents) {
    fOutputEvents->Clear();
  }
}
<|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)
//
// Contributors: Kirsten Weber

#ifndef DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
#define DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH

#include <memory>
#include <type_traits>

#include <dune/common/exceptions.hh>
#include <dune/common/fvector.hh>

#include <dune/grid/io/file/vtk.hh>

#include <dune/stuff/la/container/interfaces.hh>

#include <dune/gdt/spaces/interface.hh>

#include "local.hh"

namespace Dune {
namespace GDT {

template< class SpaceImp, class VectorImp >
class ConstDiscreteFunction
  : public Stuff::LocalizableFunctionInterface< typename SpaceImp::EntityType,
                                                typename SpaceImp::DomainFieldType, SpaceImp::dimDomain,
                                                typename SpaceImp::RangeFieldType, SpaceImp::dimRange, SpaceImp::dimRangeCols >
{
  static_assert(std::is_base_of< SpaceInterface< typename SpaceImp::Traits >, SpaceImp >::value,
                "SpaceImp has to be derived from SpaceInterface!");
  static_assert(std::is_base_of< Dune::Stuff::LA::VectorInterface< typename VectorImp::Traits >, VectorImp >::value,
                "VectorImp has to be derived from Stuff::LA::VectorInterface!");
  static_assert(std::is_same< typename SpaceImp::RangeFieldType, typename VectorImp::ScalarType >::value,
                "Types do not match!");
  typedef Stuff::LocalizableFunctionInterface
      < typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType, SpaceImp::dimDomain,
        typename SpaceImp::RangeFieldType, SpaceImp::dimRange, SpaceImp::dimRangeCols >
    BaseType;
  typedef ConstDiscreteFunction< SpaceImp, VectorImp > ThisType;
public:
  typedef SpaceImp                              SpaceType;
  typedef VectorImp                             VectorType;
  typedef typename BaseType::EntityType         EntityType;
  typedef typename BaseType::LocalfunctionType  LocalfunctionType;

  static const unsigned int                   dimDomain = BaseType::dimDomain;
  typedef typename BaseType::DomainFieldType  DomainFieldType;
  typedef typename BaseType::DomainType       DomainType;

  static const unsigned int                     dimRange = BaseType::dimRange;
  static const unsigned int                     dimRangeCols = BaseType::dimRangeCols;
  typedef typename BaseType::RangeFieldType     RangeFieldType;
  typedef typename BaseType::RangeType          RangeType;
  typedef typename BaseType::JacobianRangeType  JacobianRangeType;

  typedef ConstLocalDiscreteFunction< SpaceType, VectorType > ConstLocalDiscreteFunctionType;

  ConstDiscreteFunction(const SpaceType& sp,
                        const VectorType& vec,
                        const std::string nm = "dune.gdt.constdiscretefunction")
    : space_(sp)
    , vector_(vec)
    , name_(nm)
  {
    assert(vector_.size() == space_.mapper().size() && "Given vector has wrong size!");
  }

  ConstDiscreteFunction(const ThisType& other)
    : space_(other.space_)
    , vector_(other.vector_)
    , name_(other.name_)
  {}

  ConstDiscreteFunction(ThisType&& source)
    : space_(source.space_)
    , vector_(source.vector_)
    , name_(std::move(source.name_))
  {}

  virtual ~ConstDiscreteFunction() {}

  ThisType& operator=(const ThisType& other) = delete;

  virtual ThisType* copy() const DS_OVERRIDE
  {
    return new ThisType(*this);
  }

  virtual std::string name() const DS_OVERRIDE
  {
    return name_;
  }

  const SpaceType& space() const
  {
    return space_;
  }

  const VectorType& vector() const
  {
    return vector_;
  }

  ConstLocalDiscreteFunctionType local_discrete_function(const EntityType& entity) const
  {
    assert(space_.grid_view()->indexSet().contains(entity));
    return ConstLocalDiscreteFunctionType(space_, vector_, entity);
  }

  virtual std::unique_ptr< LocalfunctionType > local_function(const EntityType& entity) const DS_OVERRIDE
  {
    return std::unique_ptr< ConstLocalDiscreteFunctionType >
        (new ConstLocalDiscreteFunctionType(local_discrete_function(entity)));
  }

  void visualize(const std::string filename,
                 const bool subsampling = (SpaceType::polOrder > 1),
                 VTK::OutputType vtk_output_type = VTK::appendedraw) const
  {
    BaseType::template visualize< typename SpaceType::GridViewType >(*(space().grid_view()),
                                                                     filename,
                                                                     subsampling,
                                                                     vtk_output_type);
  }

protected:
  const SpaceType& space_;
private:
  const VectorType& vector_;
  const std::string name_;
}; // class ConstDiscreteFunction

template< class SpaceImp, class VectorImp >
class DiscreteFunction
  : public ConstDiscreteFunction< SpaceImp, VectorImp >
{
  typedef ConstDiscreteFunction< SpaceImp, VectorImp >  BaseType;
  typedef DiscreteFunction< SpaceImp, VectorImp >       ThisType;
public:
  typedef typename BaseType::SpaceType          SpaceType;
  typedef typename BaseType::VectorType         VectorType;
  typedef typename BaseType::EntityType         EntityType;
  typedef typename BaseType::LocalfunctionType  LocalfunctionType;

  typedef LocalDiscreteFunction< SpaceType, VectorType > LocalDiscreteFunctionType;

  DiscreteFunction(const SpaceType& sp,
                   VectorType& vec,
                   const std::string nm = "dune.gdt.discretefunction")
    : BaseType(sp, vec, nm)
    , vector_(vec)
  {}

  DiscreteFunction(const ThisType& other)
    : BaseType(other)
    , vector_(other.vector_)
  {}

  DiscreteFunction(ThisType&& source)
    : BaseType(std::move(source))
    , vector_(source.vector_)
  {}

  ~DiscreteFunction() {}

  ThisType& operator=(const ThisType& other) = delete;

  virtual ThisType* copy() const DS_OVERRIDE
  {
    return new ThisType(*this);
  }

  VectorType& vector()
  {
    return vector_;
  }

  using BaseType::local_discrete_function;

  LocalDiscreteFunctionType local_discrete_function(const EntityType& entity)
  {
    assert(space_.grid_view()->indexSet().contains(entity));
    return LocalDiscreteFunctionType(space_, vector_, entity);
  }

private:
  using BaseType::space_;
  VectorType& vector_;
}; // class DiscreteFunction

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
<commit_msg>[df] adds new DiscreteFunction with internal vector storage<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)
//
// Contributors: Kirsten Weber

#ifndef DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
#define DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH

#include <memory>
#include <type_traits>

#include <dune/common/exceptions.hh>
#include <dune/common/fvector.hh>

#include <dune/grid/io/file/vtk.hh>

#include <dune/stuff/la/container/interfaces.hh>
#include <dune/stuff/functions/interfaces.hh>

#include <dune/gdt/spaces/interface.hh>

#include "local.hh"

namespace Dune {
namespace GDT {

template< class SpaceImp, class VectorImp >
class ConstDiscreteFunction
  : public Stuff::LocalizableFunctionInterface< typename SpaceImp::EntityType,
                                                typename SpaceImp::DomainFieldType, SpaceImp::dimDomain,
                                                typename SpaceImp::RangeFieldType, SpaceImp::dimRange, SpaceImp::dimRangeCols >
{
  static_assert(std::is_base_of< SpaceInterface< typename SpaceImp::Traits >, SpaceImp >::value,
                "SpaceImp has to be derived from SpaceInterface!");
  static_assert(std::is_base_of< Dune::Stuff::LA::VectorInterface< typename VectorImp::Traits >, VectorImp >::value,
                "VectorImp has to be derived from Stuff::LA::VectorInterface!");
  static_assert(std::is_same< typename SpaceImp::RangeFieldType, typename VectorImp::ScalarType >::value,
                "Types do not match!");
  typedef Stuff::LocalizableFunctionInterface
      < typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType, SpaceImp::dimDomain,
        typename SpaceImp::RangeFieldType, SpaceImp::dimRange, SpaceImp::dimRangeCols >
    BaseType;
  typedef ConstDiscreteFunction< SpaceImp, VectorImp > ThisType;
public:
  typedef SpaceImp                              SpaceType;
  typedef VectorImp                             VectorType;
  typedef typename BaseType::EntityType         EntityType;
  typedef typename BaseType::LocalfunctionType  LocalfunctionType;

  static const unsigned int                   dimDomain = BaseType::dimDomain;
  typedef typename BaseType::DomainFieldType  DomainFieldType;
  typedef typename BaseType::DomainType       DomainType;

  static const unsigned int                     dimRange = BaseType::dimRange;
  static const unsigned int                     dimRangeCols = BaseType::dimRangeCols;
  typedef typename BaseType::RangeFieldType     RangeFieldType;
  typedef typename BaseType::RangeType          RangeType;
  typedef typename BaseType::JacobianRangeType  JacobianRangeType;

  typedef ConstLocalDiscreteFunction< SpaceType, VectorType > ConstLocalDiscreteFunctionType;

  ConstDiscreteFunction(const SpaceType& sp,
                        const VectorType& vec,
                        const std::string nm = "dune.gdt.constdiscretefunction")
    : space_(sp)
    , vector_(vec)
    , name_(nm)
  {
    assert(vector_.size() == space_.mapper().size() && "Given vector has wrong size!");
  }

  ConstDiscreteFunction(const ThisType& other)
    : space_(other.space_)
    , vector_(other.vector_)
    , name_(other.name_)
  {}

  ConstDiscreteFunction(ThisType&& source)
    : space_(source.space_)
    , vector_(source.vector_)
    , name_(std::move(source.name_))
  {}

  virtual ~ConstDiscreteFunction() {}

  ThisType& operator=(const ThisType& other) = delete;

  virtual ThisType* copy() const DS_OVERRIDE
  {
    return new ThisType(*this);
  }

  virtual std::string name() const DS_OVERRIDE
  {
    return name_;
  }

  const SpaceType& space() const
  {
    return space_;
  }

  const VectorType& vector() const
  {
    return vector_;
  }

  ConstLocalDiscreteFunctionType local_discrete_function(const EntityType& entity) const
  {
    assert(space_.grid_view()->indexSet().contains(entity));
    return ConstLocalDiscreteFunctionType(space_, vector_, entity);
  }

  virtual std::unique_ptr< LocalfunctionType > local_function(const EntityType& entity) const DS_OVERRIDE
  {
    return std::unique_ptr< ConstLocalDiscreteFunctionType >
        (new ConstLocalDiscreteFunctionType(local_discrete_function(entity)));
  }

  void visualize(const std::string filename,
                 const bool subsampling = (SpaceType::polOrder > 1),
                 VTK::OutputType vtk_output_type = VTK::appendedraw) const
  {
    BaseType::template visualize< typename SpaceType::GridViewType >(*(space().grid_view()),
                                                                     filename,
                                                                     subsampling,
                                                                     vtk_output_type);
  }

protected:
  const SpaceType& space_;
private:
  const VectorType& vector_;
  const std::string name_;
}; // class ConstDiscreteFunction

template< class SpaceImp, class VectorImp >
class DiscreteFunction
  : public ConstDiscreteFunction< SpaceImp, VectorImp >
{
  typedef ConstDiscreteFunction< SpaceImp, VectorImp >  BaseType;
  typedef DiscreteFunction< SpaceImp, VectorImp >       ThisType;
public:
  typedef typename BaseType::SpaceType          SpaceType;
  typedef typename BaseType::VectorType         VectorType;
  typedef typename BaseType::EntityType         EntityType;
  typedef typename BaseType::LocalfunctionType  LocalfunctionType;

  typedef LocalDiscreteFunction< SpaceType, VectorType > LocalDiscreteFunctionType;

  DiscreteFunction(const SpaceType& sp,
                   VectorType& vec,
                   const std::string nm = "dune.gdt.discretefunction")
    : BaseType(sp, vec, nm)
    , vector_(vec)
  {}

  DiscreteFunction(const ThisType& other)
    : BaseType(other)
    , vector_(other.vector_)
  {}

  DiscreteFunction(ThisType&& source)
    : BaseType(std::move(source))
    , vector_(source.vector_)
  {}

  ~DiscreteFunction() {}

  ThisType& operator=(const ThisType& other) = delete;

  virtual ThisType* copy() const DS_OVERRIDE
  {
    return new ThisType(*this);
  }

  VectorType& vector()
  {
    return vector_;
  }

  using BaseType::local_discrete_function;

  LocalDiscreteFunctionType local_discrete_function(const EntityType& entity)
  {
    assert(space_.grid_view()->indexSet().contains(entity));
    return LocalDiscreteFunctionType(space_, vector_, entity);
  }

private:
  using BaseType::space_;
  VectorType& vector_;
}; // class DiscreteFunction

template< class SpaceImp, class VectorImp >
class StoredDiscreteFunction
  : public DiscreteFunction< SpaceImp, VectorImp >
{
  typedef DiscreteFunction< SpaceImp, VectorImp >  BaseType;
  typedef StoredDiscreteFunction< SpaceImp, VectorImp >       ThisType;
public:
  typedef typename BaseType::SpaceType          SpaceType;
  typedef typename BaseType::VectorType         VectorType;
  typedef typename BaseType::EntityType         EntityType;
  typedef typename BaseType::LocalfunctionType  LocalfunctionType;

  typedef LocalDiscreteFunction< SpaceType, VectorType > LocalDiscreteFunctionType;

  StoredDiscreteFunction(const SpaceType& sp,
                   const std::string nm = "dune.gdt.discretefunction")
    : BaseType(sp, vector_, nm)
    , vector_(sp.mapper().size())
  {}

  ~StoredDiscreteFunction() {}

  ThisType& operator=(const ThisType& other) = delete;

  virtual ThisType* copy() const DS_OVERRIDE
  {
    return new ThisType(*this);
  }

  VectorType& vector()
  {
    return vector_;
  }

  LocalDiscreteFunctionType local_discrete_function(const EntityType& entity)
  {
    return LocalDiscreteFunctionType(BaseType::space(), vector_, entity);
  }

  bool dofsValid() const {
    for(const auto& val : vector_) {
      if(std::isnan(val) || std::isinf(val))
        return false;
    }
    return true;
  }

private:
  VectorType vector_;
}; // class DiscreteFunction

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2011 - 2017)
//   Kirsten Weber   (2013)
//   Rene Milk       (2014 - 2018)
//   Tobias Leibner  (2014, 2016 - 2017)

#ifndef DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
#define DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH

#include <dune/xt/common/memory.hh>

#include <dune/xt/grid/type_traits.hh>
#include <dune/xt/la/container/vector-interface.hh>

#include <dune/xt/functions/interfaces/grid-function.hh>

#include <dune/gdt/local/discretefunction.hh>
#include <dune/gdt/discretefunction/dof-vector.hh>
#include <dune/gdt/spaces/interface.hh>

namespace Dune {
namespace GDT {

template <class Vector, class GridView, size_t range_dim = 1, size_t range_dim_cols = 1, class RangeField = double>
class ConstDiscreteFunction
    : public XT::Functions::
          GridFunctionInterface<XT::Grid::extract_entity_t<GridView>, range_dim, range_dim_cols, RangeField>
{
  static_assert(XT::LA::is_vector<Vector>::value, "");

  using BaseType =
      XT::Functions::GridFunctionInterface<XT::Grid::extract_entity_t<GridView>, range_dim, range_dim_cols, RangeField>;
  using ThisType = ConstDiscreteFunction<Vector, GridView, range_dim, range_dim_cols, RangeField>;

public:
  using ConstDofVectorType = ConstDofVector<Vector, GridView>;
  using SpaceType = SpaceInterface<GridView, range_dim, range_dim_cols, RangeField>;
  using VectorType = Vector;
  using ConstLocalDiscreteFunctionType =
      ConstLocalDiscreteFunction<Vector, GridView, range_dim, range_dim_cols, RangeField>;

  using typename BaseType::LocalFunctionType;
  using typename BaseType::ElementType;

  ConstDiscreteFunction(const SpaceType& spc,
                        const VectorType& vector,
                        const std::string nm = "dune.gdt.constdiscretefunction")
    : space_(spc)
    , dofs_(space_.mapper(), vector)
    , name_(nm)
  {
  }

  ConstDiscreteFunction(const ThisType&) = default;
  ConstDiscreteFunction(ThisType&&) = default;

  ThisType& operator=(const ThisType&) = delete;
  ThisType& operator=(ThisType&&) = delete;

  const SpaceType& space() const
  {
    return space_;
  }

  const ConstDofVectorType& dofs() const
  {
    return dofs_;
  }

  std::unique_ptr<ConstLocalDiscreteFunctionType> local_discrete_function() const
  {
    return std::make_unique<ConstLocalDiscreteFunctionType>(space_, dofs_);
  }

  /**
   * \name ``These methods are required by XT::Functions::GridFunctionInterface.''
   * \{
   */
  std::string type() const override
  {
    return "dune.gdt.constdiscretefunction";
  }

  std::string name() const override final
  {
    return name_;
  }

  std::unique_ptr<LocalFunctionType> local_function() const override final
  {
    return local_discrete_function();
  }

  /**
   * \}
   */

  using BaseType::visualize;

  /**
   * \brief Visualizes the function using Dune::XT::Functions::GridFunctionInterface::visualize on the grid view
   *        associated with the space.
   * \sa    Dune::XT::Functions::GridFunctionInterface::visualize
   * \note  Subsampling is enabled by default for functions of order greater than one.
   */
  void visualize(const std::string filename,
                 const VTK::OutputType vtk_output_type = VTK::appendedraw,
                 const XT::Common::Parameter& param = {}) const
  {
    this->visualize(space_.grid_view(), filename, space_.max_polorder() > 1, vtk_output_type, param);
  }

protected:
  const SpaceType& space_;

private:
  const ConstDofVectorType dofs_;
  const std::string name_;
}; // class ConstDiscreteFunction

template <class V, class GV, size_t r, size_t rC, class R>
ConstDiscreteFunction<typename XT::LA::VectorInterface<V>::derived_type, GV, r, rC, R>
make_const_discrete_function(const SpaceInterface<GV, r, rC, R>& space,
                             const XT::LA::VectorInterface<V>& vector,
                             const std::string nm = "dune.gdt.constdiscretefunction")
{
  return ConstDiscreteFunction<typename XT::LA::VectorInterface<V>::derived_type, GV, r, rC, R>(
      space, vector.as_imp(), nm);
}

template <class Vector, class GridView, size_t range_dim = 1, size_t range_dim_cols = 1, class RangeField = double>
class DiscreteFunction : XT::Common::StorageProvider<Vector>,
                         public ConstDiscreteFunction<Vector, GridView, range_dim, range_dim_cols, RangeField>
{
  using ThisType = DiscreteFunction<Vector, GridView, range_dim, range_dim_cols, RangeField>;
  using VectorStorage = XT::Common::StorageProvider<Vector>;
  using BaseType = ConstDiscreteFunction<Vector, GridView, range_dim, range_dim_cols, RangeField>;

public:
  using typename BaseType::ElementType;
  using typename BaseType::SpaceType;
  using typename BaseType::VectorType;

  using DofVectorType = DofVector<Vector, GridView>;
  using LocalDiscreteFunctionType = LocalDiscreteFunction<Vector, GridView, range_dim, range_dim_cols, RangeField>;

  DiscreteFunction(const SpaceType& spc, VectorType& vector, const std::string nm = "dune.gdt.discretefunction")
    : VectorStorage(vector)
    , BaseType(spc, VectorStorage::access(), nm)
    , dofs_(space_.mapper(), VectorStorage::access())
  {
  }

  DiscreteFunction(const SpaceType& spc, VectorType&& vector, const std::string nm = "dune.gdt.discretefunction")
    : VectorStorage(new VectorType(std::move(vector)))
    , BaseType(spc, VectorStorage::access(), nm)
    , dofs_(space_.mapper(), VectorStorage::access())
  {
  }

  DiscreteFunction(const SpaceType& spc, const std::string nm = "dune.gdt.discretefunction")
    : VectorStorage(new VectorType(spc.mapper().size(), 0))
    , BaseType(spc, VectorStorage::access(), nm)
    , dofs_(space_.mapper(), VectorStorage::access())
  {
  }

  DiscreteFunction(const ThisType&) = default;
  DiscreteFunction(ThisType&&) = default;

  ThisType& operator=(const ThisType&) = delete;
  ThisType& operator=(ThisType&&) = delete;

  using BaseType::dofs;

  DofVectorType& dofs()
  {
    return dofs_;
  }

  using BaseType::local_discrete_function;

  std::unique_ptr<LocalDiscreteFunctionType> local_discrete_function()
  {
    return std::make_unique<LocalDiscreteFunctionType>(space_, dofs_);
  }

  /**
   * \name ``These methods are required by XT::Functions::GridFunctionInterface.''
   * \{
   */

  std::string type() const override final
  {
    return "dune.gdt.discretefunction";
  }

  /**
   * \}
   */

private:
  using BaseType::space_;
  DofVectorType dofs_;
}; // class DiscreteFunction

template <class V, class GV, size_t r, size_t rC, class R>
DiscreteFunction<typename XT::LA::VectorInterface<V>::derived_type, GV, r, rC, R>
make_discrete_function(const SpaceInterface<GV, r, rC, R>& space,
                       XT::LA::VectorInterface<V>& vector,
                       const std::string nm = "dune.gdt.discretefunction")
{
  return DiscreteFunction<typename XT::LA::VectorInterface<V>::derived_type, GV, r, rC, R>(space, vector.as_imp(), nm);
}

template <class V, class GV, size_t r, size_t rC, class R>
DiscreteFunction<typename XT::LA::VectorInterface<V>::derived_type, GV, r, rC, R>
make_discrete_function(const SpaceInterface<GV, r, rC, R>& space,
                       XT::LA::VectorInterface<V>&& vector,
                       const std::string nm = "dune.gdt.discretefunction")
{
  return DiscreteFunction<typename XT::LA::VectorInterface<V>::derived_type, GV, r, rC, R>(
      space, std::move(vector.as_imp()), nm);
}

template <class VectorType, class GV, size_t r, size_t rC, class R>
DiscreteFunction<VectorType, GV, r, rC, R> make_discrete_function(const SpaceInterface<GV, r, rC, R>& space,
                                                                  const std::string nm = "dune.gdt.discretefunction")
{
  return DiscreteFunction<VectorType, GV, r, rC, R>(space, nm);
}

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
<commit_msg>[discretefunction.default] some improvements<commit_after>// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2011 - 2017)
//   Kirsten Weber   (2013)
//   Rene Milk       (2014 - 2018)
//   Tobias Leibner  (2014, 2016 - 2017)

#ifndef DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
#define DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH

#include <dune/xt/common/memory.hh>

#include <dune/xt/grid/type_traits.hh>
#include <dune/xt/la/container/vector-interface.hh>

#include <dune/xt/functions/interfaces/grid-function.hh>

#include <dune/gdt/local/discretefunction.hh>
#include <dune/gdt/discretefunction/dof-vector.hh>
#include <dune/gdt/spaces/interface.hh>

namespace Dune {
namespace GDT {
namespace internal {

template <class Vector, class GridView>
struct AssertArgumentsOfConstDiscreteFunction
{
  static_assert(XT::LA::is_vector<Vector>::value, "");
  static_assert(XT::Grid::is_view<GridView>::value, "");
  using E = XT::Grid::extract_entity_t<GridView>;
};

} // namespace internal

template <class Vector, class GridView, size_t range_dim = 1, size_t range_dim_cols = 1, class RangeField = double>
class ConstDiscreteFunction : public XT::Functions::GridFunctionInterface<
                                  typename internal::AssertArgumentsOfConstDiscreteFunction<Vector, GridView>::E,
                                  range_dim,
                                  range_dim_cols,
                                  RangeField>
{
  using BaseType = XT::Functions::GridFunctionInterface<
      typename internal::AssertArgumentsOfConstDiscreteFunction<Vector, GridView>::E,
      range_dim,
      range_dim_cols,
      RangeField>;
  using ThisType = ConstDiscreteFunction<Vector, GridView, range_dim, range_dim_cols, RangeField>;

public:
  using ConstDofVectorType = ConstDofVector<Vector, GridView>;
  using SpaceType = SpaceInterface<GridView, range_dim, range_dim_cols, RangeField>;
  using VectorType = Vector;
  using ConstLocalDiscreteFunctionType =
      ConstLocalDiscreteFunction<Vector, GridView, range_dim, range_dim_cols, RangeField>;

  using typename BaseType::LocalFunctionType;
  using typename BaseType::ElementType;

  ConstDiscreteFunction(const SpaceType& spc,
                        const VectorType& vector,
                        const std::string nm = "dune.gdt.constdiscretefunction")
    : space_(spc)
    , dofs_(space_.mapper(), vector)
    , name_(nm)
  {
  }

  ConstDiscreteFunction(const ThisType&) = default;
  ConstDiscreteFunction(ThisType&&) = default;

  ThisType& operator=(const ThisType&) = delete;
  ThisType& operator=(ThisType&&) = delete;

  const SpaceType& space() const
  {
    return space_;
  }

  const ConstDofVectorType& dofs() const
  {
    return dofs_;
  }

  std::unique_ptr<ConstLocalDiscreteFunctionType> local_discrete_function() const
  {
    return std::make_unique<ConstLocalDiscreteFunctionType>(space_, dofs_);
  }

  std::unique_ptr<ConstLocalDiscreteFunctionType> local_discrete_function(const ElementType& grid_element) const
  {
    auto ldf = local_discrete_function();
    ldf->bind(grid_element);
    return ldf;
  }

  /**
   * \name ``These methods are required by XT::Functions::GridFunctionInterface.''
   * \{
   */
  std::string type() const override
  {
    return "dune.gdt.constdiscretefunction";
  }

  std::string name() const override final
  {
    return name_;
  }

  std::unique_ptr<LocalFunctionType> local_function() const override final
  {
    return local_discrete_function();
  }

  /**
   * \}
   */

  using BaseType::visualize;

  /**
   * \brief Visualizes the function using Dune::XT::Functions::GridFunctionInterface::visualize on the grid view
   *        associated with the space.
   * \sa    Dune::XT::Functions::GridFunctionInterface::visualize
   * \note  Subsampling is enabled by default for functions of order greater than one.
   */
  void visualize(const std::string filename,
                 const VTK::OutputType vtk_output_type = VTK::appendedraw,
                 const XT::Common::Parameter& param = {}) const
  {
    this->visualize(space_.grid_view(), filename, space_.max_polorder() > 1, vtk_output_type, param);
  }

protected:
  const SpaceType& space_;

private:
  const ConstDofVectorType dofs_;
  const std::string name_;
}; // class ConstDiscreteFunction

template <class V, class GV, size_t r, size_t rC, class R>
ConstDiscreteFunction<typename XT::LA::VectorInterface<V>::derived_type, GV, r, rC, R>
make_discrete_function(const SpaceInterface<GV, r, rC, R>& space,
                       const XT::LA::VectorInterface<V>& vector,
                       const std::string nm = "dune.gdt.constdiscretefunction")
{
  return ConstDiscreteFunction<typename XT::LA::VectorInterface<V>::derived_type, GV, r, rC, R>(
      space, vector.as_imp(), nm);
}

template <class Vector, class GridView, size_t range_dim = 1, size_t range_dim_cols = 1, class RangeField = double>
class DiscreteFunction : XT::Common::StorageProvider<Vector>,
                         public ConstDiscreteFunction<Vector, GridView, range_dim, range_dim_cols, RangeField>
{
  using ThisType = DiscreteFunction<Vector, GridView, range_dim, range_dim_cols, RangeField>;
  using VectorStorage = XT::Common::StorageProvider<Vector>;
  using BaseType = ConstDiscreteFunction<Vector, GridView, range_dim, range_dim_cols, RangeField>;

public:
  using typename BaseType::ElementType;
  using typename BaseType::SpaceType;
  using typename BaseType::VectorType;

  using DofVectorType = DofVector<Vector, GridView>;
  using LocalDiscreteFunctionType = LocalDiscreteFunction<Vector, GridView, range_dim, range_dim_cols, RangeField>;

  DiscreteFunction(const SpaceType& spc, VectorType& vector, const std::string nm = "dune.gdt.discretefunction")
    : VectorStorage(vector)
    , BaseType(spc, VectorStorage::access(), nm)
    , dofs_(space_.mapper(), VectorStorage::access())
  {
  }

  DiscreteFunction(const SpaceType& spc, VectorType&& vector, const std::string nm = "dune.gdt.discretefunction")
    : VectorStorage(new VectorType(std::move(vector)))
    , BaseType(spc, VectorStorage::access(), nm)
    , dofs_(space_.mapper(), VectorStorage::access())
  {
  }

  DiscreteFunction(const SpaceType& spc, const std::string nm = "dune.gdt.discretefunction")
    : VectorStorage(new VectorType(spc.mapper().size(), 0))
    , BaseType(spc, VectorStorage::access(), nm)
    , dofs_(space_.mapper(), VectorStorage::access())
  {
  }

  DiscreteFunction(const ThisType&) = default;
  DiscreteFunction(ThisType&&) = default;

  ThisType& operator=(const ThisType&) = delete;
  ThisType& operator=(ThisType&&) = delete;

  using BaseType::dofs;

  DofVectorType& dofs()
  {
    return dofs_;
  }

  using BaseType::local_discrete_function;

  std::unique_ptr<LocalDiscreteFunctionType> local_discrete_function()
  {
    return std::make_unique<LocalDiscreteFunctionType>(space_, dofs_);
  }

  std::unique_ptr<LocalDiscreteFunctionType> local_discrete_function(const ElementType& grid_element)
  {
    auto ldf = local_discrete_function();
    ldf->bind(grid_element);
    return ldf;
  }

  /**
   * \name ``These methods are required by XT::Functions::GridFunctionInterface.''
   * \{
   */

  std::string type() const override final
  {
    return "dune.gdt.discretefunction";
  }

  /**
   * \}
   */

private:
  using BaseType::space_;
  DofVectorType dofs_;
}; // class DiscreteFunction

template <class V, class GV, size_t r, size_t rC, class R>
DiscreteFunction<typename XT::LA::VectorInterface<V>::derived_type, GV, r, rC, R>
make_discrete_function(const SpaceInterface<GV, r, rC, R>& space,
                       XT::LA::VectorInterface<V>& vector,
                       const std::string nm = "dune.gdt.discretefunction")
{
  return DiscreteFunction<typename XT::LA::VectorInterface<V>::derived_type, GV, r, rC, R>(space, vector.as_imp(), nm);
}

template <class V, class GV, size_t r, size_t rC, class R>
DiscreteFunction<typename XT::LA::VectorInterface<V>::derived_type, GV, r, rC, R>
make_discrete_function(const SpaceInterface<GV, r, rC, R>& space,
                       XT::LA::VectorInterface<V>&& vector,
                       const std::string nm = "dune.gdt.discretefunction")
{
  return DiscreteFunction<typename XT::LA::VectorInterface<V>::derived_type, GV, r, rC, R>(
      space, std::move(vector.as_imp()), nm);
}

template <class VectorType, class GV, size_t r, size_t rC, class R>
DiscreteFunction<VectorType, GV, r, rC, R> make_discrete_function(const SpaceInterface<GV, r, rC, R>& space,
                                                                  const std::string nm = "dune.gdt.discretefunction")
{
  return DiscreteFunction<VectorType, GV, r, rC, R>(space, nm);
}

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
<|endoftext|>