<commit_before>#ifndef STAN_MATH_REV_MAT_FUNCTOR_KINSOL_DATA_HPP
#define STAN_MATH_REV_MAT_FUNCTOR_KINSOL_DATA_HPP

#include <stan/math/prim/mat/fun/to_array_1d.hpp>
#include <stan/math/prim/mat/fun/to_vector.hpp>
#include <stan/math/rev/mat/functor/algebra_system.hpp>
#include <stan/math/rev/mat/functor/jacobian.hpp>

#include <kinsol/kinsol.h>
#include <sunmatrix/sunmatrix_dense.h>
#include <sunlinsol/sunlinsol_dense.h>
#include <nvector/nvector_serial.h>

#include <vector>

namespace stan {
namespace math {

/**
 * Default Jacobian builder using revser-mode autodiff.
 */
struct kinsol_J_f {
  template <typename F>
  inline int operator()(const F& f, const Eigen::VectorXd& x,
                        const Eigen::VectorXd& y,
                        const std::vector<double>& dat,
                        const std::vector<int>& dat_int, std::ostream* msgs,
                        const double x_sun[], SUNMatrix J) const {
    size_t N = x.size();
    const std::vector<double> x_vec(x_sun, x_sun + N);
    system_functor<F, double, double, 1> system(f, x, y, dat, dat_int, msgs);
    Eigen::VectorXd fx;
    Eigen::MatrixXd Jac;
    jacobian(system, to_vector(x_vec), fx, Jac);

    for (int i = 0; i < Jac.rows(); i++)
      for (int j = 0; j < Jac.cols(); j++)
        SM_ELEMENT_D(J, i, j) = Jac(i, j);

    return 0;
  }
};

/**
 * KINSOL algebraic system data holder.
 * Based on cvodes_ode_data.
 *
 * @tparam F1 functor type for system function.
 * @tparam F2 functor type for jacobian function. Default is 0.
 *         If 0, use rev mode autodiff to compute the Jacobian.
 */
template <typename F1, typename F2>
class kinsol_system_data {
  const F1& f_;
  const F2& J_f_;
  const Eigen::VectorXd& x_;
  const Eigen::VectorXd& y_;
  const size_t N_;
  const std::vector<double>& dat_;
  const std::vector<int>& dat_int_;
  std::ostream* msgs_;

  typedef kinsol_system_data<F1, F2> system_data;

 public:
  N_Vector nv_x_;
  SUNMatrix J_;
  SUNLinearSolver LS_;
  void* kinsol_memory_;

  /* Constructor */
  kinsol_system_data(const F1& f, const F2& J_f, const Eigen::VectorXd& x,
                     const Eigen::VectorXd& y, const std::vector<double>& dat,
                     const std::vector<int>& dat_int, std::ostream* msgs)
      : f_(f),
        J_f_(J_f),
        x_(x),
        y_(y),
        dat_(dat),
        dat_int_(dat_int),
        msgs_(msgs),
        N_(x.size()),
        nv_x_(N_VMake_Serial(N_, &to_array_1d(x_)[0])),
        J_(SUNDenseMatrix(N_, N_)),
        LS_(SUNLinSol_Dense(nv_x_, J_)),
        kinsol_memory_(KINCreate()) {}

  ~kinsol_system_data() {
    N_VDestroy_Serial(nv_x_);
    SUNLinSolFree(LS_);
    SUNMatDestroy(J_);
    KINFree(&kinsol_memory_);
  }

  /* Implements the user-defined function passed to KINSOL. */
  static int kinsol_f_system(N_Vector x, N_Vector f, void* user_data) {
    const system_data* explicit_system
        = static_cast<const system_data*>(user_data);

    Eigen::VectorXd x_eigen(
        Eigen::Map<Eigen::VectorXd>(NV_DATA_S(x), explicit_system->N_));

    Eigen::Map<Eigen::VectorXd>(N_VGetArrayPointer(f), explicit_system->N_)
        = explicit_system->f_(x_eigen, explicit_system->y_,
                              explicit_system->dat_, explicit_system->dat_int_,
                              explicit_system->msgs_);

    return 0;
  }

  /**
   * Implements the function of type CVDlsJacFn which is the user-defined
   * callbacks for KINSOL to calculate the jacobian of the system.
   * The Jacobian is stored in column major format.
   *
   * REMARK - tmp1 and tmp2 are pointers to memory allocated for variables
   * of type N_Vector which can be used by KINJacFN (the function which
   * computes the Jacobian) as temporary storage or work space.
   * See
   * https://computation.llnl.gov/sites/default/files/public/kin_guide-dev.pdf,
   * page 55.
   */
  static int kinsol_jacobian(N_Vector x, N_Vector f, SUNMatrix J,
                             void* user_data, N_Vector tmp1, N_Vector tmp2) {
    const system_data* explicit_system
        = static_cast<const system_data*>(user_data);
    return explicit_system->J_f_(explicit_system->f_, explicit_system->x_,
                                 explicit_system->y_, explicit_system->dat_,
                                 explicit_system->dat_int_,
                                 explicit_system->msgs_, NV_DATA_S(x), J);
  }
};

}  // namespace math
}  // namespace stan
#endif
<commit_msg>Interchange loops in kinsol_data.<commit_after>#ifndef STAN_MATH_REV_MAT_FUNCTOR_KINSOL_DATA_HPP
#define STAN_MATH_REV_MAT_FUNCTOR_KINSOL_DATA_HPP

#include <stan/math/prim/mat/fun/to_array_1d.hpp>
#include <stan/math/prim/mat/fun/to_vector.hpp>
#include <stan/math/rev/mat/functor/algebra_system.hpp>
#include <stan/math/rev/mat/functor/jacobian.hpp>

#include <kinsol/kinsol.h>
#include <sunmatrix/sunmatrix_dense.h>
#include <sunlinsol/sunlinsol_dense.h>
#include <nvector/nvector_serial.h>

#include <vector>

namespace stan {
namespace math {

/**
 * Default Jacobian builder using revser-mode autodiff.
 */
struct kinsol_J_f {
  template <typename F>
  inline int operator()(const F& f, const Eigen::VectorXd& x,
                        const Eigen::VectorXd& y,
                        const std::vector<double>& dat,
                        const std::vector<int>& dat_int, std::ostream* msgs,
                        const double x_sun[], SUNMatrix J) const {
    size_t N = x.size();
    const std::vector<double> x_vec(x_sun, x_sun + N);
    system_functor<F, double, double, 1> system(f, x, y, dat, dat_int, msgs);
    Eigen::VectorXd fx;
    Eigen::MatrixXd Jac;
    jacobian(system, to_vector(x_vec), fx, Jac);

    for (int j = 0; j < Jac.cols(); j++)
      for (int i = 0; i < Jac.rows(); i++)
        SM_ELEMENT_D(J, i, j) = Jac(i, j);

    return 0;
  }
};

/**
 * KINSOL algebraic system data holder.
 * Based on cvodes_ode_data.
 *
 * @tparam F1 functor type for system function.
 * @tparam F2 functor type for jacobian function. Default is 0.
 *         If 0, use rev mode autodiff to compute the Jacobian.
 */
template <typename F1, typename F2>
class kinsol_system_data {
  const F1& f_;
  const F2& J_f_;
  const Eigen::VectorXd& x_;
  const Eigen::VectorXd& y_;
  const size_t N_;
  const std::vector<double>& dat_;
  const std::vector<int>& dat_int_;
  std::ostream* msgs_;

  typedef kinsol_system_data<F1, F2> system_data;

 public:
  N_Vector nv_x_;
  SUNMatrix J_;
  SUNLinearSolver LS_;
  void* kinsol_memory_;

  /* Constructor */
  kinsol_system_data(const F1& f, const F2& J_f, const Eigen::VectorXd& x,
                     const Eigen::VectorXd& y, const std::vector<double>& dat,
                     const std::vector<int>& dat_int, std::ostream* msgs)
      : f_(f),
        J_f_(J_f),
        x_(x),
        y_(y),
        dat_(dat),
        dat_int_(dat_int),
        msgs_(msgs),
        N_(x.size()),
        nv_x_(N_VMake_Serial(N_, &to_array_1d(x_)[0])),
        J_(SUNDenseMatrix(N_, N_)),
        LS_(SUNLinSol_Dense(nv_x_, J_)),
        kinsol_memory_(KINCreate()) {}

  ~kinsol_system_data() {
    N_VDestroy_Serial(nv_x_);
    SUNLinSolFree(LS_);
    SUNMatDestroy(J_);
    KINFree(&kinsol_memory_);
  }

  /* Implements the user-defined function passed to KINSOL. */
  static int kinsol_f_system(N_Vector x, N_Vector f, void* user_data) {
    const system_data* explicit_system
        = static_cast<const system_data*>(user_data);

    Eigen::VectorXd x_eigen(
        Eigen::Map<Eigen::VectorXd>(NV_DATA_S(x), explicit_system->N_));

    Eigen::Map<Eigen::VectorXd>(N_VGetArrayPointer(f), explicit_system->N_)
        = explicit_system->f_(x_eigen, explicit_system->y_,
                              explicit_system->dat_, explicit_system->dat_int_,
                              explicit_system->msgs_);

    return 0;
  }

  /**
   * Implements the function of type CVDlsJacFn which is the user-defined
   * callbacks for KINSOL to calculate the jacobian of the system.
   * The Jacobian is stored in column major format.
   *
   * REMARK - tmp1 and tmp2 are pointers to memory allocated for variables
   * of type N_Vector which can be used by KINJacFN (the function which
   * computes the Jacobian) as temporary storage or work space.
   * See
   * https://computation.llnl.gov/sites/default/files/public/kin_guide-dev.pdf,
   * page 55.
   */
  static int kinsol_jacobian(N_Vector x, N_Vector f, SUNMatrix J,
                             void* user_data, N_Vector tmp1, N_Vector tmp2) {
    const system_data* explicit_system
        = static_cast<const system_data*>(user_data);
    return explicit_system->J_f_(explicit_system->f_, explicit_system->x_,
                                 explicit_system->y_, explicit_system->dat_,
                                 explicit_system->dat_int_,
                                 explicit_system->msgs_, NV_DATA_S(x), J);
  }
};

}  // namespace math
}  // namespace stan
#endif
<|endoftext|>


<commit_before><commit_msg>Removed unnecessary header<commit_after><|endoftext|>


<commit_before><commit_msg>proto<commit_after><|endoftext|>


<commit_before>#include "di/Injectable.h"
#include "service/GWSDeviceServiceImpl.h"
#include "util/MultiException.h"
#include "util/ZipIterator.h"

using namespace std;
using namespace Poco;
using namespace BeeeOn;

BEEEON_OBJECT_BEGIN(BeeeOn, GWSDeviceServiceImpl)
BEEEON_OBJECT_CASTABLE(GWSDeviceService)
BEEEON_OBJECT_PROPERTY("deviceDao", &GWSDeviceServiceImpl::setDeviceDao)
BEEEON_OBJECT_PROPERTY("deviceInfoProvider", &GWSDeviceServiceImpl::setDeviceInfoProvider)
BEEEON_OBJECT_PROPERTY("transactionManager", &Transactional::setTransactionManager)
BEEEON_OBJECT_END(BeeeOn, GWSDeviceServiceImpl)

void GWSDeviceServiceImpl::setDeviceDao(DeviceDao::Ptr dao)
{
	m_deviceDao = dao;
}

void GWSDeviceServiceImpl::setDeviceInfoProvider(DeviceInfoProvider::Ptr provider)
{
	m_deviceInfoProvider = provider;
}

SharedPtr<DeviceInfo> GWSDeviceServiceImpl::verifyDescription(
		const DeviceDescription &description) const
{
	auto type = m_deviceInfoProvider->findByNameAndVendor(
		description.productName(),
		description.vendor());
	if (type.isNull()) {
		throw NotFoundException("no such device type for "
			"'" + description.toString() + "' specification");
	}

	verifyModules(type, description.dataTypes());
	return type;
}

bool GWSDeviceServiceImpl::doRegisterDevice(Device &device,
		const DeviceDescription &description,
		const Gateway &gateway)
{
	if (m_deviceDao->fetch(device, gateway)) {
		auto type = verifyDescription(description);

		if (type != device.type()) {
			throw IllegalStateException(
				"description " + description.toString()
				+ " has non-matching device type for device " + device);
		}

		device.status().setLastSeen(Timestamp());

		return m_deviceDao->update(device, gateway);
	}
	else {
		device.setName(description.productName());
		device.setType(verifyDescription(description));

		DeviceStatus &status = device.status();

		status.setFirstSeen(Timestamp());
		status.setLastSeen(Timestamp());
		status.setState(DeviceStatus::STATE_INACTIVE);
		status.setLastChanged({});

		return m_deviceDao->insert(device, gateway);
	}
}

void GWSDeviceServiceImpl::doRegisterDeviceGroup(
		const vector<DeviceDescription> &descriptions,
		const Gateway &gateway)
{
	for (auto &des : descriptions) {
		Device device(des.id());
		device.setRefresh(des.refreshTime());

		if (!doRegisterDevice(device, des, gateway)) {
			throw IllegalStateException("registration of device "
				"'" + des.toString() + "' failed");
		}
	}
}

void GWSDeviceServiceImpl::doFetchActiveWithPrefix(vector<Device> &devices,
		const Gateway &gateway,
		const DevicePrefix &prefix)
{
	m_deviceDao->fetchActiveWithPrefix(devices, gateway, prefix);
}

void GWSDeviceServiceImpl::verifyModules(
		const SharedPtr<DeviceInfo> deviceInfo,
		const list<ModuleType> &modules) const
{
	if (modules.size() > deviceInfo->modules().size()) {
		throw InvalidArgumentException("invalid count of modules "
			+ to_string(modules.size()) + " for device " + *deviceInfo);
	}

	MultiException ex;

	Zip<const set<ModuleInfo>, const list<ModuleType>> zip(
		deviceInfo->modules(), modules);

	auto i = 0;
	auto it = zip.begin();
	for (; it != zip.end(); ++it, ++i) {
		const auto &expect = (*it).first;
		const auto &given = (*it).second;

		if (expect.type()->name() != given.type().toString()) {
			ex.caught(InvalidArgumentException(
				"expected type " + expect.type()->name()
				+ " of module " + to_string(i) + " but " + given.type()
				+ " was given for device " + *deviceInfo
			));
		}
	}

	string missing;

	for (auto expectIt = it.firstIterator(); expectIt != zip.firstEnd(); ++expectIt, ++i) {
		if (!missing.empty())
			missing += ", ";

		missing += to_string(i) + " " + expectIt->type()->name();
	}

	if (!missing.empty()) {
		logger().warning("missing specification of " + missing
			 + " for device " + *deviceInfo);
	}

	if (!ex.empty())
		ex.rethrow();
}
<commit_msg>GWSDeviceServiceImpl: update device name on register<commit_after>#include "di/Injectable.h"
#include "service/GWSDeviceServiceImpl.h"
#include "util/MultiException.h"
#include "util/ZipIterator.h"

using namespace std;
using namespace Poco;
using namespace BeeeOn;

BEEEON_OBJECT_BEGIN(BeeeOn, GWSDeviceServiceImpl)
BEEEON_OBJECT_CASTABLE(GWSDeviceService)
BEEEON_OBJECT_PROPERTY("deviceDao", &GWSDeviceServiceImpl::setDeviceDao)
BEEEON_OBJECT_PROPERTY("deviceInfoProvider", &GWSDeviceServiceImpl::setDeviceInfoProvider)
BEEEON_OBJECT_PROPERTY("transactionManager", &Transactional::setTransactionManager)
BEEEON_OBJECT_END(BeeeOn, GWSDeviceServiceImpl)

void GWSDeviceServiceImpl::setDeviceDao(DeviceDao::Ptr dao)
{
	m_deviceDao = dao;
}

void GWSDeviceServiceImpl::setDeviceInfoProvider(DeviceInfoProvider::Ptr provider)
{
	m_deviceInfoProvider = provider;
}

SharedPtr<DeviceInfo> GWSDeviceServiceImpl::verifyDescription(
		const DeviceDescription &description) const
{
	auto type = m_deviceInfoProvider->findByNameAndVendor(
		description.productName(),
		description.vendor());
	if (type.isNull()) {
		throw NotFoundException("no such device type for "
			"'" + description.toString() + "' specification");
	}

	verifyModules(type, description.dataTypes());
	return type;
}

bool GWSDeviceServiceImpl::doRegisterDevice(Device &device,
		const DeviceDescription &description,
		const Gateway &gateway)
{
	if (m_deviceDao->fetch(device, gateway)) {
		auto type = verifyDescription(description);

		if (type != device.type()) {
			throw IllegalStateException(
				"description " + description.toString()
				+ " has non-matching device type for device " + device);
		}

		if (!description.productName().empty())
			device.setName(description.productName());

		device.status().setLastSeen(Timestamp());

		return m_deviceDao->update(device, gateway);
	}
	else {
		device.setName(description.productName());
		device.setType(verifyDescription(description));

		DeviceStatus &status = device.status();

		status.setFirstSeen(Timestamp());
		status.setLastSeen(Timestamp());
		status.setState(DeviceStatus::STATE_INACTIVE);
		status.setLastChanged({});

		return m_deviceDao->insert(device, gateway);
	}
}

void GWSDeviceServiceImpl::doRegisterDeviceGroup(
		const vector<DeviceDescription> &descriptions,
		const Gateway &gateway)
{
	for (auto &des : descriptions) {
		Device device(des.id());
		device.setRefresh(des.refreshTime());

		if (!doRegisterDevice(device, des, gateway)) {
			throw IllegalStateException("registration of device "
				"'" + des.toString() + "' failed");
		}
	}
}

void GWSDeviceServiceImpl::doFetchActiveWithPrefix(vector<Device> &devices,
		const Gateway &gateway,
		const DevicePrefix &prefix)
{
	m_deviceDao->fetchActiveWithPrefix(devices, gateway, prefix);
}

void GWSDeviceServiceImpl::verifyModules(
		const SharedPtr<DeviceInfo> deviceInfo,
		const list<ModuleType> &modules) const
{
	if (modules.size() > deviceInfo->modules().size()) {
		throw InvalidArgumentException("invalid count of modules "
			+ to_string(modules.size()) + " for device " + *deviceInfo);
	}

	MultiException ex;

	Zip<const set<ModuleInfo>, const list<ModuleType>> zip(
		deviceInfo->modules(), modules);

	auto i = 0;
	auto it = zip.begin();
	for (; it != zip.end(); ++it, ++i) {
		const auto &expect = (*it).first;
		const auto &given = (*it).second;

		if (expect.type()->name() != given.type().toString()) {
			ex.caught(InvalidArgumentException(
				"expected type " + expect.type()->name()
				+ " of module " + to_string(i) + " but " + given.type()
				+ " was given for device " + *deviceInfo
			));
		}
	}

	string missing;

	for (auto expectIt = it.firstIterator(); expectIt != zip.firstEnd(); ++expectIt, ++i) {
		if (!missing.empty())
			missing += ", ";

		missing += to_string(i) + " " + expectIt->type()->name();
	}

	if (!missing.empty()) {
		logger().warning("missing specification of " + missing
			 + " for device " + *deviceInfo);
	}

	if (!ex.empty())
		ex.rethrow();
}
<|endoftext|>


<commit_before>#include "phInput.h"
#include <fstream>
#include <map>
#include "ph.h"
#include <cassert>

namespace ph {

static void setDefaults(Input& in)
{
  in.outMeshFileName = "";
  in.numSplit = 10;
  in.tetrahedronize = 0;
  in.localPtn = true;
  in.recursivePtn = -1;
  in.recursiveUR = 1;
  in.parmaPtn = 0; // No Parma by default
  in.dwalMigration = 0; // Do not migrate dwal field by default
  in.buildMapping = 0; // Do not build the mapping field by default
  in.elementsPerMigration = 1000*1000; // 100k elms per round
}

typedef std::map<std::string, std::string*> StringMap;
typedef std::map<std::string, int*> IntMap;

static void formMaps(Input& in, StringMap& stringMap, IntMap& intMap)
{
  intMap["globalP"] = &in.globalP;
  intMap["timeStepNumber"] = &in.timeStepNumber;
  intMap["ensa_dof"] = &in.ensa_dof;
  stringMap["restartFileName"] = &in.restartFileName;
  stringMap["attributeFileName"] = &in.attributeFileName;
  stringMap["meshFileName"] = &in.meshFileName;
  stringMap["outMeshFileName"] = &in.outMeshFileName;
  stringMap["modelFileName"] = &in.modelFileName;
  stringMap["outputFormat"] = &in.outputFormat;
  stringMap["partitionMethod"] = &in.partitionMethod;
  intMap["adaptFlag"] = &in.adaptFlag;
  intMap["rRead"] = &in.rRead;
  intMap["rStart"] = &in.rStart;
  intMap["AdaptStrategy"] = &in.adaptStrategy;
  intMap["RecursiveUR"] = &in.recursiveUR;
  intMap["Periodic"] = &in.periodic;
  intMap["prCD"] = &in.prCD;
  intMap["timing"] = &in.timing;
  intMap["internalBCNodes"] = &in.internalBCNodes;
  intMap["WRITEASC"] = &in.writeAsc;
  intMap["phastaIO"] = &in.phastaIO;
  intMap["numTotParts"] = &in.numTotParts;
  intMap["SolutionMigration"] = &in.solutionMigration;
  intMap["DisplacementMigration"] = &in.displacementMigration;
  intMap["isReorder"] = &in.isReorder;
  intMap["numSplit"] = &in.numSplit;
  intMap["Tetrahedronize"] = &in.tetrahedronize;
  intMap["LocalPtn"] = &in.localPtn;
  intMap["RecursivePtn"] = &in.recursivePtn;
  intMap["ParmaPtn"] = &in.parmaPtn;
  intMap["dwalMigration"] = &in.dwalMigration;
  intMap["buildMapping"] = &in.buildMapping;
  intMap["elementsPerMigration"] = &in.elementsPerMigration;
  intMap["threaded"] = &in.threaded;
}

template <class T>
static bool tryReading(std::string const& name,
    std::ifstream& f,
    std::map<std::string, T*>& map)
{
  typename std::map<std::string, T*>::iterator it = map.find(name);
  if (it == map.end())
    return false;
  f >> *(it->second);
  return true;
}

static void readInputFile(
    Input& in,
    const char* filename,
    std::map<std::string, std::string*>& stringMap,
    std::map<std::string, int*>& intMap)
{
  std::ifstream f(filename);
  if (!f)
    fail("could not open \"%s\"", filename);
  std::string name;
  while (f >> name) {
    if (name[0] == '#') {
      std::getline(f, name, '\n');
      continue;
    }
    if (tryReading(name, f, stringMap))
      continue;
    if (tryReading(name, f, intMap))
      continue;
    /* the WEIRD parameter ! */
    if (name == "RecursivePtnStep") {
      if (in.recursivePtn == -1)
        fail("RecursivePtn needs to be set before RecursivePtnStep");
      in.recursivePtnStep.allocate(in.recursivePtn);
      for (int i = 0; i < in.recursivePtn; ++i)
        f >> in.recursivePtnStep[i];
      continue;
    }
    fail("unknown variable \"%s\" in %s\n", name.c_str(), filename);
  }
}

static bool contains(std::string const& a, std::string const& b)
{
  return a.find(b) != std::string::npos;
}

static void validate(Input& in)
{
  assert(in.parmaPtn == 0 || in.parmaPtn == 1);
  if (in.adaptFlag)
    assert(contains(in.attributeFileName, "NOIC.spj"));
}

Input::Input(const char* filename)
{
  setDefaults(*this);
  std::map<std::string, std::string*> stringMap;
  std::map<std::string, int*> intMap;
  formMaps(*this, stringMap, intMap);
  readInputFile(*this, filename, stringMap, intMap);
  validate(*this);
}

}
<commit_msg>require threaded<commit_after>#include "phInput.h"
#include <fstream>
#include <map>
#include "ph.h"
#include <cassert>

namespace ph {

static void setDefaults(Input& in)
{
  in.outMeshFileName = "";
  in.numSplit = 10;
  in.tetrahedronize = 0;
  in.localPtn = true;
  in.recursivePtn = -1;
  in.recursiveUR = 1;
  in.parmaPtn = 0; // No Parma by default
  in.dwalMigration = 0; // Do not migrate dwal field by default
  in.buildMapping = 0; // Do not build the mapping field by default
  in.elementsPerMigration = 1000*1000; // 100k elms per round
  in.threaded = 1;
}

typedef std::map<std::string, std::string*> StringMap;
typedef std::map<std::string, int*> IntMap;

static void formMaps(Input& in, StringMap& stringMap, IntMap& intMap)
{
  intMap["globalP"] = &in.globalP;
  intMap["timeStepNumber"] = &in.timeStepNumber;
  intMap["ensa_dof"] = &in.ensa_dof;
  stringMap["restartFileName"] = &in.restartFileName;
  stringMap["attributeFileName"] = &in.attributeFileName;
  stringMap["meshFileName"] = &in.meshFileName;
  stringMap["outMeshFileName"] = &in.outMeshFileName;
  stringMap["modelFileName"] = &in.modelFileName;
  stringMap["outputFormat"] = &in.outputFormat;
  stringMap["partitionMethod"] = &in.partitionMethod;
  intMap["adaptFlag"] = &in.adaptFlag;
  intMap["rRead"] = &in.rRead;
  intMap["rStart"] = &in.rStart;
  intMap["AdaptStrategy"] = &in.adaptStrategy;
  intMap["RecursiveUR"] = &in.recursiveUR;
  intMap["Periodic"] = &in.periodic;
  intMap["prCD"] = &in.prCD;
  intMap["timing"] = &in.timing;
  intMap["internalBCNodes"] = &in.internalBCNodes;
  intMap["WRITEASC"] = &in.writeAsc;
  intMap["phastaIO"] = &in.phastaIO;
  intMap["numTotParts"] = &in.numTotParts;
  intMap["SolutionMigration"] = &in.solutionMigration;
  intMap["DisplacementMigration"] = &in.displacementMigration;
  intMap["isReorder"] = &in.isReorder;
  intMap["numSplit"] = &in.numSplit;
  intMap["Tetrahedronize"] = &in.tetrahedronize;
  intMap["LocalPtn"] = &in.localPtn;
  intMap["RecursivePtn"] = &in.recursivePtn;
  intMap["ParmaPtn"] = &in.parmaPtn;
  intMap["dwalMigration"] = &in.dwalMigration;
  intMap["buildMapping"] = &in.buildMapping;
  intMap["elementsPerMigration"] = &in.elementsPerMigration;
  intMap["threaded"] = &in.threaded;
}

template <class T>
static bool tryReading(std::string const& name,
    std::ifstream& f,
    std::map<std::string, T*>& map)
{
  typename std::map<std::string, T*>::iterator it = map.find(name);
  if (it == map.end())
    return false;
  f >> *(it->second);
  return true;
}

static void readInputFile(
    Input& in,
    const char* filename,
    std::map<std::string, std::string*>& stringMap,
    std::map<std::string, int*>& intMap)
{
  std::ifstream f(filename);
  if (!f)
    fail("could not open \"%s\"", filename);
  std::string name;
  while (f >> name) {
    if (name[0] == '#') {
      std::getline(f, name, '\n');
      continue;
    }
    if (tryReading(name, f, stringMap))
      continue;
    if (tryReading(name, f, intMap))
      continue;
    /* the WEIRD parameter ! */
    if (name == "RecursivePtnStep") {
      if (in.recursivePtn == -1)
        fail("RecursivePtn needs to be set before RecursivePtnStep");
      in.recursivePtnStep.allocate(in.recursivePtn);
      for (int i = 0; i < in.recursivePtn; ++i)
        f >> in.recursivePtnStep[i];
      continue;
    }
    fail("unknown variable \"%s\" in %s\n", name.c_str(), filename);
  }
}

static bool contains(std::string const& a, std::string const& b)
{
  return a.find(b) != std::string::npos;
}

static void validate(Input& in)
{
  assert(in.parmaPtn == 0 || in.parmaPtn == 1);
  if (in.adaptFlag)
    assert(contains(in.attributeFileName, "NOIC.spj"));
  assert(in.threaded);
}

Input::Input(const char* filename)
{
  setDefaults(*this);
  std::map<std::string, std::string*> stringMap;
  std::map<std::string, int*> intMap;
  formMaps(*this, stringMap, intMap);
  readInputFile(*this, filename, stringMap, intMap);
  validate(*this);
}

}
<|endoftext|>


<commit_before><commit_msg>Increase tracklet error in y to 0.7 mm<commit_after><|endoftext|>


<commit_before>// **************************************************************************
// This file is property of and copyright by the ALICE HLT Project          *
// ALICE Experiment at CERN, All rights reserved.                           *
//                                                                          *
// Primary Authors: Sergey Gorbunov <sergey.gorbunov@kip.uni-heidelberg.de> *
//                  Ivan Kisel <kisel@kip.uni-heidelberg.de>                *
//                  for The ALICE HLT Project.                              *
//                                                                          *
// Permission to use, copy, modify and distribute this software and its     *
// documentation strictly for non-commercial purposes is hereby granted     *
// without fee, provided that the above copyright notice appears in all     *
// copies and that both the copyright notice and this permission notice     *
// appear in the supporting documentation. The authors make no claims       *
// about the suitability of this software for any purpose. It is            *
// provided "as is" without express or implied warranty.                    *
//                                                                          *
//***************************************************************************

///  @file   AliHLTLumiRegComponent.cxx
///  @author Davide Caffarri <davide.caffarri@cern.ch>
///  @date   January 2015
///  @brief  Luminous Region calculation component

////////////////////////////////////////////////////////////
//                                                        //
// a Luminous Region determination component for the HLT  //
//                                                        //
////////////////////////////////////////////////////////////

#include "AliHLTLumiRegComponent.h"
#include "TRegexp.h"
#include "TString.h"
#include "AliSysInfo.h"
#include "AliESDVertex.h"
#include "TF1.h"
#include "AliHLTMessage.h"

using namespace std;

ClassImp( AliHLTLumiRegComponent )
AliHLTLumiRegComponent::AliHLTLumiRegComponent():
AliHLTProcessor(),
fEventSpecie(0)
{
  for(Int_t i=0; i<3; i++){
    fPrimary[i] = 0x0;
  }

  for(Int_t i=0; i<2; i++){
    fPrimaryDefMult[i] = 0x0;
  }

}

AliHLTLumiRegComponent::AliHLTLumiRegComponent( const AliHLTLumiRegComponent& ):
AliHLTProcessor(),
fEventSpecie(0)
{
    // see header file for class documentation
    HLTFatal( "copy constructor untested" );
}

AliHLTLumiRegComponent& AliHLTLumiRegComponent::operator=( const AliHLTLumiRegComponent& )
{
    // see header file for class documentation
    HLTFatal( "assignment operator untested" );
    return *this;
}

AliHLTLumiRegComponent::~AliHLTLumiRegComponent()
{
  // see header file for class documentation

  for(Int_t i=0; i<3; i++){
    delete fPrimary[i];
  }

}

AliHLTComponentDataType AliHLTLumiRegComponent::GetOutputDataType()
{
  // see header file for class documentation
  return kAliHLTDataTypeHistogram;
}

void AliHLTLumiRegComponent::GetInputDataTypes( vector<AliHLTComponentDataType>& list )
{
  // see header file for class documentation
  list.clear();
  list.push_back(kAliHLTDataTypeESDVertex|kAliHLTDataOriginITS); //spd vertex
  list.push_back(kAliHLTDataTypeFlatESDVertex|kAliHLTDataOriginITS); // ITSSA primary vertex
  }

void AliHLTLumiRegComponent::GetOutputDataSize(unsigned long& constBase, double& inputMultiplier)
{
  //8000 is a temporary number. Find the way to
  //estimate 3 serialized TH2F.
  constBase = 80000;
  inputMultiplier = 1.;

}

AliHLTComponent *AliHLTLumiRegComponent::Spawn(){

return new AliHLTLumiRegComponent;

}

int AliHLTLumiRegComponent::DoInit(int argc, const char **argv){

  int iResults=0;
  TString strVtx = "";

  for(Int_t iHisto=0; iHisto<3; iHisto++){

    if (iHisto == 0) {
      strVtx = "X";
      fPrimary[iHisto] = new TH1F(Form("h%sTRKVtx", strVtx.Data()),Form("h%sTRKVtx", strVtx.Data()), 200,-0.7,0.7);

      fPrimaryDefMult[iHisto] = new TH1F (Form("h%sTRKDefMult", strVtx.Data()),Form("h%sTRKDefMult", strVtx.Data()), 200,-0.7,0.7);
    }

    if (iHisto == 1) {
      strVtx = "Y";
      fPrimary[iHisto] = new TH1F(Form("h%sTRKVtx", strVtx.Data()),Form("h%sTRKVtx", strVtx.Data()), 200,-0.7,0.7);
      fPrimaryDefMult[iHisto] = new TH1F (Form("h%sTRKDefMult", strVtx.Data()),Form("h%sTRKDefMult", strVtx.Data()), 200,-0.7,0.7);
    }

    if (iHisto == 2) {
      strVtx = "Z";
      fPrimary[iHisto] = new TH1F(Form("h%sTRKVtx", strVtx.Data()),Form("h%sTRKVtx", strVtx.Data()), 200,-20,20);
      fPrimaryDefMult[iHisto] = new TH1F (Form("h%sTRKDefMult", strVtx.Data()),Form("h%sTRKDefMult", strVtx.Data()), 200,-0.7,0.7);
    }
  }

  AliCDBEntry *grpEntry = AliCDBManager::Instance()->Get("/GRP/GRP/Data/");
  if(!grpEntry) {
    ::Error("AliHLTLumiRegComponent","Cannot get AliCDBEntry");
    return 0;
  }
  const AliGRPObject* grpData = dynamic_cast<AliGRPObject*>(grpEntry->GetObject());
  if(!grpData) {
    ::Error("AliHLTLumiRegComponent","Cannot get AliGRPObject");
    return 0;
  }
  TString beamType(grpData->GetBeamType());

  if(beamType == "A-A") fEventSpecie = AliHLTLumiRegComponent::kPbPb;
  else
    if((beamType == "p-A")||(beamType == "A-p")) fEventSpecie = AliHLTLumiRegComponent::kpPb;
    else fEventSpecie = AliHLTLumiRegComponent::kpp;

  return 1;
}

Int_t AliHLTLumiRegComponent::DoEvent( const AliHLTComponentEventData& /*evtData*/, AliHLTComponentTriggerData& /*trigData*/){

  AliSysInfo::AddStamp("AliHLTLumiRegComponent::DoEvent.Start");
  Int_t vertexITSSATRKok=0;
  AliESDVertex vertexTracks;
  AliFlatESDVertex *vtxFlat;

  if (!IsDataEvent())
  {
    //on EOR push unconditionally
    const AliHLTComponentBlockData* pBlock =
      GetFirstInputBlock(kAliHLTDataTypeEOR|kAliHLTDataOriginAny);
    if (pBlock)
    {
      PushAndReset();
    }
    return 0;
  }

  const AliHLTComponentBlockData* pBlock=GetFirstInputBlock(kAliHLTDataTypeFlatESDVertex|kAliHLTDataOriginITS);
  if (!pBlock) return 0;

  // fpBenchmark->AddInput(pBlock->fSize);
  vtxFlat =  reinterpret_cast<AliFlatESDVertex*>( pBlock->fPtr );
  if (!vtxFlat) return 0;
  int nContrib = vtxFlat->GetNContributors();
  if (nContrib>0)
    vertexITSSATRKok=1;

  if (!vertexITSSATRKok) {
    HLTInfo("Vertex Tracks not found, trying the SPD one...");
    return 0;
    //SPD vertex!!
  }

  Double_t vtxPos[3] = {0.,0.,0.};
  vtxFlat->GetXYZ(vtxPos);

  for (Int_t iCoord =0; iCoord<3; iCoord++){
    fPrimary[iCoord]->Fill(vtxPos[iCoord]);
  }

  if (fEventSpecie == AliHLTLumiRegComponent::kpp){
    if ((nContrib>30) && (nContrib<50)){
      for (Int_t iCoord =0; iCoord<3; iCoord++){
        fPrimaryDefMult[iCoord]->Fill(vtxPos[iCoord]);
      }
    }
  }

  if (fEventSpecie == AliHLTLumiRegComponent::kpPb) {
    if (nContrib>100){
      for (Int_t iCoord =0; iCoord<3; iCoord++){
        fPrimaryDefMult[iCoord]->Fill(vtxPos[iCoord]);
      }
    }
  }

  if (fEventSpecie == AliHLTLumiRegComponent::kPbPb){
    if (nContrib>500){
      for (Int_t iCoord =0; iCoord<3; iCoord++){
        fPrimaryDefMult[iCoord]->Fill(vtxPos[iCoord]);
      }
    }
  }

  PushAndReset();

  return 0;
}

int AliHLTLumiRegComponent::PushAndReset()
{
  HLTInfo("pushing and resetting");
  for (Int_t iCoord =0; iCoord<3; iCoord++){
    if (PushBack(fPrimary[iCoord], kAliHLTDataTypeHistogram | kAliHLTDataOriginAny) > 0)
      fPrimary[iCoord]->Reset();

    if (PushBack(fPrimaryDefMult[iCoord], kAliHLTDataTypeHistogram | kAliHLTDataOriginAny) > 0)
      fPrimaryDefMult[iCoord]->Reset();
  }
  return 0;
}

Int_t AliHLTLumiRegComponent::FitPositions(TH1F *histos[], Float_t* mean, Float_t* sigma){

  Int_t fitVtxResults1 = 0, fitVtxResults2 = 0,fitVtxResults3 = 0;
  fitVtxResults1 = AliHLTLumiRegComponent::FitHistos(histos[0], mean[0], sigma[0], -1, 1);
  fitVtxResults2 = AliHLTLumiRegComponent::FitHistos(histos[1], mean[1], sigma[1], -1, 1);
  fitVtxResults3 = AliHLTLumiRegComponent::FitHistos(histos[2], mean[2], sigma[2], -12, 12);

  return fitVtxResults1||fitVtxResults2||fitVtxResults3;

}

Int_t AliHLTLumiRegComponent::LuminousRegionExtraction(TH1F* histos[], Float_t* meanLR, Float_t* sigmaLR){

  Float_t meanMult = 38.;
  Float_t p2 = 1.3;
  Float_t resolVtx = 0.04;
  Float_t lumiregsquaredX = 0;
  Float_t lumiregsquaredY = 0;
  int rc = 0;

  AliHLTLumiRegComponent::FitHistos(histos[0], meanLR[0], sigmaLR[0], -0.4, 0.4);
  AliHLTLumiRegComponent::FitHistos(histos[1], meanLR[1], sigmaLR[1], -0.2, 0.7);

  if (AliHLTLumiRegComponent::kpp){
    lumiregsquaredX = (sigmaLR[0]*sigmaLR[0] - ((resolVtx*resolVtx)/TMath::Power(meanMult, p2)));
    lumiregsquaredY = (sigmaLR[1]*sigmaLR[1] - ((resolVtx*resolVtx)/TMath::Power(meanMult, p2)));

    if (lumiregsquaredX > 0 && lumiregsquaredX < 0.0005) {
      sigmaLR[0] = TMath::Sqrt(lumiregsquaredX);
    }

    if (lumiregsquaredY > 0 && lumiregsquaredY < 0.0005) {
      sigmaLR[1] = TMath::Sqrt(lumiregsquaredY);
    }

    if (lumiregsquaredX < 0 || lumiregsquaredX < 1E-5){
      Printf("Difficult luminous region determination X, keep convoluted sigma");
      rc = 1;
    }

    if (lumiregsquaredY < 0 || lumiregsquaredY < 1E-5){
      Printf("Difficult luminous region determination Y, keep convoluted sigma");
      rc += 2;
    }

  }

  //rc: 0 on success, 1 on bad X fit, 2 on bad Y fit, 3 on both bad
  return rc;

}

Int_t AliHLTLumiRegComponent::FitHistos(TH1F *hVtx, Float_t &mean, Float_t &sigma, Float_t rangelow, Float_t rangeup){

  Int_t isFitok = 1;
  Int_t nEntries =  hVtx->GetEntries();
  if (nEntries < 50) {
    Printf("too few entries for fitting");
    //do something!
  }

  hVtx->Fit("gaus", "M", "", rangelow, rangeup);
  TF1 *vtxFunct = hVtx->GetFunction("gaus");
  if (!vtxFunct) {
    Printf("No fit function!");
    return 1;
  }
  mean = vtxFunct->GetParameter(1);
  sigma = vtxFunct->GetParameter(2);

  delete vtxFunct;
  return isFitok;
}

<commit_msg>fix histogram range<commit_after>// **************************************************************************
// This file is property of and copyright by the ALICE HLT Project          *
// ALICE Experiment at CERN, All rights reserved.                           *
//                                                                          *
// Primary Authors: Sergey Gorbunov <sergey.gorbunov@kip.uni-heidelberg.de> *
//                  Ivan Kisel <kisel@kip.uni-heidelberg.de>                *
//                  for The ALICE HLT Project.                              *
//                                                                          *
// Permission to use, copy, modify and distribute this software and its     *
// documentation strictly for non-commercial purposes is hereby granted     *
// without fee, provided that the above copyright notice appears in all     *
// copies and that both the copyright notice and this permission notice     *
// appear in the supporting documentation. The authors make no claims       *
// about the suitability of this software for any purpose. It is            *
// provided "as is" without express or implied warranty.                    *
//                                                                          *
//***************************************************************************

///  @file   AliHLTLumiRegComponent.cxx
///  @author Davide Caffarri <davide.caffarri@cern.ch>
///  @date   January 2015
///  @brief  Luminous Region calculation component

////////////////////////////////////////////////////////////
//                                                        //
// a Luminous Region determination component for the HLT  //
//                                                        //
////////////////////////////////////////////////////////////

#include "AliHLTLumiRegComponent.h"
#include "TRegexp.h"
#include "TString.h"
#include "AliSysInfo.h"
#include "AliESDVertex.h"
#include "TF1.h"
#include "AliHLTMessage.h"

using namespace std;

ClassImp( AliHLTLumiRegComponent )
AliHLTLumiRegComponent::AliHLTLumiRegComponent():
AliHLTProcessor(),
fEventSpecie(0)
{
  for(Int_t i=0; i<3; i++){
    fPrimary[i] = 0x0;
  }

  for(Int_t i=0; i<2; i++){
    fPrimaryDefMult[i] = 0x0;
  }

}

AliHLTLumiRegComponent::AliHLTLumiRegComponent( const AliHLTLumiRegComponent& ):
AliHLTProcessor(),
fEventSpecie(0)
{
    // see header file for class documentation
    HLTFatal( "copy constructor untested" );
}

AliHLTLumiRegComponent& AliHLTLumiRegComponent::operator=( const AliHLTLumiRegComponent& )
{
    // see header file for class documentation
    HLTFatal( "assignment operator untested" );
    return *this;
}

AliHLTLumiRegComponent::~AliHLTLumiRegComponent()
{
  // see header file for class documentation

  for(Int_t i=0; i<3; i++){
    delete fPrimary[i];
  }

}

AliHLTComponentDataType AliHLTLumiRegComponent::GetOutputDataType()
{
  // see header file for class documentation
  return kAliHLTDataTypeHistogram;
}

void AliHLTLumiRegComponent::GetInputDataTypes( vector<AliHLTComponentDataType>& list )
{
  // see header file for class documentation
  list.clear();
  list.push_back(kAliHLTDataTypeESDVertex|kAliHLTDataOriginITS); //spd vertex
  list.push_back(kAliHLTDataTypeFlatESDVertex|kAliHLTDataOriginITS); // ITSSA primary vertex
  }

void AliHLTLumiRegComponent::GetOutputDataSize(unsigned long& constBase, double& inputMultiplier)
{
  //8000 is a temporary number. Find the way to
  //estimate 3 serialized TH2F.
  constBase = 80000;
  inputMultiplier = 1.;

}

AliHLTComponent *AliHLTLumiRegComponent::Spawn(){

return new AliHLTLumiRegComponent;

}

int AliHLTLumiRegComponent::DoInit(int argc, const char **argv){

  int iResults=0;
  TString strVtx = "";

  for(Int_t iHisto=0; iHisto<3; iHisto++){

    if (iHisto == 0) {
      strVtx = "X";
      fPrimary[iHisto] = new TH1F(Form("h%sTRKVtx", strVtx.Data()),Form("h%sTRKVtx", strVtx.Data()), 200,-0.7,0.7);

      fPrimaryDefMult[iHisto] = new TH1F (Form("h%sTRKDefMult", strVtx.Data()),Form("h%sTRKDefMult", strVtx.Data()), 200,-0.7,0.7);
    }

    if (iHisto == 1) {
      strVtx = "Y";
      fPrimary[iHisto] = new TH1F(Form("h%sTRKVtx", strVtx.Data()),Form("h%sTRKVtx", strVtx.Data()), 200,-0.7,0.7);
      fPrimaryDefMult[iHisto] = new TH1F (Form("h%sTRKDefMult", strVtx.Data()),Form("h%sTRKDefMult", strVtx.Data()), 200,-0.7,0.7);
    }

    if (iHisto == 2) {
      strVtx = "Z";
      fPrimary[iHisto] = new TH1F(Form("h%sTRKVtx", strVtx.Data()),Form("h%sTRKVtx", strVtx.Data()), 200,-20,20);
      fPrimaryDefMult[iHisto] = new TH1F (Form("h%sTRKDefMult", strVtx.Data()),Form("h%sTRKDefMult", strVtx.Data()), 200,-20.,20.);
    }
  }

  AliCDBEntry *grpEntry = AliCDBManager::Instance()->Get("/GRP/GRP/Data/");
  if(!grpEntry) {
    ::Error("AliHLTLumiRegComponent","Cannot get AliCDBEntry");
    return 0;
  }
  const AliGRPObject* grpData = dynamic_cast<AliGRPObject*>(grpEntry->GetObject());
  if(!grpData) {
    ::Error("AliHLTLumiRegComponent","Cannot get AliGRPObject");
    return 0;
  }
  TString beamType(grpData->GetBeamType());

  if(beamType == "A-A") fEventSpecie = AliHLTLumiRegComponent::kPbPb;
  else
    if((beamType == "p-A")||(beamType == "A-p")) fEventSpecie = AliHLTLumiRegComponent::kpPb;
    else fEventSpecie = AliHLTLumiRegComponent::kpp;

  return 1;
}

Int_t AliHLTLumiRegComponent::DoEvent( const AliHLTComponentEventData& /*evtData*/, AliHLTComponentTriggerData& /*trigData*/){

  AliSysInfo::AddStamp("AliHLTLumiRegComponent::DoEvent.Start");
  Int_t vertexITSSATRKok=0;
  AliESDVertex vertexTracks;
  AliFlatESDVertex *vtxFlat;

  if (!IsDataEvent())
  {
    //on EOR push unconditionally
    const AliHLTComponentBlockData* pBlock =
      GetFirstInputBlock(kAliHLTDataTypeEOR|kAliHLTDataOriginAny);
    if (pBlock)
    {
      PushAndReset();
    }
    return 0;
  }

  const AliHLTComponentBlockData* pBlock=GetFirstInputBlock(kAliHLTDataTypeFlatESDVertex|kAliHLTDataOriginITS);
  if (!pBlock) return 0;

  // fpBenchmark->AddInput(pBlock->fSize);
  vtxFlat =  reinterpret_cast<AliFlatESDVertex*>( pBlock->fPtr );
  if (!vtxFlat) return 0;
  int nContrib = vtxFlat->GetNContributors();
  if (nContrib>0)
    vertexITSSATRKok=1;

  if (!vertexITSSATRKok) {
    HLTInfo("Vertex Tracks not found, trying the SPD one...");
    return 0;
    //SPD vertex!!
  }

  Double_t vtxPos[3] = {0.,0.,0.};
  vtxFlat->GetXYZ(vtxPos);

  for (Int_t iCoord =0; iCoord<3; iCoord++){
    fPrimary[iCoord]->Fill(vtxPos[iCoord]);
  }

  if (fEventSpecie == AliHLTLumiRegComponent::kpp){
    if ((nContrib>30) && (nContrib<50)){
      for (Int_t iCoord =0; iCoord<3; iCoord++){
        fPrimaryDefMult[iCoord]->Fill(vtxPos[iCoord]);
      }
    }
  }

  if (fEventSpecie == AliHLTLumiRegComponent::kpPb) {
    if (nContrib>100){
      for (Int_t iCoord =0; iCoord<3; iCoord++){
        fPrimaryDefMult[iCoord]->Fill(vtxPos[iCoord]);
      }
    }
  }

  if (fEventSpecie == AliHLTLumiRegComponent::kPbPb){
    if (nContrib>500){
      for (Int_t iCoord =0; iCoord<3; iCoord++){
        fPrimaryDefMult[iCoord]->Fill(vtxPos[iCoord]);
      }
    }
  }

  PushAndReset();

  return 0;
}

int AliHLTLumiRegComponent::PushAndReset()
{
  HLTInfo("pushing and resetting");
  for (Int_t iCoord =0; iCoord<3; iCoord++){
    if (PushBack(fPrimary[iCoord], kAliHLTDataTypeHistogram | kAliHLTDataOriginAny) > 0)
      fPrimary[iCoord]->Reset();

    if (PushBack(fPrimaryDefMult[iCoord], kAliHLTDataTypeHistogram | kAliHLTDataOriginAny) > 0)
      fPrimaryDefMult[iCoord]->Reset();
  }
  return 0;
}

Int_t AliHLTLumiRegComponent::FitPositions(TH1F *histos[], Float_t* mean, Float_t* sigma){

  Int_t fitVtxResults1 = 0, fitVtxResults2 = 0,fitVtxResults3 = 0;
  fitVtxResults1 = AliHLTLumiRegComponent::FitHistos(histos[0], mean[0], sigma[0], -1, 1);
  fitVtxResults2 = AliHLTLumiRegComponent::FitHistos(histos[1], mean[1], sigma[1], -1, 1);
  fitVtxResults3 = AliHLTLumiRegComponent::FitHistos(histos[2], mean[2], sigma[2], -12, 12);

  return fitVtxResults1||fitVtxResults2||fitVtxResults3;

}

Int_t AliHLTLumiRegComponent::LuminousRegionExtraction(TH1F* histos[], Float_t* meanLR, Float_t* sigmaLR){

  Float_t meanMult = 38.;
  Float_t p2 = 1.3;
  Float_t resolVtx = 0.04;
  Float_t lumiregsquaredX = 0;
  Float_t lumiregsquaredY = 0;
  int rc = 0;

  AliHLTLumiRegComponent::FitHistos(histos[0], meanLR[0], sigmaLR[0], -0.4, 0.4);
  AliHLTLumiRegComponent::FitHistos(histos[1], meanLR[1], sigmaLR[1], -0.2, 0.7);

  if (AliHLTLumiRegComponent::kpp){
    lumiregsquaredX = (sigmaLR[0]*sigmaLR[0] - ((resolVtx*resolVtx)/TMath::Power(meanMult, p2)));
    lumiregsquaredY = (sigmaLR[1]*sigmaLR[1] - ((resolVtx*resolVtx)/TMath::Power(meanMult, p2)));

    if (lumiregsquaredX > 0 && lumiregsquaredX < 0.0005) {
      sigmaLR[0] = TMath::Sqrt(lumiregsquaredX);
    }

    if (lumiregsquaredY > 0 && lumiregsquaredY < 0.0005) {
      sigmaLR[1] = TMath::Sqrt(lumiregsquaredY);
    }

    if (lumiregsquaredX < 0 || lumiregsquaredX < 1E-5){
      Printf("Difficult luminous region determination X, keep convoluted sigma");
      rc = 1;
    }

    if (lumiregsquaredY < 0 || lumiregsquaredY < 1E-5){
      Printf("Difficult luminous region determination Y, keep convoluted sigma");
      rc += 2;
    }

  }

  //rc: 0 on success, 1 on bad X fit, 2 on bad Y fit, 3 on both bad
  return rc;

}

Int_t AliHLTLumiRegComponent::FitHistos(TH1F *hVtx, Float_t &mean, Float_t &sigma, Float_t rangelow, Float_t rangeup){

  Int_t isFitok = 1;
  Int_t nEntries =  hVtx->GetEntries();
  if (nEntries < 50) {
    Printf("too few entries for fitting");
    //do something!
  }

  hVtx->Fit("gaus", "M", "", rangelow, rangeup);
  TF1 *vtxFunct = hVtx->GetFunction("gaus");
  if (!vtxFunct) {
    Printf("No fit function!");
    return 1;
  }
  mean = vtxFunct->GetParameter(1);
  sigma = vtxFunct->GetParameter(2);

  delete vtxFunct;
  return isFitok;
}

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://www.qt.io/licensing.  For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "progressmanager_p.h"
#include <QDBusMessage>
#include <QDBusConnection>
#include <QDBusConnectionInterface>
#include <QStringList>
#include <QApplication>

namespace {
namespace Unity {

static int max = 0;
static int min = 0;
static bool isSupported = false;

static inline void sendMessage(const QVariantMap &map)
{
    QDBusMessage message = QDBusMessage::createSignal(QLatin1String("/qtcreator"), QLatin1String("com.canonical.Unity.LauncherEntry"), QLatin1String("Update"));
    QVariantList args;
    args << QLatin1String("application://qtcreator-qt-creator.desktop")
         << map;
    message.setArguments(args);
    if (!QDBusConnection::sessionBus().send(message))
        qWarning("Unable to send message");
}

template <typename T>
static void sendMessage(const char *name, const T &value)
{
    QVariantMap map;
    map.insert(QLatin1String(name), value);
    sendMessage(map);
}

} //namespace Unity
}

void Core::Internal::ProgressManagerPrivate::initInternal()
{
    QDBusConnection connection = QDBusConnection::sessionBus();
    QStringList services = connection.interface()->registeredServiceNames().value();
    Unity::isSupported = services.contains(QLatin1String("com.canonical.Unity"));
}

void Core::Internal::ProgressManagerPrivate::cleanup()
{
}

void Core::Internal::ProgressManagerPrivate::doSetApplicationLabel(const QString &text)
{
    if (Unity::isSupported) {
        qint64 count = text.toInt();
        QVariantMap map;
        map.insert(QLatin1String("count"), count);
        map.insert(QLatin1String("count-visible"), count > 0);
        Unity::sendMessage(map);
    }
}

void Core::Internal::ProgressManagerPrivate::setApplicationProgressRange(int min, int max)
{
    Unity::min = min;
    Unity::max = max;
}

void Core::Internal::ProgressManagerPrivate::setApplicationProgressValue(int value)
{
    if (Unity::isSupported) {
        int total = Unity::max-Unity::min;
        double percents = 0;
        if (total)
            percents = double(value-Unity::min)/double(total);
        Unity::sendMessage("progress", percents);
    }
}

void Core::Internal::ProgressManagerPrivate::setApplicationProgressVisible(bool visible)
{
    if (Unity::isSupported)
        Unity::sendMessage("progress-visible", visible);
}
<commit_msg>Fix application name to the correct .desktop<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://www.qt.io/licensing.  For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "progressmanager_p.h"
#include <QDBusMessage>
#include <QDBusConnection>
#include <QDBusConnectionInterface>
#include <QStringList>
#include <QApplication>

namespace {
namespace Unity {

static int max = 0;
static int min = 0;
static bool isSupported = false;

static inline void sendMessage(const QVariantMap &map)
{
    QDBusMessage message = QDBusMessage::createSignal(QLatin1String("/qtcreator"), QLatin1String("com.canonical.Unity.LauncherEntry"), QLatin1String("Update"));
    QVariantList args;
    args << QLatin1String("application://qtcreator.desktop")
         << map;
    message.setArguments(args);
    if (!QDBusConnection::sessionBus().send(message))
        qWarning("Unable to send message");
}

template <typename T>
static void sendMessage(const char *name, const T &value)
{
    QVariantMap map;
    map.insert(QLatin1String(name), value);
    sendMessage(map);
}

} //namespace Unity
}

void Core::Internal::ProgressManagerPrivate::initInternal()
{
    QDBusConnection connection = QDBusConnection::sessionBus();
    QStringList services = connection.interface()->registeredServiceNames().value();
    Unity::isSupported = services.contains(QLatin1String("com.canonical.Unity"));
}

void Core::Internal::ProgressManagerPrivate::cleanup()
{
}

void Core::Internal::ProgressManagerPrivate::doSetApplicationLabel(const QString &text)
{
    if (Unity::isSupported) {
        qint64 count = text.toInt();
        QVariantMap map;
        map.insert(QLatin1String("count"), count);
        map.insert(QLatin1String("count-visible"), count > 0);
        Unity::sendMessage(map);
    }
}

void Core::Internal::ProgressManagerPrivate::setApplicationProgressRange(int min, int max)
{
    Unity::min = min;
    Unity::max = max;
}

void Core::Internal::ProgressManagerPrivate::setApplicationProgressValue(int value)
{
    if (Unity::isSupported) {
        int total = Unity::max-Unity::min;
        double percents = 0;
        if (total)
            percents = double(value-Unity::min)/double(total);
        Unity::sendMessage("progress", percents);
    }
}

void Core::Internal::ProgressManagerPrivate::setApplicationProgressVisible(bool visible)
{
    if (Unity::isSupported)
        Unity::sendMessage("progress-visible", visible);
}
<|endoftext|>


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

Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.

*******************************************************************************/

//==============================================================================
// QScintillaWidget class
//==============================================================================

#include "filemanager.h"
#include "guiutils.h"
#include "qscintillawidget.h"

//==============================================================================

#include <QDragEnterEvent>
#include <QLabel>
#include <QMenu>
#include <QMimeData>

//==============================================================================

#include "Qsci/qscilexer.h"

//==============================================================================

namespace OpenCOR {
namespace QScintillaSupport {

//==============================================================================

QScintillaWidget::QScintillaWidget(const QString &pContents,
                                   const bool &pReadOnly,
                                   QsciLexer *pLexer, QWidget *pParent) :
    QsciScintilla(pParent),
    mCanUndo(false),
    mCanRedo(false),
    mCanSelectAll(false),
    mOverwriteMode(false)
{
    // Remove the frame around our Scintilla editor

    setFrameShape(QFrame::NoFrame);

    // Remove the margin number in our Scintilla editor

    setMarginWidth(SC_MARGIN_NUMBER, 0);

    // Associate a lexer to our Scintilla editor, should one be provided
    // Note: the default font family and size come from Qt Creator...

#if defined(Q_OS_WIN)
    mFont = QFont("Courier", 10);
#elif defined(Q_OS_LINUX)
    mFont = QFont("Monospace", 9);
#elif defined(Q_OS_MAC)
    mFont = QFont("Monaco", 12);
#else
    #error Unsupported platform
#endif

    if (pLexer) {
        // A lexer was provided, so specify its fonts and associate it with our
        // Scintilla editor

        pLexer->setFont(mFont);

        setLexer(pLexer);

        // Specify the type of tree folding to be used. Some lexers may indeed
        // use that feature, so...

        setFolding(QsciScintilla::BoxedTreeFoldStyle);
    } else {
        // No lexer was provided, so simply specify a default font family and
        // size for our Scintilla editor

        setFont(mFont);
    }

    // Set the contents of our Scintilla editor and its read-only property

    setContents(pContents);
    setReadOnly(pReadOnly);

    // Show the caret line

    setCaretLineVisible(true);

    // Initialise our colours by 'updating' them

    updateColors();

    // Clear some key mappings inherited from QsciScintilla
    // Note #1: indeed, QsciScintilla handles some shortcuts (e.g. Ctrl+L),
    //          which we don't want to see handled (e.g. Ctrl+L is used by
    //          QsciScintilla to delete the current line while OpenCOR uses it
    //          to (un)lock the current file), so...
    // Note #2: even though we are clearing those key mappings, we must also
    //          bypass QsciScintilla's handling of event() (see below). Indeed,
    //          not to do so would mean that if, for example, the user was to
    //          press Ctrl+L, then nothing would happen while we would have
    //          expected the current file to be (un)locked...

    SendScintilla(SCI_CLEARCMDKEY, (SCMOD_CTRL << 16)+'D');
    SendScintilla(SCI_CLEARCMDKEY, (SCMOD_CTRL << 16)+'L');
    SendScintilla(SCI_CLEARCMDKEY, (SCMOD_CTRL << 16)+(SCMOD_SHIFT << 16)+'L');

    // Empty context menu by default

    mContextMenu = new QMenu(this);

    // Create our two labels to show our cursor position and editing mode

    mCursorPositionWidget = new QLabel(this);
    mEditingModeWidget = new QLabel(this);

    // Keep track of the change to the UI

    connect(this, SIGNAL(SCN_UPDATEUI(int)),
            this, SLOT(updateUi()));

    // Keep track of whether we can undo/redo

    connect(this, SIGNAL(textChanged()),
            this, SLOT(updateCanUndoAndCanRedo()));

    // Keep track of changes to our editor that may affect our ability to select
    // all of its text
    // Note: we use the SCN_MODIFIED() signal rather than the textChanged()
    //       signal since the latter is only emitted when inserting or deleting
    //       some text...

    connect(this, SIGNAL(selectionChanged()),
            this, SLOT(checkCanSelectAll()));
    connect(this, SIGNAL(SCN_MODIFIED(int, int, const char *, int, int, int, int, int, int, int)),
            this, SLOT(checkCanSelectAll()));

    // Keep track of the change in the cursor position

    connect(this, SIGNAL(cursorPositionChanged(int, int)),
            this, SLOT(cursorPositionChanged(const int &, const int &)));
}

//==============================================================================

QScintillaWidget::~QScintillaWidget()
{
    // Delete some internal objects

    delete mContextMenu;
}

//==============================================================================

QMenu * QScintillaWidget::contextMenu() const
{
    // Return our context menu

    return mContextMenu;
}

//==============================================================================

void QScintillaWidget::setContextMenu(const QList<QAction *> &pContextMenuActions)
{
    // Set our context menu

    mContextMenu->clear();

    foreach (QAction *action, pContextMenuActions)
        mContextMenu->addAction(action);
}

//==============================================================================

int QScintillaWidget::currentPosition() const
{
    // Return our current position

    return SendScintilla(SCI_GETCURRENTPOS);
}

//==============================================================================

QString QScintillaWidget::contents() const
{
    // Return our contents

    return text();
}

//==============================================================================

void QScintillaWidget::setContents(const QString &pContents)
{
    // Set our contents

    setText(pContents);
}

//==============================================================================

int QScintillaWidget::contentsSize() const
{
    // Return the size of our contents

    return SendScintilla(SCI_GETLENGTH);
}

//==============================================================================

QString QScintillaWidget::textInRange(const int &pStartRange,
                                      const int &pEndRange) const
{
    // Retrieve and return the text in the given range, making sure that the
    // given range makes sense

    int maxRange = contentsSize();

    if (   (pStartRange < 0) || (pStartRange >= maxRange)
        || (pEndRange < 0) || (pEndRange >= maxRange)
        || (pStartRange >= pEndRange))
        return QString();

    char *text = new char[pEndRange-pStartRange+1];

    SendScintilla(SCI_GETTEXTRANGE, pStartRange, pEndRange, text);

    QString res = QString(text);

    delete[] text;

    return res;
}

//==============================================================================

int QScintillaWidget::findTextInRange(const int &pStartRange,
                                      const int &pEndRange,
                                      const QString &pText,
                                      const bool &pCaseSensitive) const
{
    // Find and return the position, if any, of the given text within the given
    // range

    SendScintilla(SCI_SETSEARCHFLAGS, pCaseSensitive?SCFIND_MATCHCASE:0);

    SendScintilla(SCI_SETTARGETSTART, pStartRange);
    SendScintilla(SCI_SETTARGETEND, pEndRange);

    QByteArray text = pText.toUtf8();

    return SendScintilla(SCI_SEARCHINTARGET, text.length(), text.constData());
}

//==============================================================================

bool QScintillaWidget::isSelectAllAvailable() const
{
    // Return whether we can select all the text

    return mCanSelectAll;
}

//==============================================================================

void QScintillaWidget::resetUndoHistory()
{
    // Reset our undo history

    SendScintilla(SCI_EMPTYUNDOBUFFER);

    mCanUndo = false;
    mCanRedo = false;
}

//==============================================================================

QLabel * QScintillaWidget::cursorPositionWidget() const
{
    // Return our cursort position widget

    return mCursorPositionWidget;
}

//==============================================================================

QLabel * QScintillaWidget::editingModeWidget() const
{
    // Return our editing mode widget

    return mEditingModeWidget;
}

//==============================================================================

QString QScintillaWidget::eolString() const
{
    // Return the end of line we use

    switch (eolMode()) {
    case EolUnix:
        return "\n";
    case EolMac:
        return "\r";
    default:   // EolWindows
        return "\r\n";
    }
}

//==============================================================================

void QScintillaWidget::changeEvent(QEvent *pEvent)
{
    // Default handling of the event

    QsciScintilla::changeEvent(pEvent);

    // Check whether the palette has changed and if so then update our colors

    if (pEvent->type() == QEvent::PaletteChange)
        updateColors();
}

//==============================================================================

void QScintillaWidget::contextMenuEvent(QContextMenuEvent *pEvent)
{
    // Show our context menu or QsciScintilla's one, if we don't have one

    if (mContextMenu->isEmpty())
        QsciScintilla::contextMenuEvent(pEvent);
    else
        mContextMenu->exec(pEvent->globalPos());
}

//==============================================================================

void QScintillaWidget::dragEnterEvent(QDragEnterEvent *pEvent)
{
    // Accept the proposed action for the event, but only if we are not dropping
    // URIs
    // Note: this is not (currently?) needed on Windows and OS X, but if we
    //       don't have that check on Linux, then to drop some files on our
    //       Scintilla editor will result in the text/plain version of the data
    //       (e.g. file:///home/me/myFile) to be inserted in the text, so...

    if (!pEvent->mimeData()->hasFormat(Core::FileSystemMimeType))
        pEvent->acceptProposedAction();
    else
        pEvent->ignore();
}

//==============================================================================

bool QScintillaWidget::event(QEvent *pEvent)
{
    // Bypass QsciScintilla's handling of event()
    // Note: see the note on the clearing of some key mappings in the contructor
    //       above...

    return QsciScintillaBase::event(pEvent);
}

//==============================================================================

void QScintillaWidget::keyPressEvent(QKeyEvent *pEvent)
{
    // Reset the font size, if needed

    if (   !(pEvent->modifiers() & Qt::ShiftModifier)
        &&  (pEvent->modifiers() & Qt::ControlModifier)
        && !(pEvent->modifiers() & Qt::AltModifier)
        && !(pEvent->modifiers() & Qt::MetaModifier)
        &&  (pEvent->key() == Qt::Key_0))
        zoomTo(0);
    else
        // Default handling of the event

        QsciScintilla::keyPressEvent(pEvent);
}

//==============================================================================

void QScintillaWidget::wheelEvent(QWheelEvent *pEvent)
{
    // Increasing/decrease the font size, if needed

    if (pEvent->modifiers() == Qt::ControlModifier) {
        int delta = pEvent->delta();

        if (delta > 0)
            zoomIn();
        else if (delta < 0)
            zoomOut();

        pEvent->accept();
    } else {
        QsciScintilla::wheelEvent(pEvent);
    }
}

//==============================================================================

void QScintillaWidget::updateUi()
{
    // Update our editing mode, if needed

    bool newOverwriteMode = overwriteMode();

    if (   (newOverwriteMode != mOverwriteMode)
        || mEditingModeWidget->text().isEmpty()) {
        mOverwriteMode = newOverwriteMode;

        mEditingModeWidget->setText(mOverwriteMode?"OVR":"INS");
    }
}

//==============================================================================

void QScintillaWidget::updateCanUndoAndCanRedo()
{
    // Check whether undoing/redoing is possible

    bool newCanUndo = isUndoAvailable();
    bool newCanRedo = isRedoAvailable();

    if (newCanUndo != mCanUndo) {
        mCanUndo = newCanUndo;

        emit canUndo(mCanUndo);
    }

    if (newCanRedo != mCanRedo) {
        mCanRedo = newCanRedo;

        emit canRedo(mCanRedo);
    }
}

//==============================================================================

void QScintillaWidget::checkCanSelectAll()
{
    // Check whether we can select all the text

    bool newCanSelectAll = text().size() && selectedText().compare(text());

    if (newCanSelectAll != mCanSelectAll) {
        mCanSelectAll = newCanSelectAll;

        emit canSelectAll(mCanSelectAll);
    }
}

//==============================================================================

void QScintillaWidget::updateColors()
{
    // Compute and set the background colour of our caret line

    static const qreal Threshold = 0.875;

    QColor caretLineBackgroundColor = Core::highlightColor();

    qreal r = caretLineBackgroundColor.redF();
    qreal g = caretLineBackgroundColor.greenF();
    qreal b = caretLineBackgroundColor.blueF();

    while ((r < Threshold) || (g < Threshold) || (b < Threshold)) {
        r = 0.5*(r+1.0);
        g = 0.5*(g+1.0);
        b = 0.5*(b+1.0);
    }

    setCaretLineBackgroundColor(qRgba(r*255, g*255, b*255, caretLineBackgroundColor.alpha()));
}

//==============================================================================

void QScintillaWidget::cursorPositionChanged(const int &pLine,
                                             const int &pColumn)
{
    // Update our cursor position

    mCursorPositionWidget->setText(QString("Line: %1, Col: %2").arg(QString::number(pLine+1),
                                                                    QString::number(pColumn+1)));
}

//==============================================================================

}   // namespace QScintillaSupport
}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<commit_msg>Fixed the issue with the Raw CellML view not properly extracting some Content MathML equations (closes #295).<commit_after>/*******************************************************************************

Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.

*******************************************************************************/

//==============================================================================
// QScintillaWidget class
//==============================================================================

#include "filemanager.h"
#include "guiutils.h"
#include "qscintillawidget.h"

//==============================================================================

#include <QDragEnterEvent>
#include <QLabel>
#include <QMenu>
#include <QMimeData>

//==============================================================================

#include "Qsci/qscilexer.h"

//==============================================================================

namespace OpenCOR {
namespace QScintillaSupport {

//==============================================================================

QScintillaWidget::QScintillaWidget(const QString &pContents,
                                   const bool &pReadOnly,
                                   QsciLexer *pLexer, QWidget *pParent) :
    QsciScintilla(pParent),
    mCanUndo(false),
    mCanRedo(false),
    mCanSelectAll(false),
    mOverwriteMode(false)
{
    // Remove the frame around our Scintilla editor

    setFrameShape(QFrame::NoFrame);

    // Remove the margin number in our Scintilla editor

    setMarginWidth(SC_MARGIN_NUMBER, 0);

    // Associate a lexer to our Scintilla editor, should one be provided
    // Note: the default font family and size come from Qt Creator...

#if defined(Q_OS_WIN)
    mFont = QFont("Courier", 10);
#elif defined(Q_OS_LINUX)
    mFont = QFont("Monospace", 9);
#elif defined(Q_OS_MAC)
    mFont = QFont("Monaco", 12);
#else
    #error Unsupported platform
#endif

    if (pLexer) {
        // A lexer was provided, so specify its fonts and associate it with our
        // Scintilla editor

        pLexer->setFont(mFont);

        setLexer(pLexer);

        // Specify the type of tree folding to be used. Some lexers may indeed
        // use that feature, so...

        setFolding(QsciScintilla::BoxedTreeFoldStyle);
    } else {
        // No lexer was provided, so simply specify a default font family and
        // size for our Scintilla editor

        setFont(mFont);
    }

    // Set the contents of our Scintilla editor and its read-only property

    setContents(pContents);
    setReadOnly(pReadOnly);

    // Show the caret line

    setCaretLineVisible(true);

    // Force the use of UNIX EOL mode
    // Note: by default QScintilla will use EolWindows on Windows and EolUnix on
    //       Linux and OS X. However, the fact that it uses EolWindows on
    //       Windows can cause problems on that platform with files not using a
    //       a Windows EOL mode, so...

    setEolMode(EolUnix);

    // Initialise our colours by 'updating' them

    updateColors();

    // Clear some key mappings inherited from QsciScintilla
    // Note #1: indeed, QsciScintilla handles some shortcuts (e.g. Ctrl+L),
    //          which we don't want to see handled (e.g. Ctrl+L is used by
    //          QsciScintilla to delete the current line while OpenCOR uses it
    //          to (un)lock the current file), so...
    // Note #2: even though we are clearing those key mappings, we must also
    //          bypass QsciScintilla's handling of event() (see below). Indeed,
    //          not to do so would mean that if, for example, the user was to
    //          press Ctrl+L, then nothing would happen while we would have
    //          expected the current file to be (un)locked...

    SendScintilla(SCI_CLEARCMDKEY, (SCMOD_CTRL << 16)+'D');
    SendScintilla(SCI_CLEARCMDKEY, (SCMOD_CTRL << 16)+'L');
    SendScintilla(SCI_CLEARCMDKEY, (SCMOD_CTRL << 16)+(SCMOD_SHIFT << 16)+'L');

    // Empty context menu by default

    mContextMenu = new QMenu(this);

    // Create our two labels to show our cursor position and editing mode

    mCursorPositionWidget = new QLabel(this);
    mEditingModeWidget = new QLabel(this);

    // Keep track of the change to the UI

    connect(this, SIGNAL(SCN_UPDATEUI(int)),
            this, SLOT(updateUi()));

    // Keep track of whether we can undo/redo

    connect(this, SIGNAL(textChanged()),
            this, SLOT(updateCanUndoAndCanRedo()));

    // Keep track of changes to our editor that may affect our ability to select
    // all of its text
    // Note: we use the SCN_MODIFIED() signal rather than the textChanged()
    //       signal since the latter is only emitted when inserting or deleting
    //       some text...

    connect(this, SIGNAL(selectionChanged()),
            this, SLOT(checkCanSelectAll()));
    connect(this, SIGNAL(SCN_MODIFIED(int, int, const char *, int, int, int, int, int, int, int)),
            this, SLOT(checkCanSelectAll()));

    // Keep track of the change in the cursor position

    connect(this, SIGNAL(cursorPositionChanged(int, int)),
            this, SLOT(cursorPositionChanged(const int &, const int &)));
}

//==============================================================================

QScintillaWidget::~QScintillaWidget()
{
    // Delete some internal objects

    delete mContextMenu;
}

//==============================================================================

QMenu * QScintillaWidget::contextMenu() const
{
    // Return our context menu

    return mContextMenu;
}

//==============================================================================

void QScintillaWidget::setContextMenu(const QList<QAction *> &pContextMenuActions)
{
    // Set our context menu

    mContextMenu->clear();

    foreach (QAction *action, pContextMenuActions)
        mContextMenu->addAction(action);
}

//==============================================================================

int QScintillaWidget::currentPosition() const
{
    // Return our current position

    return SendScintilla(SCI_GETCURRENTPOS);
}

//==============================================================================

QString QScintillaWidget::contents() const
{
    // Return our contents

    return text();
}

//==============================================================================

void QScintillaWidget::setContents(const QString &pContents)
{
    // Set our contents

    setText(pContents);
}

//==============================================================================

int QScintillaWidget::contentsSize() const
{
    // Return the size of our contents

    return SendScintilla(SCI_GETLENGTH);
}

//==============================================================================

QString QScintillaWidget::textInRange(const int &pStartRange,
                                      const int &pEndRange) const
{
    // Retrieve and return the text in the given range, making sure that the
    // given range makes sense

    int maxRange = contentsSize();

    if (   (pStartRange < 0) || (pStartRange >= maxRange)
        || (pEndRange < 0) || (pEndRange >= maxRange)
        || (pStartRange >= pEndRange))
        return QString();

    char *text = new char[pEndRange-pStartRange+1];

    SendScintilla(SCI_GETTEXTRANGE, pStartRange, pEndRange, text);

    QString res = QString(text);

    delete[] text;

    return res;
}

//==============================================================================

int QScintillaWidget::findTextInRange(const int &pStartRange,
                                      const int &pEndRange,
                                      const QString &pText,
                                      const bool &pCaseSensitive) const
{
    // Find and return the position, if any, of the given text within the given
    // range

    SendScintilla(SCI_SETSEARCHFLAGS, pCaseSensitive?SCFIND_MATCHCASE:0);

    SendScintilla(SCI_SETTARGETSTART, pStartRange);
    SendScintilla(SCI_SETTARGETEND, pEndRange);

    QByteArray text = pText.toUtf8();

    return SendScintilla(SCI_SEARCHINTARGET, text.length(), text.constData());
}

//==============================================================================

bool QScintillaWidget::isSelectAllAvailable() const
{
    // Return whether we can select all the text

    return mCanSelectAll;
}

//==============================================================================

void QScintillaWidget::resetUndoHistory()
{
    // Reset our undo history

    SendScintilla(SCI_EMPTYUNDOBUFFER);

    mCanUndo = false;
    mCanRedo = false;
}

//==============================================================================

QLabel * QScintillaWidget::cursorPositionWidget() const
{
    // Return our cursort position widget

    return mCursorPositionWidget;
}

//==============================================================================

QLabel * QScintillaWidget::editingModeWidget() const
{
    // Return our editing mode widget

    return mEditingModeWidget;
}

//==============================================================================

QString QScintillaWidget::eolString() const
{
    // Return the end of line we use

    switch (eolMode()) {
    case EolUnix:
        return "\n";
    case EolMac:
        return "\r";
    default:   // EolWindows
        return "\r\n";
    }
}

//==============================================================================

void QScintillaWidget::changeEvent(QEvent *pEvent)
{
    // Default handling of the event

    QsciScintilla::changeEvent(pEvent);

    // Check whether the palette has changed and if so then update our colors

    if (pEvent->type() == QEvent::PaletteChange)
        updateColors();
}

//==============================================================================

void QScintillaWidget::contextMenuEvent(QContextMenuEvent *pEvent)
{
    // Show our context menu or QsciScintilla's one, if we don't have one

    if (mContextMenu->isEmpty())
        QsciScintilla::contextMenuEvent(pEvent);
    else
        mContextMenu->exec(pEvent->globalPos());
}

//==============================================================================

void QScintillaWidget::dragEnterEvent(QDragEnterEvent *pEvent)
{
    // Accept the proposed action for the event, but only if we are not dropping
    // URIs
    // Note: this is not (currently?) needed on Windows and OS X, but if we
    //       don't have that check on Linux, then to drop some files on our
    //       Scintilla editor will result in the text/plain version of the data
    //       (e.g. file:///home/me/myFile) to be inserted in the text, so...

    if (!pEvent->mimeData()->hasFormat(Core::FileSystemMimeType))
        pEvent->acceptProposedAction();
    else
        pEvent->ignore();
}

//==============================================================================

bool QScintillaWidget::event(QEvent *pEvent)
{
    // Bypass QsciScintilla's handling of event()
    // Note: see the note on the clearing of some key mappings in the contructor
    //       above...

    return QsciScintillaBase::event(pEvent);
}

//==============================================================================

void QScintillaWidget::keyPressEvent(QKeyEvent *pEvent)
{
    // Reset the font size, if needed

    if (   !(pEvent->modifiers() & Qt::ShiftModifier)
        &&  (pEvent->modifiers() & Qt::ControlModifier)
        && !(pEvent->modifiers() & Qt::AltModifier)
        && !(pEvent->modifiers() & Qt::MetaModifier)
        &&  (pEvent->key() == Qt::Key_0))
        zoomTo(0);
    else
        // Default handling of the event

        QsciScintilla::keyPressEvent(pEvent);
}

//==============================================================================

void QScintillaWidget::wheelEvent(QWheelEvent *pEvent)
{
    // Increasing/decrease the font size, if needed

    if (pEvent->modifiers() == Qt::ControlModifier) {
        int delta = pEvent->delta();

        if (delta > 0)
            zoomIn();
        else if (delta < 0)
            zoomOut();

        pEvent->accept();
    } else {
        QsciScintilla::wheelEvent(pEvent);
    }
}

//==============================================================================

void QScintillaWidget::updateUi()
{
    // Update our editing mode, if needed

    bool newOverwriteMode = overwriteMode();

    if (   (newOverwriteMode != mOverwriteMode)
        || mEditingModeWidget->text().isEmpty()) {
        mOverwriteMode = newOverwriteMode;

        mEditingModeWidget->setText(mOverwriteMode?"OVR":"INS");
    }
}

//==============================================================================

void QScintillaWidget::updateCanUndoAndCanRedo()
{
    // Check whether undoing/redoing is possible

    bool newCanUndo = isUndoAvailable();
    bool newCanRedo = isRedoAvailable();

    if (newCanUndo != mCanUndo) {
        mCanUndo = newCanUndo;

        emit canUndo(mCanUndo);
    }

    if (newCanRedo != mCanRedo) {
        mCanRedo = newCanRedo;

        emit canRedo(mCanRedo);
    }
}

//==============================================================================

void QScintillaWidget::checkCanSelectAll()
{
    // Check whether we can select all the text

    bool newCanSelectAll = text().size() && selectedText().compare(text());

    if (newCanSelectAll != mCanSelectAll) {
        mCanSelectAll = newCanSelectAll;

        emit canSelectAll(mCanSelectAll);
    }
}

//==============================================================================

void QScintillaWidget::updateColors()
{
    // Compute and set the background colour of our caret line

    static const qreal Threshold = 0.875;

    QColor caretLineBackgroundColor = Core::highlightColor();

    qreal r = caretLineBackgroundColor.redF();
    qreal g = caretLineBackgroundColor.greenF();
    qreal b = caretLineBackgroundColor.blueF();

    while ((r < Threshold) || (g < Threshold) || (b < Threshold)) {
        r = 0.5*(r+1.0);
        g = 0.5*(g+1.0);
        b = 0.5*(b+1.0);
    }

    setCaretLineBackgroundColor(qRgba(r*255, g*255, b*255, caretLineBackgroundColor.alpha()));
}

//==============================================================================

void QScintillaWidget::cursorPositionChanged(const int &pLine,
                                             const int &pColumn)
{
    // Update our cursor position

    mCursorPositionWidget->setText(QString("Line: %1, Col: %2").arg(QString::number(pLine+1),
                                                                    QString::number(pColumn+1)));
}

//==============================================================================

}   // namespace QScintillaSupport
}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<|endoftext|>


<commit_before><commit_msg>Исправил замеченный компилятором warning.<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <unordered_map>

class SolutionOFOneTwoStep {
  private:
    static std::unordered_map<size_t, size_t> result_;

  public:
    size_t operator()(size_t steps) {
        auto iter = result_.find(steps);
        if (result_.end() != iter) {  // found.
            return iter->second;
        } else {
            size_t res = operator()(steps - 1) + operator()(steps - 2);
            result_.insert({steps, res});
            return res;
        }
    }
};

std::unordered_map<size_t, size_t>
    SolutionOFOneTwoStep::result_ = {{1, 1}, {2, 2}};

int main() {
    std::cout << SolutionOFOneTwoStep()(10) << std::endl;
    return 0;
}
<commit_msg>[10_recursive] one_two_step, nonrecursive version, done.<commit_after>#include <iostream>
#include <unordered_map>

class SolutionOFOneTwoStep {
  private:
    static std::unordered_map<size_t, size_t> result_;

  public:
    enum class POLICY {
        RECURSIVE,
        NONRECURSIVE
    };

  private:
    size_t recursive(size_t steps) {
        auto iter = result_.find(steps);
        if (result_.end() != iter) {  // found.
            return iter->second;
        } else {
            size_t res = operator()(steps - 1) + operator()(steps - 2);
            result_.insert({steps, res});
            return res;
        }
    }
    size_t nonrecursive(size_t steps) {
        auto iter = result_.find(steps);
        if (result_.end() != iter) {  // found.
            return iter->second;
        } else {
            size_t start;
            for (start = steps; start != 2 and result_.end() == result_.find(start); --start) {}
            for (size_t i = start; i != steps; ++i) {
                result_.insert({i + 1, result_[i - 1] + result_[i]});
            }
            return result_[steps];
        }
    }

  public:
    size_t operator()(size_t steps, const POLICY policy = POLICY::RECURSIVE) {
        if (policy == POLICY::RECURSIVE) {
            return recursive(steps);
        } else if (policy == POLICY::NONRECURSIVE) {
            return nonrecursive(steps);
        }
    }
    static void debug() {
        for (auto kv : result_) {
            std::cout << kv.first << ' ' << kv.second << std::endl;
        }
        std::cout << std::endl;
    }
};

std::unordered_map<size_t, size_t> SolutionOFOneTwoStep::result_ = {{1, 1}, {2, 2}};

int main() {
    SolutionOFOneTwoStep::debug();

    std::cout << SolutionOFOneTwoStep()(5, SolutionOFOneTwoStep::POLICY::RECURSIVE) << std::endl;
    SolutionOFOneTwoStep::debug();

    std::cout << SolutionOFOneTwoStep()(10, SolutionOFOneTwoStep::POLICY::NONRECURSIVE) << std::endl;
    SolutionOFOneTwoStep::debug();

    std::cout << SolutionOFOneTwoStep()(20, SolutionOFOneTwoStep::POLICY::RECURSIVE) << std::endl;
    SolutionOFOneTwoStep::debug();

    return 0;
}

<|endoftext|>


<commit_before>#ifndef __Data_course__
#define __Data_course__

#include "data-general.hpp"
#include "data-major.hpp"
#include "data-department.hpp"

using namespace std;

class Course {
private:
	void init(string identifier);
	void copy(const Course& c);
protected:
	string id;
	int number;
	string title;
	string description;
	char section;

	vector<Major> majors;
	vector<Department> department;
	string concentrations;
	string conversations;
	string professor;

	int half_semester;
	bool pass_fail;
	float credits;
	string location;

	bool lab;
	GenEd* geneds;

	bool days[7];
	float time[7];
public:
	Course();
	Course(string str);
	Course(const Course& c);
	Course& operator = (const Course &c);
	Course(istream &is);

	void cleanTitle();

	void parseID(string str);
	void updateID();
	string getID();

	ostream& getData(ostream &os);
	void display();
	void showAll();
};

ostream &operator<<(ostream &os, Course &item);
extern vector<Course> all_courses;

ostream& operator<<(ostream& os, Course& item);
Course getCourse(string id);

#endif
<commit_msg>Misc spacing tweaks to data-course<commit_after>#ifndef __Data_course__
#define __Data_course__

#include "data-general.hpp"
#include "data-major.hpp"
#include "data-department.hpp"
using namespace std;

class Course {
private:
	void init(string identifier);
	void copy(const Course& c);
protected:
	string id;
	int number;
	string title;
	string description;
	char section;

	vector<Major> majors;
	vector<Department> department;
	string concentrations;
	string conversations;
	string professor;

	int half_semester;
	bool pass_fail;
	float credits;
	string location;

	bool lab;
	GenEd* geneds;

	bool days[7];
	float time[7];
public:
	Course();
	Course(string str);
	Course(const Course& c);
	Course& operator= (const Course &c);
	Course(istream &is);

	void cleanTitle();

	void parseID(string str);
	void updateID();
	string getID();

	ostream& getData(ostream& os);
	void display();
	void showAll();
};

extern vector<Course> all_courses;

ostream& operator<<(ostream& os, Course& item);
Course getCourse(string id);

#endif
<|endoftext|>


<commit_before>/*
 * This file is part of btag.
 *
 * © 2010 Fernando Tarlá Cardoso Lemos
 *
 * Refer to the LICENSE file for licensing information.
 *
 */

#include <boost/foreach.hpp>

#include "TitleLocalizationHandler.h"

bool TitleLocalizationHandler::is_acronym(const std::wstring &word) const
{
    if (word.size() < 4 || word[word.size() - 1] != L'.')
        return false;

    bool should_be_dot = false;
    BOOST_FOREACH(wchar_t c, word) {
        if (should_be_dot && c != L'.')
            return false;
        else if (!should_be_dot && c == L'.')
            return false;
        else
            should_be_dot = !should_be_dot;
    }

    return true;
}

wchar_t *TitleLocalizationHandler::punctuation_list() const
{
    static wchar_t punctuation[] = {
        L',', L'.', L':', L'-', L';', L'?', L'¿', L'!', L'¡', L'-', L'—', L')', L'(', L'"', L'\'', L'“', L'”', L'‘', L'’'
    };
    return punctuation;
}
<commit_msg>Zero-terminate the punctuation list.<commit_after>/*
 * This file is part of btag.
 *
 * © 2010 Fernando Tarlá Cardoso Lemos
 *
 * Refer to the LICENSE file for licensing information.
 *
 */

#include <boost/foreach.hpp>

#include "TitleLocalizationHandler.h"

bool TitleLocalizationHandler::is_acronym(const std::wstring &word) const
{
    if (word.size() < 4 || word[word.size() - 1] != L'.')
        return false;

    bool should_be_dot = false;
    BOOST_FOREACH(wchar_t c, word) {
        if (should_be_dot && c != L'.')
            return false;
        else if (!should_be_dot && c == L'.')
            return false;
        else
            should_be_dot = !should_be_dot;
    }

    return true;
}

wchar_t *TitleLocalizationHandler::punctuation_list() const
{
    static wchar_t punctuation[] = {
        L',', L'.', L':', L'-', L';', L'?', L'¿', L'!', L'¡', L'-', L'—', L')', L'(', L'"', L'\'', L'“', L'”', L'‘', L'’', 0
    };
    return punctuation;
}
<|endoftext|>