<commit_before>#include "gm.h"

namespace skiagm {

/** Create a bitmap image suitable for testing SkBitmap::scrollRect().
 *
 *  @param quarterWidth bitmap will be 4x this many pixels wide
 *  @param quarterHeight bitmap will be 4x this many pixels tall
 *  @param bitmap the bitmap data is written into this object
 */
static void make_bitmap(int quarterWidth, int quarterHeight, SkBitmap *bitmap) {
    SkPaint pRed, pWhite, pGreen, pBlue, pLine;
    pRed.setColor(0xFFFF9999);
    pWhite.setColor(0xFFFFFFFF);
    pGreen.setColor(0xFF99FF99);
    pBlue.setColor(0xFF9999FF);
    pLine.setColor(0xFF000000);
    pLine.setStyle(SkPaint::kStroke_Style);

    // Prepare bitmap, and a canvas that draws into it.
    bitmap->reset();
    bitmap->setConfig(SkBitmap::kARGB_8888_Config,
                      quarterWidth*4, quarterHeight*4);
    bitmap->allocPixels();
    SkCanvas canvas(*bitmap);

    SkScalar w = SkIntToScalar(quarterWidth);
    SkScalar h = SkIntToScalar(quarterHeight);
    canvas.drawRectCoords(  0,   0, w*2, h*2, pRed);
    canvas.drawRectCoords(w*2,   0, w*4, h*2, pGreen);
    canvas.drawRectCoords(  0, h*2, w*2, h*4, pBlue);
    canvas.drawRectCoords(w*2, h*2, w*4, h*4, pWhite);
    canvas.drawLine(w*2,   0, w*2, h*4, pLine);
    canvas.drawLine(  0, h*2, w*4, h*2, pLine);
    canvas.drawRectCoords(w, h, w*3, h*3, pLine);
}

class BitmapScrollGM : public GM {
public:
    BitmapScrollGM() {
        // Create the original bitmap.
        make_bitmap(quarterWidth, quarterHeight, &origBitmap);
    }

protected:
    virtual SkString onShortName() {
        return SkString("bitmapscroll");
    }

    virtual SkISize onISize() {
      return make_isize(800, 600);
    }

    virtual void onDraw(SkCanvas* canvas) {
        SkIRect scrollCenterRegion = SkIRect::MakeXYWH(
            quarterWidth, quarterHeight, quarterWidth*2, quarterHeight*2);
        int x = quarterWidth;
        int y = quarterHeight;
        int xSpacing = quarterWidth * 20;
        int ySpacing = quarterHeight * 16;

        // Draw background and left-hand text labels.
        canvas->drawColor(0xFFDDDDDD);
        drawLabel(canvas, "scroll entire bitmap",
                  x, y, x, y + ySpacing);
        drawLabel(canvas, "scroll part of bitmap",
                  x, y + ySpacing, x, y + ySpacing*2);
        x += 30;

        // Draw various permutations of scrolled bitmaps, scrolling a bit
        // further each time.
        draw9(canvas, x, y, NULL, quarterWidth*1/2, quarterHeight*1/2);
        draw9(canvas, x, y+ySpacing, &scrollCenterRegion,
              quarterWidth*1/2, quarterHeight*1/2);
        x += xSpacing;
        draw9(canvas, x, y, NULL, quarterWidth*3/2, quarterHeight*3/2);
        draw9(canvas, x, y+ySpacing, &scrollCenterRegion,
              quarterWidth*3/2, quarterHeight*3/2);
        x += xSpacing;
        draw9(canvas, x, y, NULL, quarterWidth*5/2, quarterHeight*5/2);
        draw9(canvas, x, y+ySpacing, &scrollCenterRegion,
              quarterWidth*5/2, quarterHeight*5/2);
        x += xSpacing;
        draw9(canvas, x, y, NULL, quarterWidth*9/2, quarterHeight*9/2);
        draw9(canvas, x, y+ySpacing, &scrollCenterRegion,
              quarterWidth*9/2, quarterHeight*9/2);
    }

    void drawLabel(SkCanvas* canvas, const char *text, int startX, int startY,
                 int endX, int endY) {
        SkPaint paint;
        paint.setColor(0xFF000000);
        SkPath path;
        path.moveTo(SkIntToScalar(startX), SkIntToScalar(startY));
        path.lineTo(SkIntToScalar(endX), SkIntToScalar(endY));
        canvas->drawTextOnPath(text, strlen(text), path, NULL, paint);
    }

    /** Stamp out 9 copies of origBitmap, scrolled in each direction (and
     *  not scrolled at all).
     */
    void draw9(SkCanvas* canvas, int x, int y, SkIRect* subset,
               int scrollX, int scrollY) {
        for (int yMult=-1; yMult<=1; yMult++) {
            for (int xMult=-1; xMult<=1; xMult++) {
                // Figure out the (x,y) to draw this copy at
                SkScalar bitmapX = SkIntToScalar(
                    x + quarterWidth * 5 * (xMult+1));
                SkScalar bitmapY = SkIntToScalar(
                    y + quarterHeight * 5 * (yMult+1));

                // Scroll a new copy of the bitmap, and then draw it.
                // scrollRect() should always return true, even if it's a no-op
                SkBitmap scrolledBitmap;
                SkASSERT(origBitmap.copyTo(
                    &scrolledBitmap, origBitmap.config()));
                SkASSERT(scrolledBitmap.scrollRect(
                    subset, scrollX * xMult, scrollY * yMult));
                canvas->drawBitmap(scrolledBitmap, bitmapX, bitmapY);
            }
        }
    }

private:
    typedef GM INHERITED;
    static const int quarterWidth = 10;
    static const int quarterHeight = 14;
    SkBitmap origBitmap;
};

//////////////////////////////////////////////////////////////////////////////

static GM* MyFactory(void*) { return new BitmapScrollGM; }
static GMRegistry reg(MyFactory);

}
<commit_msg>Slightly improve visuals of bitmapscroll test in gm<commit_after>#include "gm.h"

namespace skiagm {

/** Create a bitmap image suitable for testing SkBitmap::scrollRect().
 *
 *  @param quarterWidth bitmap will be 4x this many pixels wide
 *  @param quarterHeight bitmap will be 4x this many pixels tall
 *  @param bitmap the bitmap data is written into this object
 */
static void make_bitmap(int quarterWidth, int quarterHeight, SkBitmap *bitmap) {
    SkPaint pRed, pWhite, pGreen, pBlue, pLine, pAlphaGray;
    pRed.setColor(0xFFFF9999);
    pWhite.setColor(0xFFFFFFFF);
    pGreen.setColor(0xFF99FF99);
    pBlue.setColor(0xFF9999FF);
    pLine.setColor(0xFF000000);
    pLine.setStyle(SkPaint::kStroke_Style);
    pAlphaGray.setColor(0x66888888);

    // Prepare bitmap, and a canvas that draws into it.
    bitmap->reset();
    bitmap->setConfig(SkBitmap::kARGB_8888_Config,
                      quarterWidth*4, quarterHeight*4);
    bitmap->allocPixels();
    SkCanvas canvas(*bitmap);

    SkScalar w = SkIntToScalar(quarterWidth);
    SkScalar h = SkIntToScalar(quarterHeight);
    canvas.drawRectCoords(  0,   0, w*2, h*2, pRed);
    canvas.drawRectCoords(w*2,   0, w*4, h*2, pGreen);
    canvas.drawRectCoords(  0, h*2, w*2, h*4, pBlue);
    canvas.drawRectCoords(w*2, h*2, w*4, h*4, pWhite);
    canvas.drawRectCoords(w, h, w*3, h*3, pAlphaGray);
    canvas.drawLine(w*2,   0, w*2, h*4, pLine);
    canvas.drawLine(  0, h*2, w*4, h*2, pLine);
    canvas.drawRectCoords(w, h, w*3, h*3, pLine);
}

class BitmapScrollGM : public GM {
public:
    BitmapScrollGM() {
        // Create the original bitmap.
        make_bitmap(quarterWidth, quarterHeight, &origBitmap);
    }

protected:
    virtual SkString onShortName() {
        return SkString("bitmapscroll");
    }

    virtual SkISize onISize() {
      return make_isize(800, 600);
    }

    virtual void onDraw(SkCanvas* canvas) {
        SkIRect scrollCenterRegion = SkIRect::MakeXYWH(
            quarterWidth, quarterHeight, quarterWidth*2+1, quarterHeight*2+1);
        int x = quarterWidth;
        int y = quarterHeight;
        int xSpacing = quarterWidth * 20;
        int ySpacing = quarterHeight * 16;

        // Draw background and left-hand text labels.
        canvas->drawColor(0xFFDDDDDD);
        drawLabel(canvas, "scroll entire bitmap",
                  x, y, x, y + ySpacing);
        drawLabel(canvas, "scroll part of bitmap",
                  x, y + ySpacing, x, y + ySpacing*2);
        x += 30;

        // Draw various permutations of scrolled bitmaps, scrolling a bit
        // further each time.
        draw9(canvas, x, y, NULL, quarterWidth*1/2, quarterHeight*1/2);
        draw9(canvas, x, y+ySpacing, &scrollCenterRegion,
              quarterWidth*1/2, quarterHeight*1/2);
        x += xSpacing;
        draw9(canvas, x, y, NULL, quarterWidth*3/2, quarterHeight*3/2);
        draw9(canvas, x, y+ySpacing, &scrollCenterRegion,
              quarterWidth*3/2, quarterHeight*3/2);
        x += xSpacing;
        draw9(canvas, x, y, NULL, quarterWidth*5/2, quarterHeight*5/2);
        draw9(canvas, x, y+ySpacing, &scrollCenterRegion,
              quarterWidth*5/2, quarterHeight*5/2);
        x += xSpacing;
        draw9(canvas, x, y, NULL, quarterWidth*9/2, quarterHeight*9/2);
        draw9(canvas, x, y+ySpacing, &scrollCenterRegion,
              quarterWidth*9/2, quarterHeight*9/2);
    }

    void drawLabel(SkCanvas* canvas, const char *text, int startX, int startY,
                 int endX, int endY) {
        SkPaint paint;
        paint.setColor(0xFF000000);
        SkPath path;
        path.moveTo(SkIntToScalar(startX), SkIntToScalar(startY));
        path.lineTo(SkIntToScalar(endX), SkIntToScalar(endY));
        canvas->drawTextOnPath(text, strlen(text), path, NULL, paint);
    }

    /** Stamp out 9 copies of origBitmap, scrolled in each direction (and
     *  not scrolled at all).
     */
    void draw9(SkCanvas* canvas, int x, int y, SkIRect* subset,
               int scrollX, int scrollY) {
        for (int yMult=-1; yMult<=1; yMult++) {
            for (int xMult=-1; xMult<=1; xMult++) {
                // Figure out the (x,y) to draw this copy at
                SkScalar bitmapX = SkIntToScalar(
                    x + quarterWidth * 5 * (xMult+1));
                SkScalar bitmapY = SkIntToScalar(
                    y + quarterHeight * 5 * (yMult+1));

                // Scroll a new copy of the bitmap, and then draw it.
                // scrollRect() should always return true, even if it's a no-op
                SkBitmap scrolledBitmap;
                SkASSERT(origBitmap.copyTo(
                    &scrolledBitmap, origBitmap.config()));
                SkASSERT(scrolledBitmap.scrollRect(
                    subset, scrollX * xMult, scrollY * yMult));
                canvas->drawBitmap(scrolledBitmap, bitmapX, bitmapY);
            }
        }
    }

private:
    typedef GM INHERITED;
    static const int quarterWidth = 10;
    static const int quarterHeight = 14;
    SkBitmap origBitmap;
};

//////////////////////////////////////////////////////////////////////////////

static GM* MyFactory(void*) { return new BitmapScrollGM; }
static GMRegistry reg(MyFactory);

}
<|endoftext|>


<commit_before>#ifndef STAN_MATH_REV_MAT_FUNCTOR_KINSOL_SOLVE_HPP
#define STAN_MATH_REV_MAT_FUNCTOR_KINSOL_SOLVE_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/kinsol_data.hpp>
#include <stan/math/rev/mat/functor/algebra_system.hpp>
#include <stan/math/prim/mat/err/check_flag_sundials.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 {

/**
 * Return the solution to the specified algebraic system,
 * given an initial guess. Invokes the Kinsol solver from Sundials.
 *
 * @tparam F type of equation system function.
 * @tparam T type of initial guess vector.
 * @param[in] f Functor that evaluated the system of equations.
 * @param[in] x Vector of starting values.
 * @param[in] y Parameter vector for the equation system. The function
 *            is overloaded to treat y as a vector of doubles or of a
 *            a template type T.
 * @param[in] dat Continuous data vector for the equation system.
 * @param[in] dat_int Integer data vector for the equation system.
 * @param[in, out] msgs The print stream for warning messages.
 * @param[in] scaling_step_tol Scaled-step stopping tolerance. If
 *            a Newton step is smaller than the scaling step
 *            tolerance, the code breaks, assuming the solver is no
 *            longer making significant progress (i.e. is stuck)
 * @param[in] function_tolerance determines whether roots are acceptable.
 * @param[in] max_num_steps Maximum number of function evaluations.
 * @param[in] custom_jacobian If 0, use Kinsol's default to compute the
 *            jacobian for the Newton step, namely Quotient Difference
 *            (finite difference). If 1, use reverse-mode AD, unless
 *            the user specifies their own method.
 * @param[in] J_f A functor that computes the Jacobian for the Newton step.
 *            Defaults to reverse-mode AD.
 * @param[in] steps_eval_jacobian Maximum number of steps before the
 *            Jacobian gets recomputed. Note that Kinsol's default is 10.
 *            If equal to 1, the algorithm computes exact Newton steps.
 * @param[in] global_line_search does the solver use a global line search?
 *            If equal to KIN_NONE, no, if KIN_LINESEARCH, yes.
 * @return x_solution Vector of solutions to the system of equations.
 * @throw std::invalid_argument if Kinsol returns a negative
 *        flag when setting up the solver.
 * @throw boost::math::evaluation_error if Kinsol returns a
 *        negative flag after attempting to solve the equation.
 */
template <typename F1, typename F2 = kinsol_J_f>
Eigen::VectorXd kinsol_solve(
    const F1& f, const Eigen::VectorXd& x, const Eigen::VectorXd& y,
    const std::vector<double>& dat, const std::vector<int>& dat_int,
    std::ostream* msgs = nullptr, double scaling_step_tol = 1e-3,
    double function_tolerance = 1e-6,
    long int max_num_steps = 200,  // NOLINT(runtime/int)
    bool custom_jacobian = 1, const F2& J_f = kinsol_J_f(),
    int steps_eval_jacobian = 10, int global_line_search = KIN_LINESEARCH) {
  int N = x.size();
  typedef kinsol_system_data<F1, F2> system_data;
  system_data kinsol_data(f, J_f, x, y, dat, dat_int, msgs);

  check_flag_sundials(
      KINInit(kinsol_data.kinsol_memory_,
              &system_data::kinsol_f_system, kinsol_data.nv_x_),
      "KINInit");

  N_Vector scaling = N_VNew_Serial(N);
  N_VConst_Serial(1.0, scaling);  // no scaling

  check_flag_sundials(KINSetNumMaxIters(kinsol_data.kinsol_memory_,
                      max_num_steps), "KINSetNumMaxIters");
  check_flag_sundials(KINSetFuncNormTol(kinsol_data.kinsol_memory_,
                      function_tolerance), "KINSetFuncNormTol");
  check_flag_sundials(KINSetScaledStepTol(kinsol_data.kinsol_memory_,
                      scaling_step_tol), "KINSetScaledStepTol");
  check_flag_sundials(KINSetMaxSetupCalls(kinsol_data.kinsol_memory_,
                      steps_eval_jacobian), "KINSetMaxSetupCalls");

  // CHECK
  // The default value is 1000 * ||u_0||_D where ||u_0|| is the initial guess.
  // So we run into issues if ||u_0|| = 0.
  // If the norm is non-zero, use kinsol's default (accessed with 0),
  // else use the dimension of x -- CHECK - find optimal length.
  double max_newton_step = (x.norm() == 0) ? x.size() : 0;
  check_flag_sundials(KINSetMaxNewtonStep(kinsol_data.kinsol_memory_,
                      max_newton_step), "KINSetMaxNewtonStep");
  check_flag_sundials(
      KINSetUserData(kinsol_data.kinsol_memory_,
                     static_cast<void*>(&kinsol_data)), "KINSetUserData");

  // construct Linear solver
  check_flag_sundials(
      KINSetLinearSolver(kinsol_data.kinsol_memory_, kinsol_data.LS_,
                         kinsol_data.J_), "KINSetLinearSolver");

  if (custom_jacobian)
    check_flag_sundials(
        KINSetJacFn(kinsol_data.kinsol_memory_,
                    &system_data::kinsol_jacobian), "KINSetJacFn");

  N_Vector nv_x = N_VNew_Serial(N);
  for (int i = 0; i < N; i++)
    NV_Ith_S(nv_x, i) = x(i);

  check_flag_kinsol(
      KINSol(kinsol_data.kinsol_memory_, nv_x, global_line_search,
             scaling, scaling), max_num_steps);

  Eigen::VectorXd x_solution(N);
  for (int i = 0; i < N; i++)
    x_solution(i) = NV_Ith_S(nv_x, i);

  N_VDestroy(nv_x);
  N_VDestroy(scaling);

  return x_solution;
}

}  // namespace math
}  // namespace stan
#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 5.0.0-3~16.04.1 (tags/RELEASE_500/final)<commit_after>#ifndef STAN_MATH_REV_MAT_FUNCTOR_KINSOL_SOLVE_HPP
#define STAN_MATH_REV_MAT_FUNCTOR_KINSOL_SOLVE_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/kinsol_data.hpp>
#include <stan/math/rev/mat/functor/algebra_system.hpp>
#include <stan/math/prim/mat/err/check_flag_sundials.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 {

/**
 * Return the solution to the specified algebraic system,
 * given an initial guess. Invokes the Kinsol solver from Sundials.
 *
 * @tparam F type of equation system function.
 * @tparam T type of initial guess vector.
 * @param[in] f Functor that evaluated the system of equations.
 * @param[in] x Vector of starting values.
 * @param[in] y Parameter vector for the equation system. The function
 *            is overloaded to treat y as a vector of doubles or of a
 *            a template type T.
 * @param[in] dat Continuous data vector for the equation system.
 * @param[in] dat_int Integer data vector for the equation system.
 * @param[in, out] msgs The print stream for warning messages.
 * @param[in] scaling_step_tol Scaled-step stopping tolerance. If
 *            a Newton step is smaller than the scaling step
 *            tolerance, the code breaks, assuming the solver is no
 *            longer making significant progress (i.e. is stuck)
 * @param[in] function_tolerance determines whether roots are acceptable.
 * @param[in] max_num_steps Maximum number of function evaluations.
 * @param[in] custom_jacobian If 0, use Kinsol's default to compute the
 *            jacobian for the Newton step, namely Quotient Difference
 *            (finite difference). If 1, use reverse-mode AD, unless
 *            the user specifies their own method.
 * @param[in] J_f A functor that computes the Jacobian for the Newton step.
 *            Defaults to reverse-mode AD.
 * @param[in] steps_eval_jacobian Maximum number of steps before the
 *            Jacobian gets recomputed. Note that Kinsol's default is 10.
 *            If equal to 1, the algorithm computes exact Newton steps.
 * @param[in] global_line_search does the solver use a global line search?
 *            If equal to KIN_NONE, no, if KIN_LINESEARCH, yes.
 * @return x_solution Vector of solutions to the system of equations.
 * @throw std::invalid_argument if Kinsol returns a negative
 *        flag when setting up the solver.
 * @throw boost::math::evaluation_error if Kinsol returns a
 *        negative flag after attempting to solve the equation.
 */
template <typename F1, typename F2 = kinsol_J_f>
Eigen::VectorXd kinsol_solve(
    const F1& f, const Eigen::VectorXd& x, const Eigen::VectorXd& y,
    const std::vector<double>& dat, const std::vector<int>& dat_int,
    std::ostream* msgs = nullptr, double scaling_step_tol = 1e-3,
    double function_tolerance = 1e-6,
    long int max_num_steps = 200,  // NOLINT(runtime/int)
    bool custom_jacobian = 1, const F2& J_f = kinsol_J_f(),
    int steps_eval_jacobian = 10, int global_line_search = KIN_LINESEARCH) {
  int N = x.size();
  typedef kinsol_system_data<F1, F2> system_data;
  system_data kinsol_data(f, J_f, x, y, dat, dat_int, msgs);

  check_flag_sundials(KINInit(kinsol_data.kinsol_memory_,
                              &system_data::kinsol_f_system, kinsol_data.nv_x_),
                      "KINInit");

  N_Vector scaling = N_VNew_Serial(N);
  N_VConst_Serial(1.0, scaling);  // no scaling

  check_flag_sundials(
      KINSetNumMaxIters(kinsol_data.kinsol_memory_, max_num_steps),
      "KINSetNumMaxIters");
  check_flag_sundials(
      KINSetFuncNormTol(kinsol_data.kinsol_memory_, function_tolerance),
      "KINSetFuncNormTol");
  check_flag_sundials(
      KINSetScaledStepTol(kinsol_data.kinsol_memory_, scaling_step_tol),
      "KINSetScaledStepTol");
  check_flag_sundials(
      KINSetMaxSetupCalls(kinsol_data.kinsol_memory_, steps_eval_jacobian),
      "KINSetMaxSetupCalls");

  // CHECK
  // The default value is 1000 * ||u_0||_D where ||u_0|| is the initial guess.
  // So we run into issues if ||u_0|| = 0.
  // If the norm is non-zero, use kinsol's default (accessed with 0),
  // else use the dimension of x -- CHECK - find optimal length.
  double max_newton_step = (x.norm() == 0) ? x.size() : 0;
  check_flag_sundials(
      KINSetMaxNewtonStep(kinsol_data.kinsol_memory_, max_newton_step),
      "KINSetMaxNewtonStep");
  check_flag_sundials(KINSetUserData(kinsol_data.kinsol_memory_,
                                     static_cast<void*>(&kinsol_data)),
                      "KINSetUserData");

  // construct Linear solver
  check_flag_sundials(KINSetLinearSolver(kinsol_data.kinsol_memory_,
                                         kinsol_data.LS_, kinsol_data.J_),
                      "KINSetLinearSolver");

  if (custom_jacobian)
    check_flag_sundials(
        KINSetJacFn(kinsol_data.kinsol_memory_, &system_data::kinsol_jacobian),
        "KINSetJacFn");

  N_Vector nv_x = N_VNew_Serial(N);
  for (int i = 0; i < N; i++)
    NV_Ith_S(nv_x, i) = x(i);

  check_flag_kinsol(KINSol(kinsol_data.kinsol_memory_, nv_x, global_line_search,
                           scaling, scaling),
                    max_num_steps);

  Eigen::VectorXd x_solution(N);
  for (int i = 0; i < N; i++)
    x_solution(i) = NV_Ith_S(nv_x, i);

  N_VDestroy(nv_x);
  N_VDestroy(scaling);

  return x_solution;
}

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


<commit_before>#include "finiteem.h"
#include <cmath>
#include <functional>
#include <algorithm>
#include <iostream>
#include <stdexcept>
#include <cerrno>
#include <cstring>
#include <limits>

Finiteem::Finiteem(Pileupdata p, int ploidy) : plp(p), theta(std::make_tuple(0.1,std::map::map(),1)),
	em(std::bind(&Finiteem::q_function, this, std::placeholders::_1), std::bind(&Finiteem::m_function,this,std::placeholders::_1), theta),
	ploidy(ploidy){
	possible_gts = Genotype::enumerate_gts(ploidy);
}

Finiteem::Finiteem(Pileupdata p): Finiteem(p, 2){
}

Finiteem::Finiteem(std::string samfile, std::string refname, int ploidy) : plp(samfile, refname), theta(std::make_tuple(0.1,std::map::map(),1)),
	em(std::bind(&Finiteem::q_function, this, std::placeholders::_1), std::bind(&Finiteem::m_function,this,std::placeholders::_1), theta),
	ploidy(ploidy){
	possible_gts = Genotype::enumerate_gts(ploidy);
}

Finiteem::Finiteem(std::string samfile, std::string refname) : Finiteem(samfile, refname, 2) {
}

theta_t Finiteem::start(double stop){
	return em.start(stop);
}

double Finiteem::q_function(theta_t theta){
	double likelihood = 0.0;
	for (std::vector<Genotype>::iterator g = possible_gts.begin(); g != possible_gts.end(); ++g){
		likelihood += log(g.p_finite_alleles('A',0,std::get<0>(theta),std::get<1>(theta)));
	}
	return likelihood;
}

theta_t Finiteem::m_function(theta_t theta){
	pileupdata_t plpdata = plp.get_data();
	GT_Matrix<ploidy> n();

	for (pileupdata_t::iterator tid = plpdata.begin(); tid != plpdata.end(); ++tid){
		for(std::vector<pileuptuple_t>::iterator pos = tid->begin(); pos != tid->end(); ++pos){
			const std::vector<char> &x = std::get<0>(*pos);
			const char &ref = std::get<3>(*pos);
			for (std::vector<Genotype>::iterator g = possible_gts.begin(); g != possible_gts.end(); ++g){
				std::vector<double> site_s = calc_s(x,*g,theta);
				double pg_x = pg_x_given_theta(*g,x,theta);
				for(size_t i = 0; i < s.size(); ++i){
					s[i] += pg_x * site_s[i];
				}
				t[ref][*g] += pg_x;
			}
		}
	}

	// scale to prevent underflow
	// double smallest = smallest_nonzero(s);
	// if (smallest != 0){ //there SHOULD always be an s > 0.
	// 	std::transform(s.begin(),s.end(),s.begin(),[smallest](double d){ return d / smallest; });
	// }

	//quadratic formula
	double a = 3.0 * (s[0] + s[1] + s[2]);
	double b = - (3.0/2 * s[0] + s[1] + 5.0/2 * s[2]);
	double c = s[2] / 2;
	double epsilon_minus = (-b - sqrt(std::pow(b,2) - 4 * a * c))/(2 * a);
	// double epsilon_plus = (-b + sqrt(std::pow(b,2) - 4 * a * c))/(2 * a);
	double epsilon;
	if (epsilon_minus < 0){
		epsilon = 0;
	}
	else{
		epsilon = epsilon_minus;
	}
	return std::make_tuple(epsilon);
}

//TODO:Make this work for pi
void Finiteem::optimize_q(GT_Matrix<2> m){
	std::get<0>(theta) = meep_math::nr_root(dq_dtheta,ddq_dtheta,std::get<0>(theta));
	std::get<2>(theta) = meep_math::nr_root(dq_dw,ddq_dw,std::get<2>(theta));
}

double Finiteem::dq_dtheta(double th){
	std::map<char,double> pi = std::get<1>(theta);
	double refweight = std::get<2>(theta);
	double dq = 0.0;
	int numalleles = Genotype::alleles.size();
	int numgts = possible_gts.size();
	for (int i = 0; i < numalleles; ++i){ //for each reference base
		for (int j = 0; i < numgts; ++j){ //for each genotype
			Genotype g = possible_gts[j];
			for (auto it = g.gt.begin(); it != g.gt.end(); ++it){ //for each base in genotype
				char allele = it -> first;
				for (int k = 0; k < it->second; ++k){ //add pi/(alpha + 0) twice for het; pi/(alpha + 1) for homozygote
					dq += m[i][j] * (pi[allele]/(allele_alpha(allele,Genotype::alleles[i],refweight,th,pi) + k))
				}
			}
			for (l = 0; l < ploidy; ++l){ //subtract alpha, alpha + 1
				dq -= m[i][j] * (1.0 / ref_alpha(refweight, th) + l);
			}
		}
	}
	return dq;
}

double Finiteem::ddq_dtheta(double th){
	double ddq = 0.0;
	std::map<char,double> pi = std::get<1>(theta);
	double refweight = std::get<2>(theta);
	int numalleles = Genotype::alleles.size();
	int numgts = possible_gts.size();
	for (int i = 0; i < numalleles; ++i){ //for each reference base
		for (int j = 0; i < numgts; ++j){ //for each genotype
			Genotype g = possible_gts[j];
			for (l = 0; l < ploidy; ++l){ //add  1/alpha, 1/(alpha + 1)
				dq += m[i][j] * (1.0 / (ref_alpha(refweight, theta) + l)^2);
			}
			for (auto it = g.gt.begin(); it != g.gt.end(); ++it){ //for each base in genotype
				char allele = it -> first;
				for (int k = 0; k < it->second; ++k){ //add pi/(alpha + 0) twice for het; pi/(alpha + 1) for homozygote
					ddq -= m[i][j] * ((pi[allele]^2)/(allele_alpha(allele,Genotype::alleles[i],refweight,theta,pi) + k)^2)
				}
			}
		}
	}
	return ddq;
}

double Finiteem::dq_dw(double w){
	double dq = 0.0;
	double th = std::get<0>(theta);
	std::map<char,double> pi = std::get<1>(theta);
	int numalleles = Genotype::alleles.size();
	int numgts = possible_gts.size();
	for (int i = 0; i < numalleles; ++i){ //for each reference base
		for (int j = 0; i < numgts; ++j){ //for each genotype
			Genotype g = possible_gts[j];
			for (auto it = g.gt.begin(); it != g.gt.end(); ++it){ //for each base in genotype
				char allele = it -> first;
				if (allele == Genotype::alleles[i]){
					for (int k = 0; k < it->second; ++k){ //add 1/(alpha + 0) or +0 and +1 for homozygote
						dq += m[i][j] * (1.0/(allele_alpha(allele,Genotype::alleles[i],w,theta,pi) + k))
					}
				}
			}
		}
	}
	return dq;
}

double Finiteem::ddq_dw(double w){
	double ddq = 0.0;
	double th = std::get<0>(theta);
	std::map<char,double> pi = std::get<1>(theta);
	int numalleles = Genotype::alleles.size();
	int numgts = possible_gts.size();
	for (int i = 0; i < numalleles; ++i){ //for each reference base
		for (int j = 0; i < numgts; ++j){ //for each genotype
			Genotype g = possible_gts[j];
			for (auto it = g.gt.begin(); it != g.gt.end(); ++it){ //for each base in genotype
				char allele = it -> first;
				if (allele == Genotype::alleles[i]){
					for (int k = 0; k < it->second; ++k){ //add 1/(alpha + 0) or +0 and +1 for homozygote
						ddq -= m[i][j] * (1.0/(allele_alpha(allele,Genotype::alleles[i],w,theta,pi) + k)^2)
					}
				}
			}
		}
	}
	return ddq;
}

double dq_dpi(char a, double pi){
	double dq = 0.0;
	double th = std::get<0>(theta);
	double refweight = std::get<2>(theta);
	int numalleles = Genotype::alleles.size();
	int numgts = possible_gts.size();
	for (int i = 0; i < numalleles - 1; ++i){ //for each reference base except one
		for (int j = 0; i < numgts; ++j){ //for each genotype
			Genotype g = possible_gts[j];
			for (auto it = g.gt.begin(); it != g.gt.end(); ++it){ //for each base in genotype
				char allele = it -> first;
				if (allele == a){
					for (int k = 0; k < it->second; ++k){ //add 1/(alpha + 0) or +0 and +1 for homozygote
						dq += m[i][j] * ((theta)/(allele_alpha(allele,Genotype::alleles[i],refweight,theta,pi) + k))
					}
				}
			}
		}
	}
	return dq;
}

double ddq_dpi(char a, double pi){
	double ddq = 0.0;
	double th = std::get<0>(theta);
	double refweight = std::get<2>(theta);
	int numalleles = Genotype::alleles.size();
	int numgts = possible_gts.size();
	for (int i = 0; i < numalleles - 1; ++i){ //for each reference base except one
		for (int j = 0; i < numgts; ++j){ //for each genotype
			Genotype g = possible_gts[j];
			for (auto it = g.gt.begin(); it != g.gt.end(); ++it){ //for each base in genotype
				char allele = it -> first;
				if (allele == a){
					for (int k = 0; k < it->second; ++k){ //add 1/(alpha + 0) or +0 and +1 for homozygote
						ddq -= m[i][j] * ((theta)^2/(allele_alpha(allele,Genotype::alleles[i],refweight,theta,pi) + k)^2)
					}
				}
			}
		}
	}
	return ddq;
}

std::vector<double> Finiteem::calc_s(std::vector<char> x, Genotype g, theta_t theta){ //TODO: make this generic
	std::vector<double> s(3,0.0);
	for (std::vector<char>::iterator i = x.begin(); i != x.end(); ++i){
		int numgt = g.numbase(*i);
		if (numgt == 2){
			s[0]++;
		}
		else if (numgt == 1){
			s[1]++;
		}
		else if (numgt == 0){
			s[2]++;
		}
	}
	return s;
}

//RESULT NOT IN LOG SPACE
double Finiteem::pg_x_given_theta(const Genotype g,const std::vector<char> x,const theta_t theta){
	double px = px_given_gtheta(x,g,theta);
	return exp(px + pg(g));
}

//may be faster if we represent x as a map w/ char and counts, like gt?? we support this in plpdata
double Finiteem::px_given_gtheta(const std::vector<char> x,const Genotype g,const theta_t theta){
	double px = 0.0;
	std::map<char, int> counts;

	for (std::vector<char>::const_iterator i = x.begin(); i != x.end(); ++i){
		counts[*i] += 1;
	}
	for (std::map<char,int>::iterator i = counts.begin(); i!= counts.end(); ++i){
		double pn = pn_given_gtheta(i->first,g,theta);
		if (pn == -std::numeric_limits<double>::infinity()){
			return -std::numeric_limits<double>::infinity();
		}
		else{
			px += i->second * pn;
			// px -= std::lgamma(i->second + 1);
		}
	}
	// px += std::lgamma(x.size()+1);
	return px;
}

//LOG SPACE
double Finiteem::pn_given_gtheta(char n, Genotype g, theta_t theta){
	double epsilon = std::get<0>(theta);
	double p;
	// p = ((double)g.numbase(n))/g.getploidy()*(1.0-3.0*epsilon) + ((double)g.numnotbase(n))/g.getploidy()*epsilon;
	int numgt = g.numbase(n);
	if (numgt == 2){
		p = (1.0 - 3.0 * epsilon);
	}
	else if (numgt == 1){
		p = (0.5 - epsilon);
	}
	else{
		p = epsilon;
	}
	if (p == 0){
		return -std::numeric_limits<double>::infinity();
	}
	else if (p < 0){
		std::clog << "N=" << n << "\tGT=" << g << "\tPloidy=" << g.getploidy() << "\t#N=" << g.numbase(n) << "\t#!N=" << g.numnotbase(n) << "\tP1=" << ((double)g.numbase(n))/g.getploidy()*(1-3*epsilon) << "\tP2=" << ((double)g.numnotbase(n))/g.getploidy()*epsilon << "\tP=" << p << "\tTheta=" << theta << std::endl;
		throw std::runtime_error("p < 0 detected");
	}
	else{
		return log(p);
	}
}

double Finiteem::pg(Genotype g){
	return log(1.0/possible_gts.size());
}

double Finiteem::smallest_nonzero(std::vector<double> v){
	std::vector<double> sorted_v(v);
	std::sort(sorted_v.begin(),sorted_v.end());
	double smallest = 0;
	for (std::vector<double>::iterator i = sorted_v.begin(); i != sorted_v.end(); ++i){
		if(*i > smallest){
			return *i;
		}
	}
	return 0;
}

double Finiteem::allele_alpha(char allele, char ref, double ref_weight, double theta, std::map<char,double> pi){
	double w = (ref == allele ? ref_weight : 0);
	return theta * pi[allele] + w;
}

double Finiteem::allele_alpha(char allele, char ref, double ref_weight, double theta, double pi){
	double w = (ref == allele ? ref_weight : 0);
	return theta * pi + w;
}
double Finiteem::ref_alpha(double ref_weight, double theta){
	return ref_weight + theta;
}

<commit_msg>make functions work<commit_after>#include "finiteem.h"
#include <cmath>
#include <functional>
#include <algorithm>
#include <iostream>
#include <stdexcept>
#include <cerrno>
#include <cstring>
#include <limits>

Finiteem::Finiteem(Pileupdata p, int ploidy) : plp(p), theta(std::make_tuple(0.1,std::map::map(),1)),
	em(std::bind(&Finiteem::q_function, this, std::placeholders::_1), std::bind(&Finiteem::m_function,this,std::placeholders::_1), theta),
	ploidy(ploidy){
	possible_gts = Genotype::enumerate_gts(ploidy);
	m = load_matrix();
}

Finiteem::Finiteem(Pileupdata p): Finiteem(p, 2){
}

Finiteem::Finiteem(std::string samfile, std::string refname, int ploidy) : plp(samfile, refname), theta(std::make_tuple(0.1,std::map::map(),1)),
	em(std::bind(&Finiteem::q_function, this, std::placeholders::_1), std::bind(&Finiteem::m_function,this,std::placeholders::_1), theta),
	ploidy(ploidy){
	possible_gts = Genotype::enumerate_gts(ploidy);
	m = load_matrix();
}

Finiteem::Finiteem(std::string samfile, std::string refname) : Finiteem(samfile, refname, 2) {
}

theta_t Finiteem::start(double stop){
	return em.start(stop);
}

double Finiteem::q_function(theta_t theta){
	double likelihood = 0.0;
	for (int i = 0; i < Genotype::alleles.size(); ++i){
		for (int j = 0; j < possible_gts.size(); ++j){
			Genotype g = possible_gts[j];
			for (auto it = g.gt.begin(); it != g.gt.end(); ++it){
				char allele = it->first;
				for (int k = 0; k < it->second; ++k){
					likelihood += m[i][j] * log(allele_alpha(allele,Genotype::alleles[i],std::get<2>(theta),std::get<0>(theta),std::get<1>(theta)) + k);
				}
			}
			for (l = 0; l < ploidy; ++l){
				likelihood -= m[i][j] * log(ref)alpha(std::get<2>(theta), std::get<0>(theta) + l);
			}
		}
	}
	return likelihood;
}

theta_t Finiteem::m_function(theta_t theta){
	double th = meep_math::nr_root(dq_dtheta,ddq_dtheta,std::get<0>(theta));
	double w = meep_math::nr_root(dq_dw,ddq_dw,std::get<2>(theta));

	std::map<char,double> pi = std::get<1>(theta);
	double p = 0.0;
	for (int i = 0; i < Genotype::alleles.size()-1; ++i){
		a = Genotype::alleles[i];
		auto qprime = std::bind(dq_dpi,a,_1);
		auto qprimeprime = std::bind(ddq_dpi,a,_1);
		double optimum = meep_math::nr_root(qprime,qprimeprime,pi[a]);
		pi[a] = optimum;
		p += optimum;
	}
	pi[Genotype::alleles.back()] = 1 - p;
	return std::make_tuple(th,pi,w);
}

//todo: figure out what to do with this function
GT_Matrix<ploidy> Finiteem::load_matrix(){
	for (pileupdata_t::iterator tid = plpdata.begin(); tid != plpdata.end(); ++tid){
		for(std::vector<pileuptuple_t>::iterator pos = tid->begin(); pos != tid->end(); ++pos){
			const std::vector<char> &x = std::get<0>(*pos);
			const char &ref = std::get<3>(*pos);
			// for (std::vector<Genotype>::iterator g = possible_gts.begin(); g != possible_gts.end(); ++g){
			// 	std::vector<double> site_s = calc_s(x,*g,theta);
			// 	double pg_x = pg_x_given_theta(*g,x,theta);
			// 	for(size_t i = 0; i < s.size(); ++i){
			// 		s[i] += pg_x * site_s[i];
			// 	}
			// 	t[ref][*g] += pg_x;
			// }
		}
	}
}

theta_t Finiteem::optimize_q(theta_t theta){

}

double Finiteem::dq_dtheta(double th){
	std::map<char,double> pi = std::get<1>(theta);
	double refweight = std::get<2>(theta);
	double dq = 0.0;
	int numalleles = Genotype::alleles.size();
	int numgts = possible_gts.size();
	for (int i = 0; i < numalleles; ++i){ //for each reference base
		for (int j = 0; i < numgts; ++j){ //for each genotype
			Genotype g = possible_gts[j];
			for (auto it = g.gt.begin(); it != g.gt.end(); ++it){ //for each base in genotype
				char allele = it -> first;
				for (int k = 0; k < it->second; ++k){ //add pi/(alpha + 0) twice for het; pi/(alpha + 1) for homozygote
					dq += m[i][j] * (pi[allele]/(allele_alpha(allele,Genotype::alleles[i],refweight,th,pi) + k))
				}
			}
			for (l = 0; l < ploidy; ++l){ //subtract alpha, alpha + 1
				dq -= m[i][j] * (1.0 / ref_alpha(refweight, th) + l);
			}
		}
	}
	return dq;
}

double Finiteem::ddq_dtheta(double th){
	double ddq = 0.0;
	std::map<char,double> pi = std::get<1>(theta);
	double refweight = std::get<2>(theta);
	int numalleles = Genotype::alleles.size();
	int numgts = possible_gts.size();
	for (int i = 0; i < numalleles; ++i){ //for each reference base
		for (int j = 0; i < numgts; ++j){ //for each genotype
			Genotype g = possible_gts[j];
			for (l = 0; l < ploidy; ++l){ //add  1/alpha, 1/(alpha + 1)
				dq += m[i][j] * (1.0 / (ref_alpha(refweight, theta) + l)^2);
			}
			for (auto it = g.gt.begin(); it != g.gt.end(); ++it){ //for each base in genotype
				char allele = it -> first;
				for (int k = 0; k < it->second; ++k){ //add pi/(alpha + 0) twice for het; pi/(alpha + 1) for homozygote
					ddq -= m[i][j] * ((pi[allele]^2)/(allele_alpha(allele,Genotype::alleles[i],refweight,theta,pi) + k)^2)
				}
			}
		}
	}
	return ddq;
}

double Finiteem::dq_dw(double w){
	double dq = 0.0;
	double th = std::get<0>(theta);
	std::map<char,double> pi = std::get<1>(theta);
	int numalleles = Genotype::alleles.size();
	int numgts = possible_gts.size();
	for (int i = 0; i < numalleles; ++i){ //for each reference base
		for (int j = 0; i < numgts; ++j){ //for each genotype
			Genotype g = possible_gts[j];
			for (auto it = g.gt.begin(); it != g.gt.end(); ++it){ //for each base in genotype
				char allele = it -> first;
				if (allele == Genotype::alleles[i]){
					for (int k = 0; k < it->second; ++k){ //add 1/(alpha + 0) or +0 and +1 for homozygote
						dq += m[i][j] * (1.0/(allele_alpha(allele,Genotype::alleles[i],w,theta,pi) + k))
					}
				}
			}
		}
	}
	return dq;
}

double Finiteem::ddq_dw(double w){
	double ddq = 0.0;
	double th = std::get<0>(theta);
	std::map<char,double> pi = std::get<1>(theta);
	int numalleles = Genotype::alleles.size();
	int numgts = possible_gts.size();
	for (int i = 0; i < numalleles; ++i){ //for each reference base
		for (int j = 0; i < numgts; ++j){ //for each genotype
			Genotype g = possible_gts[j];
			for (auto it = g.gt.begin(); it != g.gt.end(); ++it){ //for each base in genotype
				char allele = it -> first;
				if (allele == Genotype::alleles[i]){
					for (int k = 0; k < it->second; ++k){ //add 1/(alpha + 0) or +0 and +1 for homozygote
						ddq -= m[i][j] * (1.0/(allele_alpha(allele,Genotype::alleles[i],w,theta,pi) + k)^2)
					}
				}
			}
		}
	}
	return ddq;
}

double dq_dpi(char a, double pi){
	double dq = 0.0;
	double th = std::get<0>(theta);
	double refweight = std::get<2>(theta);
	int numalleles = Genotype::alleles.size();
	int numgts = possible_gts.size();
	for (int i = 0; i < numalleles - 1; ++i){ //for each reference base except one
		for (int j = 0; i < numgts; ++j){ //for each genotype
			Genotype g = possible_gts[j];
			for (auto it = g.gt.begin(); it != g.gt.end(); ++it){ //for each base in genotype
				char allele = it -> first;
				if (allele == a){
					for (int k = 0; k < it->second; ++k){ //add 1/(alpha + 0) or +0 and +1 for homozygote
						dq += m[i][j] * ((theta)/(allele_alpha(allele,Genotype::alleles[i],refweight,theta,pi) + k))
					}
				}
			}
		}
	}
	return dq;
}

double ddq_dpi(char a, double pi){
	double ddq = 0.0;
	double th = std::get<0>(theta);
	double refweight = std::get<2>(theta);
	int numalleles = Genotype::alleles.size();
	int numgts = possible_gts.size();
	for (int i = 0; i < numalleles - 1; ++i){ //for each reference base except one
		for (int j = 0; i < numgts; ++j){ //for each genotype
			Genotype g = possible_gts[j];
			for (auto it = g.gt.begin(); it != g.gt.end(); ++it){ //for each base in genotype
				char allele = it -> first;
				if (allele == a){
					for (int k = 0; k < it->second; ++k){ //add 1/(alpha + 0) or +0 and +1 for homozygote
						ddq -= m[i][j] * ((theta)^2/(allele_alpha(allele,Genotype::alleles[i],refweight,theta,pi) + k)^2)
					}
				}
			}
		}
	}
	return ddq;
}

double Finiteem::allele_alpha(char allele, char ref, double ref_weight, double theta, std::map<char,double> pi){
	double w = (ref == allele ? ref_weight : 0);
	return theta * pi[allele] + w;
}

double Finiteem::allele_alpha(char allele, char ref, double ref_weight, double theta, double pi){
	double w = (ref == allele ? ref_weight : 0);
	return theta * pi + w;
}
double Finiteem::ref_alpha(double ref_weight, double theta){
	return ref_weight + theta;
}

<|endoftext|>


<commit_before>#include "gtest/gtest.h"
#include "../src/scene/SceneManager.h"
#include "../src/scene/Ionosphere.h"
#include "../src/tracer/Ray.h"
#include "../src/math/Vector3d.h"
#include "../src/math/Line3d.h"
#include "../src/core/Config.h"
#include "../src/core/Application.h"

namespace {

	using namespace raytracer::scene;
	using namespace raytracer::math;

	class SceneManagerTest : public ::testing::Test {

		protected:
			void SetUp() {

				conf = Config("config/scenario_test.json");
				Application::getInstance().setCelestialConfig(conf);
				appConf = Config("config/config.json");
				Application::getInstance().setApplicationConfig(conf);

				sm = SceneManager();
				io = Ionosphere();
				Plane3d mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(100e3, 3390e3 + 100e3, 0));
				mesh.size = 1e3;
				io.setMesh(mesh);

				sm.addToScene(&io);
			}

			SceneManager sm;
			Ionosphere io;
			Config conf, appConf;
	};

	TEST_F(SceneManagerTest, MeshIsSet) {

		for (Geometry* g : sm.getScene()) {
			ASSERT_EQ(100e3, g->getMesh().centerpoint.x);
			ASSERT_EQ(3390e3 + 100e3, g->getMesh().centerpoint.y);
			ASSERT_EQ(0, g->getMesh().centerpoint.z);
			ASSERT_EQ(0, g->getMesh().normal.x);
			ASSERT_EQ(1, g->getMesh().normal.y);
			ASSERT_EQ(GeometryType::ionosphere, g->type);
		}
	}

	TEST_F(SceneManagerTest, Intersection) {

		raytracer::tracer::Ray r = raytracer::tracer::Ray();
		r.o = Vector3d(0, 0, 0);

		Line3d rayLine = Line3d(Vector3d(0, 0, 0), Vector3d(100e3, 3390e3 + 101e3, 0));

		Intersection is = sm.intersect(r, rayLine);
		Plane3d mesh = is.g.mesh3d;

		ASSERT_NE(GeometryType::none, is.o);
		ASSERT_NEAR((mesh.centerpoint.y / rayLine.destination.y) * mesh.centerpoint.x, is.pos.x, 10);
		ASSERT_EQ(3390e3 + 100e3, is.pos.y);
		ASSERT_NEAR(100e3, mesh.centerpoint.x, 10);
		ASSERT_NEAR(3390e3 + 100e3, mesh.centerpoint.y, 10);
		ASSERT_NEAR(0, mesh.centerpoint.z, 10);
	}

	TEST_F(SceneManagerTest, SortScene) {

		SceneManager scm2 = SceneManager();

		Plane3d mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(0, 3390e3 + 10, 0));
		Geometry g1 = Geometry(mesh);
		mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(0, 3390e3 + 13, 0));
		Geometry g2 = Geometry(mesh);
		mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(0, 3390e3 + 14, 0));
		Geometry g3 = Geometry(mesh);
		mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(0, 3390e3 + 12, 0));
		Geometry g4 = Geometry(mesh);
		mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(0, 3390e3 + 11, 0));
		Geometry g5 = Geometry(mesh);

		scm2.addToScene(&g1);
		scm2.addToScene(&g2);
		scm2.addToScene(&g3);
		scm2.addToScene(&g4);
		scm2.addToScene(&g5);

		scm2.sortScene();

		double lastAlt = 0;
		for (Geometry* g : scm2.getScene()) {

			ASSERT_GT(g->altitude, 0);
			ASSERT_GT(g->altitude, lastAlt);
			lastAlt = g->altitude;
			ASSERT_GT(lastAlt, 0);
		}
	}

	TEST_F(SceneManagerTest, IntersectionOutOfBounds) {

		raytracer::tracer::Ray r = raytracer::tracer::Ray();
		r.o = Vector3d(0, 0, 0);

		Line3d rayLine = Line3d(Vector3d(0, 0, 0), Vector3d(100e3, 3390e3 + 99e3, 0));

		Intersection is = sm.intersect(r, rayLine);

		ASSERT_EQ(GeometryType::none, is.o);
	}

	TEST_F(SceneManagerTest, IntersectionAngled) {

		raytracer::tracer::Ray r = raytracer::tracer::Ray();
		r.o = Vector3d(0, 0, 0);

		double angle = Constants::PI/3;
		double offset  = 250;

		Line3d rayLine = Line3d();
		rayLine.origin = Vector3d(100e3 - 100e3/tan(angle) - offset, 3390e3, 0);
		rayLine.destination.x = 100e3 / tan(angle) + 100e3 - offset;
		rayLine.destination.y = 200e3 + 3390e3;

		Intersection is = sm.intersect(r, rayLine);
		Plane3d mesh = is.g.mesh3d;

		ASSERT_NEAR((rayLine.destination.y - rayLine.origin.y) / (rayLine.destination.x - rayLine.origin.x), tan(angle), 1e-3);
		ASSERT_EQ(GeometryType::ionosphere, is.o);
		ASSERT_NEAR(100e3 - offset, is.pos.x, 10);
		ASSERT_EQ(3390e3 + 100e3, is.pos.y);
		ASSERT_NEAR(100e3, mesh.centerpoint.x, 10);
		ASSERT_NEAR(3390e3 + 100e3, mesh.centerpoint.y, 10);
		ASSERT_NEAR(0, mesh.centerpoint.z, 10);

		rayLine.origin.x -= 1e3;
		rayLine.destination.x -= 1e3;

		is = sm.intersect(r, rayLine);
		ASSERT_EQ(GeometryType::none, is.o);
	}

	TEST_F(SceneManagerTest, IntersectionMultiple) {

		Ionosphere io4 = Ionosphere();
		Plane3d mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(100e3, 3390e3 + 101e3, 0));
		mesh.size = 1e3;
		io4.setMesh(mesh);

		sm.addToScene(&io4);

		Ionosphere io2 = Ionosphere();
		mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(100e3, 3390e3 + 102e3, 0));
		mesh.size = 1e3;
		io2.setMesh(mesh);

		sm.addToScene(&io2);

		Ionosphere io3 = Ionosphere();
		mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(100e3, 3390e3 + 103e3, 0));
		mesh.size = 1e3;
		io3.setMesh(mesh);

		sm.addToScene(&io3);

		raytracer::tracer::Ray r = raytracer::tracer::Ray();
		r.o = Vector3d(0, 0, 0);

		Line3d rayLine = Line3d(Vector3d(0, 0, 0), Vector3d(100e3, 3390e3 + 105e3, 0));

		Intersection is = sm.intersect(r, rayLine);
		Plane3d mesh2 = is.g.mesh3d;

		ASSERT_NE(GeometryType::none, is.o);
		ASSERT_NEAR((mesh2.centerpoint.y / rayLine.destination.y) * mesh2.centerpoint.x, is.pos.x, 10);
		ASSERT_EQ(3390e3 + 100e3, is.pos.y);
		ASSERT_NEAR(100e3, mesh2.centerpoint.x, 10);
		ASSERT_NEAR(3390e3 + 100e3, mesh2.centerpoint.y, 10);
		ASSERT_NEAR(0, mesh2.centerpoint.z, 10);

	}
}
<commit_msg>Minor bugfix in test<commit_after>#include "gtest/gtest.h"
#include "../src/scene/SceneManager.h"
#include "../src/scene/Ionosphere.h"
#include "../src/tracer/Ray.h"
#include "../src/math/Vector3d.h"
#include "../src/math/Line3d.h"
#include "../src/core/Config.h"
#include "../src/core/Application.h"

namespace {

	using namespace raytracer::scene;
	using namespace raytracer::math;

	class SceneManagerTest : public ::testing::Test {

		protected:
			void SetUp() {

				conf = Config("config/scenario_test.json");
				Application::getInstance().setCelestialConfig(conf);
				appConf = Config("config/config.json");
				Application::getInstance().setApplicationConfig(conf);

				sm = SceneManager();
				io = Ionosphere();
				Plane3d mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(100e3, 3390e3 + 100e3, 0));
				mesh.size = 1e3;
				io.setMesh(mesh);

				sm.addToScene(&io);
			}

			SceneManager sm;
			Ionosphere io;
			Config conf, appConf;
	};

	TEST_F(SceneManagerTest, MeshIsSet) {

		for (Geometry* g : sm.getScene()) {
			ASSERT_EQ(100e3, g->getMesh().centerpoint.x);
			ASSERT_EQ(3390e3 + 100e3, g->getMesh().centerpoint.y);
			ASSERT_EQ(0, g->getMesh().centerpoint.z);
			ASSERT_EQ(0, g->getMesh().normal.x);
			ASSERT_EQ(1, g->getMesh().normal.y);
			ASSERT_EQ(GeometryType::ionosphere, g->type);
		}
	}

	TEST_F(SceneManagerTest, Intersection) {

		raytracer::tracer::Ray r = raytracer::tracer::Ray();
		r.o = Vector3d(0, 0, 0);

		Line3d rayLine = Line3d(Vector3d(0, 0, 0), Vector3d(100e3, 3390e3 + 101e3, 0));

		Intersection is = sm.intersect(r, rayLine);
		Plane3d mesh = is.g->mesh3d;

		ASSERT_NE(GeometryType::none, is.o);
		ASSERT_NEAR((mesh.centerpoint.y / rayLine.destination.y) * mesh.centerpoint.x, is.pos.x, 10);
		ASSERT_EQ(3390e3 + 100e3, is.pos.y);
		ASSERT_NEAR(100e3, mesh.centerpoint.x, 10);
		ASSERT_NEAR(3390e3 + 100e3, mesh.centerpoint.y, 10);
		ASSERT_NEAR(0, mesh.centerpoint.z, 10);
	}

	TEST_F(SceneManagerTest, SortScene) {

		SceneManager scm2 = SceneManager();

		Plane3d mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(0, 3390e3 + 10, 0));
		Geometry g1 = Geometry(mesh);
		mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(0, 3390e3 + 13, 0));
		Geometry g2 = Geometry(mesh);
		mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(0, 3390e3 + 14, 0));
		Geometry g3 = Geometry(mesh);
		mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(0, 3390e3 + 12, 0));
		Geometry g4 = Geometry(mesh);
		mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(0, 3390e3 + 11, 0));
		Geometry g5 = Geometry(mesh);

		scm2.addToScene(&g1);
		scm2.addToScene(&g2);
		scm2.addToScene(&g3);
		scm2.addToScene(&g4);
		scm2.addToScene(&g5);

		scm2.sortScene();

		double lastAlt = 0;
		for (Geometry* g : scm2.getScene()) {

			ASSERT_GT(g->altitude, 0);
			ASSERT_GT(g->altitude, lastAlt);
			lastAlt = g->altitude;
			ASSERT_GT(lastAlt, 0);
		}
	}

	TEST_F(SceneManagerTest, IntersectionOutOfBounds) {

		raytracer::tracer::Ray r = raytracer::tracer::Ray();
		r.o = Vector3d(0, 0, 0);

		Line3d rayLine = Line3d(Vector3d(0, 0, 0), Vector3d(100e3, 3390e3 + 99e3, 0));

		Intersection is = sm.intersect(r, rayLine);

		ASSERT_EQ(GeometryType::none, is.o);
	}

	TEST_F(SceneManagerTest, IntersectionAngled) {

		raytracer::tracer::Ray r = raytracer::tracer::Ray();
		r.o = Vector3d(0, 0, 0);

		double angle = Constants::PI/3;
		double offset  = 250;

		Line3d rayLine = Line3d();
		rayLine.origin = Vector3d(100e3 - 100e3/tan(angle) - offset, 3390e3, 0);
		rayLine.destination.x = 100e3 / tan(angle) + 100e3 - offset;
		rayLine.destination.y = 200e3 + 3390e3;

		Intersection is = sm.intersect(r, rayLine);
		Plane3d mesh = is.g->mesh3d;

		ASSERT_NEAR((rayLine.destination.y - rayLine.origin.y) / (rayLine.destination.x - rayLine.origin.x), tan(angle), 1e-3);
		ASSERT_EQ(GeometryType::ionosphere, is.o);
		ASSERT_NEAR(100e3 - offset, is.pos.x, 10);
		ASSERT_EQ(3390e3 + 100e3, is.pos.y);
		ASSERT_NEAR(100e3, mesh.centerpoint.x, 10);
		ASSERT_NEAR(3390e3 + 100e3, mesh.centerpoint.y, 10);
		ASSERT_NEAR(0, mesh.centerpoint.z, 10);

		rayLine.origin.x -= 1e3;
		rayLine.destination.x -= 1e3;

		is = sm.intersect(r, rayLine);
		ASSERT_EQ(GeometryType::none, is.o);
	}

	TEST_F(SceneManagerTest, IntersectionMultiple) {

		Ionosphere io4 = Ionosphere();
		Plane3d mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(100e3, 3390e3 + 101e3, 0));
		mesh.size = 1e3;
		io4.setMesh(mesh);

		sm.addToScene(&io4);

		Ionosphere io2 = Ionosphere();
		mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(100e3, 3390e3 + 102e3, 0));
		mesh.size = 1e3;
		io2.setMesh(mesh);

		sm.addToScene(&io2);

		Ionosphere io3 = Ionosphere();
		mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(100e3, 3390e3 + 103e3, 0));
		mesh.size = 1e3;
		io3.setMesh(mesh);

		sm.addToScene(&io3);

		raytracer::tracer::Ray r = raytracer::tracer::Ray();
		r.o = Vector3d(0, 0, 0);

		Line3d rayLine = Line3d(Vector3d(0, 0, 0), Vector3d(100e3, 3390e3 + 105e3, 0));

		Intersection is = sm.intersect(r, rayLine);
		Plane3d mesh2 = is.g->mesh3d;

		ASSERT_NE(GeometryType::none, is.o);
		ASSERT_NEAR((mesh2.centerpoint.y / rayLine.destination.y) * mesh2.centerpoint.x, is.pos.x, 10);
		ASSERT_EQ(3390e3 + 100e3, is.pos.y);
		ASSERT_NEAR(100e3, mesh2.centerpoint.x, 10);
		ASSERT_NEAR(3390e3 + 100e3, mesh2.centerpoint.y, 10);
		ASSERT_NEAR(0, mesh2.centerpoint.z, 10);

	}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dstribut.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 17:04:09 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SVX_DSTRIBUT_HXX
#define _SVX_DSTRIBUT_HXX

#ifndef _SVX_DLG_CTRL_HXX
#include <svx/dlgctrl.hxx>
#endif

#ifndef _SV_GROUP_HXX
#include <vcl/group.hxx>
#endif

#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif

#ifndef _SVX_DSTRIBUT_ENUM_HXX
#include <svx/dstribut_enum.hxx> //CHINA001
#endif
/*************************************************************************
|*
\************************************************************************/

/*
enum SvxDistributeHorizontal
{
    SvxDistributeHorizontalNone = 0,
    SvxDistributeHorizontalLeft,
    SvxDistributeHorizontalCenter,
    SvxDistributeHorizontalDistance,
    SvxDistributeHorizontalRight
};

enum SvxDistributeVertical
{
    SvxDistributeVerticalNone = 0,
    SvxDistributeVerticalTop,
    SvxDistributeVerticalCenter,
    SvxDistributeVerticalDistance,
    SvxDistributeVerticalBottom
};
*/

/*************************************************************************
|*
\************************************************************************/

class SvxDistributePage : public SvxTabPage
{
    SvxDistributeHorizontal     meDistributeHor;
    SvxDistributeVertical       meDistributeVer;

    FixedLine                   maFlHorizontal      ;
    RadioButton                 maBtnHorNone        ;
    RadioButton                 maBtnHorLeft        ;
    RadioButton                 maBtnHorCenter      ;
    RadioButton                 maBtnHorDistance    ;
    RadioButton                 maBtnHorRight       ;
    FixedImage                  maHorLow            ;
    FixedImage                  maHorCenter         ;
    FixedImage                  maHorDistance       ;
    FixedImage                  maHorHigh           ;
    FixedLine                   maFlVertical        ;
    RadioButton                 maBtnVerNone        ;
    RadioButton                 maBtnVerTop         ;
    RadioButton                 maBtnVerCenter      ;
    RadioButton                 maBtnVerDistance    ;
    RadioButton                 maBtnVerBottom      ;
    FixedImage                  maVerLow            ;
    FixedImage                  maVerCenter         ;
    FixedImage                  maVerDistance       ;
    FixedImage                  maVerHigh           ;

public:
    SvxDistributePage(Window* pWindow, const SfxItemSet& rInAttrs,
        SvxDistributeHorizontal eHor = SvxDistributeHorizontalNone,
        SvxDistributeVertical eVer = SvxDistributeVerticalNone);
    ~SvxDistributePage();

    static SfxTabPage* Create(Window*, const SfxItemSet&,
        SvxDistributeHorizontal eHor, SvxDistributeVertical eVer);
    static UINT16* GetRanges();
    virtual BOOL FillItemSet(SfxItemSet&);
    virtual void Reset(const SfxItemSet&);
    virtual void PointChanged(Window* pWindow, RECT_POINT eRP);

    SvxDistributeHorizontal GetDistributeHor() const { return meDistributeHor; }
    SvxDistributeVertical GetDistributeVer() const { return meDistributeVer; }
};

/*************************************************************************
|*
\************************************************************************/

class SvxDistributeDialog : public SfxSingleTabDialog
{
    SvxDistributePage*          mpPage;

public:
    SvxDistributeDialog(Window* pParent, const SfxItemSet& rAttr,
        SvxDistributeHorizontal eHor = SvxDistributeHorizontalNone,
        SvxDistributeVertical eVer = SvxDistributeVerticalNone);
    ~SvxDistributeDialog();

    SvxDistributeHorizontal GetDistributeHor() const { return mpPage->GetDistributeHor(); }
    SvxDistributeVertical GetDistributeVer() const { return mpPage->GetDistributeVer(); }
};

#endif // _SVX_DSTRIBUT_HXX

<commit_msg>INTEGRATION: CWS changefileheader (1.5.368); FILE MERGED 2008/04/01 15:50:19 thb 1.5.368.3: #i85898# Stripping all external header guards 2008/04/01 12:48:11 thb 1.5.368.2: #i85898# Stripping all external header guards 2008/03/31 14:19:24 rt 1.5.368.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: dstribut.hxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _SVX_DSTRIBUT_HXX
#define _SVX_DSTRIBUT_HXX

#include <svx/dlgctrl.hxx>
#include <vcl/group.hxx>
#include <vcl/fixed.hxx>
#include <svx/dstribut_enum.hxx> //CHINA001
/*************************************************************************
|*
\************************************************************************/

/*
enum SvxDistributeHorizontal
{
    SvxDistributeHorizontalNone = 0,
    SvxDistributeHorizontalLeft,
    SvxDistributeHorizontalCenter,
    SvxDistributeHorizontalDistance,
    SvxDistributeHorizontalRight
};

enum SvxDistributeVertical
{
    SvxDistributeVerticalNone = 0,
    SvxDistributeVerticalTop,
    SvxDistributeVerticalCenter,
    SvxDistributeVerticalDistance,
    SvxDistributeVerticalBottom
};
*/

/*************************************************************************
|*
\************************************************************************/

class SvxDistributePage : public SvxTabPage
{
    SvxDistributeHorizontal     meDistributeHor;
    SvxDistributeVertical       meDistributeVer;

    FixedLine                   maFlHorizontal      ;
    RadioButton                 maBtnHorNone        ;
    RadioButton                 maBtnHorLeft        ;
    RadioButton                 maBtnHorCenter      ;
    RadioButton                 maBtnHorDistance    ;
    RadioButton                 maBtnHorRight       ;
    FixedImage                  maHorLow            ;
    FixedImage                  maHorCenter         ;
    FixedImage                  maHorDistance       ;
    FixedImage                  maHorHigh           ;
    FixedLine                   maFlVertical        ;
    RadioButton                 maBtnVerNone        ;
    RadioButton                 maBtnVerTop         ;
    RadioButton                 maBtnVerCenter      ;
    RadioButton                 maBtnVerDistance    ;
    RadioButton                 maBtnVerBottom      ;
    FixedImage                  maVerLow            ;
    FixedImage                  maVerCenter         ;
    FixedImage                  maVerDistance       ;
    FixedImage                  maVerHigh           ;

public:
    SvxDistributePage(Window* pWindow, const SfxItemSet& rInAttrs,
        SvxDistributeHorizontal eHor = SvxDistributeHorizontalNone,
        SvxDistributeVertical eVer = SvxDistributeVerticalNone);
    ~SvxDistributePage();

    static SfxTabPage* Create(Window*, const SfxItemSet&,
        SvxDistributeHorizontal eHor, SvxDistributeVertical eVer);
    static UINT16* GetRanges();
    virtual BOOL FillItemSet(SfxItemSet&);
    virtual void Reset(const SfxItemSet&);
    virtual void PointChanged(Window* pWindow, RECT_POINT eRP);

    SvxDistributeHorizontal GetDistributeHor() const { return meDistributeHor; }
    SvxDistributeVertical GetDistributeVer() const { return meDistributeVer; }
};

/*************************************************************************
|*
\************************************************************************/

class SvxDistributeDialog : public SfxSingleTabDialog
{
    SvxDistributePage*          mpPage;

public:
    SvxDistributeDialog(Window* pParent, const SfxItemSet& rAttr,
        SvxDistributeHorizontal eHor = SvxDistributeHorizontalNone,
        SvxDistributeVertical eVer = SvxDistributeVerticalNone);
    ~SvxDistributeDialog();

    SvxDistributeHorizontal GetDistributeHor() const { return mpPage->GetDistributeHor(); }
    SvxDistributeVertical GetDistributeVer() const { return mpPage->GetDistributeVer(); }
};

#endif // _SVX_DSTRIBUT_HXX

<|endoftext|>


<commit_before>#include "databasewizard.h"
#include "traycontrol.h"

#include <QApplication>
#include <QDebug>
#include <dialogmaster.h>
#include <databasecontroller.h>
#include "contentdialog.h"
#include "editpackageswidget.h"

TrayControl::TrayControl(QObject *parent) :
	QObject(parent),
	_tray(new QSystemTrayIcon(QIcon(QStringLiteral(":/icons/tray.ico")), this)),
	_trayMenu(new QMenu())
{
	_trayMenu->addAction(QIcon::fromTheme("package-new"), tr("Change Database"), this, &TrayControl::changeDatabase);
	_trayMenu->addSeparator();
	_trayMenu->addAction(QIcon::fromTheme("package-upgrade"), tr("Edit Packages"), this, &TrayControl::editPackages);
	_trayMenu->addSeparator();
	_trayMenu->addAction(QIcon::fromTheme("help-about"), tr("About"), this, &TrayControl::about);
	_trayMenu->addAction(QIcon::fromTheme("qt-logo"), tr("About Qt"), qApp, &QApplication::aboutQt);
	_trayMenu->addSeparator();
	_trayMenu->addAction(QIcon::fromTheme("gtk-quit"), tr("Quit"), qApp, &QApplication::quit);

	_tray->setContextMenu(_trayMenu);
	_tray->setToolTip(QApplication::applicationDisplayName());
	_tray->show();
}

TrayControl::~TrayControl()
{
	_trayMenu->deleteLater();
}

void TrayControl::changeDatabase()
{
	DatabaseWizard::run();
}

void TrayControl::editPackages()
{
	auto ctr = DatabaseController::instance();
	auto ok = false;
	auto packages = ContentDialog::execute<EditPackagesWidget, QStringList>(ctr->listPackages(),
																			nullptr,
																			&ok);
	if(ok) {
		ctr->updateDb(packages);
		ctr->sync();
	}
}

void TrayControl::about()
{
	DialogMaster::about(nullptr,
						tr("TODO"),
						true,
						QStringLiteral("https://github.com/Baum42/pacsync"));
}
<commit_msg>remove unused sync<commit_after>#include "databasewizard.h"
#include "traycontrol.h"

#include <QApplication>
#include <QDebug>
#include <dialogmaster.h>
#include <databasecontroller.h>
#include "contentdialog.h"
#include "editpackageswidget.h"

TrayControl::TrayControl(QObject *parent) :
	QObject(parent),
	_tray(new QSystemTrayIcon(QIcon(QStringLiteral(":/icons/tray.ico")), this)),
	_trayMenu(new QMenu())
{
	_trayMenu->addAction(QIcon::fromTheme("package-new"), tr("Change Database"), this, &TrayControl::changeDatabase);
	_trayMenu->addSeparator();
	_trayMenu->addAction(QIcon::fromTheme("package-upgrade"), tr("Edit Packages"), this, &TrayControl::editPackages);
	_trayMenu->addSeparator();
	_trayMenu->addAction(QIcon::fromTheme("help-about"), tr("About"), this, &TrayControl::about);
	_trayMenu->addAction(QIcon::fromTheme("qt-logo"), tr("About Qt"), qApp, &QApplication::aboutQt);
	_trayMenu->addSeparator();
	_trayMenu->addAction(QIcon::fromTheme("gtk-quit"), tr("Quit"), qApp, &QApplication::quit);

	_tray->setContextMenu(_trayMenu);
	_tray->setToolTip(QApplication::applicationDisplayName());
	_tray->show();
}

TrayControl::~TrayControl()
{
	_trayMenu->deleteLater();
}

void TrayControl::changeDatabase()
{
	DatabaseWizard::run();
}

void TrayControl::editPackages()
{
	auto ctr = DatabaseController::instance();
	auto ok = false;
	auto packages = ContentDialog::execute<EditPackagesWidget, QStringList>(ctr->listPackages(),
																			nullptr,
																			&ok);
	if(ok)
		ctr->updateDb(packages);
}

void TrayControl::about()
{
	DialogMaster::about(nullptr,
						tr("TODO"),
						true,
						QStringLiteral("https://github.com/Baum42/pacsync"));
}
<|endoftext|>


<commit_before>/************************************************************************
  This file is part of Freekick.

  Freekick is free software: you can redistribute it and/or modify
  it under the terms of the GNU Affero General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  Freekick is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU Affero General Public License for more details.

  You should have received a copy of the GNU Affero General Public License
  along with Freekick.  If not, see <http://www.gnu.org/licenses/>.

  Copyright Antti Salonen, 2008
  This file was generated on So Okt 26 2008 at 12:09:20
**************************************************************************/

#include "Pitch.h"

namespace freekick
{
    namespace soccer
    {
        Pitch::Pitch (float w, float l)
            : width(w), length(l)
        {
            float half_width = width / 2.0f;

            float goal_area_left = half_width - (goal_width / 2.0f) - goal_area_width;
            float goal_area_right = half_width + (goal_width / 2.0f) + goal_area_width;
            float goal_area_up = goal_area_length;
            float goal_area_down = length - goal_area_length;
            goal_area_points[0] = addutil::Vector3(goal_area_left,  0.0f, 0.0f);
            goal_area_points[1] = addutil::Vector3(goal_area_right, 0.0f, goal_area_up);
            goal_area_points[2] = addutil::Vector3(goal_area_left,  0.0f, goal_area_down);
            goal_area_points[3] = addutil::Vector3(goal_area_right, 0.0f, length);

            float penalty_box_area_left  = half_width - penalty_box_area_width / 2.0f;
            float penalty_box_area_right = half_width + penalty_box_area_width / 2.0f;
            float penalty_box_area_up    = penalty_box_area_length;
            float penalty_box_area_down  = length - penalty_box_area_length;
            penalty_box_area_points[0] = addutil::Vector3(penalty_box_area_left,  0.0f, 0.0f);
            penalty_box_area_points[1] = addutil::Vector3(penalty_box_area_right, 0.0f, penalty_box_area_up);
            penalty_box_area_points[2] = addutil::Vector3(penalty_box_area_left,  0.0f, penalty_box_area_down);
            penalty_box_area_points[3] = addutil::Vector3(penalty_box_area_right, 0.0f, length);
        }

        float Pitch::getWidth() const
        {
            return width;
        }

        float Pitch::getLength() const
        {
            return length;
        }

        bool Pitch::onPitch(float x, float y) const
        {
            if(x < 0.0f || y < 0.0f || x > width || y > length) return false;
            return true;
        }

        bool Pitch::onSide(bool top, float x, float y) const
        {
            if(!onPitch(x, y)) return false;
            bool ontopside = (y < (length / 2.0f));
            if(top) return ontopside;
            return !ontopside;
        }

        bool Pitch::inFirstGoal(const addutil::Vector3& v) const
        {
            if(!maybeInGoal(v.x, v.y, v.z)) return false;
            return (v.z < 0.0f);
        }

        bool Pitch::inSecondGoal(const addutil::Vector3& v) const
        {
            if(!maybeInGoal(v.x, v.y, v.z)) return false;
            return (v.z > length);
        }

        bool Pitch::inFirstGoal(float x, float y, float z) const
        {
            return inFirstGoal(addutil::Vector3(x, y, z));
        }

        bool Pitch::inSecondGoal(float x, float y, float z) const
        {
            return inSecondGoal(addutil::Vector3(x, y, z));
        }

        bool Pitch::maybeInGoal(float x, float y, float z) const
        {
            if(onPitch(x, z)) return false;
            if(abs((width / 2.0f) - x) > goal_width) return false;
            if(y < 0.0f || y > goal_height) return false;
            return true;
        }

        GoalQuery Pitch::inGoalArea(const addutil::Vector3& v) const
        {
            if(addutil::inArea(goal_area_points[0], goal_area_points[1], v)) return HomeGoal;
            if(addutil::inArea(goal_area_points[2], goal_area_points[3], v)) return AwayGoal;
            return NoGoal;
        }

        GoalQuery Pitch::inPenaltyBoxArea(const addutil::Vector3& v) const
        {
            if(addutil::inArea(penalty_box_area_points[0], penalty_box_area_points[1], v)) return HomeGoal;
            if(addutil::inArea(penalty_box_area_points[2], penalty_box_area_points[3], v)) return AwayGoal;
            return NoGoal;
        }
    }
}
<commit_msg>libsoccer: fixed goal checking<commit_after>/************************************************************************
  This file is part of Freekick.

  Freekick is free software: you can redistribute it and/or modify
  it under the terms of the GNU Affero General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  Freekick is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU Affero General Public License for more details.

  You should have received a copy of the GNU Affero General Public License
  along with Freekick.  If not, see <http://www.gnu.org/licenses/>.

  Copyright Antti Salonen, 2008
  This file was generated on So Okt 26 2008 at 12:09:20
**************************************************************************/

#include "Pitch.h"

namespace freekick
{
    namespace soccer
    {
        Pitch::Pitch (float w, float l)
            : width(w), length(l)
        {
            float half_width = width / 2.0f;

            float goal_area_left = half_width - (goal_width / 2.0f) - goal_area_width;
            float goal_area_right = half_width + (goal_width / 2.0f) + goal_area_width;
            float goal_area_up = goal_area_length;
            float goal_area_down = length - goal_area_length;
            goal_area_points[0] = addutil::Vector3(goal_area_left,  0.0f, 0.0f);
            goal_area_points[1] = addutil::Vector3(goal_area_right, 0.0f, goal_area_up);
            goal_area_points[2] = addutil::Vector3(goal_area_left,  0.0f, goal_area_down);
            goal_area_points[3] = addutil::Vector3(goal_area_right, 0.0f, length);

            float penalty_box_area_left  = half_width - penalty_box_area_width / 2.0f;
            float penalty_box_area_right = half_width + penalty_box_area_width / 2.0f;
            float penalty_box_area_up    = penalty_box_area_length;
            float penalty_box_area_down  = length - penalty_box_area_length;
            penalty_box_area_points[0] = addutil::Vector3(penalty_box_area_left,  0.0f, 0.0f);
            penalty_box_area_points[1] = addutil::Vector3(penalty_box_area_right, 0.0f, penalty_box_area_up);
            penalty_box_area_points[2] = addutil::Vector3(penalty_box_area_left,  0.0f, penalty_box_area_down);
            penalty_box_area_points[3] = addutil::Vector3(penalty_box_area_right, 0.0f, length);
        }

        float Pitch::getWidth() const
        {
            return width;
        }

        float Pitch::getLength() const
        {
            return length;
        }

        bool Pitch::onPitch(float x, float y) const
        {
            if(x < 0.0f || y < 0.0f || x > width || y > length) return false;
            return true;
        }

        bool Pitch::onSide(bool top, float x, float y) const
        {
            if(!onPitch(x, y)) return false;
            bool ontopside = (y < (length / 2.0f));
            if(top) return ontopside;
            return !ontopside;
        }

        bool Pitch::inFirstGoal(const addutil::Vector3& v) const
        {
            if(!maybeInGoal(v.x, v.y, v.z)) return false;
            return (v.z < 0.0f);
        }

        bool Pitch::inSecondGoal(const addutil::Vector3& v) const
        {
            if(!maybeInGoal(v.x, v.y, v.z)) return false;
            return (v.z > length);
        }

        bool Pitch::inFirstGoal(float x, float y, float z) const
        {
            return inFirstGoal(addutil::Vector3(x, y, z));
        }

        bool Pitch::inSecondGoal(float x, float y, float z) const
        {
            return inSecondGoal(addutil::Vector3(x, y, z));
        }

        bool Pitch::maybeInGoal(float x, float y, float z) const
        {
            if(onPitch(x, z)) return false;
            if(abs((width * 0.5f) - x) > goal_width * 0.5f) return false;
            if(y < 0.0f || y > goal_height) return false;
            return true;
        }

        GoalQuery Pitch::inGoalArea(const addutil::Vector3& v) const
        {
            if(addutil::inArea(goal_area_points[0], goal_area_points[1], v)) return HomeGoal;
            if(addutil::inArea(goal_area_points[2], goal_area_points[3], v)) return AwayGoal;
            return NoGoal;
        }

        GoalQuery Pitch::inPenaltyBoxArea(const addutil::Vector3& v) const
        {
            if(addutil::inArea(penalty_box_area_points[0], penalty_box_area_points[1], v)) return HomeGoal;
            if(addutil::inArea(penalty_box_area_points[2], penalty_box_area_points[3], v)) return AwayGoal;
            return NoGoal;
        }
    }
}
<|endoftext|>