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

#if defined(UNIX_ENABLED) || defined(LIBC_FILEIO_ENABLED)

#ifndef ANDROID_ENABLED
#include <sys/statvfs.h>
#endif

#include "os/memory.h"
#include "print_string.h"
#include <errno.h>
#include <stdio.h>

DirAccess *DirAccessUnix::create_fs() {

	return memnew(DirAccessUnix);
}

Error DirAccessUnix::list_dir_begin() {

	list_dir_end(); //close any previous dir opening!

	//char real_current_dir_name[2048]; //is this enough?!
	//getcwd(real_current_dir_name,2048);
	//chdir(curent_path.utf8().get_data());
	dir_stream = opendir(current_dir.utf8().get_data());
	//chdir(real_current_dir_name);
	if (!dir_stream)
		return ERR_CANT_OPEN; //error!

	return OK;
}

bool DirAccessUnix::file_exists(String p_file) {

	GLOBAL_LOCK_FUNCTION

	if (p_file.is_rel_path())
		p_file = current_dir.plus_file(p_file);

	p_file = fix_path(p_file);

	struct stat flags;
	bool success = (stat(p_file.utf8().get_data(), &flags) == 0);

	if (success && S_ISDIR(flags.st_mode)) {
		success = false;
	}

	return success;
}

bool DirAccessUnix::dir_exists(String p_dir) {

	GLOBAL_LOCK_FUNCTION

	if (p_dir.is_rel_path())
		p_dir = get_current_dir().plus_file(p_dir);

	p_dir = fix_path(p_dir);

	struct stat flags;
	bool success = (stat(p_dir.utf8().get_data(), &flags) == 0);

	if (success && S_ISDIR(flags.st_mode))
		return true;

	return false;
}

uint64_t DirAccessUnix::get_modified_time(String p_file) {

	if (p_file.is_rel_path())
		p_file = current_dir.plus_file(p_file);

	p_file = fix_path(p_file);

	struct stat flags;
	bool success = (stat(p_file.utf8().get_data(), &flags) == 0);

	if (success) {
		return flags.st_mtime;
	} else {

		ERR_FAIL_V(0);
	};
	return 0;
};

String DirAccessUnix::get_next() {

	if (!dir_stream)
		return "";
	dirent *entry;

	entry = readdir(dir_stream);

	if (entry == NULL) {

		list_dir_end();
		return "";
	}

	//typedef struct stat Stat;
	struct stat flags;

	String fname = fix_unicode_name(entry->d_name);

	String f = current_dir.plus_file(fname);

	if (stat(f.utf8().get_data(), &flags) == 0) {

		if (S_ISDIR(flags.st_mode)) {

			_cisdir = true;

		} else {

			_cisdir = false;
		}

	} else {

		_cisdir = false;
	}

	_cishidden = (fname != "." && fname != ".." && fname.begins_with("."));

	return fname;
}

bool DirAccessUnix::current_is_dir() const {

	return _cisdir;
}

bool DirAccessUnix::current_is_hidden() const {

	return _cishidden;
}

void DirAccessUnix::list_dir_end() {

	if (dir_stream)
		closedir(dir_stream);
	dir_stream = 0;
	_cisdir = false;
}

int DirAccessUnix::get_drive_count() {

	return 0;
}
String DirAccessUnix::get_drive(int p_drive) {

	return "";
}

Error DirAccessUnix::make_dir(String p_dir) {

	GLOBAL_LOCK_FUNCTION

	if (p_dir.is_rel_path())
		p_dir = get_current_dir().plus_file(p_dir);

	p_dir = fix_path(p_dir);

#if 1

	bool success = (mkdir(p_dir.utf8().get_data(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0);
	int err = errno;

#else
	char real_current_dir_name[2048];
	getcwd(real_current_dir_name, 2048);
	chdir(current_dir.utf8().get_data()); //ascii since this may be unicode or wathever the host os wants

	bool success = (mkdir(p_dir.utf8().get_data(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0);
	int err = errno;

	chdir(real_current_dir_name);
#endif
	if (success) {
		return OK;
	};

	if (err == EEXIST) {
		return ERR_ALREADY_EXISTS;
	};

	return ERR_CANT_CREATE;
}

Error DirAccessUnix::change_dir(String p_dir) {

	GLOBAL_LOCK_FUNCTION
	p_dir = fix_path(p_dir);

	char real_current_dir_name[2048];
	getcwd(real_current_dir_name, 2048);
	String prev_dir;
	if (prev_dir.parse_utf8(real_current_dir_name))
		prev_dir = real_current_dir_name; //no utf8, maybe latin?

	chdir(current_dir.utf8().get_data()); //ascii since this may be unicode or wathever the host os wants
	bool worked = (chdir(p_dir.utf8().get_data()) == 0); // we can only give this utf8

	String base = _get_root_path();
	if (base != "") {

		getcwd(real_current_dir_name, 2048);
		String new_dir;
		new_dir.parse_utf8(real_current_dir_name);
		if (!new_dir.begins_with(base))
			worked = false;
	}

	if (worked) {

		getcwd(real_current_dir_name, 2048);
		if (current_dir.parse_utf8(real_current_dir_name))
			current_dir = real_current_dir_name; //no utf8, maybe latin?
	}

	chdir(prev_dir.utf8().get_data());
	return worked ? OK : ERR_INVALID_PARAMETER;
}

String DirAccessUnix::get_current_dir() {

	String base = _get_root_path();
	if (base != "") {

		String bd = current_dir.replace_first(base, "");
		if (bd.begins_with("/"))
			return _get_root_string() + bd.substr(1, bd.length());
		else
			return _get_root_string() + bd;
	}
	return current_dir;
}

Error DirAccessUnix::rename(String p_path, String p_new_path) {

	if (p_path.is_rel_path())
		p_path = get_current_dir().plus_file(p_path);

	p_path = fix_path(p_path);

	if (p_new_path.is_rel_path())
		p_new_path = get_current_dir().plus_file(p_new_path);

	p_new_path = fix_path(p_new_path);

	return ::rename(p_path.utf8().get_data(), p_new_path.utf8().get_data()) == 0 ? OK : FAILED;
}
Error DirAccessUnix::remove(String p_path) {

	if (p_path.is_rel_path())
		p_path = get_current_dir().plus_file(p_path);

	p_path = fix_path(p_path);

	struct stat flags;
	if ((stat(p_path.utf8().get_data(), &flags) != 0))
		return FAILED;

	if (S_ISDIR(flags.st_mode))
		return ::rmdir(p_path.utf8().get_data()) == 0 ? OK : FAILED;
	else
		return ::unlink(p_path.utf8().get_data()) == 0 ? OK : FAILED;
}

size_t DirAccessUnix::get_space_left() {

#ifndef NO_STATVFS
	struct statvfs vfs;
	if (statvfs(current_dir.utf8().get_data(), &vfs) != 0) {

		return 0;
	};

	return vfs.f_bfree * vfs.f_bsize;
#else
#warning THIS IS BROKEN
	return 0;
#endif
};

DirAccessUnix::DirAccessUnix() {

	dir_stream = 0;
	current_dir = ".";
	_cisdir = false;

	/* determine drive count */

	change_dir(current_dir);
}

DirAccessUnix::~DirAccessUnix() {

	list_dir_end();
}

#endif //posix_enabled
<commit_msg>Reworked change_dir to support symlinks<commit_after>/*************************************************************************/
/*  dir_access_unix.cpp                                                  */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                    http://www.godotengine.org                         */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur.                 */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/
#include "dir_access_unix.h"

#if defined(UNIX_ENABLED) || defined(LIBC_FILEIO_ENABLED)

#ifndef ANDROID_ENABLED
#include <sys/statvfs.h>
#endif

#include "os/memory.h"
#include "print_string.h"
#include <errno.h>
#include <stdio.h>

DirAccess *DirAccessUnix::create_fs() {

	return memnew(DirAccessUnix);
}

Error DirAccessUnix::list_dir_begin() {

	list_dir_end(); //close any previous dir opening!

	//char real_current_dir_name[2048]; //is this enough?!
	//getcwd(real_current_dir_name,2048);
	//chdir(curent_path.utf8().get_data());
	dir_stream = opendir(current_dir.utf8().get_data());
	//chdir(real_current_dir_name);
	if (!dir_stream)
		return ERR_CANT_OPEN; //error!

	return OK;
}

bool DirAccessUnix::file_exists(String p_file) {

	GLOBAL_LOCK_FUNCTION

	if (p_file.is_rel_path())
		p_file = current_dir.plus_file(p_file);

	p_file = fix_path(p_file);

	struct stat flags;
	bool success = (stat(p_file.utf8().get_data(), &flags) == 0);

	if (success && S_ISDIR(flags.st_mode)) {
		success = false;
	}

	return success;
}

bool DirAccessUnix::dir_exists(String p_dir) {

	GLOBAL_LOCK_FUNCTION

	if (p_dir.is_rel_path())
		p_dir = get_current_dir().plus_file(p_dir);

	p_dir = fix_path(p_dir);

	struct stat flags;
	bool success = (stat(p_dir.utf8().get_data(), &flags) == 0);

	if (success && S_ISDIR(flags.st_mode))
		return true;

	return false;
}

uint64_t DirAccessUnix::get_modified_time(String p_file) {

	if (p_file.is_rel_path())
		p_file = current_dir.plus_file(p_file);

	p_file = fix_path(p_file);

	struct stat flags;
	bool success = (stat(p_file.utf8().get_data(), &flags) == 0);

	if (success) {
		return flags.st_mtime;
	} else {

		ERR_FAIL_V(0);
	};
	return 0;
};

String DirAccessUnix::get_next() {

	if (!dir_stream)
		return "";
	dirent *entry;

	entry = readdir(dir_stream);

	if (entry == NULL) {

		list_dir_end();
		return "";
	}

	//typedef struct stat Stat;
	struct stat flags;

	String fname = fix_unicode_name(entry->d_name);

	String f = current_dir.plus_file(fname);

	if (stat(f.utf8().get_data(), &flags) == 0) {

		if (S_ISDIR(flags.st_mode)) {

			_cisdir = true;

		} else {

			_cisdir = false;
		}

	} else {

		_cisdir = false;
	}

	_cishidden = (fname != "." && fname != ".." && fname.begins_with("."));

	return fname;
}

bool DirAccessUnix::current_is_dir() const {

	return _cisdir;
}

bool DirAccessUnix::current_is_hidden() const {

	return _cishidden;
}

void DirAccessUnix::list_dir_end() {

	if (dir_stream)
		closedir(dir_stream);
	dir_stream = 0;
	_cisdir = false;
}

int DirAccessUnix::get_drive_count() {

	return 0;
}
String DirAccessUnix::get_drive(int p_drive) {

	return "";
}

Error DirAccessUnix::make_dir(String p_dir) {

	GLOBAL_LOCK_FUNCTION

	if (p_dir.is_rel_path())
		p_dir = get_current_dir().plus_file(p_dir);

	p_dir = fix_path(p_dir);

#if 1

	bool success = (mkdir(p_dir.utf8().get_data(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0);
	int err = errno;

#else
	char real_current_dir_name[2048];
	getcwd(real_current_dir_name, 2048);
	chdir(current_dir.utf8().get_data()); //ascii since this may be unicode or wathever the host os wants

	bool success = (mkdir(p_dir.utf8().get_data(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0);
	int err = errno;

	chdir(real_current_dir_name);
#endif
	if (success) {
		return OK;
	};

	if (err == EEXIST) {
		return ERR_ALREADY_EXISTS;
	};

	return ERR_CANT_CREATE;
}

Error DirAccessUnix::change_dir(String p_dir) {

	GLOBAL_LOCK_FUNCTION

	// make sure current_dir is valid absolute path
	if (current_dir == "." || current_dir == "") {
		char real_current_dir_name[2048];
		getcwd(real_current_dir_name, 2048);
		current_dir.parse_utf8(real_current_dir_name);
	}

	if (p_dir == ".") {
		return OK;
	}

	p_dir = fix_path(p_dir);

	String prev_dir = current_dir;

	if (p_dir.is_rel_path()) {
		String next_dir = current_dir + "/" + p_dir;
		next_dir = next_dir.simplify_path();
		current_dir = next_dir;
	} else {
		current_dir = p_dir;
	}

	bool worked = (chdir(current_dir.utf8().get_data()) == 0); // we can only give this utf8
	if (!worked) {
		current_dir = prev_dir;
		return ERR_INVALID_PARAMETER;
	}

	return OK;
}

String DirAccessUnix::get_current_dir() {

	String base = _get_root_path();
	if (base != "") {

		String bd = current_dir.replace_first(base, "");
		if (bd.begins_with("/"))
			return _get_root_string() + bd.substr(1, bd.length());
		else
			return _get_root_string() + bd;
	}
	return current_dir;
}

Error DirAccessUnix::rename(String p_path, String p_new_path) {

	if (p_path.is_rel_path())
		p_path = get_current_dir().plus_file(p_path);

	p_path = fix_path(p_path);

	if (p_new_path.is_rel_path())
		p_new_path = get_current_dir().plus_file(p_new_path);

	p_new_path = fix_path(p_new_path);

	return ::rename(p_path.utf8().get_data(), p_new_path.utf8().get_data()) == 0 ? OK : FAILED;
}
Error DirAccessUnix::remove(String p_path) {

	if (p_path.is_rel_path())
		p_path = get_current_dir().plus_file(p_path);

	p_path = fix_path(p_path);

	struct stat flags;
	if ((stat(p_path.utf8().get_data(), &flags) != 0))
		return FAILED;

	if (S_ISDIR(flags.st_mode))
		return ::rmdir(p_path.utf8().get_data()) == 0 ? OK : FAILED;
	else
		return ::unlink(p_path.utf8().get_data()) == 0 ? OK : FAILED;
}

size_t DirAccessUnix::get_space_left() {

#ifndef NO_STATVFS
	struct statvfs vfs;
	if (statvfs(current_dir.utf8().get_data(), &vfs) != 0) {

		return 0;
	};

	return vfs.f_bfree * vfs.f_bsize;
#else
#warning THIS IS BROKEN
	return 0;
#endif
};

DirAccessUnix::DirAccessUnix() {

	dir_stream = 0;
	current_dir = ".";
	_cisdir = false;

	/* determine drive count */

	change_dir(current_dir);
}

DirAccessUnix::~DirAccessUnix() {

	list_dir_end();
}

#endif //posix_enabled
<|endoftext|>


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

#ifndef DUNE_GDT_ASSEMBLER_GRIDWALKER_HH
#define DUNE_GDT_ASSEMBLER_GRIDWALKER_HH

#include <vector>
#include <memory>
#include <type_traits>

#include <dune/stuff/grid/boundaryinfo.hh>

namespace Dune {
namespace GDT {
namespace Functor {

template <class GridViewImp>
class Codim0
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;

  virtual ~Codim0()
  {
  }

  virtual void prepare()
  {
  }

  virtual void apply_local(const EntityType& entity) = 0;

  virtual void finalize()
  {
  }
}; // class Codim0

template <class GridViewImp>
class Codim1
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual ~Codim1()
  {
  }

  virtual void prepare()
  {
  }

  virtual void apply_local(const IntersectionType& intersection) = 0;

  virtual void finalize()
  {
  }
}; // class Codim1

} // namespace Functor
namespace ApplyOn {

/**
 *  \brief Interface for functors to tell on which entity to apply.
 *
 *  The derived class has to provide a method with the following signature:
 *  \code
virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const
{
  ...
}
\endcode
 */
template <class GridViewImp>
class WhichEntity
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;

  virtual ~WhichEntity()
  {
  }

  virtual bool apply_on(const GridViewType& /*grid_view*/, const EntityType& /*entity*/) const = 0;
}; // class WhichEntity

/**
 *  \brief Selects all entities.
 */
template <class GridViewImp>
class AllEntities : public WhichEntity<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;

  virtual bool apply_on(const GridViewType& /*grid_view*/, const EntityType& /*entity*/) const DS_FINAL
  {
    return true;
  }
}; // class AllEntities

/**
 *  \brief Selects entities which have a boundary intersection.
 */
template <class GridViewImp>
class BoundaryEntities : public WhichEntity<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;

  virtual bool apply_on(const GridViewType& /*grid_view*/, const EntityType& entity) const DS_FINAL
  {
    return entity.hasBoundaryIntersections();
  }
}; // class BoundaryEntities

/**
 *  \brief Interface for functors to tell on which intersection to apply.
 *
 *  The derived class has to provide a method with the following signature:
 *  \code
virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const
{
  ...
}
\endcode
 */
template <class GridViewImp>
class WhichIntersection
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual ~WhichIntersection<GridViewImp>()
  {
  }

  virtual bool apply_on(const GridViewType& /*grid_view*/, const IntersectionType& /*intersection*/) const = 0;
}; // class WhichIntersection< GridViewImp >

/**
 *  \brief Selects all intersections.
 */
template <class GridViewImp>
class AllIntersections : public WhichIntersection<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual bool apply_on(const GridViewType& /*grid_view*/, const IntersectionType& /*intersection*/) const DS_FINAL
  {
    return true;
  }
}; // class AllIntersections

/**
 *  \brief Selects each inner intersection.
 *
 *  To decide if this in an inner intersection,
\code
intersection.neighbor() && !intersection.boundary()
\endcode
 *  is used.
 */
template <class GridViewImp>
class InnerIntersections : public WhichIntersection<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual bool apply_on(const GridViewType& /*grid_view*/, const IntersectionType& intersection) const DS_FINAL
  {
    return intersection.neighbor() && !intersection.boundary();
  }
}; // class InnerIntersections

/**
 *  \brief Selects each inner intersection only once.
 *
 *  To decide if this in an inner intersection,
\code
intersection.neighbor() && !intersection.boundary()
\endcode
 *  is used, and true is returned, if the index of the inside() entity is smaller than the index of the outside()
 *  entity.
 */
template <class GridViewImp>
class InnerIntersectionsPrimally : public WhichIntersection<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const DS_FINAL
  {
    if (intersection.neighbor() && !intersection.boundary()) {
      const auto insideEntityPtr    = intersection.inside();
      const auto& insideEntity      = *insideEntityPtr;
      const auto outsideNeighborPtr = intersection.outside();
      const auto& outsideNeighbor = *outsideNeighborPtr;
      return grid_view.indexSet().index(insideEntity) < grid_view.indexSet().index(outsideNeighbor);
    } else
      return false;
  }
}; // class InnerIntersections

template <class GridViewImp>
class BoundaryIntersections : public WhichIntersection<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual bool apply_on(const GridViewType& /*grid_view*/, const IntersectionType& intersection) const DS_FINAL
  {
    return intersection.boundary();
  }
}; // class BoundaryIntersections

template <class GridViewImp>
class DirichletIntersections : public WhichIntersection<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;
  typedef Stuff::GridboundaryInterface<IntersectionType> BoundaryInfoType;

  DirichletIntersections(const BoundaryInfoType& boundary_info)
    : boundary_info_(boundary_info)
  {
  }

  virtual bool apply_on(const GridViewType& /*grid_view*/, const IntersectionType& intersection) const DS_FINAL
  {
    return boundary_info_.dirichlet(intersection);
  }

private:
  const BoundaryInfoType& boundary_info_;
}; // class DirichletIntersections

template <class GridViewImp>
class NeumannIntersections : public WhichIntersection<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;
  typedef Stuff::GridboundaryInterface<IntersectionType> BoundaryInfoType;

  NeumannIntersections(const BoundaryInfoType& boundary_info)
    : boundary_info_(boundary_info)
  {
  }

  virtual bool apply_on(const GridViewType& /*grid_view*/, const IntersectionType& intersection) const DS_FINAL
  {
    return boundary_info_.neumann(intersection);
  }

private:
  const BoundaryInfoType& boundary_info_;
}; // class NeumannIntersections

} // namespace ApplyOn

template <class GridViewImp>
class GridWalker
{
  typedef GridWalker<GridViewImp> ThisType;

public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;
  typedef typename GridViewType::Intersection IntersectionType;

protected:
  typedef Stuff::GridboundaryInterface<IntersectionType> BoundaryInfoType;

  class Codim0Object : public Functor::Codim0<GridViewType>
  {
  public:
    ~Codim0Object()
    {
    }
    virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const = 0;
  };

  template <class Codim0FunctorType>
  class Codim0FunctorWrapper : public Codim0Object
  {
  public:
    Codim0FunctorWrapper(Codim0FunctorType& wrapped_functor, const ApplyOn::WhichEntity<GridViewType>* where)
      : wrapped_functor_(wrapped_functor)
      , where_(where)
    {
    }

    virtual ~Codim0FunctorWrapper()
    {
    }

    virtual void prepare() DS_FINAL
    {
      wrapped_functor_.prepare();
    }

    virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const DS_FINAL
    {
      return where_->apply_on(grid_view, entity);
    }

    virtual void apply_local(const EntityType& entity) DS_FINAL
    {
      wrapped_functor_.apply_local(entity);
    }

    virtual void finalize() DS_FINAL
    {
      wrapped_functor_.finalize();
    }

  private:
    Codim0FunctorType& wrapped_functor_;
    std::unique_ptr<const ApplyOn::WhichEntity<GridViewType>> where_;
  }; // class Codim0FunctorWrapper

  class Codim1Object : public Functor::Codim1<GridViewType>
  {
  public:
    ~Codim1Object()
    {
    }
    virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const = 0;
  };

  template <class Codim1FunctorType>
  class Codim1FunctorWrapper : public Codim1Object
  {
  public:
    Codim1FunctorWrapper(Codim1FunctorType& wrapped_functor, const ApplyOn::WhichIntersection<GridViewType>* where)
      : wrapped_functor_(wrapped_functor)
      , where_(where)
    {
    }

    virtual void prepare() DS_FINAL
    {
      wrapped_functor_.prepare();
    }

    virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const DS_FINAL
    {
      return where_->apply_on(grid_view, intersection);
    }

    virtual void apply_local(const IntersectionType& intersection) DS_FINAL
    {
      wrapped_functor_.apply_local(intersection);
    }

    virtual void finalize() DS_FINAL
    {
      wrapped_functor_.finalize();
    }

  private:
    Codim1FunctorType& wrapped_functor_;
    std::unique_ptr<const ApplyOn::WhichIntersection<GridViewType>> where_;
  }; // class Codim1FunctorWrapper

public:
  GridWalker(const GridViewType& grid_view)
    : grid_view_(grid_view)
  {
  }

  const GridViewType& grid_view() const
  {
    return grid_view_;
  }

  void add(Functor::Codim0<GridViewType>& functor,
           const ApplyOn::WhichEntity<GridViewType>* where = new ApplyOn::AllEntities<GridViewType>())
  {
    codim0_functors_.emplace_back(new Codim0FunctorWrapper<Functor::Codim0<GridViewType>>(functor, where));
  }

  void add(Functor::Codim1<GridViewType>& functor,
           const ApplyOn::WhichIntersection<GridViewType>* where = new ApplyOn::AllIntersections<GridViewType>())
  {
    codim1_functors_.emplace_back(new Codim1FunctorWrapper<Functor::Codim1<GridViewType>>(functor, where));
  }

  void walk(const bool clear_stack = true)
  {
    // prepare functors
    for (auto& functor : codim0_functors_)
      functor->prepare();
    for (auto& functor : codim1_functors_)
      functor->prepare();

    // only do something, if we have to
    if ((codim0_functors_.size() + codim1_functors_.size()) > 0) {
      // walk the grid
      const auto entity_it_end = grid_view_.template end<0>();
      for (auto entity_it = grid_view_.template begin<0>(); entity_it != entity_it_end; ++entity_it) {
        const EntityType& entity = *entity_it;

        // apply codim0 functors
        for (auto& functor : codim0_functors_)
          if (functor->apply_on(grid_view_, entity))
            functor->apply_local(entity);

        // only walk the intersections, if there are codim1 functors present
        if (codim1_functors_.size() > 0) {
          // walk the intersections
          const auto intersection_it_end = grid_view_.iend(entity);
          for (auto intersection_it = grid_view_.ibegin(entity); intersection_it != intersection_it_end;
               ++intersection_it) {
            const auto& intersection = *intersection_it;

            // apply codim1 functors
            for (auto& functor : codim1_functors_)
              if (functor->apply_on(grid_view_, intersection))
                functor->apply_local(intersection);

          } // walk the intersections
        } // only walk the intersections, if there are codim1 functors present
      } // walk the grid
    } // only do something, if we have to

    // finalize functors
    for (auto& functor : codim0_functors_)
      functor->finalize();
    for (auto& functor : codim1_functors_)
      functor->finalize();

    // clear the stack of functors
    if (clear_stack)
      clear();
  } // ... walk()

  void clear()
  {
    codim0_functors_ = std::vector<std::unique_ptr<Codim0Object>>();
    codim1_functors_ = std::vector<std::unique_ptr<Codim1Object>>();
  }

protected:
  const GridViewType& grid_view_;
  std::vector<std::unique_ptr<Codim0Object>> codim0_functors_;
  std::vector<std::unique_ptr<Codim1Object>> codim1_functors_;
}; // class GridWalker

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_ASSEMBLER_GRIDWALKER_HH
<commit_msg>[assembler.gridwalker] added override and final keywords<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_ASSEMBLER_GRIDWALKER_HH
#define DUNE_GDT_ASSEMBLER_GRIDWALKER_HH

#include <vector>
#include <memory>
#include <type_traits>

#include <dune/stuff/grid/boundaryinfo.hh>

namespace Dune {
namespace GDT {
namespace Functor {

template <class GridViewImp>
class Codim0
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;

  virtual ~Codim0()
  {
  }

  virtual void prepare()
  {
  }

  virtual void apply_local(const EntityType& entity) = 0;

  virtual void finalize()
  {
  }
}; // class Codim0

template <class GridViewImp>
class Codim1
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual ~Codim1()
  {
  }

  virtual void prepare()
  {
  }

  virtual void apply_local(const IntersectionType& intersection) = 0;

  virtual void finalize()
  {
  }
}; // class Codim1

} // namespace Functor
namespace ApplyOn {

/**
 *  \brief Interface for functors to tell on which entity to apply.
 *
 *  The derived class has to provide a method with the following signature:
 *  \code
virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const
{
  ...
}
\endcode
 */
template <class GridViewImp>
class WhichEntity
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;

  virtual ~WhichEntity()
  {
  }

  virtual bool apply_on(const GridViewType& /*grid_view*/, const EntityType& /*entity*/) const = 0;
}; // class WhichEntity

/**
 *  \brief Selects all entities.
 */
template <class GridViewImp>
class AllEntities : public WhichEntity<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;

  virtual bool apply_on(const GridViewType& /*grid_view*/, const EntityType& /*entity*/) const DS_OVERRIDE DS_FINAL
  {
    return true;
  }
}; // class AllEntities

/**
 *  \brief Selects entities which have a boundary intersection.
 */
template <class GridViewImp>
class BoundaryEntities : public WhichEntity<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;

  virtual bool apply_on(const GridViewType& /*grid_view*/, const EntityType& entity) const DS_OVERRIDE DS_FINAL
  {
    return entity.hasBoundaryIntersections();
  }
}; // class BoundaryEntities

/**
 *  \brief Interface for functors to tell on which intersection to apply.
 *
 *  The derived class has to provide a method with the following signature:
 *  \code
virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const
{
  ...
}
\endcode
 */
template <class GridViewImp>
class WhichIntersection
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual ~WhichIntersection<GridViewImp>()
  {
  }

  virtual bool apply_on(const GridViewType& /*grid_view*/, const IntersectionType& /*intersection*/) const = 0;
}; // class WhichIntersection< GridViewImp >

/**
 *  \brief Selects all intersections.
 */
template <class GridViewImp>
class AllIntersections : public WhichIntersection<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual bool apply_on(const GridViewType& /*grid_view*/,
                        const IntersectionType& /*intersection*/) const DS_OVERRIDE DS_FINAL
  {
    return true;
  }
}; // class AllIntersections

/**
 *  \brief Selects each inner intersection.
 *
 *  To decide if this in an inner intersection,
\code
intersection.neighbor() && !intersection.boundary()
\endcode
 *  is used.
 */
template <class GridViewImp>
class InnerIntersections : public WhichIntersection<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual bool apply_on(const GridViewType& /*grid_view*/,
                        const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
  {
    return intersection.neighbor() && !intersection.boundary();
  }
}; // class InnerIntersections

/**
 *  \brief Selects each inner intersection only once.
 *
 *  To decide if this in an inner intersection,
\code
intersection.neighbor() && !intersection.boundary()
\endcode
 *  is used, and true is returned, if the index of the inside() entity is smaller than the index of the outside()
 *  entity.
 */
template <class GridViewImp>
class InnerIntersectionsPrimally : public WhichIntersection<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
  {
    if (intersection.neighbor() && !intersection.boundary()) {
      const auto insideEntityPtr    = intersection.inside();
      const auto& insideEntity      = *insideEntityPtr;
      const auto outsideNeighborPtr = intersection.outside();
      const auto& outsideNeighbor = *outsideNeighborPtr;
      return grid_view.indexSet().index(insideEntity) < grid_view.indexSet().index(outsideNeighbor);
    } else
      return false;
  }
}; // class InnerIntersections

template <class GridViewImp>
class BoundaryIntersections : public WhichIntersection<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual bool apply_on(const GridViewType& /*grid_view*/,
                        const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
  {
    return intersection.boundary();
  }
}; // class BoundaryIntersections

template <class GridViewImp>
class DirichletIntersections : public WhichIntersection<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;
  typedef Stuff::GridboundaryInterface<IntersectionType> BoundaryInfoType;

  DirichletIntersections(const BoundaryInfoType& boundary_info)
    : boundary_info_(boundary_info)
  {
  }

  virtual bool apply_on(const GridViewType& /*grid_view*/,
                        const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
  {
    return boundary_info_.dirichlet(intersection);
  }

private:
  const BoundaryInfoType& boundary_info_;
}; // class DirichletIntersections

template <class GridViewImp>
class NeumannIntersections : public WhichIntersection<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;
  typedef Stuff::GridboundaryInterface<IntersectionType> BoundaryInfoType;

  NeumannIntersections(const BoundaryInfoType& boundary_info)
    : boundary_info_(boundary_info)
  {
  }

  virtual bool apply_on(const GridViewType& /*grid_view*/,
                        const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
  {
    return boundary_info_.neumann(intersection);
  }

private:
  const BoundaryInfoType& boundary_info_;
}; // class NeumannIntersections

} // namespace ApplyOn

template <class GridViewImp>
class GridWalker
{
  typedef GridWalker<GridViewImp> ThisType;

public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;
  typedef typename GridViewType::Intersection IntersectionType;

protected:
  typedef Stuff::GridboundaryInterface<IntersectionType> BoundaryInfoType;

  class Codim0Object : public Functor::Codim0<GridViewType>
  {
  public:
    ~Codim0Object()
    {
    }
    virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const = 0;
  };

  template <class Codim0FunctorType>
  class Codim0FunctorWrapper : public Codim0Object
  {
  public:
    Codim0FunctorWrapper(Codim0FunctorType& wrapped_functor, const ApplyOn::WhichEntity<GridViewType>* where)
      : wrapped_functor_(wrapped_functor)
      , where_(where)
    {
    }

    virtual ~Codim0FunctorWrapper()
    {
    }

    virtual void prepare() DS_OVERRIDE DS_FINAL
    {
      wrapped_functor_.prepare();
    }

    virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const DS_OVERRIDE DS_FINAL
    {
      return where_->apply_on(grid_view, entity);
    }

    virtual void apply_local(const EntityType& entity) DS_OVERRIDE DS_FINAL
    {
      wrapped_functor_.apply_local(entity);
    }

    virtual void finalize() DS_OVERRIDE DS_FINAL
    {
      wrapped_functor_.finalize();
    }

  private:
    Codim0FunctorType& wrapped_functor_;
    std::unique_ptr<const ApplyOn::WhichEntity<GridViewType>> where_;
  }; // class Codim0FunctorWrapper

  class Codim1Object : public Functor::Codim1<GridViewType>
  {
  public:
    ~Codim1Object()
    {
    }
    virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const = 0;
  };

  template <class Codim1FunctorType>
  class Codim1FunctorWrapper : public Codim1Object
  {
  public:
    Codim1FunctorWrapper(Codim1FunctorType& wrapped_functor, const ApplyOn::WhichIntersection<GridViewType>* where)
      : wrapped_functor_(wrapped_functor)
      , where_(where)
    {
    }

    virtual void prepare() DS_OVERRIDE DS_FINAL
    {
      wrapped_functor_.prepare();
    }

    virtual bool apply_on(const GridViewType& grid_view,
                          const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
    {
      return where_->apply_on(grid_view, intersection);
    }

    virtual void apply_local(const IntersectionType& intersection) DS_OVERRIDE DS_FINAL
    {
      wrapped_functor_.apply_local(intersection);
    }

    virtual void finalize() DS_OVERRIDE DS_FINAL
    {
      wrapped_functor_.finalize();
    }

  private:
    Codim1FunctorType& wrapped_functor_;
    std::unique_ptr<const ApplyOn::WhichIntersection<GridViewType>> where_;
  }; // class Codim1FunctorWrapper

public:
  GridWalker(const GridViewType& grid_view)
    : grid_view_(grid_view)
  {
  }

  const GridViewType& grid_view() const
  {
    return grid_view_;
  }

  void add(Functor::Codim0<GridViewType>& functor,
           const ApplyOn::WhichEntity<GridViewType>* where = new ApplyOn::AllEntities<GridViewType>())
  {
    codim0_functors_.emplace_back(new Codim0FunctorWrapper<Functor::Codim0<GridViewType>>(functor, where));
  }

  void add(Functor::Codim1<GridViewType>& functor,
           const ApplyOn::WhichIntersection<GridViewType>* where = new ApplyOn::AllIntersections<GridViewType>())
  {
    codim1_functors_.emplace_back(new Codim1FunctorWrapper<Functor::Codim1<GridViewType>>(functor, where));
  }

  void walk(const bool clear_stack = true)
  {
    // prepare functors
    for (auto& functor : codim0_functors_)
      functor->prepare();
    for (auto& functor : codim1_functors_)
      functor->prepare();

    // only do something, if we have to
    if ((codim0_functors_.size() + codim1_functors_.size()) > 0) {
      // walk the grid
      const auto entity_it_end = grid_view_.template end<0>();
      for (auto entity_it = grid_view_.template begin<0>(); entity_it != entity_it_end; ++entity_it) {
        const EntityType& entity = *entity_it;

        // apply codim0 functors
        for (auto& functor : codim0_functors_)
          if (functor->apply_on(grid_view_, entity))
            functor->apply_local(entity);

        // only walk the intersections, if there are codim1 functors present
        if (codim1_functors_.size() > 0) {
          // walk the intersections
          const auto intersection_it_end = grid_view_.iend(entity);
          for (auto intersection_it = grid_view_.ibegin(entity); intersection_it != intersection_it_end;
               ++intersection_it) {
            const auto& intersection = *intersection_it;

            // apply codim1 functors
            for (auto& functor : codim1_functors_)
              if (functor->apply_on(grid_view_, intersection))
                functor->apply_local(intersection);

          } // walk the intersections
        } // only walk the intersections, if there are codim1 functors present
      } // walk the grid
    } // only do something, if we have to

    // finalize functors
    for (auto& functor : codim0_functors_)
      functor->finalize();
    for (auto& functor : codim1_functors_)
      functor->finalize();

    // clear the stack of functors
    if (clear_stack)
      clear();
  } // ... walk(...)

  void clear()
  {
    codim0_functors_ = std::vector<std::unique_ptr<Codim0Object>>();
    codim1_functors_ = std::vector<std::unique_ptr<Codim1Object>>();
  } // ... clear()

protected:
  const GridViewType& grid_view_;
  std::vector<std::unique_ptr<Codim0Object>> codim0_functors_;
  std::vector<std::unique_ptr<Codim1Object>> codim1_functors_;
}; // class GridWalker

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_ASSEMBLER_GRIDWALKER_HH
<|endoftext|>


<commit_before>// dune-multiscale
// Copyright Holders: Patrick Henning, Rene Milk
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_MULTISCALE_COMMON_TRAITS_HH
#define DUNE_MULTISCALE_COMMON_TRAITS_HH

#include <dune/multiscale/common/la_backend.hh>
#include <dune/common/tuples.hh>
#include <dune/grid/yaspgrid.hh>
#include <dune/grid/sgrid.hh>
#include <dune/fem/space/common/functionspace.hh>
#include <dune/fem/gridpart/adaptiveleafgridpart.hh>
#include <dune/fem/space/lagrange.hh>
#include <dune/fem/quadrature/cachingquadrature.hh>
#include <dune/pdelab/gridfunctionspace/gridfunctionspace.hh>
#include <dune/pdelab/finiteelementmap/qkfem.hh>
#include <dune/pdelab/backend/istlvectorbackend.hh>
#include <dune/pdelab/backend/backendselector.hh>
#include <dune/pdelab/constraints/conforming.hh>

#include <dune/stuff/common/memory.hh>
#include <dune/stuff/aliases.hh>

namespace Dune {

template <class T>
struct GridPtr;

namespace PDELab {

class NoConstraints;
//class ConformingDirichletConstraints;

} //namespace PDELab

namespace Fem {
template <class T, class R>
class GridFunctionAdapter;
template <class T, class R>
class DataOutput;
template <class T, class R>
class DataWriter;
template <class T, class R>
class AdaptationManager;
} // namespace Fem

namespace Stuff {
template <class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim>
class GlobalFunction;
template <class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim>
class GlobalConstantFunction;
}
namespace Multiscale {
namespace Problem {

struct DiffusionBase;
struct LowerOrderBase;
class NeumannDataBase;
class DirichletDataBase;
class IModelProblemData;

} // namespace Problem

//! type construction for the HMM algorithm
struct CommonTraits {
  static constexpr int world_dim = 2;
//  typedef Dune::GridSelector::GridType GridType;
  typedef Dune::SGrid<world_dim, world_dim> GridType;
//  typedef Dune::YaspGrid<world_dim> GridType;
  typedef GridType::Codim<0>::Entity EntityType;
  typedef Dune::Fem::AdaptiveLeafGridPart<GridType> GridPartType;
  typedef Dune::GridPtr<GridType> GridPointerType;
  typedef double FieldType;
  typedef Dune::Fem::FunctionSpace<FieldType, FieldType, GridType::dimension, 1> FunctionSpaceType;

  typedef Dune::Stuff::GlobalFunction<EntityType, FunctionSpaceType::DomainFieldType, FunctionSpaceType::dimDomain,
                                      FunctionSpaceType::RangeFieldType, FunctionSpaceType::dimRange> FunctionBaseType;

  typedef Dune::Stuff::GlobalConstantFunction<EntityType, FunctionSpaceType::DomainFieldType,
                                              FunctionSpaceType::dimDomain, FunctionSpaceType::RangeFieldType,
                                              FunctionSpaceType::dimRange> ConstantFunctionBaseType;

  typedef Problem::IModelProblemData ModelProblemDataType;
  //! type of first source term (right hand side of differential equation or type of 'f')
  typedef FunctionBaseType FirstSourceType;
  //! type of second source term 'G' (second right hand side of differential equation 'div G')
  typedef FunctionBaseType SecondSourceType;
  //! type of (possibly non-linear) diffusion term (i.e. 'A^{\epsilon}')
  typedef Problem::DiffusionBase DiffusionType;
  //! type of (possibly non-linear) lower order term F( x, u(x), grad u(x) )
  typedef Problem::LowerOrderBase LowerOrderTermType;
  //! type of inhomogeneous Dirichlet boundary condition
  typedef FunctionBaseType DirichletBCType;
  //! type of inhomogeneous Neumann boundary condition
  typedef FunctionBaseType NeumannBCType;
  //! type of dirichlet data
  typedef Problem::DirichletDataBase DirichletDataType;
  //! type of neumann data
  typedef Problem::NeumannDataBase NeumannDataType;
  //! type of mass (or reaction) term (i.e. 'm' or 'c')
  typedef FunctionBaseType MassTermType;
  //! default type for any missing coefficient function (e.g. advection,...)
  typedef FunctionBaseType DefaultDummyFunctionType;

  //! type of exact solution (in general unknown)
  typedef FunctionBaseType ExactSolutionType;
  static constexpr unsigned int exact_solution_space_order = 3 * st_lagrangespace_order;

  typedef FunctionSpaceType::DomainType DomainType;
  //! define the type of elements of the codomain v(\Omega) (typically a subset of \R)
  typedef FunctionSpaceType::RangeType RangeType;
  //! defines the function space to which the numerical solution belongs to
  //! see dune/fem/lagrangebase.hh
  typedef Dune::Fem::LagrangeDiscreteFunctionSpace<FunctionSpaceType, GridPartType, st_lagrangespace_order>
  DiscreteFunctionSpaceType;
  typedef DiscreteFunctionSpaceType::DomainFieldType TimeType;
  typedef DiscreteFunctionSpaceType::JacobianRangeType JacobianRangeType;

  typedef GridPartType::IntersectionType FaceType;
  typedef GridType::Codim<0>::EntityPointer EntityPointerType;
  typedef GridType::Codim<0>::Geometry EntityGeometryType;
  typedef GridType::Codim<1>::Geometry FaceGeometryType;
  //!TODO carry the rename over to the type def'ed name
  typedef DiscreteFunctionSpaceType::BasisFunctionSetType BasisFunctionSetType;
  typedef DiscreteFunctionSpaceType::RangeFieldType RangeFieldType;

  typedef BackendChooser<DiscreteFunctionSpaceType>::DiscreteFunctionType DiscreteFunctionType;
  typedef std::shared_ptr<DiscreteFunctionType> DiscreteFunction_ptr;
  typedef BackendChooser<DiscreteFunctionSpaceType>::LinearOperatorType LinearOperatorType;

  typedef std::vector<RangeType> RangeVector;
  typedef std::vector<RangeVector> RangeVectorVector;

  static constexpr int polynomial_order = DiscreteFunctionSpaceType::polynomialOrder;
  static constexpr int quadrature_order = 2 * polynomial_order + 2;

  typedef PDELab::QkLocalFiniteElementMap<GridType::LeafGridView,GridType::ctype,FieldType,polynomial_order>
  FEMapType;
  typedef BackendChooser<DiscreteFunctionSpaceType>::VectorBackendType VectorBackendType;
  typedef PDELab::GridFunctionSpace<GridType::LeafGridView,FEMapType,PDELab::ConformingDirichletConstraints,
            VectorBackendType> GridFunctionSpaceType;
  typedef typename PDELab::BackendVectorSelector<GridFunctionSpaceType,FieldType>::Type PdelabVectorType;

};

template <class T = CommonTraits::DiscreteFunctionType>
std::shared_ptr<T> make_df_ptr(const std::string name, const typename T::DiscreteFunctionSpaceType& space) {
  return std::make_shared<T>(name, space);
  //  return DSC::make_unique<T>(name, space);
}

} // namespace Multiscale
} // namespace Dune

#endif // DUNE_MULTISCALE_COMMON_TRAITS_HH
<commit_msg>[common.traits] updated stuff.function.global signature<commit_after>// dune-multiscale
// Copyright Holders: Patrick Henning, Rene Milk
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_MULTISCALE_COMMON_TRAITS_HH
#define DUNE_MULTISCALE_COMMON_TRAITS_HH

#include <dune/multiscale/common/la_backend.hh>
#include <dune/common/tuples.hh>
#include <dune/grid/yaspgrid.hh>
#include <dune/grid/sgrid.hh>
#include <dune/fem/space/common/functionspace.hh>
#include <dune/fem/gridpart/adaptiveleafgridpart.hh>
#include <dune/fem/space/lagrange.hh>
#include <dune/fem/quadrature/cachingquadrature.hh>
#include <dune/pdelab/gridfunctionspace/gridfunctionspace.hh>
#include <dune/pdelab/finiteelementmap/qkfem.hh>
#include <dune/pdelab/backend/istlvectorbackend.hh>
#include <dune/pdelab/backend/backendselector.hh>
#include <dune/pdelab/constraints/conforming.hh>

#include <dune/stuff/common/memory.hh>
#include <dune/stuff/aliases.hh>

namespace Dune {

template <class T>
struct GridPtr;

namespace PDELab {

class NoConstraints;
//class ConformingDirichletConstraints;

} //namespace PDELab

namespace Fem {
template <class T, class R>
class GridFunctionAdapter;
template <class T, class R>
class DataOutput;
template <class T, class R>
class DataWriter;
template <class T, class R>
class AdaptationManager;
} // namespace Fem

namespace Stuff {
template <class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCol = 1 >
class GlobalFunction;
template <class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCol = 1 >
class GlobalConstantFunction;
}
namespace Multiscale {
namespace Problem {

struct DiffusionBase;
struct LowerOrderBase;
class NeumannDataBase;
class DirichletDataBase;
class IModelProblemData;

} // namespace Problem

//! type construction for the HMM algorithm
struct CommonTraits {
  static constexpr int world_dim = 2;
//  typedef Dune::GridSelector::GridType GridType;
  typedef Dune::SGrid<world_dim, world_dim> GridType;
//  typedef Dune::YaspGrid<world_dim> GridType;
  typedef GridType::Codim<0>::Entity EntityType;
  typedef Dune::Fem::AdaptiveLeafGridPart<GridType> GridPartType;
  typedef Dune::GridPtr<GridType> GridPointerType;
  typedef double FieldType;
  typedef Dune::Fem::FunctionSpace<FieldType, FieldType, GridType::dimension, 1> FunctionSpaceType;

  typedef Dune::Stuff::GlobalFunction<EntityType, FunctionSpaceType::DomainFieldType, FunctionSpaceType::dimDomain,
                                      FunctionSpaceType::RangeFieldType, FunctionSpaceType::dimRange> FunctionBaseType;

  typedef Dune::Stuff::GlobalConstantFunction<EntityType, FunctionSpaceType::DomainFieldType,
                                              FunctionSpaceType::dimDomain, FunctionSpaceType::RangeFieldType,
                                              FunctionSpaceType::dimRange> ConstantFunctionBaseType;

  typedef Problem::IModelProblemData ModelProblemDataType;
  //! type of first source term (right hand side of differential equation or type of 'f')
  typedef FunctionBaseType FirstSourceType;
  //! type of second source term 'G' (second right hand side of differential equation 'div G')
  typedef FunctionBaseType SecondSourceType;
  //! type of (possibly non-linear) diffusion term (i.e. 'A^{\epsilon}')
  typedef Problem::DiffusionBase DiffusionType;
  //! type of (possibly non-linear) lower order term F( x, u(x), grad u(x) )
  typedef Problem::LowerOrderBase LowerOrderTermType;
  //! type of inhomogeneous Dirichlet boundary condition
  typedef FunctionBaseType DirichletBCType;
  //! type of inhomogeneous Neumann boundary condition
  typedef FunctionBaseType NeumannBCType;
  //! type of dirichlet data
  typedef Problem::DirichletDataBase DirichletDataType;
  //! type of neumann data
  typedef Problem::NeumannDataBase NeumannDataType;
  //! type of mass (or reaction) term (i.e. 'm' or 'c')
  typedef FunctionBaseType MassTermType;
  //! default type for any missing coefficient function (e.g. advection,...)
  typedef FunctionBaseType DefaultDummyFunctionType;

  //! type of exact solution (in general unknown)
  typedef FunctionBaseType ExactSolutionType;
  static constexpr unsigned int exact_solution_space_order = 3 * st_lagrangespace_order;

  typedef FunctionSpaceType::DomainType DomainType;
  //! define the type of elements of the codomain v(\Omega) (typically a subset of \R)
  typedef FunctionSpaceType::RangeType RangeType;
  //! defines the function space to which the numerical solution belongs to
  //! see dune/fem/lagrangebase.hh
  typedef Dune::Fem::LagrangeDiscreteFunctionSpace<FunctionSpaceType, GridPartType, st_lagrangespace_order>
  DiscreteFunctionSpaceType;
  typedef DiscreteFunctionSpaceType::DomainFieldType TimeType;
  typedef DiscreteFunctionSpaceType::JacobianRangeType JacobianRangeType;

  typedef GridPartType::IntersectionType FaceType;
  typedef GridType::Codim<0>::EntityPointer EntityPointerType;
  typedef GridType::Codim<0>::Geometry EntityGeometryType;
  typedef GridType::Codim<1>::Geometry FaceGeometryType;
  //!TODO carry the rename over to the type def'ed name
  typedef DiscreteFunctionSpaceType::BasisFunctionSetType BasisFunctionSetType;
  typedef DiscreteFunctionSpaceType::RangeFieldType RangeFieldType;

  typedef BackendChooser<DiscreteFunctionSpaceType>::DiscreteFunctionType DiscreteFunctionType;
  typedef std::shared_ptr<DiscreteFunctionType> DiscreteFunction_ptr;
  typedef BackendChooser<DiscreteFunctionSpaceType>::LinearOperatorType LinearOperatorType;

  typedef std::vector<RangeType> RangeVector;
  typedef std::vector<RangeVector> RangeVectorVector;

  static constexpr int polynomial_order = DiscreteFunctionSpaceType::polynomialOrder;
  static constexpr int quadrature_order = 2 * polynomial_order + 2;

  typedef PDELab::QkLocalFiniteElementMap<GridType::LeafGridView,GridType::ctype,FieldType,polynomial_order>
  FEMapType;
  typedef BackendChooser<DiscreteFunctionSpaceType>::VectorBackendType VectorBackendType;
  typedef PDELab::GridFunctionSpace<GridType::LeafGridView,FEMapType,PDELab::ConformingDirichletConstraints,
            VectorBackendType> GridFunctionSpaceType;
  typedef typename PDELab::BackendVectorSelector<GridFunctionSpaceType,FieldType>::Type PdelabVectorType;

};

template <class T = CommonTraits::DiscreteFunctionType>
std::shared_ptr<T> make_df_ptr(const std::string name, const typename T::DiscreteFunctionSpaceType& space) {
  return std::make_shared<T>(name, space);
  //  return DSC::make_unique<T>(name, space);
}

} // namespace Multiscale
} // namespace Dune

#endif // DUNE_MULTISCALE_COMMON_TRAITS_HH
<|endoftext|>


<commit_before>// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_STUFF_COMMON_FVECTOR_HH
#define DUNE_STUFF_COMMON_FVECTOR_HH

#include <vector>
#include <initializer_list>

#include <dune/stuff/common/disable_warnings.hh>
# include <dune/common/fvector.hh>
#include <dune/stuff/common/reenable_warnings.hh>

#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/debug.hh>

namespace Dune {
namespace Stuff {
namespace Common {

template< class K, int SIZE >
class FieldVector
  : public Dune::FieldVector< K, SIZE >
{
  typedef Dune::FieldVector< K, SIZE > BaseType;
  typedef FieldVector< K, SIZE >       ThisType;

public:
  FieldVector(const K kk = K(0))
    : BaseType(kk)
  {}

  FieldVector(const size_t UNUSED_UNLESS_DEBUG(sz), const K kk)
    : BaseType(kk)
  {
#ifndef NDEBUG
    if (sz != SIZE)
      DUNE_THROW(Exceptions::wrong_input_given,
                 "You are trying to construct a FieldVector< ..., " << SIZE << " > (of " << "static size) with " << sz
                 << " elements!");
#endif // NDEBUG
  } // ... FieldVector(...)

  FieldVector(const BaseType& other)
    : BaseType(other)
  {}

  FieldVector(const std::vector< K >& vec)
    : BaseType(K(0))
  {
#ifndef NDEBUG
    if (vec.size() != SIZE)
      DUNE_THROW(Exceptions::wrong_input_given,
                 "You are trying to construct a FieldVector< ..., " << SIZE << " > (of "
                 << "static size) from a vector of size " << vec.size() << "!");
#endif // NDEBUG
    for (size_t ii = 0; ii < SIZE; ++ii)
      this->operator[](ii) = vec[ii];
  } // FieldVector(...)

  FieldVector(std::initializer_list< K > list)
    : BaseType(K(0))
  {
#ifndef NDEBUG
    if (list.size() != SIZE)
      DUNE_THROW(Exceptions::wrong_input_given,
                 "You are trying to construct a FieldVector< ..., " << SIZE << " > (of "
                 << "static size) from a list of size " << list.size() << "!");
#endif // NDEBUG
    size_t ii = 0;
    for (auto element : list) {
      this->operator[](ii) = element;
      ++ii;
    }
  } // FieldVector(...)

  ThisType& operator=(const BaseType& other)
  {
    return BaseType::operator=(other);
  }
}; // class FieldVector

} // namespace Common
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_COMMON_FVECTOR_HH
<commit_msg>[common.fvector] fixed operator=<commit_after>// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_STUFF_COMMON_FVECTOR_HH
#define DUNE_STUFF_COMMON_FVECTOR_HH

#include <vector>
#include <initializer_list>

#include <dune/stuff/common/disable_warnings.hh>
# include <dune/common/fvector.hh>
#include <dune/stuff/common/reenable_warnings.hh>

#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/debug.hh>

namespace Dune {
namespace Stuff {
namespace Common {

template< class K, int SIZE >
class FieldVector
  : public Dune::FieldVector< K, SIZE >
{
  typedef Dune::FieldVector< K, SIZE > BaseType;
  typedef FieldVector< K, SIZE >       ThisType;

public:
  FieldVector(const K kk = K(0))
    : BaseType(kk)
  {}

  FieldVector(const size_t UNUSED_UNLESS_DEBUG(sz), const K kk)
    : BaseType(kk)
  {
#ifndef NDEBUG
    if (sz != SIZE)
      DUNE_THROW(Exceptions::wrong_input_given,
                 "You are trying to construct a FieldVector< ..., " << SIZE << " > (of " << "static size) with " << sz
                 << " elements!");
#endif // NDEBUG
  } // ... FieldVector(...)

  FieldVector(const BaseType& other)
    : BaseType(other)
  {}

  FieldVector(const std::vector< K >& vec)
    : BaseType(K(0))
  {
#ifndef NDEBUG
    if (vec.size() != SIZE)
      DUNE_THROW(Exceptions::wrong_input_given,
                 "You are trying to construct a FieldVector< ..., " << SIZE << " > (of "
                 << "static size) from a vector of size " << vec.size() << "!");
#endif // NDEBUG
    for (size_t ii = 0; ii < SIZE; ++ii)
      this->operator[](ii) = vec[ii];
  } // FieldVector(...)

  FieldVector(std::initializer_list< K > list)
    : BaseType(K(0))
  {
#ifndef NDEBUG
    if (list.size() != SIZE)
      DUNE_THROW(Exceptions::wrong_input_given,
                 "You are trying to construct a FieldVector< ..., " << SIZE << " > (of "
                 << "static size) from a list of size " << list.size() << "!");
#endif // NDEBUG
    size_t ii = 0;
    for (auto element : list) {
      this->operator[](ii) = element;
      ++ii;
    }
  } // FieldVector(...)

  ThisType& operator=(const BaseType& other)
  {
    BaseType::operator=(other);
    return *this;
  }
}; // class FieldVector

} // namespace Common
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_COMMON_FVECTOR_HH
<|endoftext|>


<commit_before>/**
   *  \file   stuff.hh
   *  \brief  contains some stuff
   **/
#ifndef DUNE_STUFF_COMMON_STRING_HH
#define DUNE_STUFF_COMMON_STRING_HH

#include <config.h>

#include <cstring>
#include <ctime>
#include <map>
#include <assert.h>
#include <algorithm>

#include <dune/common/array.hh>
#include <dune/common/deprecated.hh>
#include <dune/common/static_assert.hh>
#include <ostream>
#include <iomanip>
#include <vector>
#include <string>
#include <ctime>

#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

namespace Dune {
namespace Stuff {
namespace Common {

//! simple and dumb std::string to anything conversion
template< class ReturnType >
inline ReturnType fromString(const std::string& s) {
  return boost::lexical_cast<ReturnType, std::string>(s);
} // fromString

//! simple and dumb anything to std::string conversion
template< class ReturnType >
inline std::string toString(const ReturnType& s) {
  return boost::lexical_cast<std::string, ReturnType>(s);
} // toString

/**
  \brief      Returns a string of lengths s' whitespace (or c chars).
  \param[in]  s
              std::string, defines the length of the return string
  \param[in]  whitespace
              char, optional argument, defines entries of return string
  \return     std::string
              Returns a string of lengths s' whitespace (or c chars).
  **/
template< class T >
std::string whitespaceify(const T& t, const char whitespace = ' ')
{
  const std::string s = toString< T >(t);
  std::string ret = "";
  for (unsigned int i = 0; i < s.size(); ++i) {
    ret += whitespace;
  }
  return ret;
} // std::string whitespaceify(const std::string s, const char whitespace = ' ')

/** \brief convenience wrapper around boost::algorithm::split to split one string into a vector of strings
 * \param msg the spring to be split
 * \param seperators a list of seperaors, duh
 * \param mode token_compress_off --> potentially empty strings in return,
              token_compress_on --> empty tokens are discarded
 * \return all tokens in a vector, if msg contains no seperators, this'll contain msg as its only element
 **/
template < class T = std::string >
inline std::vector<T> tokenize( const std::string& msg,
                             const std::string& seperators,
                             const boost::algorithm::token_compress_mode_type mode = boost::algorithm::token_compress_off )
{
    std::vector<std::string> strings;
    boost::algorithm::split( strings, msg, boost::algorithm::is_any_of(seperators),
                             mode );
    std::vector<T> ret(strings.size());
    size_t i = 0;
    //special case for empty strings to avoid non-default init
    std::generate(std::begin(ret), std::end(ret), [&] (){ return strings[i++].empty() ? T() : fromString<T>(strings[i-1]); });
    return ret;
}

template < >
inline std::vector<std::string> tokenize( const std::string& msg,
                             const std::string& seperators,
                             const boost::algorithm::token_compress_mode_type mode )
{
    std::vector<std::string> strings;
    boost::algorithm::split( strings, msg, boost::algorithm::is_any_of(seperators),
                             mode );
    return strings;
}

//! returns string with local time in current locale's format
inline std::string stringFromTime(time_t cur_time = time(NULL)) {
  return ctime(&cur_time);
}

//! helper struct for lexical cast
template <typename ElemT>
struct HexToString {
  // see http://stackoverflow.com/a/2079728
  ElemT value;
  operator ElemT() const {return value;}
  friend std::istream& operator>>(std::istream& in, HexToString& out) {
    in >> std::hex >> out.value;
    return in;
  }
};

// some legacy stuff I'd like to keep for a while
namespace String {

template< class T >
DUNE_DEPRECATED_MSG("use DSC::fromString instead, removal with stuff 2.3") T from(const std::string& s)
{
  std::stringstream ss;
  ss << s;
  T t;
  ss >> t;
  return t;
}

template< class T >
DUNE_DEPRECATED_MSG("use DSC::toString instead, removal with stuff 2.3") std::string to(const T& t)
{
  std::stringstream ss;
  ss << t;
  std::string s;
  ss >> s;
  return s;
}

DUNE_DEPRECATED_MSG("use the constructor call directly")
inline std::vector< std::string > mainArgsToVector(int argc, char** argv)
{
  return std::vector< std::string >(argv, argv + argc);
}

inline char** vectorToMainArgs(const std::vector< std::string > args)
{
  char** argv = new char* [args.size()];
  for (unsigned int ii = 0; ii < args.size(); ++ii) {
    argv[ii] = new char[args[ii].length() + 1];
    strcpy(argv[ii], args[ii].c_str());
  }
  return argv;
} // char** vectorToMainArgs(const std::vector< std::string > args)

} // namespace String

} // namespace Common
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_COMMON_STRING_HH

/** Copyright (c) 2012, Rene Milk    , Sven Kaulmann
   * All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are met:
   *
   * 1. Redistributions of source code must retain the above copyright notice, this
   *    list of conditions and the following disclaimer.
   * 2. Redistributions in binary form must reproduce the above copyright notice,
   *    this list of conditions and the following disclaimer in the documentation
   *    and/or other materials provided with the distribution.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
   * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   *
   * The views and conclusions contained in the software and documentation are those
   * of the authors and should not be interpreted as representing official policies,
   * either expressed or implied, of the FreeBSD Project.
   **/
<commit_msg>[common] rewire to/from string<commit_after>/**
   *  \file   stuff.hh
   *  \brief  contains some stuff
   **/
#ifndef DUNE_STUFF_COMMON_STRING_HH
#define DUNE_STUFF_COMMON_STRING_HH

#include <config.h>

#include <cstring>
#include <ctime>
#include <map>
#include <assert.h>
#include <algorithm>

#include <dune/common/array.hh>
#include <dune/common/deprecated.hh>
#include <dune/common/static_assert.hh>
#include <ostream>
#include <iomanip>
#include <vector>
#include <string>
#include <ctime>

#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

namespace Dune {
namespace Stuff {
namespace Common {

//! simple and dumb std::string to anything conversion
template< class ReturnType >
inline ReturnType fromString(const std::string s) {
  return boost::lexical_cast<ReturnType, std::string>(s);
} // fromString

inline std::string toString(const char* s) {
  return std::string(s);
} // toString

inline std::string toString(const std::string s) {
  return std::string(s);
} // toString

//! simple and dumb anything to std::string conversion
template< class ReturnType >
inline std::string toString(const ReturnType& s) {
  return std::to_string(s);
} // toString

#define DSC_TOSTR(tn,tns) \
template<> \
inline tn fromString<tn>(const std::string s) { \
  return std::sto##tns(s); \
}

DSC_TOSTR(int, i)
DSC_TOSTR(long, l)
DSC_TOSTR(long long, ll)
DSC_TOSTR(unsigned long, ul)
DSC_TOSTR(unsigned long long, ull)
DSC_TOSTR(float,f)
DSC_TOSTR(double,d)
DSC_TOSTR(long double,ld)

#undef DSC_TOSTR

/**
  \brief      Returns a string of lengths s' whitespace (or c chars).
  \param[in]  s
              std::string, defines the length of the return string
  \param[in]  whitespace
              char, optional argument, defines entries of return string
  \return     std::string
              Returns a string of lengths s' whitespace (or c chars).
  **/
template< class T >
std::string whitespaceify(const T& t, const char whitespace = ' ')
{
  const std::string s = toString< T >(t);
  std::string ret = "";
  for (unsigned int i = 0; i < s.size(); ++i) {
    ret += whitespace;
  }
  return ret;
} // std::string whitespaceify(const std::string s, const char whitespace = ' ')

/** \brief convenience wrapper around boost::algorithm::split to split one string into a vector of strings
 * \param msg the spring to be split
 * \param seperators a list of seperaors, duh
 * \param mode token_compress_off --> potentially empty strings in return,
              token_compress_on --> empty tokens are discarded
 * \return all tokens in a vector, if msg contains no seperators, this'll contain msg as its only element
 **/
template < class T = std::string >
inline std::vector<T> tokenize( const std::string& msg,
                             const std::string& seperators,
                             const boost::algorithm::token_compress_mode_type mode = boost::algorithm::token_compress_off )
{
    std::vector<std::string> strings;
    boost::algorithm::split( strings, msg, boost::algorithm::is_any_of(seperators),
                             mode );
    std::vector<T> ret(strings.size());
    size_t i = 0;
    //special case for empty strings to avoid non-default init
    std::generate(std::begin(ret), std::end(ret), [&] (){ return strings[i++].empty() ? T() : fromString<T>(strings[i-1]); });
    return ret;
}

template < >
inline std::vector<std::string> tokenize( const std::string& msg,
                             const std::string& seperators,
                             const boost::algorithm::token_compress_mode_type mode )
{
    std::vector<std::string> strings;
    boost::algorithm::split( strings, msg, boost::algorithm::is_any_of(seperators),
                             mode );
    return strings;
}

//! returns string with local time in current locale's format
inline std::string stringFromTime(time_t cur_time = time(NULL)) {
  return ctime(&cur_time);
}

//! helper struct for lexical cast
template <typename ElemT>
struct HexToString {
  // see http://stackoverflow.com/a/2079728
  ElemT value;
  operator ElemT() const {return value;}
  friend std::istream& operator>>(std::istream& in, HexToString& out) {
    in >> std::hex >> out.value;
    return in;
  }
};

// some legacy stuff I'd like to keep for a while
namespace String {

template< class T >
DUNE_DEPRECATED_MSG("use DSC::fromString instead, removal with stuff 2.3") T from(const std::string& s)
{
  std::stringstream ss;
  ss << s;
  T t;
  ss >> t;
  return t;
}

template< class T >
DUNE_DEPRECATED_MSG("use DSC::toString instead, removal with stuff 2.3") std::string to(const T& t)
{
  std::stringstream ss;
  ss << t;
  std::string s;
  ss >> s;
  return s;
}

DUNE_DEPRECATED_MSG("use the constructor call directly")
inline std::vector< std::string > mainArgsToVector(int argc, char** argv)
{
  return std::vector< std::string >(argv, argv + argc);
}

inline char** vectorToMainArgs(const std::vector< std::string > args)
{
  char** argv = new char* [args.size()];
  for (unsigned int ii = 0; ii < args.size(); ++ii) {
    argv[ii] = new char[args[ii].length() + 1];
    strcpy(argv[ii], args[ii].c_str());
  }
  return argv;
} // char** vectorToMainArgs(const std::vector< std::string > args)

} // namespace String

} // namespace Common
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_COMMON_STRING_HH

/** Copyright (c) 2012, Rene Milk    , Sven Kaulmann
   * All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are met:
   *
   * 1. Redistributions of source code must retain the above copyright notice, this
   *    list of conditions and the following disclaimer.
   * 2. Redistributions in binary form must reproduce the above copyright notice,
   *    this list of conditions and the following disclaimer in the documentation
   *    and/or other materials provided with the distribution.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
   * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   *
   * The views and conclusions contained in the software and documentation are those
   * of the authors and should not be interpreted as representing official policies,
   * either expressed or implied, of the FreeBSD Project.
   **/
<|endoftext|>


<commit_before>#ifndef DUNE_STUFF_TOOLS_COMMON_VEECTOR_HH
#define DUNE_STUFF_TOOLS_COMMON_VEECTOR_HH

#include <iostream>

// dune-common
#include <dune/common/densevector.hh>

namespace Dune {

namespace Stuff {

namespace Common {

//template< class T, class stream = std::ostream >
//void print(const T& arg, stream& out = std::cout, std::string name = "", std::string prefix = "") {
//  out << prefix;
//  if (!name.empty())
//    out << name << " = ";
//  out << "[";
//  for (unsigned int i = 0; i < (arg.size() - 1); ++i)
//  {
//      out << arg[i] << ", ";
//  }
//  out << arg[arg.size() - 1] << "]" << std::endl;
//}

template< class VectorImp >
void clear(Dune::DenseVector< VectorImp >& vector)
{
  vector = typename Dune::DenseVector< VectorImp >::value_type(0);
//  typedef typename DenseVectorType::value_type
//    ValueType;

//  const unsigned int size = vector.size();
//  for( unsigned int i = 0; i < size; ++i )
//  {
//    vector[i] = ValueType(0.0);
//  }
} // void clear( DenseVectorType& vector )

} // namespace Common
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_TOOLS_COMMON_VEECTOR_HH
<commit_msg>[common.vector] added resize() for Dune::DynamicVector<commit_after>#ifndef DUNE_STUFF_TOOLS_COMMON_VEECTOR_HH
#define DUNE_STUFF_TOOLS_COMMON_VEECTOR_HH

#include <iostream>

// dune-common
#include <dune/common/densevector.hh>
#include <dune/common/dynvector.hh>

namespace Dune {
namespace Stuff {
namespace Common {

//template< class T, class stream = std::ostream >
//void print(const T& arg, stream& out = std::cout, std::string name = "", std::string prefix = "") {
//  out << prefix;
//  if (!name.empty())
//    out << name << " = ";
//  out << "[";
//  for (unsigned int i = 0; i < (arg.size() - 1); ++i)
//  {
//      out << arg[i] << ", ";
//  }
//  out << arg[arg.size() - 1] << "]" << std::endl;
//}

template< class VectorImp >
void clear(Dune::DenseVector< VectorImp >& vector)
{
  vector = typename Dune::DenseVector< VectorImp >::value_type(0);
//  typedef typename DenseVectorType::value_type
//    ValueType;

//  const unsigned int size = vector.size();
//  for( unsigned int i = 0; i < size; ++i )
//  {
//    vector[i] = ValueType(0.0);
//  }
} // void clear( DenseVectorType& vector )

template< class T >
Dune::DynamicVector< T > resize(const Dune::DynamicVector< T >& inVector,
                                const size_t newSize,
                                const T fill = T(0))
{
  Dune::DynamicVector< T > outVector(newSize);
  for (size_t ii = 0; ii < std::min(inVector.size(), newSize); ++ii)
    outVector[ii] = inVector[ii];
  for (size_t ii = std::min(inVector.size(), newSize); ii < newSize; ++ii)
    outVector[ii] = fill;
  return outVector;
}

} // namespace Common
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_TOOLS_COMMON_VEECTOR_HH
<|endoftext|>


<commit_before>#ifndef DUNE_STUFF_GRID_PROVIDER_HH
#define DUNE_STUFF_GRID_PROVIDER_HH

#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#else
  #include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG

#if HAVE_DUNE_GRID

#include "provider/interface.hh"
#include "provider/cube.hh"
#include "provider/gmsh.hh"
#include "provider/starcd.hh"

namespace Dune {
namespace Stuff {
namespace Grid {
namespace Provider {

std::vector< std::string > types()
{
  std::vector< std::string > ret;
  ret.push_back("stuff.grid.provider.cube");
#if HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG
#if defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID
  ret.push_back("stuff.grid.provider.gmsh");
#endif // defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID
#endif // HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG
  ret.push_back("stuff.grid.provider.starcd");
  return ret;
} // std::vector< const std::string > types()

#if defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
template< class GridType = Dune::GridSelector::GridType >
#else // defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
template< class GridType = Dune::SGrid< 2, 2 > >
#endif // defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
Dune::ParameterTree createSampleDescription(const std::string type)
{
  if (type == "stuff.grid.provider.cube") {
    typedef Dune::Stuff::Grid::Provider::Cube< GridType > ProviderType;
    return ProviderType::createSampleDescription();
#if HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG
#if defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID
  } else if (type == "stuff.grid.provider.gmsh") {
    typedef Dune::Stuff::Grid::Provider::Gmsh< GridType > ProviderType;
    return ProviderType::createSampleDescription();
#endif // defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID
#endif // HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG
  } else if (type == "stuff.grid.provider.starcd") {
    typedef Dune::Stuff::Grid::Provider::StarCD< GridType > ProviderType;
    return ProviderType::createSampleDescription();
  } else
    DUNE_THROW(Dune::RangeError,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
               << " unknown grid provider '" << type << "' requested!");
} // ... create(...)

#if defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
template< class GridType = Dune::GridSelector::GridType >
#else // defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
template< class GridType = Dune::SGrid< 2, 2 > >
#endif // defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
Interface< GridType >* create(const std::string& type = "stuff.grid.provider.cube", const Dune::ParameterTree paramTree = Dune::ParameterTree())
{
  // choose provider
  if (type == "stuff.grid.provider.cube") {
    typedef Dune::Stuff::Grid::Provider::Cube< GridType > CubeProviderType;
    CubeProviderType* cubeProvider = new CubeProviderType(CubeProviderType::createFromDescription(paramTree));
    return cubeProvider;
#if HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG
#if defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID
  } else if (type == "stuff.grid.provider.gmsh") {
    typedef Dune::Stuff::Grid::Provider::Gmsh< GridType > GmshProviderType;
    GmshProviderType* gmshProvider = new GmshProviderType(GmshProviderType::createFromDescription(paramTree));
    return gmshProvider;
#endif // defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID
#endif // HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG
  } else if (type == "stuff.grid.provider.starcd") {
    typedef Dune::Stuff::Grid::Provider::StarCD< GridType > StarCDProviderType;
    StarCDProviderType* starCDProvider = new StarCDProviderType(StarCDProviderType::createFromDescription(paramTree));
    return starCDProvider;
  } else
    DUNE_THROW(Dune::RangeError,
               "\nERROR: unknown grid provider '" << type << "' requested!");
} // Interface< GridImp >* create(const std::string& type, const Dune::ParameterTree paramTree = Dune::ParameterTree())

} // namespace Provider
} // namespace Grid
} // namespace Stuff
} // namespace Dune

#endif // HAVE_DUNE_GRID

#endif // DUNE_STUFF_GRID_PROVIDER_HH
<commit_msg>[grid] cleanup/simplify provider.hh<commit_after>#ifndef DUNE_STUFF_GRID_PROVIDER_HH
#define DUNE_STUFF_GRID_PROVIDER_HH

#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#else
  #include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG

#if HAVE_DUNE_GRID

#include <functional>
#include <dune/common/shared_ptr.hh>
#include <dune/stuff/aliases.hh>

#include "provider/interface.hh"
#include "provider/cube.hh"
#include "provider/gmsh.hh"
#include "provider/starcd.hh"

namespace Dune {
namespace Stuff {
namespace Grid {
namespace Provider {

std::vector< std::string > types()
{
  std::vector< std::string > ret;
  ret.push_back("stuff.grid.provider.cube");
#if HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG
#if defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID
  ret.push_back("stuff.grid.provider.gmsh");
#endif // defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID
#endif // HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG
  ret.push_back("stuff.grid.provider.starcd");
  return ret;
} // std::vector< const std::string > types()

#if defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
template< class GridType = Dune::GridSelector::GridType >
#else // defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
template< class GridType = Dune::SGrid< 2, 2 > >
#endif // defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
Dune::ParameterTree createSampleDescription(const std::string type)
{
  if (type == "stuff.grid.provider.cube") {
    typedef Dune::Stuff::Grid::Provider::Cube< GridType > ProviderType;
    return ProviderType::createSampleDescription();
#if HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG
#if defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID
  } else if (type == "stuff.grid.provider.gmsh") {
    typedef Dune::Stuff::Grid::Provider::Gmsh< GridType > ProviderType;
    return ProviderType::createSampleDescription();
#endif // defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID
#endif // HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG
  } else if (type == "stuff.grid.provider.starcd") {
    typedef Dune::Stuff::Grid::Provider::StarCD< GridType > ProviderType;
    return ProviderType::createSampleDescription();
  } else
    DUNE_THROW(Dune::RangeError,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
               << " unknown grid provider '" << type << "' requested!");
} // ... create(...)

#if defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
template< class GridType = Dune::GridSelector::GridType >
#else // defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
template< class GridType = Dune::SGrid< 2, 2 > >
#endif // defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
Interface< GridType >* create(const std::string& type = "stuff.grid.provider.cube", const Dune::ParameterTree paramTree = Dune::ParameterTree())
{
  using namespace DSG::Provider;
  typedef std::map<std::string, std::pair<std::string,typename FunctionObject<GridType>::Type>> MapType;

  MapType ptr_map = { {"stuff.grid.provider.cube",  DSGP_MAKE(GenericCube)},
#ifdef HAVE_UNSTRUCTURED_GRIDFACTORY
                      {"stuff.grid.provider.gmsh",  DSGP_MAKE(Gmsh)},
#endif
                      {"stuff.grid.provider.starcd",DSGP_MAKE(StarCD)}};
  auto id_func_it = ptr_map.find(type);
  if(id_func_it == ptr_map.end())
    DUNE_THROW(Dune::RangeError, "\nERROR: unknown grid provider '" << type << "' requested!");
  auto id_func = id_func_it->second;
  return id_func.second(id_func.first);
} // Interface< GridImp >* create(const std::string& type, const Dune::ParameterTree paramTree = Dune::ParameterTree())

} // namespace Provider
} // namespace Grid
} // namespace Stuff
} // namespace Dune

#endif // HAVE_DUNE_GRID

#endif // DUNE_STUFF_GRID_PROVIDER_HH
<|endoftext|>