<commit_before>////////////////////////////////////////////////////////////////////////////////
// jump_diffusion.cpp
// ------------------
//
// Computes the price of a European call with jump-diffusion driven by a Poisson
// process. The jump amplitude is assumed to be lognormally distributed.
//
// Author: Parsiad Azimzadeh
////////////////////////////////////////////////////////////////////////////////

#include <QuantPDE/Core>
#include <QuantPDE/Modules/Lambdas>
#include <QuantPDE/Modules/Operators>
#include <QuantPDE/Modules/Utilities>

using namespace QuantPDE;
using namespace QuantPDE::Modules;

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

#include <iostream> // cerr
#include <memory>   // unique_ptr

using namespace std;

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

enum JumpType { merton, kou };

JumpType jump_type;
Real
	T, r, vol, divs, S_0, K,
	jump_arrival_rate,
	jump_mean, jump_std,
	jump_up_probability,
	jump_up_mean_reciprocal, jump_down_mean_reciprocal
;
int N;
bool call, digital, american, variable;
RectilinearGrid1 *grid;

ResultsTuple1 run(int k) {

	// 2^k or 2^(2k)
	int factor = 1;
	for(int i = 0; i < k; ++i) {
		if(american) { factor *= 4; }
		else         { factor *= 2; }
	}

	////////////////////////////////////////////////////////////////////////
	// Spatial grid
	////////////////////////////////////////////////////////////////////////

	// Refine grid R times
	auto refined_grid = grid->refined(k);

	////////////////////////////////////////////////////////////////////////
	// Payoff
	// ------
	//
	// Payoffs are lambda functions. The following is equivalent to
	//
	// auto payoff = [K] (Real S) {
	// 	return S < K ? K - S : 0.;
	// };
	////////////////////////////////////////////////////////////////////////

	auto payoff = callPayoff(K);

	////////////////////////////////////////////////////////////////////////
	// Iteration tree
	// --------------
	//
	// Sets up the loop structure:
	// for(int n = 0; n < N; ++n) {
	// 	// Solve a linear system
	// }
	////////////////////////////////////////////////////////////////////////

	ReverseConstantStepper stepper(
		0.,              // Initial time
		T,               // Expiry time
		T / (N * factor) // Timestep size
	);

	////////////////////////////////////////////////////////////////////////
	// Linear system tree
	// ------------------
	//
	// Makes the linear system to solve at each iteration
	////////////////////////////////////////////////////////////////////////

	auto jump_density = (jump_type == JumpType::merton) ?
		lognormal(
			jump_mean,
			jump_std
		) :
		doubleExponential(
			jump_up_probability,
			jump_up_mean_reciprocal,
			jump_down_mean_reciprocal
		)
	;

	BlackScholesJumpDiffusion1 bs(
		refined_grid,
		r,    // Interest
		vol,  // Volatility
		divs, // Dividend rate
		jump_arrival_rate, jump_density
	);
	bs.setIteration(stepper);

	typedef ReverseBDFOne Discretization;
	Discretization discretization(refined_grid, bs);
	discretization.setIteration(stepper);

	////////////////////////////////////////////////////////////////////////
	// Running
	// -------
	//
	// Everything prior to this was setup. Now we run the method.
	////////////////////////////////////////////////////////////////////////

	// Linear system solver
	SparseLUSolver solver;

	auto solution = stepper.solve(
		refined_grid,    // Domain
		payoff,         // Initial condition
		discretization, // Root of linear system tree
		solver          // Linear system solver
	);

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

	// Timesteps
	unsigned timesteps = stepper.iterations()[0];

	return ResultsTuple1(
		{ (Real) refined_grid.size(), (Real) timesteps, },
		solution, S_0
	);
}

int main(int argc, char **argv) {
	// Parse configuration file
	Configuration configuration = getConfiguration(argc, argv);

	// Get options
	int kn, k0;
	Real S_max, S_min, dS;
	kn = getInt(configuration, "maximum_refinement", 8);
	k0 = getInt(configuration, "minimum_refinement", 3);
	T = getReal(configuration, "time_to_expiry", .25);
	r = getReal(configuration, "interest_rate", .05);
	vol = getReal(configuration, "volatility", .15);
	divs = getReal(configuration, "dividend_rate", 0.);
	S_0 = getReal(configuration, "asset_price", 100.);
	K = getReal(configuration, "strike_price", 100.);
	S_min = getReal(configuration, "print_asset_price_minimum", 0.);
	S_max = getReal(configuration, "print_asset_price_maximum", S_0 * 2.);
	dS = getReal(configuration, "print_asset_price_step_size", S_0 / 10.);
	jump_arrival_rate = getReal(configuration, "jump_arrival_rate", .1);
	N = getInt(configuration, "initial_number_of_timesteps", 12);
	RectilinearGrid1 default_grid( (S_0 * Axis::special) + (K * Axis::special) );
	RectilinearGrid1 tmp = getGrid(configuration, "initial_grid", default_grid);
	grid = &tmp;
	string jump_type_str = getString(configuration, "jump_type", "lognormal");
	if(jump_type_str == "lognormal") {
		jump_type = JumpType::merton;
		jump_mean = getReal(configuration, "jump_amplitude_mean", -.1);
		jump_std = getReal(configuration, "jump_amplitude_deviation", .45);
	} else if(jump_type_str == "double_exponential") {
		jump_type = JumpType::kou;
		jump_up_probability = getReal(configuration, "jump_up_probability", .3445);
		jump_up_mean_reciprocal = getReal(configuration, "jump_up_mean_reciprocal", 3.0465);
		jump_down_mean_reciprocal = getReal(configuration, "jump_down_mean_reciprocal", 3.0775);
		// Exact solution with default parameters is 3.973479 at S = 100
	} else {
		cerr << "error: jump_model can either be \"lognormal\" or \"double_exponential\"" << endl;
		return 2;
	}

	// Print configuration file
	cerr << configuration << endl << endl;

	// Run and print results
	ResultsBuffer1 buffer(
		run,
		{ "Nodes", "Steps" },
		kn, k0
	);
	buffer.addPrintGrid( RectilinearGrid1(Axis::range(S_min, dS, S_max)) );
	buffer.stream();

	return 0;
}

<commit_msg>jump_diffusion.cpp: added more nodes for accuracy with up-jumps.<commit_after>////////////////////////////////////////////////////////////////////////////////
// jump_diffusion.cpp
// ------------------
//
// Computes the price of a European call with jump-diffusion driven by a Poisson
// process. The jump amplitude is assumed to be lognormally distributed.
//
// Author: Parsiad Azimzadeh
////////////////////////////////////////////////////////////////////////////////

#include <QuantPDE/Core>
#include <QuantPDE/Modules/Lambdas>
#include <QuantPDE/Modules/Operators>
#include <QuantPDE/Modules/Utilities>

using namespace QuantPDE;
using namespace QuantPDE::Modules;

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

#include <iostream> // cerr
#include <memory>   // unique_ptr

using namespace std;

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

enum JumpType { merton, kou };

JumpType jump_type;
Real
	T, r, vol, divs, S_0, K,
	jump_arrival_rate,
	jump_mean, jump_std,
	jump_up_probability,
	jump_up_mean_reciprocal, jump_down_mean_reciprocal
;
int N;
bool call, digital, variable;
RectilinearGrid1 *grid;

ResultsTuple1 run(int k) {

	// 2^k
	int factor = 1;
	for(int i = 0; i < k; ++i) {
		factor *= 2;
	}

	////////////////////////////////////////////////////////////////////////
	// Spatial grid
	////////////////////////////////////////////////////////////////////////

	// Refine grid R times
	auto refined_grid = grid->refined(k);

	////////////////////////////////////////////////////////////////////////
	// Payoff
	// ------
	//
	// Payoffs are lambda functions. The following is equivalent to
	//
	// auto payoff = [K] (Real S) {
	// 	return S < K ? K - S : 0.;
	// };
	////////////////////////////////////////////////////////////////////////

	auto payoff = callPayoff(K);

	////////////////////////////////////////////////////////////////////////
	// Iteration tree
	// --------------
	//
	// Sets up the loop structure:
	// for(int n = 0; n < N; ++n) {
	// 	// Solve a linear system
	// }
	////////////////////////////////////////////////////////////////////////

	ReverseConstantStepper stepper(
		0.,              // Initial time
		T,               // Expiry time
		T / (N * factor) // Timestep size
	);

	////////////////////////////////////////////////////////////////////////
	// Linear system tree
	// ------------------
	//
	// Makes the linear system to solve at each iteration
	////////////////////////////////////////////////////////////////////////

	auto jump_density = (jump_type == JumpType::merton) ?
		lognormal(
			jump_mean,
			jump_std
		) :
		doubleExponential(
			jump_up_probability,
			jump_up_mean_reciprocal,
			jump_down_mean_reciprocal
		)
	;

	BlackScholesJumpDiffusion1 bs(
		refined_grid,
		r,    // Interest
		vol,  // Volatility
		divs, // Dividend rate
		jump_arrival_rate, jump_density
	);
	bs.setIteration(stepper);

	typedef ReverseBDFOne Discretization;
	Discretization discretization(refined_grid, bs);
	discretization.setIteration(stepper);

	////////////////////////////////////////////////////////////////////////
	// Running
	// -------
	//
	// Everything prior to this was setup. Now we run the method.
	////////////////////////////////////////////////////////////////////////

	// Linear system solver
	SparseLUSolver solver;

	auto solution = stepper.solve(
		refined_grid,    // Domain
		payoff,         // Initial condition
		discretization, // Root of linear system tree
		solver          // Linear system solver
	);

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

	// Timesteps
	unsigned timesteps = stepper.iterations()[0];

	return ResultsTuple1(
		{ (Real) refined_grid.size(), (Real) timesteps, },
		solution, S_0
	);
}

int main(int argc, char **argv) {
	// Parse configuration file
	Configuration configuration = getConfiguration(argc, argv);

	// Get options
	int kn, k0;
	Real S_max, S_min, dS;
	kn = getInt(configuration, "maximum_refinement", 8);
	k0 = getInt(configuration, "minimum_refinement", 3);
	T = getReal(configuration, "time_to_expiry", .25);
	r = getReal(configuration, "interest_rate", .05);
	vol = getReal(configuration, "volatility", .15);
	divs = getReal(configuration, "dividend_rate", 0.);
	S_0 = getReal(configuration, "asset_price", 100.);
	K = getReal(configuration, "strike_price", 100.);
	S_min = getReal(configuration, "print_asset_price_minimum", 0.);
	S_max = getReal(configuration, "print_asset_price_maximum", S_0 * 2.);
	dS = getReal(configuration, "print_asset_price_step_size", S_0 / 10.);
	jump_arrival_rate = getReal(configuration, "jump_arrival_rate", .1);
	N = getInt(configuration, "initial_number_of_timesteps", 12);
	RectilinearGrid1 default_grid( (S_0 * Axis::special) + (K * Axis::special) + (S_0 * Axis { 1000. }) + (K * Axis { 1000. }) );
	RectilinearGrid1 tmp = getGrid(configuration, "initial_grid", default_grid);
	grid = &tmp;
	string jump_type_str = getString(configuration, "jump_type", "lognormal");
	if(jump_type_str == "lognormal") {
		jump_type = JumpType::merton;
		jump_mean = getReal(configuration, "jump_amplitude_mean", -.1);
		jump_std = getReal(configuration, "jump_amplitude_deviation", .45);
	} else if(jump_type_str == "double_exponential") {
		jump_type = JumpType::kou;
		jump_up_probability = getReal(configuration, "jump_up_probability", .3445);
		jump_up_mean_reciprocal = getReal(configuration, "jump_up_mean_reciprocal", 3.0465);
		jump_down_mean_reciprocal = getReal(configuration, "jump_down_mean_reciprocal", 3.0775);
		// Exact solution with default parameters is 3.973479 at S = 100
	} else {
		cerr << "error: jump_model can either be \"lognormal\" or \"double_exponential\"" << endl;
		return 2;
	}

	// Print configuration file
	cerr << configuration << endl << endl;

	// Run and print results
	ResultsBuffer1 buffer(
		run,
		{ "Nodes", "Steps" },
		kn, k0
	);
	buffer.addPrintGrid( RectilinearGrid1(Axis::range(S_min, dS, S_max)) );
	buffer.stream();

	return 0;
}

<|endoftext|>


<commit_before>#include "wrapper_py_optical_flow.h"
#include "../benchmarks.h"

#include "Halide.h"
#include "halide_image_io.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <stdlib.h>

int main(int, char**)
{
    std::vector<std::chrono::duration<double,std::milli>> duration_vector_1;
    std::vector<std::chrono::duration<double,std::milli>> duration_vector_2;

#if SYNTHETIC_INPUT
    Halide::Buffer<uint8_t> im1(SYNTHETIC_INPUT_SIZE, SYNTHETIC_INPUT_SIZE);
    Halide::Buffer<uint8_t> im2(SYNTHETIC_INPUT_SIZE, SYNTHETIC_INPUT_SIZE);

    for (int i = 0; i < SYNTHETIC_INPUT_SIZE; i++)
	    for (int j = 0; j < SYNTHETIC_INPUT_SIZE; j++)
	    {
		    im1(i, j) = (uint8_t) i*i+j*j;
		    im2(i, j) = (uint8_t) i*i+j*j;
	    }
#else
    Halide::Buffer<uint8_t> im1 = Halide::Tools::load_image("./utils/images/rgb.png");
    Halide::Buffer<uint8_t> im2 = Halide::Tools::load_image("./utils/images/rgb.png");
#endif

    Halide::Buffer<float> Ix_m(im1.width(), im1.height());
    Halide::Buffer<float> Iy_m(im1.width(), im1.height());
    Halide::Buffer<float> It_m(im1.width(), im1.height());
    Halide::Buffer<int> C1(_NC);
    Halide::Buffer<int> C2(_NC);
    Halide::Buffer<int> SIZES(2);
    Halide::Buffer<int> u(_NC);
    Halide::Buffer<int> v(_NC);
    Halide::Buffer<float> A(2, 4*w*w);
    Halide::Buffer<float> tA(4*w*w, 2);
    Halide::Buffer<double> pinvA(4*w*w, 2);
    Halide::Buffer<double> det(1);
    Halide::Buffer<float> tAA(2, 2);
    Halide::Buffer<double> X(2, 2);
    Halide::Buffer<uint8_t> pyramids1(im1.width(), im1.height(), npyramids);
    Halide::Buffer<uint8_t> pyramids2(im1.width(), im1.height(), npyramids);

    SIZES(0) = im1.height();
    SIZES(1) = im1.width();
#ifdef SYNTHETIC_INPUT
    C1(0) = 4; C2(0) = 5;
    C1(1) = 6; C2(1) = 6;
#else
    C1(0) = 500; C2(0) = 400;
    C1(1) = 800; C2(1) = 900;
    C1(2) = 200; C2(2) = 400;
    C1(3) = 400; C2(3) = 200;
    C1(4) = 400; C2(4) = 500;
    C1(5) = 800; C2(5) = 200;
    C1(6) = 200; C2(6) = 900;
    C1(7) = 900; C2(7) = 200;
#endif

    det(0) = 0;
    init_buffer(Ix_m, (float) 0);
    init_buffer(Iy_m, (float) 0);
    init_buffer(It_m, (float) 0);
    init_buffer(A, (float) 0);
    init_buffer(tA, (float) 0);
    init_buffer(pinvA, (double) 0);
    init_buffer(tAA, (float) 0);
    init_buffer(X, (double) 0);
    init_buffer(pyramids1, (uint8_t) 0);
    init_buffer(pyramids2, (uint8_t) 0);

    // Warm up
    py_optical_flow_tiramisu(SIZES.raw_buffer(), im1.raw_buffer(), im2.raw_buffer(),
			  Ix_m.raw_buffer(), Iy_m.raw_buffer(), It_m.raw_buffer(),
			  C1.raw_buffer(), C2.raw_buffer(), u.raw_buffer(), v.raw_buffer(),
			  A.raw_buffer(), pinvA.raw_buffer(), det.raw_buffer(), tAA.raw_buffer(),
			  tA.raw_buffer(), X.raw_buffer(), pyramids1.raw_buffer(), pyramids2.raw_buffer());

    // Tiramisu
    for (int i=0; i<NB_TESTS; i++)
    {
        auto start1 = std::chrono::high_resolution_clock::now();
        py_optical_flow_tiramisu(SIZES.raw_buffer(), im1.raw_buffer(), im2.raw_buffer(),
			  Ix_m.raw_buffer(), Iy_m.raw_buffer(), It_m.raw_buffer(),
			  C1.raw_buffer(), C2.raw_buffer(), u.raw_buffer(), v.raw_buffer(),
			  A.raw_buffer(), pinvA.raw_buffer(), det.raw_buffer(), tAA.raw_buffer(),
			  tA.raw_buffer(), X.raw_buffer(), pyramids1.raw_buffer(), pyramids2.raw_buffer());
        auto end1 = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double,std::milli> duration1 = end1 - start1;
        duration_vector_1.push_back(duration1);
    }

    std::cout << "Time: " << median(duration_vector_1) << std::endl;

#if SYNTHETIC_INPUT
    std::cout << "Im1 and Im2." << std::endl;
    print_buffer(im1);
    print_buffer(im2);

    std::cout << "Ix_m, Iy_m and It_m." << std::endl;
    print_buffer(Ix_m);
    print_buffer(Iy_m);
    print_buffer(It_m);

    std::cout << "A, tA, tAA, det." << std::endl;
    print_buffer(A);
    print_buffer(tA);
    print_buffer(tAA);
    print_buffer(det);

    std::cout << "X" << std::endl;
    print_buffer(X);

    std::cout << "pinvA" << std::endl;
    print_buffer(pinvA);

    std::cout << "pyramids1" << std::endl;
    print_buffer(pyramids1);
    std::cout << "pyramids2" << std::endl;
    print_buffer(pyramids2);
#endif

    std::cout << "Output" << std::endl;

    print_buffer(u);
    print_buffer(v);

    return 0;
}
<commit_msg>Update wrapper<commit_after>#include "wrapper_py_optical_flow.h"
#include "../benchmarks.h"

#include "Halide.h"
#include "halide_image_io.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <stdlib.h>

int main(int, char**)
{
    std::vector<std::chrono::duration<double,std::milli>> duration_vector_1;
    std::vector<std::chrono::duration<double,std::milli>> duration_vector_2;

#if SYNTHETIC_INPUT
    Halide::Buffer<uint8_t> im1(SYNTHETIC_INPUT_SIZE, SYNTHETIC_INPUT_SIZE);
    Halide::Buffer<uint8_t> im2(SYNTHETIC_INPUT_SIZE, SYNTHETIC_INPUT_SIZE);

    for (int i = 0; i < SYNTHETIC_INPUT_SIZE; i++)
	    for (int j = 0; j < SYNTHETIC_INPUT_SIZE; j++)
	    {
		    im1(i, j) = (uint8_t) i*i+j*j;
		    im2(i, j) = (uint8_t) i*i+j*j;
	    }
#else
    Halide::Buffer<uint8_t> im1 = Halide::Tools::load_image("./utils/images/rgb.png");
    Halide::Buffer<uint8_t> im2 = Halide::Tools::load_image("./utils/images/rgb.png");
#endif

    Halide::Buffer<float> Ix_m(im1.width(), im1.height());
    Halide::Buffer<float> Iy_m(im1.width(), im1.height());
    Halide::Buffer<float> It_m(im1.width(), im1.height());
    Halide::Buffer<int> C1(_NC);
    Halide::Buffer<int> C2(_NC);
    Halide::Buffer<int> SIZES(2);
    Halide::Buffer<int> u(_NC);
    Halide::Buffer<int> v(_NC);
    Halide::Buffer<float> A(2, 4*w*w);
    Halide::Buffer<float> tA(4*w*w, 2);
    Halide::Buffer<double> pinvA(4*w*w, 2);
    Halide::Buffer<double> det(1);
    Halide::Buffer<float> tAA(2, 2);
    Halide::Buffer<double> X(2, 2);
    Halide::Buffer<uint8_t> pyramids1(im1.width(), im1.height(), npyramids);
    Halide::Buffer<uint8_t> pyramids2(im1.width(), im1.height(), npyramids);

    SIZES(0) = im1.height();
    SIZES(1) = im1.width();
#ifdef SYNTHETIC_INPUT
    C1(0) = 4; C2(0) = 5;
    C1(1) = 6; C2(1) = 6;
#else
    C1(0) = 500; C2(0) = 400;
    C1(1) = 800; C2(1) = 900;
    C1(2) = 200; C2(2) = 400;
    C1(3) = 400; C2(3) = 200;
    C1(4) = 400; C2(4) = 500;
    C1(5) = 800; C2(5) = 200;
    C1(6) = 200; C2(6) = 900;
    C1(7) = 900; C2(7) = 200;
#endif

    det(0) = 0;
    init_buffer(Ix_m, (float) 0);
    init_buffer(Iy_m, (float) 0);
    init_buffer(It_m, (float) 0);
    init_buffer(A, (float) 0);
    init_buffer(tA, (float) 0);
    init_buffer(pinvA, (double) 0);
    init_buffer(tAA, (float) 0);
    init_buffer(X, (double) 0);
    init_buffer(pyramids1, (uint8_t) 0);
    init_buffer(pyramids2, (uint8_t) 0);

    // Warm up
    py_optical_flow_tiramisu(SIZES.raw_buffer(), im1.raw_buffer(), im2.raw_buffer(),
			  Ix_m.raw_buffer(), Iy_m.raw_buffer(), It_m.raw_buffer(),
			  C1.raw_buffer(), C2.raw_buffer(), u.raw_buffer(), v.raw_buffer(),
			  A.raw_buffer(), pinvA.raw_buffer(), det.raw_buffer(), tAA.raw_buffer(),
			  tA.raw_buffer(), X.raw_buffer(), pyramids1.raw_buffer(), pyramids2.raw_buffer());

    // Tiramisu
    for (int i=0; i<NB_TESTS; i++)
    {
        auto start1 = std::chrono::high_resolution_clock::now();
        py_optical_flow_tiramisu(SIZES.raw_buffer(), im1.raw_buffer(), im2.raw_buffer(),
			  Ix_m.raw_buffer(), Iy_m.raw_buffer(), It_m.raw_buffer(),
			  C1.raw_buffer(), C2.raw_buffer(), u.raw_buffer(), v.raw_buffer(),
			  A.raw_buffer(), pinvA.raw_buffer(), det.raw_buffer(), tAA.raw_buffer(),
			  tA.raw_buffer(), X.raw_buffer(), pyramids1.raw_buffer(), pyramids2.raw_buffer());
        auto end1 = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double,std::milli> duration1 = end1 - start1;
        duration_vector_1.push_back(duration1);
    }

    std::cout << "Time: " << median(duration_vector_1) << std::endl;

#if SYNTHETIC_INPUT
    std::cout << "Im1." << std::endl;
    print_buffer(im1);
    std::cout << "Im2." << std::endl;
    print_buffer(im2);

    std::cout << "pyramids1" << std::endl;
    print_buffer(pyramids1);
    std::cout << "pyramids2" << std::endl;
    print_buffer(pyramids2);

    std::cout << "Ix_m." << std::endl;
    print_buffer(Ix_m);
    std::cout << "Iy_m." << std::endl;
    print_buffer(Iy_m);
    std::cout << "It_m." << std::endl;
    print_buffer(It_m);

    std::cout << "A." << std::endl;
    print_buffer(A);
    std::cout << "tA." << std::endl;
    print_buffer(tA);
    std::cout << "tAA." << std::endl;
    print_buffer(tAA);
    std::cout << "det." << std::endl;
    print_buffer(det);

    std::cout << "X" << std::endl;
    print_buffer(X);

    std::cout << "pinvA" << std::endl;
    print_buffer(pinvA);
#endif

    std::cout << "Output" << std::endl;
    print_buffer(u);
    print_buffer(v);

    return 0;
}
<|endoftext|>


<commit_before>// $Id$
/**
 * @file streamerinfo-from-raw.C
 * @brief Extract the streamer info for a raw file and AliRoot version
 *
 * This macro generates the streamer info for all objects in the HLTOUT
 * payload of the specified raw file. The AliRoot version of the when
 * running this macro needs to be the same as the HLTOUT payload was
 * generatted with.
 *
 * The macro has two optional parameters:
 * - filename:  default 'raw://'
 * - OCDB URI:  default 'raw.root'
 *
 * If either file or URI refers to the GRID, the macro connects to alien.
 * Make sure that ROOT is compiled with ALIEN support and that the required
 * alien API libraries can be loaded.
 *
 * You can run this macro with defaults using the following shell command:
 * @code
 *   > aliroot -b -q $ALICE_ROOT/HLT/rec/streamerinfo-from-raw.C
 * @endcode
 * With a raw file from the GRID
 * @code
 *   > aliroot -b -q streamerinfo-from-raw.C'("alien:///alice/data/2009/LHC09d/000102925/raw/09000102925035.10.root")'
 * @endcode
 *
 * Streamer info is stored in a TObjArray wrapped into an AliCDBEntry
 * object, and stored to HLT.StreamerInfo.root. This file can be used
 * directly as OCDB object, it just needs to be renamed.
 *
 * @author Matthias.Richter@ift.uib.no
 */
void streamerinfo_from_raw(const char *filename="raw.root", const char* cdbUri="raw://")
{
  TString tmpStr1=filename;
  TString tmpStr2=cdbUri;
  if ((tmpStr1.Contains("://") && !tmpStr1.BeginsWith("local://")) ||
      !tmpStr2.BeginsWith("local://")) {
    // setup the GRID connection if raw file or OCDB are from GRID
    TGrid::Connect("alien");
  }

  // Set the CDB storage location
  AliCDBManager * man = AliCDBManager::Instance();
  man->SetDefaultStorage(cdbUri);

  // Reconstruction settings
  AliReconstruction rec;
  rec.SetRunPlaneEff(kFALSE);
  rec.SetCleanESD(kFALSE);

  rec.SetInput(filename);
  rec.SetRunReconstruction("HLT");
  rec.SetOption("HLT","skip-hltout chains=schemaevo");

  AliHLTSystem* pHLT=AliHLTPluginBase::GetInstance();
  AliHLTConfiguration publisher("hltout-publisher", "AliHLTOUTPublisher" , NULL, "");
  AliHLTConfiguration collector("schemaevo", "ROOTSchemaEvolutionComponent"   , "hltout-publisher", "-file=HLT.StreamerInfo.root");

  // QA options
  rec.SetRunQA(":") ;

  AliLog::Flush();
  rec.Run();
}
<commit_msg>minor update in macro documentation<commit_after>// $Id$
/**
 * @file streamerinfo-from-raw.C
 * @brief Extract the streamer info for a raw file and AliRoot version
 *
 * This macro generates the streamer info for all objects in the HLTOUT
 * payload of the specified raw file. The AliRoot version needs to be the
 * same as the one the HLTOUT payload was generated with.
 *
 * The macro has two optional parameters:
 * - filename:  default 'raw://'
 * - OCDB URI:  default 'raw.root'
 *
 * If either file or URI refers to the GRID, the macro connects to alien.
 * Make sure that ROOT is compiled with ALIEN support and that the required
 * alien API libraries can be loaded.
 *
 * You can run this macro with defaults using the following shell command:
 * @code
 *   > aliroot -b -q $ALICE_ROOT/HLT/rec/streamerinfo-from-raw.C
 * @endcode
 * With a raw file from the GRID
 * @code
 *   > aliroot -b -q streamerinfo-from-raw.C'("alien:///alice/data/2009/LHC09d/000102925/raw/09000102925035.10.root")'
 * @endcode
 *
 * Streamer info is stored in a TObjArray wrapped into an AliCDBEntry
 * object, and stored to HLT.StreamerInfo.root. This file can be used
 * directly as OCDB object, it just needs to be renamed.
 *
 * @author Matthias.Richter@ift.uib.no
 */
void streamerinfo_from_raw(const char *filename="raw.root", const char* cdbUri="raw://")
{
  TString tmpStr1=filename;
  TString tmpStr2=cdbUri;
  if ((tmpStr1.Contains("://") && !tmpStr1.BeginsWith("local://")) ||
      !tmpStr2.BeginsWith("local://")) {
    // setup the GRID connection if raw file or OCDB are from GRID
    TGrid::Connect("alien");
  }

  // Set the CDB storage location
  AliCDBManager * man = AliCDBManager::Instance();
  man->SetDefaultStorage(cdbUri);

  // Reconstruction settings
  AliReconstruction rec;
  rec.SetRunPlaneEff(kFALSE);
  rec.SetCleanESD(kFALSE);

  rec.SetInput(filename);
  rec.SetRunReconstruction("HLT");
  rec.SetOption("HLT","skip-hltout chains=schemaevo");

  AliHLTSystem* pHLT=AliHLTPluginBase::GetInstance();
  AliHLTConfiguration publisher("hltout-publisher", "AliHLTOUTPublisher" , NULL, "");
  AliHLTConfiguration collector("schemaevo", "ROOTSchemaEvolutionComponent"   , "hltout-publisher", "-file=HLT.StreamerInfo.root");

  // QA options
  rec.SetRunQA(":") ;

  AliLog::Flush();
  rec.Run();
}
<|endoftext|>


<commit_before>/**
 * projectM -- Milkdrop-esque visualisation SDK
 * Copyright (C)2003-2004 projectM Team
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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
 * See 'LICENSE.txt' included within this release
 *
 */
/**
 * $Id: pbuffer.c,v 1.1.1.1 2005/12/23 18:05:00 psperl Exp $
 *
 * Render target methods
 */

#include <stdio.h>
//#include <GL/gl.h>

#include "common.h"
#include "pbuffer.h"

#ifdef MACOS
#include <agl.h>
#endif /** MACOS */

/** Creates new pbuffers */
void createPBuffers( int width, int height, RenderTarget *target ) {

    int mindim = 0;
    int origtexsize = 0;

    printf( "createPBuffers()\n" );
#ifdef FBO
    printf( "FBO init\n" );
    DWRITE( "FBO init: usePbuffers: %d\n", target->usePbuffers );
    if(target->usePbuffers)
      {
	glewInit();

	GLuint   fb, color_rb, depth_rb, rgba_tex, depth_tex, i, other_tex;
	glGenFramebuffersEXT(1, &fb);
	glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, fb );

	glGenRenderbuffersEXT(1, &depth_rb);
	glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, depth_rb );
	glRenderbufferStorageEXT( GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24, target->texsize,target->texsize  );
	glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_rb );
	target->fbuffer[0] = depth_rb;

	glGenTextures(1, &other_tex);
	glBindTexture(GL_TEXTURE_2D,other_tex);
 	glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, target->texsize, target->texsize, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL );
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	//glGenerateMipmapEXT(GL_TEXTURE_2D);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

	glGenTextures(1, &rgba_tex);
	glBindTexture(GL_TEXTURE_2D, rgba_tex);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, target->texsize, target->texsize, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL );
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	//glGenerateMipmapEXT(GL_TEXTURE_2D);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

	glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, rgba_tex, 0 );
	target->textureID[0] = rgba_tex;
	target->textureID[1] = other_tex;

	GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
	if (status == GL_FRAMEBUFFER_COMPLETE_EXT) return;
	else goto fallback;
      }

#endif

#ifdef MACOS2
#ifdef MACOSX_10_3
    /** PBuffers are only supported in MacOS X 10.3+ */
    AGLPbuffer pbuffer, pbuffer2;
    AGLPixelFormat pixelFormat;
    AGLContext context;
    GLint attrib[] =
        { AGL_RGBA, AGL_PIXEL_SIZE, 32, AGL_ACCELERATED, AGL_NONE };

    pixelFormat = aglChoosePixelFormat( NULL, 0, attrib );
    if ( pixelFormat == NULL ) {

        goto fallback;
      } else {

      }

    /** Fetch the original context for rendering directly */
    /** Only AGL can be used, otherwise, it'll fall back to texhack */
    /** Try AGL first */
    target->origContext = (void *)aglGetCurrentContext();
    if ( target->origContext == NULL ) {
        /** Try NSGL */
//        target->origContext = (void *)nsglGetCurrentContext();
        target->origContext = NULL;
        if ( target->origContext == NULL ) {
            /** Try CGL */
            target->origContext = (void *)CGLGetCurrentContext();
            if ( target->origContext != NULL ) {
                target->origContext = NULL;
                target->origContextType = CGL_CONTEXT;
              }
          } else {
            target->origContext = NULL;
            target->origContextType = NSGL_CONTEXT;
          }
      } else {
        target->origContextType = AGL_CONTEXT;
      }

    /**
     * If we can't stash the original context for switching, don't use
     * pbuffers
     */
    if ( target->origContext == NULL ) {

        goto fallback;
      } else {

      }

    context = aglCreateContext( pixelFormat, target->origContext );
    if ( context == NULL ) {

        aglDestroyPixelFormat( pixelFormat );
        goto fallback;
      } else {
        aglDestroyPixelFormat( pixelFormat );

      }

    /** Stash the context and pbuffer */
    target->pbufferContext = (void *)context;

    /** Create the pass1 pbuffer */
    aglCreatePBuffer( target->texsize, target->texsize, GL_TEXTURE_2D,
                      GL_RGBA, 0, &pbuffer );
    if ( pbuffer == NULL ) {

      } else {
        target->pbuffer = pbuffer;

      }

    /** Finally, bind the target texture ID */
    aglSetCurrentContext( target->origContext );
    glGenTextures( 2, &target->textureID[0] );

    glBindTexture( GL_TEXTURE_2D, target->textureID[0] );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );

    if ( aglTexImagePBuffer( target->origContext, target->pbuffer, GL_FRONT ) == 0 ) {

      }
    glBindTexture( GL_TEXTURE_2D, 0 );

    glBindTexture( GL_TEXTURE_2D, target->textureID[1] );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glTexImage2D(GL_TEXTURE_2D,
		    0,
		    GL_RGB,
		    target->texsize, target->texsize,
		    0,
		    GL_RGB,
		    GL_UNSIGNED_BYTE,
		    NULL);
    glBindTexture( GL_TEXTURE_2D, 0 );

    glBindTexture( GL_TEXTURE_2D, target->textureID[0] );

    return;

#endif /** MACOSX_10_3 */

    goto fallback;

#else
#endif /** !MACOS */

    /** Successful creation */
    // return;

fallback:
    DWRITE( "using teximage hack fallback\n" );

    /** Fallback pbuffer creation via teximage hack */
    /** Check the texture size against the viewport size */
    /** If the viewport is smaller, then we'll need to scale the texture size down */
    /** If the viewport is larger, scale it up */
    mindim = width < height ? width : height;
    origtexsize = target->texsize;
    target->texsize = nearestPower2( mindim, SCALE_MINIFY );

    /* Create the texture that will be bound to the render target */
    if ( glIsTexture( target->textureID[0] ) ) {
        DWRITE( "texture already exists\n" );
        if ( target->texsize != origtexsize ) {
            DWRITE( "deleting existing texture due to resize\n" );
            glDeleteTextures( 1, &target->textureID[0] );
          }
      }

    if ( !glIsTexture( target->textureID[0] ) ) {
        glGenTextures(1, &target->textureID[0] );

        DWRITE( "allocate texture: %d\ttexsize: %d x %d\n",
                target->textureID[0], target->texsize, target->texsize );
        glBindTexture(GL_TEXTURE_2D, target->textureID[0] );
        //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

        glTexImage2D(GL_TEXTURE_2D,
		    0,
		    3,
		    target->texsize, target->texsize,
		    0,
		    GL_RGB,
		    GL_UNSIGNED_BYTE,
		    NULL);
      }
    return;
  }

/** Destroys the pbuffer */

/** Locks the pbuffer */
void lockPBuffer( RenderTarget *target, PBufferPass pass ) {

#ifdef FBO
  if(target->usePbuffers)
    {
      glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, target->fbuffer[0]);
    }

#endif

#ifdef MACOS2
    if ( target->pbufferContext != NULL &&
         target->pbuffer != NULL ) {
        GLint vs;
        DWRITE( "-> locking pbuffer: %d\n", pass );
        if ( !aglSetCurrentContext( (AGLContext)target->pbufferContext ) ) {
            DWRITE( "lockPBuffer(): failed to set context\n" );
          }
        vs = aglGetVirtualScreen ( (AGLContext)target->origContext );
        if ( pass == PBUFFER_PASS1 ) {
            aglSetPBuffer( (AGLContext)target->pbufferContext, (AGLPbuffer)target->pbuffer, 0, 0, vs );
//            glBindTexture( GL_TEXTURE_2D, target->textureID[0] );
          }
      }
#endif
  }

/** Unlocks the pbuffer */
void unlockPBuffer( RenderTarget *target ) {

#ifdef FBO

  if(target->usePbuffers)
    {
      glBindTexture( GL_TEXTURE_2D, target->textureID[1] );
      glCopyTexSubImage2D( GL_TEXTURE_2D,
                         0, 0, 0, 0, 0,
                         target->texsize, target->texsize );
      glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
      return;
    }

#endif

#ifdef MACOS2
    if ( target->pbufferContext != NULL &&
         target->pbuffer != NULL ) {
        DWRITE( "<- unlocking pbuffer\n" );

        /** Flush the pbuffer */
        glFlush();

        /** Reset the texture ID to the pbuffer */
        glBindTexture( GL_TEXTURE_2D, target->textureID[0] );
        glBindTexture( GL_TEXTURE_2D, 0 );
        glBindTexture( GL_TEXTURE_2D, target->textureID[1] );
        glCopyTexSubImage2D( GL_TEXTURE_2D,
                             0, 0, 0, 0, 0,
                             target->texsize, target->texsize );
        glBindTexture( GL_TEXTURE_2D, 0 );
        glBindTexture( GL_TEXTURE_2D, target->textureID[0] );

        /** Reset the OpenGL context to the original context */
        aglSetCurrentContext( NULL );
        if ( target->origContext != NULL ) {
            if ( !aglSetCurrentContext( target->origContext ) ) {
                DWRITE( "failed to setting origContext current\n" );
              } else {
                DWRITE( "setting origContext current\n" );
              }
          }

        return;
     }
#endif

    /** Fallback texture path */
    DWRITE( "copying framebuffer to texture\n" );
    glBindTexture( GL_TEXTURE_2D, target->textureID[0] );
    glCopyTexSubImage2D( GL_TEXTURE_2D,
                         0, 0, 0, 0, 0,
                         target->texsize, target->texsize );
  }

/**
 * Calculates the nearest power of two to the given number using the
 * appropriate rule
 */
int nearestPower2( int value, TextureScale scaleRule ) {

    int x = value;
    int power = 0;

    DWRITE( "nearestPower2(): %d\n", value );

    while ( ( x & 0x01 ) != 1 ) {
        x >>= 1;
      }

    if ( x == 1 ) {
        return value;
      } else {
        x = value;
        while ( x != 0 ) {
            x >>= 1;
            power++;
          }
        switch ( scaleRule ) {
            case SCALE_NEAREST:
                if ( ( ( 1 << power ) - value ) <= ( value - ( 1 << ( power - 1 ) ) ) ) {
                    return 1 << power;
                  } else {
                    return 1 << ( power - 1 );
                  }
            case SCALE_MAGNIFY:
                return 1 << power;
            case SCALE_MINIFY:
                return 1 << ( power - 1 );
            default:
                break;
          }
      }
    return 0;
  }

<commit_msg>Updated fallthrough logic for failing FBO to teximage hack. Renamed FBO to USE_FBO. Removed old AGL pbuffering paths<commit_after>/**
 * projectM -- Milkdrop-esque visualisation SDK
 * Copyright (C)2003-2004 projectM Team
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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
 * See 'LICENSE.txt' included within this release
 *
 */
/**
 * $Id: pbuffer.c,v 1.1.1.1 2005/12/23 18:05:00 psperl Exp $
 *
 * Render target methods
 */

#include <stdio.h>
//#include <GL/gl.h>

#include "common.h"
#include "pbuffer.h"

#ifdef MACOS
#include <agl.h>
#endif /** MACOS */

/** Creates new pbuffers */
void createPBuffers( int width, int height, RenderTarget *target ) {

    int mindim = 0;
    int origtexsize = 0;

#ifdef USE_FBO
    DWRITE( "FBO init: usePbuffers: %d\n", target->usePbuffers );
    if(target->usePbuffers) {
	    glewInit();

	    GLuint   fb, color_rb, depth_rb, rgba_tex, depth_tex, i, other_tex;
	    glGenFramebuffersEXT(1, &fb);
	    glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, fb );

	    glGenRenderbuffersEXT(1, &depth_rb);
	    glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, depth_rb );
	    glRenderbufferStorageEXT( GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24, target->texsize,target->texsize  );
	    glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_rb );
	    target->fbuffer[0] = depth_rb;

	    glGenTextures(1, &other_tex);
	    glBindTexture(GL_TEXTURE_2D,other_tex);
 	    glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, target->texsize, target->texsize, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL );
	    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	    //glGenerateMipmapEXT(GL_TEXTURE_2D);
	    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
	    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

	    glGenTextures(1, &rgba_tex);
	    glBindTexture(GL_TEXTURE_2D, rgba_tex);
	    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	    glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, target->texsize, target->texsize, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL );
	    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	    //glGenerateMipmapEXT(GL_TEXTURE_2D);
	    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
	    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

	    glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, rgba_tex, 0 );
	    target->textureID[0] = rgba_tex;
	    target->textureID[1] = other_tex;

	    GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
	    if (status == GL_FRAMEBUFFER_COMPLETE_EXT) {
	        return;
	      }
      }
#endif

fallback:
    DWRITE( "using teximage hack fallback\n" );

    /** Fallback pbuffer creation via teximage hack */
    /** Check the texture size against the viewport size */
    /** If the viewport is smaller, then we'll need to scale the texture size down */
    /** If the viewport is larger, scale it up */
    mindim = width < height ? width : height;
    origtexsize = target->texsize;
    target->texsize = nearestPower2( mindim, SCALE_MINIFY );

    /* Create the texture that will be bound to the render target */
    if ( glIsTexture( target->textureID[0] ) ) {
        DWRITE( "texture already exists\n" );
        if ( target->texsize != origtexsize ) {
            DWRITE( "deleting existing texture due to resize\n" );
            glDeleteTextures( 1, &target->textureID[0] );
          }
      }

    if ( !glIsTexture( target->textureID[0] ) ) {
        glGenTextures(1, &target->textureID[0] );

        DWRITE( "allocate texture: %d\ttexsize: %d x %d\n",
                target->textureID[0], target->texsize, target->texsize );
        glBindTexture(GL_TEXTURE_2D, target->textureID[0] );
        //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

        glTexImage2D(GL_TEXTURE_2D,
		    0,
		    3,
		    target->texsize, target->texsize,
		    0,
		    GL_RGB,
		    GL_UNSIGNED_BYTE,
		    NULL);
      }

    target->usePbuffers = 0;

    return;
  }

/** Destroys the pbuffer */

/** Locks the pbuffer */
void lockPBuffer( RenderTarget *target, PBufferPass pass ) {

#ifdef USE_FBO
  if(target->usePbuffers)
    {
      glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, target->fbuffer[0]);
    }

#endif
  }

/** Unlocks the pbuffer */
void unlockPBuffer( RenderTarget *target ) {

#ifdef USE_FBO
  if(target->usePbuffers)
    {
      glBindTexture( GL_TEXTURE_2D, target->textureID[1] );
      glCopyTexSubImage2D( GL_TEXTURE_2D,
                         0, 0, 0, 0, 0,
                         target->texsize, target->texsize );
      glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
      return;
    }

#endif

    /** Fallback texture path */
    DWRITE( "copying framebuffer to texture\n" );
    glBindTexture( GL_TEXTURE_2D, target->textureID[0] );
    glCopyTexSubImage2D( GL_TEXTURE_2D,
                         0, 0, 0, 0, 0,
                         target->texsize, target->texsize );
  }

/**
 * Calculates the nearest power of two to the given number using the
 * appropriate rule
 */
int nearestPower2( int value, TextureScale scaleRule ) {

    int x = value;
    int power = 0;

    DWRITE( "nearestPower2(): %d\n", value );

    while ( ( x & 0x01 ) != 1 ) {
        x >>= 1;
      }

    if ( x == 1 ) {
        return value;
      } else {
        x = value;
        while ( x != 0 ) {
            x >>= 1;
            power++;
          }
        switch ( scaleRule ) {
            case SCALE_NEAREST:
                if ( ( ( 1 << power ) - value ) <= ( value - ( 1 << ( power - 1 ) ) ) ) {
                    return 1 << power;
                  } else {
                    return 1 << ( power - 1 );
                  }
            case SCALE_MAGNIFY:
                return 1 << power;
            case SCALE_MINIFY:
                return 1 << ( power - 1 );
            default:
                break;
          }
      }
    return 0;
  }
<|endoftext|>


<commit_before>/**
 * The Seeks proxy and plugin framework are part of the SEEKS project.
 * Copyright (C) 2011 Emmanuel Benazera, ebenazer@seeks-project.info
 *
 * This program 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.
 *
 * This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "user_db.h"
#include "user_db_fix.h"
#include "seeks_proxy.h"
#include "proxy_configuration.h"
#include "miscutil.h"
#include "errlog.h"
#include "plugin_manager.h"

#include <iostream>
#include <fstream>
#include <stdlib.h>

using namespace sp;

std::string get_usage()
{
  std::string usage = "Usage: <db_file> <seeks base dir> <command>\n";
  usage += "commands:\n";
  usage += "remove_non_utf8\t\tRemoves non UTF8 queries and URLs\n";
  usage += "optimize\t\tOptimizes database, weeding out blank space\n";
  usage += "fetch_urls\t\tfetch URL titles for URLs captured along with queries\n";
  usage += "merge\t\t\tmerge records with those of another DB\n\t\t\tUsage: <db_file> <seeks base dir> <command> <db to merge>";
  return usage;
}

int main(int argc, char **argv)
{
  if (argc < 5)
    {
      std::cout << get_usage() << std::endl;
      exit(0);
    }

  std::string dbfile = argv[1];
  std::string basedir = argv[2];
  std::string command = argv[3];

  if (command.empty())
    {
      std::cout << get_usage() << std::endl;
      exit(0);
    }

  //seeks_proxy::_configfile = basedir + "/config";
  seeks_proxy::initialize_mutexes();
  errlog::init_log_module();
  errlog::set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO | LOG_LEVEL_DEBUG);

  seeks_proxy::_basedir = basedir.c_str();
  plugin_manager::_plugin_repository = basedir + "/plugins/";
  seeks_proxy::_config = new proxy_configuration(seeks_proxy::_configfile);
  seeks_proxy::_config->_user_db_file = dbfile;
  seeks_proxy::_config->_user_db_startup_check = false;
  seeks_proxy::_config->_user_db_optimize = false;

  seeks_proxy::_user_db = new user_db(dbfile);
  seeks_proxy::_user_db->open_db();

  plugin_manager::load_all_plugins();
  plugin_manager::start_plugins();

  if (command == "remove_non_utf8")
    {
      seeks_proxy::_user_db->close_db();
      user_db_fix::fix_issue_154();
    }
  else if (command == "optimize")
    {
      seeks_proxy::_user_db->optimize_db();
      seeks_proxy::_user_db->close_db();
    }
  else if (command == "fetch_urls")
    {
      seeks_proxy::_user_db->close_db();
      std::string ua = "user-agent: ";
      std::string uacust = "Mozilla/5.0 (X11; Linux x86_64; rv:2.0.1) Gecko/20100101 Firefox/4.0.1";
      ua += uacust;
      long timeout = 5;
      std::vector<std::list<const char*>*> headers;
      std::list<const char*> *lheaders = new std::list<const char*>();
      miscutil::enlist(lheaders,ua.c_str());
      headers.push_back(lheaders);
      user_db_fix::fill_up_uri_titles(timeout,&headers);
      for (size_t i=0; i<headers.size(); i++)
        {
          miscutil::list_remove_all(headers.at(i));
          delete headers.at(i);
        }
    }
  else if (command == "merge")
    {
      std::string dbtomerge = argv[4];
      std::cout << "db to merge: " << dbtomerge << std::endl;
      //seeks_proxy::_user_db->close_db();
      user_db_fix::merge_with(dbtomerge.c_str());
    }
  else
    {
      std::cout << "unknown command: " << command << std::endl;
      std::cout << get_usage() << std::endl;
      seeks_proxy::_user_db->close_db();
    }
}
<commit_msg>fixed wrong number of argument check in user db op util<commit_after>/**
 * The Seeks proxy and plugin framework are part of the SEEKS project.
 * Copyright (C) 2011 Emmanuel Benazera, ebenazer@seeks-project.info
 *
 * This program 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.
 *
 * This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "user_db.h"
#include "user_db_fix.h"
#include "seeks_proxy.h"
#include "proxy_configuration.h"
#include "miscutil.h"
#include "errlog.h"
#include "plugin_manager.h"

#include <iostream>
#include <fstream>
#include <stdlib.h>

using namespace sp;

std::string get_usage()
{
  std::string usage = "Usage: <db_file> <seeks base dir> <command>\n";
  usage += "commands:\n";
  usage += "remove_non_utf8\t\tRemoves non UTF8 queries and URLs\n";
  usage += "optimize\t\tOptimizes database, weeding out blank space\n";
  usage += "fetch_urls\t\tfetch URL titles for URLs captured along with queries\n";
  usage += "merge\t\t\tmerge records with those of another DB\n\t\t\tUsage: <db_file> <seeks base dir> <command> <db to merge>";
  return usage;
}

int main(int argc, char **argv)
{
  if (argc < 4)
    {
      std::cout << get_usage() << std::endl;
      exit(0);
    }

  std::string dbfile = argv[1];
  std::string basedir = argv[2];
  std::string command = argv[3];

  if (command.empty())
    {
      std::cout << get_usage() << std::endl;
      exit(0);
    }

  //seeks_proxy::_configfile = basedir + "/config";
  seeks_proxy::initialize_mutexes();
  errlog::init_log_module();
  errlog::set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO | LOG_LEVEL_DEBUG);

  seeks_proxy::_basedir = basedir.c_str();
  plugin_manager::_plugin_repository = basedir + "/plugins/";
  seeks_proxy::_config = new proxy_configuration(seeks_proxy::_configfile);
  seeks_proxy::_config->_user_db_file = dbfile;
  seeks_proxy::_config->_user_db_startup_check = false;
  seeks_proxy::_config->_user_db_optimize = false;

  seeks_proxy::_user_db = new user_db(dbfile);
  seeks_proxy::_user_db->open_db();

  plugin_manager::load_all_plugins();
  plugin_manager::start_plugins();

  if (command == "remove_non_utf8")
    {
      seeks_proxy::_user_db->close_db();
      user_db_fix::fix_issue_154();
    }
  else if (command == "optimize")
    {
      seeks_proxy::_user_db->optimize_db();
      seeks_proxy::_user_db->close_db();
    }
  else if (command == "fetch_urls")
    {
      seeks_proxy::_user_db->close_db();
      std::string ua = "user-agent: ";
      std::string uacust = "Mozilla/5.0 (X11; Linux x86_64; rv:2.0.1) Gecko/20100101 Firefox/4.0.1";
      ua += uacust;
      long timeout = 5;
      std::vector<std::list<const char*>*> headers;
      std::list<const char*> *lheaders = new std::list<const char*>();
      miscutil::enlist(lheaders,ua.c_str());
      headers.push_back(lheaders);
      user_db_fix::fill_up_uri_titles(timeout,&headers);
      for (size_t i=0; i<headers.size(); i++)
        {
          miscutil::list_remove_all(headers.at(i));
          delete headers.at(i);
        }
    }
  else if (command == "merge")
    {
      std::string dbtomerge = argv[4];
      std::cout << "db to merge: " << dbtomerge << std::endl;
      //seeks_proxy::_user_db->close_db();
      user_db_fix::merge_with(dbtomerge.c_str());
    }
  else
    {
      std::cout << "unknown command: " << command << std::endl;
      std::cout << get_usage() << std::endl;
      seeks_proxy::_user_db->close_db();
    }
}
<|endoftext|>


<commit_before>//=============================================================================
// ■ terminal.cpp
//-----------------------------------------------------------------------------
//   字符模式显卡驱动。
//=============================================================================

namespace Terminal {
	//---------------------------------------------------------------------------
	// ● 定义类型
	//---------------------------------------------------------------------------
	enum color {
		BLACK = 0,
		NAVY = 1,
		GREEN = 2,
		TEAL = 3,
		MAROON = 4,
		PURPLE = 5,
		OLIVE = 6,
		SILVER = 7,
		GRAY = 8,
		BLUE = 9,
		LIME = 10,
		AQUA = 11,
		RED = 12,
		FUCHSIA = 13,
		YELLOW = 14,
		WHITE = 15,
	};
	struct char_color {
		enum color bg, fg;
	};

	//---------------------------------------------------------------------------
	// ● 定义变量
	//---------------------------------------------------------------------------
	unsigned int width;
	unsigned int height;
	static int cursor_x;
	static int cursor_y;

	//---------------------------------------------------------------------------
	// ● 计算显示位置的内存地址
	//---------------------------------------------------------------------------
	inline type_address memory_address(struct pos pos) {
		return 0xb8000 + (pos.x + pos.y * width) * 2;
	}

	//---------------------------------------------------------------------------
	// ● 移动光标
	//---------------------------------------------------------------------------
	void set_pos(struct pos pos) {
		cursor_x = pos.x;
		cursor_y = pos.y;
		uint8_t pos_info = pos.x + pos.y * width;
		asm_out8(0x03d4, 14);
		asm_out8(0x03d5, pos_info >> 8);
		asm_out8(0x03d4, 15);
		asm_out8(0x03d5, pos_info & 0xff);
	}

	//---------------------------------------------------------------------------
	// ● 写出一个字符
	//   pos : 目标字符的位置
	//   c : 字符
	//   color : 字符的颜色
	//---------------------------------------------------------------------------
	void write_char(struct pos pos, char c, struct char_color color) {
		type_address address = memory_address(pos);
		write_memory(address, c);
		unsigned char attribute = 1 << 7 | color.bg << 4 | color.fg;
		write_memory(address + 1, attribute);
	}
}
<commit_msg>修正注释格式<commit_after>//=============================================================================
// ■ terminal.cpp
//-----------------------------------------------------------------------------
//   字符模式显卡驱动。
//=============================================================================

namespace Terminal {
	//-------------------------------------------------------------------------
	// ● 定义类型
	//-------------------------------------------------------------------------
	enum color {
		BLACK = 0,
		NAVY = 1,
		GREEN = 2,
		TEAL = 3,
		MAROON = 4,
		PURPLE = 5,
		OLIVE = 6,
		SILVER = 7,
		GRAY = 8,
		BLUE = 9,
		LIME = 10,
		AQUA = 11,
		RED = 12,
		FUCHSIA = 13,
		YELLOW = 14,
		WHITE = 15,
	};
	struct char_color {
		enum color bg, fg;
	};

	//-------------------------------------------------------------------------
	// ● 定义变量
	//-------------------------------------------------------------------------
	unsigned int width;
	unsigned int height;
	static int cursor_x;
	static int cursor_y;

	//-------------------------------------------------------------------------
	// ● 计算显示位置的内存地址
	//-------------------------------------------------------------------------
	inline type_address memory_address(struct pos pos) {
		return 0xb8000 + (pos.x + pos.y * width) * 2;
	}

	//-------------------------------------------------------------------------
	// ● 移动光标
	//-------------------------------------------------------------------------
	void set_pos(struct pos pos) {
		cursor_x = pos.x;
		cursor_y = pos.y;
		uint8_t pos_info = pos.x + pos.y * width;
		asm_out8(0x03d4, 14);
		asm_out8(0x03d5, pos_info >> 8);
		asm_out8(0x03d4, 15);
		asm_out8(0x03d5, pos_info & 0xff);
	}

	//-------------------------------------------------------------------------
	// ● 写出一个字符
	//   pos : 目标字符的位置
	//   c : 字符
	//   color : 字符的颜色
	//-------------------------------------------------------------------------
	void write_char(struct pos pos, char c, struct char_color color) {
		type_address address = memory_address(pos);
		write_memory(address, c);
		unsigned char attribute = 1 << 7 | color.bg << 4 | color.fg;
		write_memory(address + 1, attribute);
	}
}
<|endoftext|>


<commit_before>//
//  causticdata.cpp
//  SLsimLib
//
//  Created by bmetcalf on 5/6/13.
//
//

#include "causticdata.h"

CausticData::CausticData(std::string filename){
  ncolumns = 13;
  readfile(filename);
}
CausticData::CausticData(size_t size){
  ncolumns = 13;

  data.resize(size);
/*  redshifts.resize(size);
  crit_centers.reserve(size);
  caustic_centers.resize(size);

  crit_radius.resize(size);
  caustic_radius.resize(size);

  crit_area.resize(size);
  caustic_area.resize(size);

  for(size_t i = 0; i < size ; ++i){
    crit_centers[i] = new double[2];
    crit_radius[i] = new double[3];
    caustic_centers[i] = new double[2];
    caustic_radius[i] = new double[3];
  }
 */
}
CausticData::~CausticData(){

  data.clear();
  /*
  while(crit_centers.size() > 0){
    delete[] crit_centers.back();
    crit_centers.pop_back();
    delete[] crit_radius.back();
    crit_radius.pop_back();
    delete[] caustic_centers.back();
    caustic_centers.pop_back();
    delete[] crit_radius.back();
    caustic_radius.pop_back();
  }
   */
}

void CausticData::resize(size_t size){

  data.resize(size);
  /*size_t oldsize = redshifts.size();

  for(size_t i = oldsize - 1; i > size-1  ; --i){
    delete[] crit_centers[i];
    delete[] crit_radius[i];
    delete[] caustic_centers[i];
    delete[] crit_radius[i];
  }

  redshifts.resize(size);
  crit_centers.reserve(size);
  caustic_centers.resize(size);

  crit_radius.resize(size);
  caustic_radius.resize(size);

  crit_area.resize(size);
  caustic_area.resize(size);

  for(size_t i = oldsize; i < size ; ++i){
    crit_centers[i] = new double[2];
    crit_radius[i] = new double[3];
    caustic_centers[i] = new double[2];
    caustic_radius[i] = new double[3];
  }
   */
}

void CausticData::readfile(std::string filename){
  std::ifstream file_in(filename.c_str());
  std::string myline;
  std::string space = " ";
  unsigned long myint;
	double mydouble;

	std::string strg;
	std::string f=",";
	std::stringstream buffer;
	size_t length;

  if(!file_in){
    std::cout << "Can't open file " << filename << std::endl;
    exit(1);
  }

  std::cout << "Reading caustic information from " << filename << std::endl;
  size_t i=0;
  while(file_in.peek() == '#'){
    file_in.ignore(10000,'\n');
    ++i;
  }
  std::cout << "skipped "<< i << " comment lines in " << filename << std::endl;

  size_t pos;
  double tmp[3];
  CausticStructure tmp_data;
  // read in data
//	for(i=0; i < 20; ++i){
  while(getline(file_in,myline)){

		if(myline[0] == '#'){
      std::cout << "skipped line " << i << std::endl;
			continue;
    }

		for(int l=0;l<ncolumns; l++){
			pos = myline.find(space);
			strg.assign(myline,0,pos);
			buffer << strg;
      switch (l) {
        case 0:
          buffer >> mydouble;
          tmp_data.redshift = mydouble;
          break;
        case 1:
          buffer >> mydouble;
          tmp_data.crit_center[0] = mydouble;
          break;
        case 2:
          buffer >> mydouble;
          tmp_data.crit_center[1] = mydouble;
          break;
        case 3:
          buffer >> mydouble;
          tmp_data.crit_radius[0] = mydouble;
          break;
        case 4:
          buffer >> mydouble;
          tmp_data.crit_radius[1] = mydouble;
          break;
        case 5:
          buffer >> mydouble;
          tmp_data.crit_radius[2] = mydouble;
          break;
        case 6:
          buffer >> mydouble;
          tmp_data.crit_area = mydouble;
          break;

        case 7:
          buffer >> mydouble;
          tmp_data.caustic_center[0] = mydouble;
          break;
        case 8:
          buffer >> mydouble;
          tmp_data.caustic_center[1] = mydouble;
          break;
        case 9:
          buffer >> mydouble;
          tmp_data.caustic_radius[0] = mydouble;
          break;
        case 10:
          buffer >> mydouble;
          tmp_data.caustic_radius[1] = mydouble;
          break;
        case 11:
          buffer >> mydouble;
          tmp_data.caustic_radius[2] = mydouble;
          break;
        case 12:
          buffer >> mydouble;
          tmp_data.caustic_area = mydouble;
          break;

        default:
          break;
      }

			myline.erase(0,pos+1);
      pos= myline.find_first_not_of(space);
      myline.erase(0,pos);

			strg.clear();
			buffer.clear();
			buffer.str(std::string());
    }
    myline.clear();
    data.push_back(tmp_data);
  }
  /*for(i=0; i < 20; ++i){
    std::cout << data[i].redshift << " " << data[i].crit_center[0] << " " << data[i].crit_center[1]
    << " " << data[i].crit_radius[0] << " " << data[i].crit_radius[1]<< " " << data[i].crit_radius[2] << std::endl;
  }*/

 }
void CausticData::printfile(std::string filename,std::string paramfile,double fieldofview,double minscale){
  std::ofstream catalog_caustic(filename.c_str());

  catalog_caustic << "# column 1 redshift of source plane" << std::endl;
  catalog_caustic << "# column 2 critical curve center x position in degrees" << std::endl;
  catalog_caustic << "# column 3 critical curve center y position in degrees" << std::endl;
  catalog_caustic << "# column 4 critical curve average radius" << std::endl;
  catalog_caustic << "# column 5 critical curve max radius" << std::endl;
  catalog_caustic << "# column 6 critical curve min radius" << std::endl;
  catalog_caustic << "# column 7 critical curve area" << std::endl;
  catalog_caustic << "# column 8 caustic center x position in degrees" << std::endl;
  catalog_caustic << "# column 9 caustic center y position in degrees" << std::endl;
  catalog_caustic << "# column 10 caustic average radius" << std::endl;
  catalog_caustic << "# column 11 caustic max radius" << std::endl;
  catalog_caustic << "# column 12 caustic min radius" << std::endl;
  catalog_caustic << "# column 13 caustic area" << std::endl;
  catalog_caustic << "# parameter file: " << paramfile << std::endl;

  catalog_caustic << "# " << " all critical lines above a scale of " << 180*60*60*minscale/pi << " arcsec,  field of view: " << fieldofview << " square degrees" << std::endl;

  for(size_t i = 0; i < data.size(); ++i){
    catalog_caustic << data[i].redshift
    << " " << data[i].crit_center[0] << " " << data[i].crit_center[1]
    << " " << data[i].crit_radius[0] << " " << data[i].crit_radius[1] << " " << data[i].crit_radius[2]
    << " " << data[i].crit_area
    << " " << data[i].caustic_center[0] << " " << data[i].caustic_center[1]
    << " " << data[i].caustic_radius[0] << " " << data[i].caustic_radius[1] << " " << data[i].caustic_radius[2]
    << " " << data[i].caustic_area
    << std::endl;
  }
}
<commit_msg>fixed causticdata.cpp<commit_after>//
//  causticdata.cpp
//  SLsimLib
//
//  Created by bmetcalf on 5/6/13.
//
//

#include "causticdata.h"

CausticData::CausticData(std::string filename){
  ncolumns = 13;
  readfile(filename);
}
CausticData::CausticData(size_t size){
  ncolumns = 13;

  data.resize(size);
/*  redshifts.resize(size);
  crit_centers.reserve(size);
  caustic_centers.resize(size);

  crit_radius.resize(size);
  caustic_radius.resize(size);

  crit_area.resize(size);
  caustic_area.resize(size);

  for(size_t i = 0; i < size ; ++i){
    causticdata[i].crit_centers = new double[2];
    crit_radius[i] = new double[3];
    caustic_centers[i] = new double[2];
    caustic_radius[i] = new double[3];
  }
 */
}
CausticData::~CausticData(){

  data.clear();
  /*
  while(crit_centers.size() > 0){
    delete[] crit_centers.back();
    crit_centers.pop_back();
    delete[] crit_radius.back();
    crit_radius.pop_back();
    delete[] caustic_centers.back();
    caustic_centers.pop_back();
    delete[] crit_radius.back();
    caustic_radius.pop_back();
  }
   */
}

void CausticData::resize(size_t size){

  data.resize(size);
}

/// Read in data from a caustic catalog file
void CausticData::readfile(std::string filename){

  data.clear();

  std::ifstream file_in(filename.c_str());
  std::string myline;
  std::string space = " ";
  unsigned long myint;
	double mydouble;

	std::string strg;
	std::string f=",";
	std::stringstream buffer;
	size_t length;

  if(!file_in){
    std::cout << "Can't open file " << filename << std::endl;
    exit(1);
  }

  std::cout << "Reading caustic information from " << filename << std::endl;
  size_t i=0;
  while(file_in.peek() == '#'){
    file_in.ignore(10000,'\n');
    ++i;
  }
  std::cout << "skipped "<< i << " comment lines in " << filename << std::endl;

  size_t pos;
  double tmp[3];
  CausticStructure tmp_data;
  // read in data
//	for(i=0; i < 20; ++i){
  while(getline(file_in,myline)){

		if(myline[0] == '#'){
      std::cout << "skipped line " << i << std::endl;
			continue;
    }
	/*
	 if(causticdata[i].crit_radius[0] > 0 ){
	 //*** need to calculate area and max min sizes
	 catalog_caustic << z_sources
	 << " " << causticdata[i].crit_center[0] << " " << causticdata[i].crit_center[1]
	 << " " << causticdata[i].crit_radius[0] << " " << causticdata[i].crit_radius[2]
	 << " "<< causticdata[i].crit_radius[1]  << " " << imageinfo[i].area
	 << " " << causticdata[i].caustic_center[0] << " " << causticdata[i].caustic_center[1]
	 << " " << causticdata[i].caustic_radius[0] << " " << causticdata[i].caustic_radius[2]   << " "
	 << causticdata[i].caustic_radius[1]
	 << " " << causticdata[i].caustic_area
	 << std::endl;
	 }*/

		for(int l=0;l<ncolumns; l++){
			pos = myline.find(space);
			strg.assign(myline,0,pos);
			buffer << strg;
      switch (l) {
        case 0:
          buffer >> mydouble;
          tmp_data.redshift = mydouble;
          break;
        case 1:
          buffer >> mydouble;
          tmp_data.crit_center[0] = mydouble;
          break;
        case 2:
          buffer >> mydouble;
          tmp_data.crit_center[1] = mydouble;
          break;
        case 3:
          buffer >> mydouble;
          tmp_data.crit_radius[0] = mydouble;
          break;
        case 4:
          buffer >> mydouble;
          tmp_data.crit_radius[2] = mydouble;
          break;
        case 5:
          buffer >> mydouble;
          tmp_data.crit_radius[1] = mydouble;
          break;
        case 6:
          buffer >> mydouble;
          tmp_data.crit_area = mydouble;
          break;

        case 7:
          buffer >> mydouble;
          tmp_data.caustic_center[0] = mydouble;
          break;
        case 8:
          buffer >> mydouble;
          tmp_data.caustic_center[1] = mydouble;
          break;
        case 9:
          buffer >> mydouble;
          tmp_data.caustic_radius[0] = mydouble;
          break;
        case 10:
          buffer >> mydouble;
          tmp_data.caustic_radius[2] = mydouble;
          break;
        case 11:
          buffer >> mydouble;
          tmp_data.caustic_radius[1] = mydouble;
          break;
        case 12:
          buffer >> mydouble;
          tmp_data.caustic_area = mydouble;
          break;

        default:
          break;
      }

			myline.erase(0,pos+1);
      pos= myline.find_first_not_of(space);
      myline.erase(0,pos);

			strg.clear();
			buffer.clear();
			buffer.str(std::string());
    }
    myline.clear();
    data.push_back(tmp_data);
  }
  /*for(i=0; i < 20; ++i){
    std::cout << data[i].redshift << " " << data[i].crit_center[0] << " " << data[i].crit_center[1]
    << " " << data[i].crit_radius[0] << " " << data[i].crit_radius[1]<< " " << data[i].crit_radius[2] << std::endl;
  }*/

 }
void CausticData::printfile(std::string filename,std::string paramfile,double fieldofview,double minscale){
  std::ofstream catalog_caustic(filename.c_str());

  catalog_caustic << "# column 1 redshift of source plane" << std::endl;
  catalog_caustic << "# column 2 critical curve center x position in degrees" << std::endl;
  catalog_caustic << "# column 3 critical curve center y position in degrees" << std::endl;
  catalog_caustic << "# column 4 critical curve average radius" << std::endl;
  catalog_caustic << "# column 5 critical curve max radius" << std::endl;
  catalog_caustic << "# column 6 critical curve min radius" << std::endl;
  catalog_caustic << "# column 7 critical curve area" << std::endl;
  catalog_caustic << "# column 8 caustic center x position in degrees" << std::endl;
  catalog_caustic << "# column 9 caustic center y position in degrees" << std::endl;
  catalog_caustic << "# column 10 caustic average radius" << std::endl;
  catalog_caustic << "# column 11 caustic max radius" << std::endl;
  catalog_caustic << "# column 12 caustic min radius" << std::endl;
  catalog_caustic << "# column 13 caustic area" << std::endl;
  catalog_caustic << "# parameter file: " << paramfile << std::endl;

  catalog_caustic << "# " << " all critical lines above a scale of " << 180*60*60*minscale/pi << " arcsec,  field of view: " << fieldofview << " square degrees" << std::endl;

  for(size_t i = 0; i < data.size(); ++i){
    catalog_caustic << data[i].redshift
    << " " << data[i].crit_center[0] << " " << data[i].crit_center[1]
    << " " << data[i].crit_radius[0] << " " << data[i].crit_radius[2] << " " << data[i].crit_radius[1]
    << " " << data[i].crit_area
    << " " << data[i].caustic_center[0] << " " << data[i].caustic_center[1]
    << " " << data[i].caustic_radius[0] << " " << data[i].caustic_radius[2] << " " << data[i].caustic_radius[1]
    << " " << data[i].caustic_area
    << std::endl;
  }
}

void CausticData::SortByCritSize(){
  std::sort(data.begin(),data.end(),comparcritsize);
}

bool comparcritsize(CausticStructure &caust1,CausticStructure &caust2){
  return (caust1.crit_radius[0] > caust2.crit_radius[0]);
}
<|endoftext|>


<commit_before>// Copyright (c) 2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "timedata.h"

#include "netbase.h"
#include "sync.h"
#include "ui_interface.h"
#include "util.h"
#include "utilstrencodings.h"

#include <boost/foreach.hpp>

using namespace std;

static CCriticalSection cs_nTimeOffset;
static int64_t nTimeOffset = 0;

/**
 * "Never go to sea with two chronometers; take one or three."
 * Our three time sources are:
 *  - System clock
 *  - Median of other nodes clocks
 *  - The user (asking the user to fix the system clock if the first two disagree)
 */
int64_t GetTimeOffset()
{
    LOCK(cs_nTimeOffset);
    return nTimeOffset;
}

int64_t GetAdjustedTime()
{
    return GetTime() + GetTimeOffset();
}

static int64_t abs64(int64_t n)
{
    return (n >= 0 ? n : -n);
}

void AddTimeData(const CNetAddr& ip, int64_t nTime)
{
    int64_t nOffsetSample = nTime - GetTime();

    LOCK(cs_nTimeOffset);
    // Ignore duplicates
    static set<CNetAddr> setKnown;
    if (!setKnown.insert(ip).second)
        return;

    // Add data
    static CMedianFilter<int64_t> vTimeOffsets(200,0);
    vTimeOffsets.input(nOffsetSample);
    LogPrintf("Added time data, samples %d, offset %+d (%+d minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);

    // There is a known issue here (see issue #4521):
    //
    // - The structure vTimeOffsets contains up to 200 elements, after which
    // any new element added to it will not increase its size, replacing the
    // oldest element.
    //
    // - The condition to update nTimeOffset includes checking whether the
    // number of elements in vTimeOffsets is odd, which will never happen after
    // there are 200 elements.
    //
    // But in this case the 'bug' is protective against some attacks, and may
    // actually explain why we've never seen attacks which manipulate the
    // clock offset.
    //
    // So we should hold off on fixing this and clean it up as part of
    // a timing cleanup that strengthens it in a number of other ways.
    //
    if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
    {
        int64_t nMedian = vTimeOffsets.median();
        std::vector<int64_t> vSorted = vTimeOffsets.sorted();
        // Only let other nodes change our time by so much
        if (abs64(nMedian) < 70 * 60)
        {
            nTimeOffset = nMedian;
        }
        else
        {
            nTimeOffset = 0;

            static bool fDone;
            if (!fDone)
            {
                // If nobody has a time different than ours but within 5 minutes of ours, give a warning
                bool fMatch = false;
                BOOST_FOREACH(int64_t nOffset, vSorted)
                    if (nOffset != 0 && abs64(nOffset) < 5 * 60)
                        fMatch = true;

                if (!fMatch)
                {
                    fDone = true;
                    string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong Bitcoin Core will not work properly.");
                    strMiscWarning = strMessage;
                    LogPrintf("*** %s\n", strMessage);
                    uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING);
                }
            }
        }
        if (fDebug) {
            BOOST_FOREACH(int64_t n, vSorted)
                LogPrintf("%+d  ", n);
            LogPrintf("|  ");
        }
        LogPrintf("nTimeOffset = %+d  (%+d minutes)\n", nTimeOffset, nTimeOffset/60);
    }
}
<commit_msg>fix reference to Reddcoin<commit_after>// Copyright (c) 2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "timedata.h"

#include "netbase.h"
#include "sync.h"
#include "ui_interface.h"
#include "util.h"
#include "utilstrencodings.h"

#include <boost/foreach.hpp>

using namespace std;

static CCriticalSection cs_nTimeOffset;
static int64_t nTimeOffset = 0;

/**
 * "Never go to sea with two chronometers; take one or three."
 * Our three time sources are:
 *  - System clock
 *  - Median of other nodes clocks
 *  - The user (asking the user to fix the system clock if the first two disagree)
 */
int64_t GetTimeOffset()
{
    LOCK(cs_nTimeOffset);
    return nTimeOffset;
}

int64_t GetAdjustedTime()
{
    return GetTime() + GetTimeOffset();
}

static int64_t abs64(int64_t n)
{
    return (n >= 0 ? n : -n);
}

void AddTimeData(const CNetAddr& ip, int64_t nTime)
{
    int64_t nOffsetSample = nTime - GetTime();

    LOCK(cs_nTimeOffset);
    // Ignore duplicates
    static set<CNetAddr> setKnown;
    if (!setKnown.insert(ip).second)
        return;

    // Add data
    static CMedianFilter<int64_t> vTimeOffsets(200,0);
    vTimeOffsets.input(nOffsetSample);
    LogPrintf("Added time data, samples %d, offset %+d (%+d minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);

    // There is a known issue here (see issue #4521):
    //
    // - The structure vTimeOffsets contains up to 200 elements, after which
    // any new element added to it will not increase its size, replacing the
    // oldest element.
    //
    // - The condition to update nTimeOffset includes checking whether the
    // number of elements in vTimeOffsets is odd, which will never happen after
    // there are 200 elements.
    //
    // But in this case the 'bug' is protective against some attacks, and may
    // actually explain why we've never seen attacks which manipulate the
    // clock offset.
    //
    // So we should hold off on fixing this and clean it up as part of
    // a timing cleanup that strengthens it in a number of other ways.
    //
    if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
    {
        int64_t nMedian = vTimeOffsets.median();
        std::vector<int64_t> vSorted = vTimeOffsets.sorted();
        // Only let other nodes change our time by so much
        if (abs64(nMedian) < 70 * 60)
        {
            nTimeOffset = nMedian;
        }
        else
        {
            nTimeOffset = 0;

            static bool fDone;
            if (!fDone)
            {
                // If nobody has a time different than ours but within 5 minutes of ours, give a warning
                bool fMatch = false;
                BOOST_FOREACH(int64_t nOffset, vSorted)
                    if (nOffset != 0 && abs64(nOffset) < 5 * 60)
                        fMatch = true;

                if (!fMatch)
                {
                    fDone = true;
                    string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong Reddcoin Core will not work properly.");
                    strMiscWarning = strMessage;
                    LogPrintf("*** %s\n", strMessage);
                    uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING);
                }
            }
        }
        if (fDebug) {
            BOOST_FOREACH(int64_t n, vSorted)
                LogPrintf("%+d  ", n);
            LogPrintf("|  ");
        }
        LogPrintf("nTimeOffset = %+d  (%+d minutes)\n", nTimeOffset, nTimeOffset/60);
    }
}
<|endoftext|>


<commit_before>// unittree.cpp
#include "unittree.h"
#include <exception>

UnitTree::UnitTree()
{
	//
}

UnitTree::~UnitTree()
{
	vUnitList.clear();
}

void UnitTree::addUnit(string name, int mineralCost, int gasCost, int buildTime, int supplyCost, int supplyProvided, string prereq, string buildsFrom)
{
	Unit *newUnit = new Unit(name, mineralCost, gasCost, buildTime, supplyCost, supplyProvided, prereq, buildsFrom);
	vUnitList.push_back(*newUnit);
}

void UnitTree::init()
{
	for (Unit &iUnit : vUnitList)
	{
		Unit *prereq = NULL;
		Unit *buildsFrom = NULL;

		for (Unit &iFindUnit : vUnitList)
		{
			if (iUnit.getPrereqName() == iFindUnit.getName())
			{
				prereq = &iFindUnit;
			}
			if (iUnit.getBuildsFromName() == iFindUnit.getName())
			{
				buildsFrom = &iFindUnit;
			}
		}
		iUnit.init(*prereq, *buildsFrom);
	}
}

//return the unit
Unit &UnitTree::findUnit(string unitName)
{
	for (Unit &iUnit : vUnitList)
	{
		if (iUnit.getName() == unitName)
		{
			return iUnit;
		}
	}
	throw "Unit " + unitName + " not found.";
}

//load unit data
//start each race with its worker unit first!!
void UnitTree::loadRace(char race)
{
	if (race == 't')
	{
		addUnit("Terran SCV",50,0,300,1,0,"Terran Command Center","Terran Command Center");
		addUnit("Terran Command Center",400,0,1800,0,10,"Terran SCV","Terran SCV");
	}
	init();
}

<commit_msg>added basic buildings and rax units<commit_after>// unittree.cpp
#include "unittree.h"
#include <exception>

UnitTree::UnitTree()
{
	//
}

UnitTree::~UnitTree()
{
	vUnitList.clear();
}

void UnitTree::addUnit(string name, int mineralCost, int gasCost, int buildTime, int supplyCost, int supplyProvided, string prereq, string buildsFrom)
{
	Unit *newUnit = new Unit(name, mineralCost, gasCost, buildTime, supplyCost, supplyProvided, prereq, buildsFrom);
	vUnitList.push_back(*newUnit);
}

void UnitTree::init()
{
	for (Unit &iUnit : vUnitList)
	{
		Unit *prereq = NULL;
		Unit *buildsFrom = NULL;

		for (Unit &iFindUnit : vUnitList)
		{
			if (iUnit.getPrereqName() == iFindUnit.getName())
			{
				prereq = &iFindUnit;
			}
			if (iUnit.getBuildsFromName() == iFindUnit.getName())
			{
				buildsFrom = &iFindUnit;
			}
		}
		iUnit.init(*prereq, *buildsFrom);
	}
}

//return the unit
Unit &UnitTree::findUnit(string unitName)
{
	for (Unit &iUnit : vUnitList)
	{
		if (iUnit.getName() == unitName)
		{
			return iUnit;
		}
	}
	throw "Unit " + unitName + " not found.";
}

//load unit data
//start each race with its worker unit first!!
void UnitTree::loadRace(char race)
{
	if (race == 't')
	{
		//ground units
		addUnit("Terran SCV",50,0,300,1,0,"Terran Command Center","Terran Command Center");
		addUnit("Terran Marine",50,0,360,1,0,"Terran Barracks","Terran Barracks");
		addUnit("Terran Firebat",50,25,360,1,0,"Terran Academy","Terran Barracks");
		//addUnit("Terran Ghost",25,75,750,1,0,"Terran Covert Ops","Terran Barracks");
		addUnit("Terran Medic",50,25,450,1,0,"Terran Academy","Terran Academy");
		//addUnit("Terran Vulture",75,0,450,2,0,"Terran Factory","Terran Factory");
		//addUnit("Terran Goliath",100,50,600,2,0,"Terran Armory","Terran Factory");
		//iaddUnit("Terran Siege Tank",150,100,750,2,0,"Terran Machine Shop","Terran Factory");
		//ranged units
		//addUnit("Terran Wraith",50,0,300,1,0,"Terran REPLACEMEPLS","Terran REPLACEMEPLS");
		//addUnit("Terran Dropship",50,0,300,1,0,"Terran REPLACEMEPLS","Terran REPLACEMEPLS");
		//addUnit("Terran Valkyrie",50,0,300,1,0,"Terran REPLACEMEPLS","Terran REPLACEMEPLS");
		//addUnit("Terran Science Vessel",50,0,300,1,0,"Terran REPLACEMEPLS","Terran REPLACEMEPLS");
		//addUnit("Terran Battlecruiser",50,0,300,1,0,"Terran REPLACEMEPLS","Terran REPLACEMEPLS");
		//basic buildings
		addUnit("Terran Command Center",400,0,1800,0,10,"Terran SCV","Terran SCV");
		addUnit("Terran Supply Depot",100,0,600,0,8,"Terran SCV","Terran SCV");
		addUnit("Terran Refinery",100,0,600,0,0,"Terran SCV","Terran SCV");
		addUnit("Terran Barracks",150,0,1200,0,0,"Terran Command Center","Terran SCV");
		addUnit("Terran Engineering Bay",125,0,900,0,0,"Terran Command Center","Terran SCV");
		addUnit("Terran Academy",150,0,1200,0,0,"Terran Barracks","Terran SCV");
		addUnit("Terran Bunker",100,0,450,0,0,"Terran Barracks","Terran SCV");
		addUnit("Terran Missile Turret",75,0,450,0,0,"Terran Engineering Bay","Terran SCV");
		//advanced buildings
		//addUnit("Terran REPLACEMEPLS",100,0,600,0,0,"Terran REPLACEMEPLS","Terran SCV");
		//addUnit("Terran REPLACEMEPLS",100,0,600,0,0,"Terran REPLACEMEPLS","Terran SCV");
	}
	init();
}

<|endoftext|>


<commit_before>#include <QtCore/QCoreApplication>
#include <QFile>
#include <QTextStream>
#include <vld.h>
#include "lexer.hpp"
#include "parser.hpp"
#include "stringfuncs.h"
#include "treefuncs.h"
#include "semanticerrors.h"
#include "output.h"

extern Package package;
extern QList<Import> imports;
extern QList<Enum> enums;
extern QList<Interface> interfaces;
extern QList<Class> classes;
extern QList<Field> fields;
extern QList<Method> methods;
extern char *filename;
extern int yynerrs;

int main(int argc, char *argv[])
{
    try
    {
        if (argc != 2)
        {
            throw QString("Invalid number of parameters");
        }

        QFile file(argv[1]);
        if (!file.open(QIODevice::ReadOnly))
        {
            throw QString("Couldn`t open file");
        }

        QTextStream in(&file);
        const QString fileContent = in.readAll();

        filename = argv[1]; //
        yy_scan_string(fileContent.toStdString().c_str()); //

        int parseResult = yyparse();
        yylex_destroy(); //

        switch (parseResult)
        {
            case 0: break;
            case 1: throw QString("There are syntax errors"); break;
            case 2: throw QString("Bison: error while freeing memory"); break;
        }

        if (yynerrs)
        { //  ,
            throw QString("Couldn`t parse file");
        }

        QList<SemanticError> semanticErrors;
        semanticErrors = checkSemanticErrorsBeforeTreeWillBeBuilt(package, imports, enums, interfaces, classes, fields, methods);

        getComponentsText(fileContent, package, imports, enums, interfaces, classes, fields, methods);

        Program program;
        addComponentsToTree(program, package, imports, enums, interfaces, classes, fields, methods);
        semanticErrors << checkSemanticErrorsAfterTreeWasBuilt(program);

        if (!semanticErrors.length())
        {
            QString contentBetweenTwoLastPoints = QString(argv[1]).split('.')[QString(argv[1]).count('.') - 1];
            QString fileName = contentBetweenTwoLastPoints.section(QRegularExpression("[\\\\/]"), -1);
            writeTreeToFiles(fileName, program);
        }
        else
        {
            printSemanticErrors(semanticErrors);
        }
    }
    catch (const QString &e)
    {
        QTextStream out(stderr);
        out << e << endl;
    }

    return 0;
}
<commit_msg>Исправил кодировку main.cpp<commit_after>#include <QtCore/QCoreApplication>
#include <QFile>
#include <QTextStream>
#include <vld.h>
#include "lexer.hpp"
#include "parser.hpp"
#include "stringfuncs.h"
#include "treefuncs.h"
#include "semanticerrors.h"
#include "output.h"

extern Package package;
extern QList<Import> imports;
extern QList<Enum> enums;
extern QList<Interface> interfaces;
extern QList<Class> classes;
extern QList<Field> fields;
extern QList<Method> methods;
extern char *filename;
extern int yynerrs;

int main(int argc, char *argv[])
{
    try
    {
        if (argc != 2)
        {
            throw QString("Invalid number of parameters");
        }

        QFile file(argv[1]);
        if (!file.open(QIODevice::ReadOnly))
        {
            throw QString("Couldn`t open file");
        }

        QTextStream in(&file);
        const QString fileContent = in.readAll();

        filename = argv[1]; // Для вывода синтаксических ошибок
        yy_scan_string(fileContent.toStdString().c_str()); // Чтобы флекс брал символы из строки

        int parseResult = yyparse();
        yylex_destroy(); // Освобождение памяти

        switch (parseResult)
        {
            case 0: break;
            case 1: throw QString("There are syntax errors"); break;
            case 2: throw QString("Bison: error while freeing memory"); break;
        }

        if (yynerrs)
        { // Есть ошибки, после которых удалось восстановиться и продолжить разбор
            throw QString("Couldn`t parse file");
        }

        QList<SemanticError> semanticErrors;
        semanticErrors = checkSemanticErrorsBeforeTreeWillBeBuilt(package, imports, enums, interfaces, classes, fields, methods);

        getComponentsText(fileContent, package, imports, enums, interfaces, classes, fields, methods);

        Program program;
        addComponentsToTree(program, package, imports, enums, interfaces, classes, fields, methods);
        semanticErrors << checkSemanticErrorsAfterTreeWasBuilt(program);

        if (!semanticErrors.length())
        {
            QString contentBetweenTwoLastPoints = QString(argv[1]).split('.')[QString(argv[1]).count('.') - 1];
            QString fileName = contentBetweenTwoLastPoints.section(QRegularExpression("[\\\\/]"), -1);
            writeTreeToFiles(fileName, program);
        }
        else
        {
            printSemanticErrors(semanticErrors);
        }
    }
    catch (const QString &e)
    {
        QTextStream out(stderr);
        out << e << endl;
    }

    return 0;
}
<|endoftext|>